test(bazel): runfiles helpers + declared inputs for scan-guard tests (#6828)

* test(bazel): add internal/testutil/bazeltest runfiles helpers

Repository-path resolution for tests that works identically under plain
go test (package cwd, full checkout), bazel test locally, and remote
execution (declared runfiles only):

- IsBazel, RepoRoot (BEADS_TEST_REPO_ROOT, then the runfiles workspace
  root, then a go.mod walk), OverrideRoot (drop-in condition for existing
  helpers; empty under plain go test), CallerDir
- Runfile for $(rlocationpath) values, GOROOT for type-checking tests
- ShardFreeEnv for helpers that re-exec a test binary

Every helper reduces to the pre-Bazel behavior under go test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(bazel): declare source/data reads for 14 scan-guard targets

Source-scanning and repo-file tests read files their Bazel targets never
declared, so they failed under `bazel test` (and could not run on remote
workers at all). Declare narrow inputs as `data` and resolve paths through
bazeltest where the test located the tree via runtime.Caller:

- tools/bazel/go_srcs.py (run by `make bazel-sync` after gazelle) keeps a
  managed `go_srcs` filegroup in the packages whose Go source tests scan,
  plus `//internal/storage:tree_go_srcs` for the storage-tree walk. Bazel
  globs stop at package boundaries, so the aggregate needs one filegroup
  per package; the script keeps it in sync and gazelle-stable.
- Hand-written narrow inputs: //internal/storage/schema:migrations,
  //:docsync_files, //plugins/beads:plugin_files, and exports of
  .gitattributes, .claude-plugin/marketplace.json, cmd/bd list.go and
  ready.go, testutil/testdoltcommon.go, scripts README.md and the release
  catalog, each visible only to its consumer.
- runtime.Caller-based roots in backend, backend/conformance,
  internal/storage, internal/formula and test/docsync now go through
  bazeltest.CallerDir / OverrideRoot; relative-path tests need data only.
- integrations/ leaves .bazelignore (it is still gazelle-excluded) so the
  docsync link check can declare integrations/beads-mcp/PYPI.md.

Under --config=prcore every target reports the same PASS/SKIP/FAIL test
set as `go test -race -short` for its package, locally and remotely.
Plain `go test` behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(bazel): guard generated go_srcs and harden bazeltest root override

- tools/bazel/go_srcs.py: add --check (print diff, exit 1 on stale blocks);
  new `make bazel-sync-check` target runs it.
- scripts/bazel_policy_test.go: under go test, assert every tree_go_srcs
  (//internal/storage) lists exactly the BUILD.bazel packages below its
  root, run go_srcs.py --check, and forbid BUILD files under docs/ and
  engdocs/ (they would cut subtrees out of //:docsync_files).
- bazeltest: honor BEADS_TEST_REPO_ROOT only when it holds go.mod
  (RepoRoot fails loudly otherwise); drop the unused GOROOT() helper,
  whose compiled-in branch could never fire under rules_go.
- scripts/ci/lib/test-env.sh: unset BEADS_TEST_REPO_ROOT.
- Document the hand-listed out-of-tree link targets in //:docsync_files.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(bazel): re-sync BUILD files with main

Regenerated with make bazel-sync after commits that landed while the
scaffold PR was in CI (new internal/execenv, gitenv, gitignore packages
and new sources/deps).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(bazel): declare init_safety_help.go for docsync

TestInitSafetyCLIHelpCoversReCloneGotchas (#6431) reads
cmd/bd/init_safety_help.go; export it to //test/docsync only.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-09-27 08:24:08 -07:00 • committed by GitHub
commit f66375459f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
75 changed files with 1448 additions and 9 deletions

View file

@ -1,6 +1,5 @@
examples/library-usage
examples/bd-example-extension-go
integrations
npm-package
website
node_modules

View file

@ -3,6 +3,9 @@ load("@rules_go//go:def.bzl", "go_library", "go_test")
# gazelle:prefix github.com/steveyegge/beads
# gazelle:build_tags gms_pure_go
# integrations/ holds no Go; it stays visible to Bazel (not in .bazelignore)
# only so //test/docsync can declare the markdown its link checks resolve.
# gazelle:exclude integrations
gazelle(name = "gazelle")
exports_files([
@ -10,6 +13,38 @@ exports_files([
"go.sum",
])
# Repository files read by source-scanning tests, declared as their `data` so
# the tests run under `bazel test` and remote execution.
exports_files(
[".gitattributes"],
visibility = ["//scripts/gitattributespolicy:__pkg__"],
)
exports_files(
[".claude-plugin/marketplace.json"],
visibility = ["//cmd/bd/setup:__pkg__"],
)
# //test/docsync: the Mintlify site, engdocs, root markdown, and the files
# outside those trees that their local links point at.
#
# The out-of-tree link targets are hand-listed: a new docs/engdocs link to a
# file outside these globs passes `go test` but fails under Bazel until the
# target is added here. The globs stop at package boundaries, so no BUILD file
# may live under docs/ or engdocs/ (enforced by scripts/bazel_policy_test.go).
filegroup(
name = "docsync_files",
srcs = glob([
"*.md",
"docs/**",
"engdocs/**",
]) + [
"integrations/beads-mcp/PYPI.md",
"//scripts:README.md",
],
visibility = ["//test/docsync:__pkg__"],
)
# Inputs of the Bazel policy tests in //scripts (bazel_policy_test.go), so they
# run under `bazel test` as well as `go test`.
filegroup(

View file

@ -46,7 +46,7 @@ endif
.PHONY: all build doctor-build test test-icu-path test-full-cgo test-regression test-upgrade test-cross-version test-migration corpus-regen githooks-regen bench bench-quick clean clean-test-tmp install install-force help check-up-to-date fmt fmt-check check-testing-short
.PHONY: ci-pr-core ci-pr-policy ci-pr-lint ci-complexity ci-complexity-diff ci-complexity-check ci-package-mcp ci-package-npm
.PHONY: api-gen api-check
.PHONY: bazel-sync
.PHONY: bazel-sync bazel-sync-check
# Default target
all: build
@ -411,12 +411,21 @@ docs-dev:
# Bazel (side-by-side with the Go toolchain; `go build`/`go test` do not need
# it). Regenerate BUILD.bazel files with gazelle and refresh the MODULE.bazel
# use_repo list + MODULE.bazel.lock. Run after changing Go imports or go.mod.
# use_repo list + MODULE.bazel.lock, then refresh the go_srcs filegroups that
# source-scanning tests declare as data (tools/bazel/go_srcs.py). Run after
# changing Go imports, go.mod, or packages.
BAZEL ?= bazel
bazel-sync:
$(BAZEL) run //:gazelle
python3 tools/bazel/go_srcs.py
$(BAZEL) mod tidy
# Fail (printing a diff) when a go_srcs block that tools/bazel/go_srcs.py
# manages is stale, e.g. after gazelle added a package under a scanned tree.
# Needs no Bazel; scripts/bazel_policy_test.go runs the same check.
bazel-sync-check:
python3 tools/bazel/go_srcs.py --check
# Ensure -short is not used as an implicit CI tier boundary.
check-testing-short:
@./scripts/check-testing-short.sh
@ -466,6 +475,7 @@ help:
@echo " make api-gen - Regenerate HTTP API types from the OpenAPI spec"
@echo " make api-check - OpenAPI drift gate (regenerate, diff-or-fail, spec tests)"
@echo " make bazel-sync - Regenerate Bazel BUILD files and tidy MODULE.bazel (gazelle + mod tidy)"
@echo " make bazel-sync-check - Fail if generated go_srcs Bazel filegroups are stale"
@echo " make clean - Remove build artifacts and profile files"
@echo " make clean-test-tmp - Sweep orphaned cmd/bd test temp dirs from \$$TMPDIR"
@echo " make help - Show this help message"

View file

@ -22,9 +22,24 @@ go_test(
"completeness_test.go",
"errors_test.go",
],
data = [":go_srcs"],
deps = [
":backend",
"//backend/conformance",
"//internal/storage",
"//internal/testutil/bazeltest",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -5,7 +5,6 @@ import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"reflect"
"runtime"
"sort"
@ -14,6 +13,7 @@ import (
"github.com/steveyegge/beads/backend"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
)
const internalPrefix = "github.com/steveyegge/beads/internal/"
@ -77,7 +77,7 @@ func publicAliases(t *testing.T) map[string]bool {
if !ok {
t.Fatal("runtime.Caller failed")
}
dir := filepath.Dir(thisFile)
dir := bazeltest.CallerDir(thisFile, "backend")
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, dir, func(fi fs.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")

View file

@ -80,11 +80,33 @@ go_test(
"role_coverage_scan_test.go",
"versioned_history_wiring_test.go",
],
data = [
":go_srcs",
"//beadserrors:go_srcs",
"//internal/types:go_srcs",
"//issueops:go_srcs",
"//journalops:go_srcs",
"//memoryops:go_srcs",
],
embed = [":conformance"],
deps = [
"//internal/storage",
"//internal/testutil/bazeltest",
"//issueops",
"//journalops",
"//memoryops",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -9,12 +9,13 @@ import (
"io/fs"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
)
// TestRoleContractCasesCoverEveryContractCase is the drift guard on the role
@ -333,7 +334,7 @@ func parseRoleContractCases(t *testing.T) []string {
t.Fatal("runtime.Caller failed")
}
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, filepath.Dir(thisFile), func(fi fs.FileInfo) bool {
pkgs, err := parser.ParseDir(fset, bazeltest.CallerDir(thisFile, "backend/conformance"), func(fi fs.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}, 0)
if err != nil {

View file

@ -16,6 +16,7 @@ import (
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
"github.com/steveyegge/beads/issueops"
"github.com/steveyegge/beads/journalops"
"github.com/steveyegge/beads/memoryops"
@ -59,6 +60,9 @@ var errorType = reflect.TypeOf((*error)(nil)).Elem()
// repoRoot locates the module root from this file's own path, so the gate
// finds the facade packages without depending on the working directory.
func repoRoot() (string, error) {
if root := bazeltest.OverrideRoot(); root != "" {
return root, nil
}
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
return "", errors.New("runtime.Caller failed")

View file

@ -6,3 +6,16 @@ go_library(
importpath = "github.com/steveyegge/beads/beadserrors",
visibility = ["//visibility:public"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -35,6 +35,7 @@ go_library(
"compact.go",
"compact_dolt.go",
"compact_dolt_proxied_server.go",
"compact_plan.go",
"compact_proxied_server.go",
"completions.go",
"config.go",
@ -88,6 +89,7 @@ go_library(
"dolt_autopush.go",
"dolt_clean_databases.go",
"dolt_clean_databases_proxied_server.go",
"dolt_commit_proxied_server.go",
"dolt_local_only.go",
"dolt_proxied_lifecycle.go",
"dolt_remote_adopt.go",
@ -356,10 +358,13 @@ go_library(
"//internal/doltserver",
"//internal/doltversion",
"//internal/eventsjournal",
"//internal/execenv",
"//internal/formula",
"//internal/git",
"//internal/gitenv",
"//internal/githooksenv",
"//internal/github",
"//internal/gitignore",
"//internal/gitlab",
"//internal/hooks",
"//internal/httpapi",
@ -493,6 +498,7 @@ go_test(
"children_test.go",
"claim_pools_embedded_test.go",
"close_embedded_test.go",
"close_failure_report_test.go",
"close_gate_test.go",
"close_last_touched_test.go",
"close_proxied_integration_test.go",
@ -507,6 +513,7 @@ go_test(
"comments_test.go",
"compact_embedded_test.go",
"compact_gc_flag_test.go",
"compact_plan_test.go",
"compact_test.go",
"compact_tier2_embedded_test.go",
"completions_test.go",
@ -579,6 +586,7 @@ go_test(
"delete_input_test.go",
"delete_proxied_integration_test.go",
"delete_proxied_server_output_test.go",
"dep_add_target_test.go",
"dep_batch_test.go",
"dep_bulk_role_test.go",
"dep_cycles_test.go",
@ -609,12 +617,15 @@ go_test(
"doctor_repair_test.go",
"doctor_test.go",
"doctor_validate_test.go",
"dolt_autocommit_exemption_wiring_test.go",
"dolt_autocommit_server_test.go",
"dolt_autocommit_test.go",
"dolt_autopush_test.go",
"dolt_clean_databases_purge_proxied_integration_test.go",
"dolt_clean_databases_purge_test.go",
"dolt_clean_databases_quote_test.go",
"dolt_commit_proxied_integration_test.go",
"dolt_commit_proxied_server_test.go",
"dolt_embedded_test.go",
"dolt_help_auth_test.go",
"dolt_lifecycle_proxied_server_test.go",
@ -771,6 +782,8 @@ go_test(
"linear_test.go",
"lint_embedded_test.go",
"lint_stale_proxied_integration_test.go",
"list_comments_embedded_test.go",
"list_comments_proxied_integration_test.go",
"list_embedded_test.go",
"list_footer_counts_test.go",
"list_format_json_test.go",
@ -783,6 +796,7 @@ go_test(
"list_roles_test.go",
"list_skip_labels_test.go",
"list_test.go",
"list_tree_cycle_test.go",
"list_tree_deps_test.go",
"list_wisp_type_reachability_test.go",
"lite_filter_spy_test.go",
@ -1093,8 +1107,11 @@ go_test(
"//internal/doltremote",
"//internal/doltserver",
"//internal/eventsjournal",
"//internal/execenv",
"//internal/formula",
"//internal/git",
"//internal/gitenv",
"//internal/githooksenv",
"//internal/hooks",
"//internal/httpapi",
"//internal/linear",
@ -1189,3 +1206,18 @@ go_test(
"//conditions:default": [],
}),
)
# CLI flag registrations pinned by //internal/httpapi spec parity tests.
exports_files(
[
"list.go",
"ready.go",
],
visibility = ["//internal/httpapi:__pkg__"],
)
# Init-safety help text pinned by //test/docsync recovery-doc tests.
exports_files(
["init_safety_help.go"],
visibility = ["//test/docsync:__pkg__"],
)

View file

@ -62,6 +62,7 @@ go_library(
"//internal/doltremote",
"//internal/doltserver",
"//internal/git",
"//internal/gitignore",
"//internal/storage",
"//internal/storage/dberrors",
"//internal/storage/dolt",

View file

@ -47,6 +47,10 @@ go_test(
"plugin_layout_test.go",
"utils_test.go",
],
data = [
"//:.claude-plugin/marketplace.json",
"//plugins/beads:plugin_files",
],
embed = [":setup"],
deps = [
"//internal/templates",

View file

@ -18,6 +18,7 @@ go_library(
visibility = ["//:__subpackages__"],
deps = [
"//internal/debug",
"//internal/gitenv",
"@com_github_spf13_viper//:viper",
"@in_gopkg_yaml_v3//:yaml_v3",
] + select({
@ -36,6 +37,7 @@ go_test(
srcs = [
"agents_file_test.go",
"config_test.go",
"git_routing_test.go",
"permissions_linux_test.go",
"permissions_test.go",
"repos_test.go",
@ -51,6 +53,7 @@ go_test(
embed = [":config"],
deps = [
"//internal/git",
"//internal/gitenv",
"@com_github_spf13_viper//:viper",
"@in_gopkg_yaml_v3//:yaml_v3",
] + select({

View file

@ -0,0 +1,14 @@
load("@rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "execenv",
srcs = ["execenv.go"],
importpath = "github.com/steveyegge/beads/internal/execenv",
visibility = ["//:__subpackages__"],
)
go_test(
name = "execenv_test",
srcs = ["execenv_test.go"],
embed = [":execenv"],
)

View file

@ -37,11 +37,16 @@ go_test(
"schema_test.go",
"stepcondition_test.go",
],
data = [
"schema_gen.go",
"types.go",
],
embed = [":formula"],
deps = [
"//internal/beads",
"//internal/formula/schemagen",
"//internal/git",
"//internal/testutil",
"//internal/testutil/bazeltest",
],
)

View file

@ -7,6 +7,7 @@ import (
"testing"
"github.com/steveyegge/beads/internal/formula/schemagen"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
)
// TestSchemaGenIsCurrent re-runs the schemagen walker over types.go
@ -17,7 +18,7 @@ func TestSchemaGenIsCurrent(t *testing.T) {
if !ok {
t.Fatal("runtime.Caller failed")
}
pkgDir := filepath.Dir(thisFile)
pkgDir := bazeltest.CallerDir(thisFile, "internal/formula")
typesPath := filepath.Join(pkgDir, "types.go")
committedPath := filepath.Join(pkgDir, "schema_gen.go")

View file

@ -0,0 +1,15 @@
load("@rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "gitenv",
srcs = ["routing.go"],
importpath = "github.com/steveyegge/beads/internal/gitenv",
visibility = ["//:__subpackages__"],
deps = ["//internal/execenv"],
)
go_test(
name = "gitenv_test",
srcs = ["routing_test.go"],
embed = [":gitenv"],
)

View file

@ -5,6 +5,7 @@ go_library(
srcs = ["githooksenv.go"],
importpath = "github.com/steveyegge/beads/internal/githooksenv",
visibility = ["//:__subpackages__"],
deps = ["//internal/execenv"],
)
go_test(

View file

@ -0,0 +1,14 @@
load("@rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "gitignore",
srcs = ["append.go"],
importpath = "github.com/steveyegge/beads/internal/gitignore",
visibility = ["//:__subpackages__"],
)
go_test(
name = "gitignore_test",
srcs = ["append_test.go"],
embed = [":gitignore"],
)

View file

@ -5,6 +5,7 @@ go_library(
srcs = ["gittraceenv.go"],
importpath = "github.com/steveyegge/beads/internal/gittraceenv",
visibility = ["//:__subpackages__"],
deps = ["//internal/execenv"],
)
go_test(

View file

@ -81,6 +81,7 @@ go_test(
"events_test.go",
"events_watch_test.go",
"get_issue_test.go",
"list_comments_omitted_test.go",
"list_sort_test.go",
"memories_test.go",
"metadata_cas_test.go",
@ -102,6 +103,11 @@ go_test(
"update_test.go",
"wire_bijection_test.go",
],
data = [
"claim.go",
"//cmd/bd:list.go",
"//cmd/bd:ready.go",
],
embed = [":httpapi"],
deps = [
"//internal/config",

View file

@ -14,6 +14,7 @@ go_library(
visibility = ["//:__subpackages__"],
deps = [
"//internal/config",
"//internal/execenv",
"@com_github_dolthub_eventkit//:eventkit",
"@com_github_dolthub_eventkit//transport/ga4",
"@in_gopkg_yaml_v3//:yaml_v3",

View file

@ -100,12 +100,69 @@ go_test(
"metadata_test.go",
"role_accessor_decorator_test.go",
],
data = [
":tree_go_srcs",
"//backend/conformance:go_srcs",
],
embed = [":storage"],
deps = [
"//internal/hooks",
"//internal/testutil/bazeltest",
"//internal/types",
"//issueops",
"//journalops",
"//memoryops",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
filegroup(
name = "tree_go_srcs",
srcs = [
":go_srcs",
"//internal/storage/backendnames:go_srcs",
"//internal/storage/backends:go_srcs",
"//internal/storage/contextinfo:go_srcs",
"//internal/storage/dberrors:go_srcs",
"//internal/storage/dbproxy/identity:go_srcs",
"//internal/storage/dbproxy/pidfile:go_srcs",
"//internal/storage/dbproxy/proxy:go_srcs",
"//internal/storage/dbproxy/server:go_srcs",
"//internal/storage/dbproxy/util:go_srcs",
"//internal/storage/depid:go_srcs",
"//internal/storage/dolt:go_srcs",
"//internal/storage/doltutil:go_srcs",
"//internal/storage/domain:go_srcs",
"//internal/storage/domain/db:go_srcs",
"//internal/storage/domain/fs:go_srcs",
"//internal/storage/domain/git:go_srcs",
"//internal/storage/embeddeddolt:go_srcs",
"//internal/storage/embeddeddolt/cmd:go_srcs",
"//internal/storage/externaldeps:go_srcs",
"//internal/storage/fs:go_srcs",
"//internal/storage/git:go_srcs",
"//internal/storage/issueops:go_srcs",
"//internal/storage/journalscan:go_srcs",
"//internal/storage/kvkeys:go_srcs",
"//internal/storage/memoryops:go_srcs",
"//internal/storage/rowid:go_srcs",
"//internal/storage/schema:go_srcs",
"//internal/storage/sqlbuild:go_srcs",
"//internal/storage/storagecontract:go_srcs",
"//internal/storage/uow:go_srcs",
"//internal/storage/versioncontrolops:go_srcs",
],
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -6,3 +6,16 @@ go_library(
importpath = "github.com/steveyegge/beads/internal/storage/backendnames",
visibility = ["//:__subpackages__"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -24,3 +24,16 @@ go_test(
"//internal/storage",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -16,3 +16,16 @@ go_test(
srcs = ["provider_test.go"],
embed = [":contextinfo"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -20,3 +20,16 @@ go_test(
embed = [":dberrors"],
deps = ["@com_github_go_sql_driver_mysql//:mysql"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -20,3 +20,16 @@ go_test(
"@com_github_stretchr_testify//require",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -13,3 +13,16 @@ go_test(
srcs = ["pidfile_test.go"],
embed = [":pidfile"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -83,3 +83,16 @@ go_test(
"@com_github_stretchr_testify//require",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -47,3 +47,16 @@ go_test(
"@com_github_stretchr_testify//require",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -19,3 +19,16 @@ go_test(
srcs = ["dsn_test.go"],
embed = [":util"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -13,3 +13,16 @@ go_test(
srcs = ["depid_test.go"],
embed = [":depid"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -77,6 +77,7 @@ go_library(
"//internal/creds",
"//internal/debug",
"//internal/doltserver",
"//internal/execenv",
"//internal/githooksenv",
"//internal/gittraceenv",
"//internal/idgen",
@ -142,6 +143,7 @@ go_test(
"cli_transfer_timeout_test.go",
"close_issue_checked_test.go",
"close_policy_gate_test.go",
"close_recheck_blocked_test.go",
"commenter_contract_test.go",
"commenter_persistence_test.go",
"comments_page_test.go",
@ -311,6 +313,7 @@ go_test(
"update_same_status_test.go",
"version_commit_deferred_test.go",
"version_reconciler_contract_test.go",
"version_scope_completeness_test.go",
"versioned_test.go",
"wisp_custom_type_tx_test.go",
"wisp_gc_test.go",
@ -352,3 +355,16 @@ go_test(
"@com_github_google_uuid//:uuid",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -29,3 +29,16 @@ go_test(
],
embed = [":doltutil"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -49,3 +49,16 @@ go_test(
"@com_github_go_sql_driver_mysql//:mysql",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -99,6 +99,7 @@ go_test(
"suite_test.go",
"update_same_status_test.go",
],
data = [":go_srcs"],
embed = [":db"],
deps = [
"//internal/storage",
@ -119,3 +120,16 @@ go_test(
"@com_github_stretchr_testify//suite",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -13,6 +13,7 @@ go_library(
"//internal/config",
"//internal/configfile",
"//internal/doltserver",
"//internal/gitignore",
"//internal/storage/domain",
"//internal/utils",
],
@ -38,3 +39,16 @@ go_test(
"@com_github_stretchr_testify//suite",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -23,3 +23,16 @@ go_test(
"@com_github_stretchr_testify//suite",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -95,6 +95,7 @@ go_test(
"batch_apply_contract_test.go",
"batch_closer_contract_test.go",
"batch_creator_contract_test.go",
"blocked_recheck_internal_test.go",
"blocked_recompute_test.go",
"blocking_annotator_contract_test.go",
"bootstrapper_contract_test.go",
@ -231,3 +232,16 @@ go_test(
"@org_golang_x_sync//errgroup",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -13,3 +13,16 @@ go_binary(
embed = [":cmd_lib"],
visibility = ["//:__subpackages__"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -41,3 +41,16 @@ go_test(
"//issueops",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -10,3 +10,16 @@ go_library(
"//internal/storage/domain/fs",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -10,3 +10,16 @@ go_library(
"//internal/storage/domain/git",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -10,6 +10,7 @@ go_library(
"blocked.go",
"blocked_consistency.go",
"blocked_merge.go",
"blocked_recheck.go",
"blocked_state.go",
"blocking_annotation.go",
"bootstrap.go",
@ -122,6 +123,7 @@ go_test(
"batch_apply_test.go",
"batching_test.go",
"blocked_consistency_test.go",
"blocked_recheck_test.go",
"blocked_state_result_test.go",
"blocked_state_template_test.go",
"close_test.go",
@ -177,7 +179,12 @@ go_test(
"version_history_test.go",
"wisp_routing_test.go",
],
data = glob(["testdata/**"]),
data = glob(["testdata/**"]) + [
":go_srcs",
"//internal/storage/domain/db:go_srcs",
"//internal/storage/schema:migrations",
"//internal/storage/versioncontrolops:go_srcs",
],
embed = [":issueops"],
deps = [
"//internal/config",
@ -194,3 +201,16 @@ go_test(
"@com_github_go_sql_driver_mysql//:mysql",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -12,3 +12,16 @@ go_test(
srcs = ["journalscan_test.go"],
embed = [":journalscan"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -12,3 +12,16 @@ go_test(
srcs = ["kvkeys_test.go"],
embed = [":kvkeys"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -12,6 +12,8 @@ import (
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
)
// conformancePackage is the import path whose Run entrypoints each leg wires.
@ -264,6 +266,9 @@ func inspectLegWiring(t *testing.T, dir string, entrypoints []string, waived map
// repositoryRoot locates the module root from this file's own path.
func repositoryRoot(t *testing.T) string {
t.Helper()
if root := bazeltest.OverrideRoot(); root != "" {
return root
}
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("runtime.Caller failed")

View file

@ -16,3 +16,16 @@ go_test(
srcs = ["memories_test.go"],
embed = [":memoryops"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -13,3 +13,16 @@ go_test(
srcs = ["rowid_test.go"],
embed = [":rowid"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -116,6 +116,7 @@ go_library(
"migrations/ignored/0025_add_events_journal_actor.up.sql",
"migrations/ignored/0026_dep_rekey_dedup_marker.up.sql",
"migrations/ignored/0027_add_wisps_current_revision.up.sql",
"migrations/0069_widen_issue_versions_datetime_precision.up.sql",
],
importpath = "github.com/steveyegge/beads/internal/storage/schema",
visibility = ["//:__subpackages__"],
@ -147,6 +148,7 @@ go_test(
"lock_test.go",
"migration_0067_versioned_beads_test.go",
"migration_0068_add_attribution_status_test.go",
"migration_0069_datetime_precision_test.go",
"migration_body_drain_test.go",
"progress_test.go",
"remote_migrate_gate_test.go",
@ -155,6 +157,7 @@ go_test(
"shared_store_migrate_gate_test.go",
"smart_remote_migrate_gate_test.go",
],
data = [":migrations"],
embed = [":schema"],
deps = [
"//internal/debug",
@ -165,3 +168,24 @@ go_test(
"@com_github_go_sql_driver_mysql//:mysql",
],
)
# Migration SQL (up, down, ignored/) and the nondeterminism allowlist, read
# from disk by schema and issueops tests beyond what the library embeds.
filegroup(
name = "migrations",
srcs = glob(["migrations/**"]),
visibility = ["//internal/storage:__subpackages__"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -30,6 +30,23 @@ go_test(
"reclaim_test.go",
"sqlbuild_test.go",
],
data = [
":go_srcs",
"//internal/storage/domain:go_srcs",
],
embed = [":sqlbuild"],
deps = ["//internal/types"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -7,3 +7,16 @@ go_library(
visibility = ["//:__subpackages__"],
deps = ["//internal/storage"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -65,6 +65,7 @@ go_library(
"//internal/storage/issueops",
"//internal/storage/memoryops",
"//internal/storage/schema",
"//internal/storage/sqlbuild",
"//internal/types",
"//internal/workapi",
"//issueops",
@ -115,6 +116,7 @@ go_test(
"lifecycle_create_contract_test.go",
"lifecycle_role_hooks_test.go",
"lifecycle_update_contract_test.go",
"list_comments_plane_test.go",
"lostupdate_dolt_test.go",
"memories_contract_test.go",
"metadata_cas_contract_test.go",
@ -147,6 +149,7 @@ go_test(
"version_reconciler_contract_test.go",
"workspace_config_contract_test.go",
],
data = [":go_srcs"],
embed = [":uow"],
deps = [
"//backend/conformance",
@ -175,3 +178,16 @@ go_test(
"@com_github_stretchr_testify//require",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -51,3 +51,16 @@ go_test(
"@com_github_data_dog_go_sqlmock//:go-sqlmock",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -112,3 +112,9 @@ go_test(
data = glob(["testdata/**"]),
embed = [":testutil"],
)
# Dolt image pin read as text by //test/docsync.
exports_files(
["testdoltcommon.go"],
visibility = ["//test/docsync:__pkg__"],
)

View file

@ -0,0 +1,15 @@
load("@rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "bazeltest",
srcs = ["bazeltest.go"],
importpath = "github.com/steveyegge/beads/internal/testutil/bazeltest",
visibility = ["//:__subpackages__"],
)
go_test(
name = "bazeltest_test",
srcs = ["bazeltest_test.go"],
data = glob(["testdata/**"]),
embed = [":bazeltest"],
)

View file

@ -0,0 +1,174 @@
// Package bazeltest resolves repository paths for tests so the same test code
// works under plain `go test` (working directory inside the package, full
// checkout on disk), under `bazel test` locally, and under remote execution,
// where the only filesystem a test sees is its declared runfiles.
//
// Under plain `go test` every helper reduces to the pre-Bazel behavior, so
// adopting it never changes what `go test` does.
//
// Repository-root resolution order:
//
// 1. BEADS_TEST_REPO_ROOT, an explicit override (debug escape hatch); it is
// honored only when it names a directory holding go.mod
// 2. under Bazel, the runfiles workspace root ($TEST_SRCDIR/$TEST_WORKSPACE);
// it holds exactly the files the test declares in its BUILD `data`
// 3. a walk up from the working directory to go.mod (plain `go test`)
package bazeltest
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// RepoRootEnv names the environment variable that overrides repository-root
// resolution for every helper in this package.
const RepoRootEnv = "BEADS_TEST_REPO_ROOT"
// IsBazel reports whether the test binary runs under `bazel test`.
func IsBazel() bool {
return os.Getenv("TEST_SRCDIR") != ""
}
// runfilesDir returns the absolute runfiles directory, or "" outside Bazel.
func runfilesDir() string {
dir := os.Getenv("RUNFILES_DIR")
if dir == "" {
dir = os.Getenv("TEST_SRCDIR")
}
if dir == "" {
return ""
}
if abs, err := filepath.Abs(dir); err == nil {
return abs
}
return dir
}
// workspaceRoot returns the runfiles directory of the main repository, or ""
// outside Bazel.
func workspaceRoot() string {
rf := runfilesDir()
if rf == "" {
return ""
}
ws := os.Getenv("TEST_WORKSPACE")
if ws == "" {
ws = "_main"
}
root := filepath.Join(rf, ws)
if fi, err := os.Stat(root); err != nil || !fi.IsDir() {
return ""
}
return root
}
// envRoot returns BEADS_TEST_REPO_ROOT and whether it is usable: set and
// holding a go.mod, so a stale or mistyped value never redirects a scan.
func envRoot() (string, bool) {
root := os.Getenv(RepoRootEnv)
if root == "" {
return "", false
}
_, err := os.Stat(filepath.Join(root, "go.mod"))
return root, err == nil
}
// OverrideRoot returns the repository root when BEADS_TEST_REPO_ROOT names a
// directory holding go.mod or the test runs under Bazel, and "" otherwise. It is the drop-in condition
// for existing path helpers:
//
// if root := bazeltest.OverrideRoot(); root != "" {
// return filepath.Join(root, "docs")
// }
// // pre-Bazel resolution, unchanged under plain go test
//
// Under Bazel the returned tree holds only the test's declared data.
func OverrideRoot() string {
if root, ok := envRoot(); ok {
return root
}
return workspaceRoot()
}
// RepoRoot resolves the repository root; see the package comment for the
// resolution order. It fails the test when no root can be found.
func RepoRoot(t testing.TB) string {
t.Helper()
if root, ok := envRoot(); ok {
return root
} else if root != "" {
t.Fatalf("%s=%s has no go.mod", RepoRootEnv, root)
}
if root := workspaceRoot(); root != "" {
return root
}
wd, err := os.Getwd()
if err != nil {
t.Fatalf("getwd: %v", err)
}
for dir := wd; ; dir = filepath.Dir(dir) {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir
}
if filepath.Dir(dir) == dir {
t.Fatalf("could not locate go.mod above %s", wd)
}
}
}
// CallerDir returns the directory of a source file reported by
// runtime.Caller. Under Bazel the reported path is workspace-relative, so the
// directory is rebuilt from repoPkg (for example "test/docsync") under the
// runfiles workspace root. Outside Bazel it is filepath.Dir(callerFile).
func CallerDir(callerFile, repoPkg string) string {
if root := OverrideRoot(); root != "" {
return filepath.Join(root, filepath.FromSlash(repoPkg))
}
return filepath.Dir(callerFile)
}
// Runfile resolves a runfiles-relative path, the form produced by
// $(rlocationpath <label>) (for example "_main/cmd/bd/bd_/bd"), to an
// absolute path. Outside Bazel, or when the path is absent from the
// runfiles tree, it returns an error.
func Runfile(path string) (string, error) {
rf := runfilesDir()
if rf == "" {
return "", fmt.Errorf("runfile %q: not running under bazel", path)
}
full := filepath.Join(rf, filepath.FromSlash(path))
if _, err := os.Stat(full); err != nil {
return "", fmt.Errorf("runfile %q: %w", path, err)
}
return full, nil
}
// shardEnvVars are the Bazel sharding protocol variables. A helper process
// that re-executes a test binary must not inherit them: the child would apply
// the parent's shard filter to its own test selection and could touch the
// parent's shard status file.
var shardEnvVars = []string{
"TEST_SHARD_INDEX",
"TEST_TOTAL_SHARDS",
"TEST_SHARD_STATUS_FILE",
}
// ShardFreeEnv returns env (in os.Environ form) without the Bazel sharding
// variables. Under plain `go test` those variables are absent, so the result
// equals the input.
func ShardFreeEnv(env []string) []string {
out := make([]string, 0, len(env))
outer:
for _, kv := range env {
for _, name := range shardEnvVars {
if strings.HasPrefix(kv, name+"=") {
continue outer
}
}
out = append(out, kv)
}
return out
}

View file

@ -0,0 +1,119 @@
package bazeltest
import (
"os"
"path/filepath"
"runtime"
"slices"
"testing"
)
const probeRel = "internal/testutil/bazeltest/testdata/probe.txt"
func TestIsBazelMatchesEnvironment(t *testing.T) {
if got, want := IsBazel(), os.Getenv("TEST_SRCDIR") != ""; got != want {
t.Fatalf("IsBazel() = %v, want %v", got, want)
}
}
func TestRepoRootHoldsDeclaredData(t *testing.T) {
root := RepoRoot(t)
if !filepath.IsAbs(root) {
t.Fatalf("RepoRoot() = %q, want an absolute path", root)
}
if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(probeRel))); err != nil {
t.Fatalf("probe not found under RepoRoot %s: %v", root, err)
}
if !IsBazel() {
// Plain go test: the root is the module root.
if _, err := os.Stat(filepath.Join(root, "go.mod")); err != nil {
t.Fatalf("RepoRoot %s has no go.mod under plain go test: %v", root, err)
}
}
}
func TestRepoRootHonorsOverride(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module example.com/m\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv(RepoRootEnv, dir)
if got := RepoRoot(t); got != dir {
t.Fatalf("RepoRoot() = %q, want override %q", got, dir)
}
if got := OverrideRoot(); got != dir {
t.Fatalf("OverrideRoot() = %q, want override %q", got, dir)
}
}
func TestOverrideRootIgnoresRootWithoutGoMod(t *testing.T) {
t.Setenv(RepoRootEnv, "")
want := OverrideRoot()
t.Setenv(RepoRootEnv, t.TempDir())
if got := OverrideRoot(); got != want {
t.Fatalf("OverrideRoot() = %q with a go.mod-less override, want %q (override ignored)", got, want)
}
}
func TestOverrideRootIsEmptyOnlyOutsideBazel(t *testing.T) {
t.Setenv(RepoRootEnv, "")
got := OverrideRoot()
if IsBazel() {
if got != RepoRoot(t) {
t.Fatalf("OverrideRoot() = %q under bazel, want RepoRoot %q", got, RepoRoot(t))
}
return
}
if got != "" {
t.Fatalf("OverrideRoot() = %q under plain go test, want empty", got)
}
}
func TestCallerDirLocatesThisPackage(t *testing.T) {
_, file, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("runtime.Caller failed")
}
dir := CallerDir(file, "internal/testutil/bazeltest")
if _, err := os.Stat(filepath.Join(dir, "testdata", "probe.txt")); err != nil {
t.Fatalf("CallerDir() = %q does not hold testdata/probe.txt: %v", dir, err)
}
}
func TestRunfileResolvesOnlyUnderBazel(t *testing.T) {
ws := os.Getenv("TEST_WORKSPACE")
if ws == "" {
ws = "_main"
}
path, err := Runfile(ws + "/" + probeRel)
if !IsBazel() {
if err == nil {
t.Fatalf("Runfile() = %q outside bazel, want an error", path)
}
return
}
if err != nil {
t.Fatalf("Runfile(): %v", err)
}
if _, err := os.Stat(path); err != nil {
t.Fatalf("Runfile() = %q does not exist: %v", path, err)
}
if _, err := Runfile(ws + "/does/not/exist"); err == nil {
t.Fatal("Runfile() of a missing path succeeded")
}
}
func TestShardFreeEnvStripsShardingVariables(t *testing.T) {
in := []string{
"PATH=/bin",
"TEST_SHARD_INDEX=1",
"TEST_TOTAL_SHARDS=4",
"TEST_SHARD_STATUS_FILE=/tmp/x",
"TEST_SHARD_INDEX_NOT=kept",
"HOME=/home/x",
}
want := []string{"PATH=/bin", "TEST_SHARD_INDEX_NOT=kept", "HOME=/home/x"}
if got := ShardFreeEnv(in); !slices.Equal(got, want) {
t.Fatalf("ShardFreeEnv() = %q, want %q", got, want)
}
}

View file

@ -0,0 +1 @@
bazeltest runfiles probe

View file

@ -22,3 +22,16 @@ go_test(
],
embed = [":types"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -9,6 +9,7 @@ go_library(
"detail.go",
"doc.go",
"list.go",
"list_comments.go",
"metadata.go",
"page.go",
"query.go",
@ -41,6 +42,7 @@ go_test(
"count_test.go",
"delete_test.go",
"detail_test.go",
"list_comments_test.go",
"list_ephemeral_test.go",
"list_golden_test.go",
"list_keyset_test.go",

View file

@ -54,3 +54,16 @@ go_test(
"//:beads",
],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -10,3 +10,16 @@ go_library(
importpath = "github.com/steveyegge/beads/journalops",
visibility = ["//visibility:public"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -11,3 +11,16 @@ go_library(
visibility = ["//visibility:public"],
deps = ["//beadserrors"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---

View file

@ -7,3 +7,16 @@ go_library(
importpath = "github.com/steveyegge/beads/plugins/beads",
visibility = ["//visibility:public"],
)
# Plugin manifests and skill commands checked by //cmd/bd/setup layout tests.
filegroup(
name = "plugin_files",
srcs = glob(
["**"],
exclude = [
"BUILD.bazel",
"*.go",
],
),
visibility = ["//cmd/bd/setup:__pkg__"],
)

View file

@ -22,3 +22,13 @@ go_test(
"@in_gopkg_yaml_v3//:yaml_v3",
],
)
exports_files(
["migration-test/release-catalog.json"],
visibility = ["//scripts/migration-test/catalog:__pkg__"],
)
exports_files(
["README.md"],
visibility = ["//:__pkg__"],
)

View file

@ -496,3 +496,170 @@ func TestBazelNoRemoteEndpointsInTrackedFiles(t *testing.T) {
t.Errorf("%s:%d: remote endpoint or credential %q in a tracked file; it belongs in a gitignored user.bazelrc/.bazelrc.local or a CI-generated rc outside the workspace", h.path, h.line, h.what)
}
}
// --- generated go_srcs filegroups are current -------------------------------
// These checks walk the source checkout, which is not declared as Bazel data,
// so they run under plain `go test` (the gating lane) and skip under Bazel.
var (
treeGoSrcsRe = regexp.MustCompile(`(?s)filegroup\(\s*name\s*=\s*"tree_go_srcs",\s*srcs\s*=\s*\[(.*?)\]`)
goSrcsLabelRe = regexp.MustCompile(`"//([^":]+):go_srcs"`)
)
// treeGoSrcsMembers returns the packages whose go_srcs a tree_go_srcs
// filegroup aggregates, other than the tree root's own ":go_srcs".
func treeGoSrcsMembers(build string) ([]string, bool) {
m := treeGoSrcsRe.FindStringSubmatch(stripStarlarkComments(build))
if m == nil {
return nil, false
}
var members []string
for _, l := range goSrcsLabelRe.FindAllStringSubmatch(m[1], -1) {
members = append(members, l[1])
}
return members, true
}
// bazelPackagesUnder lists the repo-relative directories below treeRel (not
// treeRel itself) holding a BUILD.bazel, skipping the directories
// tools/bazel/go_srcs.py skips.
func bazelPackagesUnder(root, treeRel string) ([]string, error) {
var pkgs []string
err := filepath.WalkDir(filepath.Join(root, filepath.FromSlash(treeRel)), func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
name := d.Name()
if name == "testdata" || name == "node_modules" || (strings.HasPrefix(name, ".") && name != ".") {
return filepath.SkipDir
}
return nil
}
if d.Name() != "BUILD.bazel" {
return nil
}
rel, err := filepath.Rel(root, filepath.Dir(path))
if err != nil {
return err
}
if rel = filepath.ToSlash(rel); rel != treeRel {
pkgs = append(pkgs, rel)
}
return nil
})
return pkgs, err
}
func diffStringSets(want, got []string) (missing, extra []string) {
gotSet := map[string]bool{}
for _, g := range got {
gotSet[g] = true
}
wantSet := map[string]bool{}
for _, w := range want {
wantSet[w] = true
if !gotSet[w] {
missing = append(missing, w)
}
}
for _, g := range got {
if !wantSet[g] {
extra = append(extra, g)
}
}
return missing, extra
}
// goSrcsTrees are the tools/bazel/go_srcs.py TREES roots. A test that walks
// one of these trees under Bazel sees only the packages its tree_go_srcs
// lists, so an unlisted package makes the walk pass vacuously.
var goSrcsTrees = []string{"internal/storage"}
func TestBazelTreeGoSrcsListsEveryPackage(t *testing.T) {
build := "filegroup(\n name = \"tree_go_srcs\",\n srcs = [\n \":go_srcs\",\n \"//a/b:go_srcs\",\n # \"//a/c:go_srcs\",\n ],\n)\n"
if got, ok := treeGoSrcsMembers(build); !ok || len(got) != 1 || got[0] != "a/b" {
t.Errorf("treeGoSrcsMembers(fixture) = %v, %v; want [a/b], true", got, ok)
}
if missing, extra := diffStringSets([]string{"a/b", "a/c"}, []string{"a/b", "a/d"}); len(missing) != 1 || missing[0] != "a/c" || len(extra) != 1 || extra[0] != "a/d" {
t.Errorf("diffStringSets fixture: missing=%v extra=%v", missing, extra)
}
if os.Getenv("TEST_SRCDIR") != "" {
t.Skip("walks the source checkout; runs under go test")
}
root := sourceRepoRoot(t)
script := readPolicyFile(t, root, "tools/bazel/go_srcs.py")
for _, tree := range goSrcsTrees {
if !strings.Contains(script, strconv.Quote(tree)) {
t.Errorf("tools/bazel/go_srcs.py no longer lists tree %q; update goSrcsTrees", tree)
}
members, ok := treeGoSrcsMembers(readPolicyFile(t, root, tree+"/BUILD.bazel"))
if !ok {
t.Errorf("%s/BUILD.bazel has no tree_go_srcs filegroup; run `make bazel-sync`", tree)
continue
}
pkgs, err := bazelPackagesUnder(root, tree)
if err != nil {
t.Fatalf("walk %s: %v", tree, err)
}
if len(pkgs) == 0 {
t.Fatalf("found no BUILD.bazel packages under %s; the walk is broken", tree)
}
missing, extra := diffStringSets(pkgs, members)
for _, m := range missing {
t.Errorf("//%s:tree_go_srcs does not list //%s:go_srcs; run `make bazel-sync` (tools/bazel/go_srcs.py)", tree, m)
}
for _, e := range extra {
t.Errorf("//%s:tree_go_srcs lists //%s:go_srcs, which has no BUILD.bazel; run `make bazel-sync`", tree, e)
}
}
}
// TestBazelGoSrcsBlocksCurrent runs `tools/bazel/go_srcs.py --check`, which
// compares every managed block with what the script would generate.
func TestBazelGoSrcsBlocksCurrent(t *testing.T) {
if os.Getenv("TEST_SRCDIR") != "" {
t.Skip("reads the source checkout; runs under go test")
}
python, err := exec.LookPath("python3")
if err != nil {
t.Skip("python3 not available; TestBazelTreeGoSrcsListsEveryPackage still guards tree membership")
}
cmd := exec.Command(python, filepath.Join("tools", "bazel", "go_srcs.py"), "--check")
cmd.Dir = sourceRepoRoot(t)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("go_srcs.py --check: %v; run `make bazel-sync`\n%s", err, out)
}
}
// --- no Bazel packages under the docs trees ---------------------------------
// //:docsync_files globs docs/** and engdocs/**; a glob stops at a package
// boundary, so a BUILD file under either tree would silently drop that
// subtree from //test/docsync's orphan and link checks.
func TestBazelNoPackagesUnderDocsTrees(t *testing.T) {
if os.Getenv("TEST_SRCDIR") != "" {
t.Skip("walks the source checkout; runs under go test")
}
root := sourceRepoRoot(t)
for _, tree := range []string{"docs", "engdocs"} {
err := filepath.WalkDir(filepath.Join(root, tree), func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() && d.Name() == "node_modules" {
return filepath.SkipDir
}
if !d.IsDir() && (d.Name() == "BUILD.bazel" || d.Name() == "BUILD") {
rel, _ := filepath.Rel(root, path)
t.Errorf("%s: no Bazel package may live under %s/ (it would cut that subtree out of //:docsync_files)", filepath.ToSlash(rel), tree)
}
return nil
})
if err != nil {
t.Fatalf("walk %s: %v", tree, err)
}
}
}

View file

@ -66,6 +66,9 @@ beads_test_env_enter() {
unset BEADS_DOLT_SERVER_DATABASE
unset BEADS_DOLT_SERVER_SOCKET
unset BEADS_DOLT_PASSWORD
# bazeltest debug override: never let an exported value point source-scan
# guards at another checkout.
unset BEADS_TEST_REPO_ROOT
if command -v dolt >/dev/null 2>&1; then
dolt config --global --add user.name "beads-test" >/dev/null 2>&1 || true

View file

@ -7,4 +7,5 @@ go_test(
"gitattributes_policy_test.go",
"required_host_test.go",
],
data = ["//:.gitattributes"],
)

View file

@ -16,5 +16,6 @@ go_binary(
go_test(
name = "catalog_test",
srcs = ["main_test.go"],
data = ["//scripts:migration-test/release-catalog.json"],
embed = [":catalog_lib"],
)

View file

@ -6,6 +6,7 @@ go_library(
importpath = "github.com/steveyegge/beads/scripts/repro-dolt-prod-timeouts",
visibility = ["//visibility:private"],
deps = [
"//internal/execenv",
"//internal/storage/depid",
"//internal/storage/doltutil",
"@com_github_go_sql_driver_mysql//:mysql",
@ -23,6 +24,7 @@ go_test(
srcs = ["main_test.go"],
embed = [":repro-dolt-prod-timeouts_lib"],
deps = [
"//internal/execenv",
"//internal/storage/depid",
"//internal/storage/doltutil",
"//internal/storage/schema",

View file

@ -5,5 +5,12 @@ go_test(
srcs = [
"docsync_test.go",
"doltpin_test.go",
"init_safety_recovery_test.go",
],
data = [
"//:docsync_files",
"//cmd/bd:init_safety_help.go",
"//internal/testutil:testdoltcommon.go",
],
deps = ["//internal/testutil/bazeltest"],
)

View file

@ -19,9 +19,14 @@ import (
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
)
func repoRoot() string {
if root := bazeltest.OverrideRoot(); root != "" {
return root
}
_, filename, _, _ := runtime.Caller(0)
return filepath.Join(filepath.Dir(filename), "..", "..")
}

168
tools/bazel/go_srcs.py Executable file
View file

@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Maintain `go_srcs` filegroups for tests that scan Go source under Bazel.
Some guards parse Go source at test time (journal completeness, role census,
import boundaries, contract-leg registry). Under `bazel test`, and above all
under remote execution, a test sees only its declared runfiles, so the source
it scans must be declared as `data`. Bazel globs stop at package boundaries,
so a scan over a directory tree needs one filegroup per package plus an
aggregate. Gazelle does not generate either; this script does, restricted to
the packages listed below, so only tests that need source pay for it.
For every package in PACKAGES, and every package under a root in TREES, the
BUILD.bazel file gets a managed block holding
filegroup(name = "go_srcs", srcs = glob(["**/*.go"]))
(the package's own Go files plus those in non-package subdirectories). Each
TREES root also gets `tree_go_srcs`, aggregating every `go_srcs` under it.
Blocks in packages that are no longer listed are removed.
Run from the repository root after gazelle (see `make bazel-sync`). Output is
deterministic and gazelle-stable, so a clean sync leaves git clean.
With --check nothing is written: stale blocks are printed as a diff and the
exit status is 1 (see `make bazel-sync-check`).
"""
from __future__ import annotations
import difflib
import os
import re
import sys
# Packages whose own Go source a test scans.
PACKAGES = (
"backend", # //backend:backend_test (public alias census)
"backend/conformance", # //backend/conformance, //internal/storage
"beadserrors", # role facade alias targets
"internal/types", # role facade alias targets
"issueops", # //backend/conformance (role facade census)
"journalops", # //backend/conformance (role facade census)
"memoryops", # //backend/conformance (role facade census)
)
# Roots whose whole Go tree a test scans.
TREES = (
"internal/storage", # //internal/storage walks every *_test.go below it
)
BEGIN = "# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---"
END = "# --- end go_srcs ---"
BLOCK_RE = re.compile(r"\n*" + re.escape(BEGIN) + r".*?" + re.escape(END) + r"\n*", re.DOTALL)
SKIP_DIRS = {"testdata", "node_modules"}
def packages_under(root: str) -> list[str]:
found = []
for dirpath, dirnames, files in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.startswith("."))
if "BUILD.bazel" in files:
found.append(os.path.relpath(dirpath).replace(os.sep, "/"))
return sorted(found)
def block(pkg: str, tree_members: list[str] | None) -> str:
lines = [
BEGIN,
"",
"filegroup(",
' name = "go_srcs",',
' srcs = glob(',
' ["**/*.go"],',
" allow_empty = True,",
" ),",
' visibility = ["//:__subpackages__"],',
")",
]
if tree_members is not None:
lines += [
"",
"filegroup(",
' name = "tree_go_srcs",',
" srcs = [",
' ":go_srcs",',
]
lines += [f' "//{m}:go_srcs",' for m in tree_members if m != pkg]
lines += [
" ],",
' visibility = ["//:__subpackages__"],',
")",
]
lines += ["", END]
return "\n".join(lines) + "\n"
def rewrite(path: str, new_block: str | None, check: bool) -> bool:
"""Bring path's managed block up to date; return True if it was stale.
In check mode the file is left alone and the needed change is printed.
"""
with open(path) as f:
src = f.read()
stripped = BLOCK_RE.sub("\n", src).rstrip("\n") + "\n"
out = stripped if new_block is None else stripped + "\n" + new_block
if out == src:
return False
if check:
sys.stdout.writelines(
difflib.unified_diff(
src.splitlines(keepends=True),
out.splitlines(keepends=True),
fromfile=f"a/{path}",
tofile=f"b/{path}",
)
)
else:
with open(path, "w") as f:
f.write(out)
return True
def main(argv: list[str]) -> int:
check = False
for arg in argv:
if arg == "--check":
check = True
else:
print(f"usage: go_srcs.py [--check] (unknown argument {arg!r})", file=sys.stderr)
return 2
if not (os.path.exists("MODULE.bazel") and os.path.exists("BUILD.bazel")):
print("run from the repository root", file=sys.stderr)
return 1
wanted: dict[str, list[str] | None] = {}
for pkg in PACKAGES:
if not os.path.exists(os.path.join(pkg, "BUILD.bazel")):
print(f"go_srcs.py: {pkg} has no BUILD.bazel", file=sys.stderr)
return 1
wanted[pkg] = None
for root in TREES:
members = packages_under(root)
if root not in members:
print(f"go_srcs.py: tree root {root} has no BUILD.bazel", file=sys.stderr)
return 1
for pkg in members:
wanted.setdefault(pkg, None)
wanted[root] = members
stale = []
for pkg in packages_under("."):
path = os.path.join(pkg, "BUILD.bazel")
if pkg in wanted:
changed = rewrite(path, block(pkg, wanted[pkg]), check)
else:
with open(path) as f:
changed = BEGIN in f.read() and rewrite(path, None, check)
if changed:
stale.append(path)
if check and stale:
print(
f"go_srcs.py: {len(stale)} stale go_srcs block(s): {', '.join(stale)}; run `make bazel-sync`",
file=sys.stderr,
)
return 1
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))