fix(ci): resolve gofmt from go.mod's toolchain, not PATH (be-gx8) (#6294)

* fix(ci): resolve gofmt from go.mod's toolchain, not PATH (be-gx8)

gofmt's output is not stable across Go releases, so whichever binary runs
decides the formatting verdict. Three sites reached for a bare `gofmt` on
PATH -- scripts/ci/fmt-check.sh, the Makefile fmt target, and
.githooks/pre-commit -- and PATH belongs to whatever Go is installed
locally. CI has no such freedom: actions/setup-go installs exactly the
go.mod version via go-version-file.

GOTOOLCHAIN=auto does not correct for this, which is why `go env GOROOT`
or `go fmt` would not have been a fix either. The toolchain switch only
ever moves UP to satisfy the go directive, never down, so a host running
a newer Go keeps formatting with the newer gofmt. Measured against
go.mod's go 1.26.5 on a go1.27.0 host: 1.27 flags three
role_fixture_kit_test.go files that 1.26.5 calls clean, and no branch
touches them.

The failure ran in the dangerous direction. The required lint gate went
red on untouched code, which reads as "main's lint is broken" and poisons
the pre-existing-on-main judgement every PR author uses to decide whether
a red gate is theirs. Its own advice -- "Run 'make fmt' to fix
formatting" -- then rewrote those files into a form CI's pinned gofmt
rejects. The pre-commit hook did that same rewrite and re-staged it
silently on every Go commit, with nobody choosing it.

Route all three through one resolver rather than patch three sites, so
the next gofmt call site cannot drift. scripts/ci/gofmt-bin.sh names
go.mod's toolchain explicitly and reads GOROOT from it, short-circuiting
to a plain `go env GOROOT` when the host go already is the pinned version
(the CI case, so nothing is fetched where nothing needs fetching). A
fallback to the PATH binary stays available but warns loudly on stderr:
silently falling back is indistinguishable from resolving correctly, and
reintroduces exactly this skew. fmt-check.sh now prints the gofmt version
it used, so a skew presents as a skew instead of as a repo defect.

The new tests pin the resolution, not the reporting, because the
resolution is where the bug lived: every output assertion around the bare
gofmt stayed green. Reverting gofmt-bin.sh to `command -v gofmt` fails
all three. The pre-existing fmt-check tests move their shim from PATH to
GOFMT -- a PATH shim is now correctly ignored, so leaving them there
would have made them grade the real toolchain instead of the case they
name.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PoN7f9TMmGTCLRpDPzSH4y

Executed-By: beadsrig/polecats/nux

* fix(ci): resolve gofmt from go.mod's toolchain directive, and declare it to Bazel

Maintainer review fixes for #6294 (adoption iterations 1 and 2, one squashed
commit). Sections 1-6 address all six findings in the attempt-1 synthesis; the
two majors are the substantive ones. Sections 7-8 address the two minors the
attempt-2 synthesis left (it decided approve, 1000/1000, no blocker or major).

1. Contract & Interface Fidelity (major, the scorecard's only Required Change).
   gofmt-bin.sh read the `go` directive (1.26.5) while go.mod also carries
   `toolchain go1.26.7`, and toolchain-first is the repo's own declared
   precedence -- Makefile:85-90 exports GOTOOLCHAIN from the same pair for
   every make target, and scripts/bazel_policy_test.go's goModToolchainVersion
   is the same rule in Go. The consequence was not cosmetic: `go env GOVERSION`
   at the repo root is go1.26.7 (the directive auto-switches), so the fast-path
   test compared go1.26.7 against go1.26.5 and was false by construction on
   every route, sending each required fmt-check run down the elif arm to fetch
   a second, older toolchain. Parse `toolchain go<version>` first, fall back to
   the `go` directive. Measured after the change: pinned=1.26.7, the fast path
   fires (`go env GOVERSION` then `go env GOROOT`, no GOTOOLCHAIN= prefix and
   nothing fetched), and `make fmt-check` now reports
   `Using gofmt go1.26.7 (.../toolchain@v0.0.1-go1.26.7.../bin/gofmt)`.
   .githooks/pre-commit:24's `go`-directive read is deliberately left alone --
   its comment explains it is a golangci-lint pin for a different reason.

   gofmtbin_test.go's helper now implements the same precedence, and
   TestGofmtBinMatchesGoModDirective is renamed TestGofmtBinMatchesGoModToolchain
   so the pinned contract is legible from the test name.

   Deviation from the prescription, recorded deliberately: the review asked for
   a helper "name" change as well. The name goModToolchainVersion already
   described toolchain-first semantics; it was the implementation that did not.
   Correcting the semantics is what removes the collision with
   scripts/bazel_policy_test.go's identically-named, opposite-behaving helper,
   so the name is kept and the doc comment now states the precedence and cites
   both in-repo sources of it.

2. Release Safety (major). fmt-check.sh now execs a sibling script
   unconditionally under `set -euo pipefail`. Live origin/main gives
   //scripts/prlintmake a `data` list containing exactly ci/fmt-check.sh, so on
   merge all three TestFmtCheck* cases would have died at rc 127 in the Bazel
   runfiles sandbox -- the GOFMT short-circuit cannot rescue them because it
   lives inside the missing script. Export ci/gofmt-bin.sh to
   //scripts/prlintmake and put it in the target's `data`, and add
   gofmtbin_test.go to `srcs` (it carries no build tag, so its omission was not
   explained away).

   Only ci/gofmt-bin.sh is exported here, not ci/fmt-check.sh: main already
   exports that one for this same package, and a second exports_files call
   naming the same file in one package is an error. This base predates both of
   main's additions, which is also why editing the three-line go_test rule
   conflicts with main's independent edit of it. Verified by materialising the
   merge: every other file auto-merges and the resolution is the union of the
   two attribute sets (srcs = both test files; data = both scripts plus
   //:go.mod per section 7; keep main's deps on //internal/testutil/bazeltest).
   That deps edge is load-bearing at main even though it was stale at this base:
   main rewrote sourceRepoRoot to bazeltest.CallerDir, so the union must keep it.

3. Test Evidence Quality (minor). environment() starts from os.Environ(), so
   deleting GOFMT from the override map did not unset it. Export it empty
   instead -- gofmt-bin.sh reads `[[ -n "${GOFMT:-}" ]]`, so empty already is
   its "not set" case, and the override test stays distinguishable by setting a
   non-empty value.

4. Architectural Consistency (minor). "Every gofmt invocation in this repo goes
   through here" was false at authoring: cmd/bd/preflight.go's doctor check is
   a fourth front door on bare PATH gofmt. Scope the claim to the repo's
   shell-side call sites (re-censused: fmt-check.sh, the Makefile fmt target,
   and .githooks/pre-commit are the complete set; the two workflow "Check
   gofmt" steps and scripts/ci/pr-lint.sh reach them through make fmt-check),
   and name the in-binary exception with the reason it is one -- bd runs
   against whatever project the user points it at, so it has no scripts/ci/ to
   call. preflight.go is byte-identical at base, at HEAD and at origin/main, so
   nothing in this PR widens it; converting it is a separate change.

5. Test Evidence Quality (minor). describe_gofmt's version-bearing arm had zero
   coverage -- all three existing cases inject a bash script, for which
   `go version` errors and only the bare-path arm can run. Add
   TestFmtCheckReportsGofmtVersion against a real Go-built no-op binary, which
   is the only shim shape `go version` can report on.

6. Error Handling & Resilience (nit). Warn (without refusing) when GOFMT names
   something non-executable, so a typo is reported by the resolver that
   accepted it rather than as a "not found" from whichever call site ran it;
   and guard the fields index in the resolver test.

Mutation proofs, each red isolated to the intended test with the other six
green (7/7 pass unmutated, `go test ./scripts/prlintmake/`):

  - revert the toolchain-first parse -> resolver returns the 1.26.5 gofmt and
    TestGofmtBinMatchesGoModToolchain alone fails.
  - delete describe_gofmt's `if command -v go` block (codex's own mutation,
    previously all-green) -> TestFmtCheckReportsGofmtVersion alone fails, the
    three incumbents stay green. That asymmetry is both the coverage-hole proof
    and the proof the new case is not a duplicate.
  - ambient GOFMT, two values x two arms: with the fix both /nonexistent and a
    correctly-pinned gofmt leave all three resolver tests passing; with the
    delete restored, /nonexistent fails TestGofmtBinMatchesGoModToolchain with a
    message blaming the script, and a correctly-pinned value turns all three
    green vacuously without the resolver ever running.

7. Release Safety (minor, iteration 2). The target now reads go.mod at run
   time -- the resolver opens "$REPO_ROOT/go.mod" and the test helper opens
   filepath.Join(sourceRepoRoot(), "go.mod"), where the base test read it not at
   all -- but go.mod appeared in no `data` list, so the rule declared strictly
   less than it uses. Add //:go.mod to //scripts/prlintmake's `data`. No new
   export is needed: //:BUILD.bazel already exports go.mod publicly, and
   //internal/storage/dolt and //internal/testutil/integration already consume
   it as "//:go.mod" in `data`, so this is the sanctioned shape rather than a
   new one.

8. Contract & Interface Fidelity (minor, iteration 2). `toolchain default` is a
   legal go.mod directive value, and the parse matched on the field name alone,
   so sub(/^go/, "", "default") no-opped and left pinned=default. Because that
   is non-empty, neither the `go`-directive fallback nor the "no toolchain or go
   directive" guard could fire, and the script degraded to the bare PATH gofmt
   it exists to eliminate while a usable `go 1.26.5` sat two lines above. The
   mangled "godefault" in the warning was the tell. Require the literal `go`
   prefix, which is exactly what the repo's two other readers of this pair
   already do (Makefile:85's `s/^toolchain go//p` and bazel_policy_test.go's
   `^toolchain\s+go(\S+)\s*$`), so `default` falls through to the `go`
   directive.

   The same guard is added to gofmtbin_test.go's goModToolchainVersion, and that
   is not redundant: strings.TrimPrefix("default", "go") returns "default"
   unchanged and withPatchComponent leaves a dotless string alone, so the helper
   mirrored the bug exactly and the test could never have caught it. Guarding
   only the script would have left the test agreeing with a buggy resolver.

   Measured on a synthetic tree, five arms (the script resolves REPO_ROOT from
   its own location, so each arm is a copied script beside a written go.mod):

     - `toolchain default` + `go 1.26.5`: before, /usr/local/go/bin/gofmt with
       the "godefault" warning; after, the go1.26.5 toolchain gofmt -- i.e. the
       `go` directive, identical to the arm where no toolchain line exists.
     - `toolchain go1.26.7`: unchanged before and after (no regression).
     - `go 1.26.5` alone: unchanged before and after (no regression).
     - `toolchain default` with no `go` directive: now reaches the previously
       bypassed "no toolchain or go directive" guard and falls back loudly, with
       the correct message rather than the mangled one.
     - `toolchain default` written before `go`: also resolves 1.26.5, so the
       fallthrough is order-independent.

   The Go helper's parse was checked over the same six inputs and now agrees
   with the shell on every one.

   No regression test is added for this case. Doing so would need a new
   synthetic-go.mod fixture -- every existing case runs the real script against
   the real repo go.mod through sourceRepoRoot() -- which is a new test
   instrument rather than the prescribed remedy, on a finding whose gate impact
   is none (go.mod carries `toolchain go1.26.7`, so nothing can fire today).

Iteration 2 validation: go test ./scripts/prlintmake/ -count=1 -v 7/7 PASS
(same roster as iteration 1, no test added or removed), go vet rc 0,
go test ./scripts/ -run 'Bazel|BUILD' 11/11 PASS (the BUILD-policy gate, run
because this touches a BUILD file), python3 tools/bazel/go_srcs.py --check
rc 0 (`srcs` is unchanged; only `data` moved), make fmt-check rc 0 still
reporting go1.26.7, shellcheck clean, git diff --check clean.

Also run: go vet ./scripts/prlintmake, go test ./scripts/... (all packages ok),
make fmt-check (rc 0), python3 tools/bazel/go_srcs.py --check (rc 0),
shellcheck on both changed scripts.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
This commit is contained in:
mtccressall 2026-09-30 19:38:46 -06:00 • committed by GitHub
commit 1f7a5f1eaf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 432 additions and 18 deletions

View file

@ -27,8 +27,12 @@ if [ -n "$staged_go_files" ]; then
exit 1
fi
# Auto-format and re-stage
echo "$staged_go_files" | xargs gofmt -w
# Auto-format and re-stage, through the go.mod-pinned gofmt. A bare PATH
# gofmt belongs to the host toolchain, and on a host newer than the go
# directive it rewrites and re-stages files into a form CI's gofmt rejects
# -- silently, on every Go commit. See scripts/ci/gofmt-bin.sh.
gofmt_bin="$(./scripts/ci/gofmt-bin.sh)"
echo "$staged_go_files" | xargs "$gofmt_bin" -w
echo "$staged_go_files" | xargs git add
# Lint changed code with auto-fix; block on remaining issues.

View file

@ -367,10 +367,13 @@ endif
install: check-up-to-date
# Format all Go files
# Format all Go files.
# Through the go.mod-pinned gofmt, never a bare PATH one: a newer local Go
# formats differently from CI, so a bare gofmt -w here rewrites files into a
# form CI's gofmt then rejects. See scripts/ci/gofmt-bin.sh.
fmt:
@echo "Formatting Go files..."
@gofmt -w .
@gofmt_bin="$$(./scripts/ci/gofmt-bin.sh)" && "$$gofmt_bin" -w .
@echo "Done"
# Check that all Go files are properly formatted (for CI)

View file

@ -86,3 +86,8 @@ exports_files(
["README.md"],
visibility = ["//:__pkg__"],
)
exports_files(
["ci/gofmt-bin.sh"],
visibility = ["//scripts/prlintmake:__pkg__"],
)

View file

@ -8,8 +8,27 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$REPO_ROOT"
# Which gofmt runs decides the verdict, so resolve it from go.mod instead of
# PATH and report it. Naming the binary here is what makes a toolchain skew
# legible as a skew, rather than as unformatted files in code no branch
# touched. See scripts/ci/gofmt-bin.sh.
GOFMT_BIN="$("$SCRIPT_DIR/gofmt-bin.sh")"
describe_gofmt() {
local bin="$1" version=""
if command -v go >/dev/null 2>&1; then
version="$(go version "$bin" 2>/dev/null | awk '{ print $NF }')"
fi
if [[ -n "$version" ]]; then
printf '%s (%s)' "$version" "$bin"
else
printf '%s' "$bin"
fi
}
printf 'Checking Go formatting...\n'
if UNFORMATTED="$(gofmt -l .)"; then
printf 'Using gofmt %s\n' "$(describe_gofmt "$GOFMT_BIN")"
if UNFORMATTED="$("$GOFMT_BIN" -l .)"; then
:
else
status=$?

114
scripts/ci/gofmt-bin.sh Executable file
View file

@ -0,0 +1,114 @@
#!/usr/bin/env bash
# Resolve the gofmt that matches go.mod's pinned Go toolchain, and print its
# absolute path on stdout.
#
# gofmt's output is not stable across Go releases, so whichever binary runs
# decides the verdict. A bare `gofmt` on PATH belongs to whatever Go happens to
# be installed locally, and GOTOOLCHAIN=auto does not correct for that: the
# toolchain switch only ever moves UP to satisfy go.mod's requirements, never
# down. CI has no such freedom -- actions/setup-go installs exactly the go.mod
# version via go-version-file -- so a host running a newer Go formats
# differently from the gate that judges it.
#
# The failure is in the dangerous direction. The gate reds on files no branch
# touched, which reads as "main's lint is broken", and its own advice ("run
# make fmt") rewrites those files into a form CI's pinned gofmt then rejects.
#
# The repo's shell-side gofmt call sites resolve through here:
# scripts/ci/fmt-check.sh, the Makefile fmt target, and .githooks/pre-commit.
# Add new shell call sites to that list rather than reaching for a bare gofmt.
#
# One front door is deliberately not on that list, because it does not run from
# this repo's checkout: cmd/bd/preflight.go's "Formatting" doctor check execs a
# bare PATH `gofmt -l .` (and prescribes `gofmt -w .`) against whatever project
# the user points bd at, so it has no scripts/ci/ to call and is reporting on
# the developer's own environment rather than reproducing CI's verdict. Routing
# it through a resolver is a separate change.
#
# Set GOFMT to override the resolution entirely.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
warn() {
printf 'gofmt-bin: %s\n' "$*" >&2
}
# Falling back is safer than failing, but it must be LOUD: a silent fallback to
# the PATH binary is indistinguishable from a correct resolution, and it
# reintroduces exactly the skew this script exists to remove.
fallback() {
local reason="$1" path
if ! path="$(command -v gofmt 2>/dev/null)"; then
warn "$reason, and there is no gofmt on PATH either"
return 1
fi
warn "$reason"
warn "falling back to $path, which may format differently from CI"
printf '%s\n' "$path"
}
if [[ -n "${GOFMT:-}" ]]; then
# An override is honoured as given -- refusing it would defeat the escape
# hatch -- but say so here, or a typo surfaces as a "gofmt: not found" from
# whichever of the three call sites happened to run it.
if [[ ! -x "$GOFMT" ]]; then
warn "GOFMT is set to $GOFMT, which is not executable; using it anyway"
fi
printf '%s\n' "$GOFMT"
exit 0
fi
# The `toolchain` directive wins over the `go` directive when present: `go` is
# the floor promised to importers, `toolchain` is what this repo is actually
# built and formatted with. That precedence is not a choice made here -- it is
# the repo's, implemented at Makefile:85-90 (which exports GOTOOLCHAIN from the
# same pair for every make target) and in Go at scripts/bazel_policy_test.go's
# goModToolchainVersion. Reading `go` here would resolve a second, older
# toolchain than the one every other route formats with, and would miss the
# GOVERSION fast path below on every host that honours the directive.
#
# Match on the value, not just the field name: `toolchain default` is a legal
# directive meaning "no toolchain upgrade", and accepting it verbatim would set
# pinned=default, which is non-empty, so the `go` fallback below never fires and
# the resolution degrades to the bare PATH gofmt this script exists to replace.
# Requiring the literal `go` prefix is what the repo's other two readers of this
# pair do (Makefile:85's `s/^toolchain go//p`, scripts/bazel_policy_test.go's
# `^toolchain\s+go(\S+)\s*$`), so `default` falls through to the `go` directive.
pinned="$(awk '$1 == "toolchain" && $2 ~ /^go/ { sub(/^go/, "", $2); print $2; exit }' "$REPO_ROOT/go.mod")"
if [[ -z "$pinned" ]]; then
pinned="$(awk '$1 == "go" { print $2; exit }' "$REPO_ROOT/go.mod")"
fi
if [[ -z "$pinned" ]]; then
fallback "no toolchain or go directive in $REPO_ROOT/go.mod"
exit
fi
# A "go 1.26" directive is legal; GOTOOLCHAIN names need the patch component.
if [[ "$pinned" =~ ^[0-9]+\.[0-9]+$ ]]; then
pinned="$pinned.0"
fi
if ! command -v go >/dev/null 2>&1; then
fallback "go is not on PATH, so go.mod's go$pinned toolchain cannot be resolved"
exit
fi
goroot=""
if [[ "$(go env GOVERSION 2>/dev/null)" == "go$pinned" ]]; then
# The CI case: the host go already is the pinned one. Read GOROOT directly
# rather than naming a GOTOOLCHAIN, so nothing is fetched on a machine that
# has nothing to fetch.
goroot="$(go env GOROOT 2>/dev/null || true)"
elif ! goroot="$(GOTOOLCHAIN="go$pinned" go env GOROOT 2>/dev/null)"; then
goroot=""
fi
if [[ -z "$goroot" || ! -x "$goroot/bin/gofmt" ]]; then
fallback "could not resolve a gofmt from go.mod's go$pinned toolchain"
exit
fi
printf '%s\n' "$goroot/bin/gofmt"

View file

@ -2,7 +2,14 @@ load("@rules_go//go:def.bzl", "go_test")
go_test(
name = "prlintmake_test",
srcs = ["prlintmake_test.go"],
data = ["//scripts:ci/fmt-check.sh"],
srcs = [
"gofmtbin_test.go",
"prlintmake_test.go",
],
data = [
"//:go.mod",
"//scripts:ci/fmt-check.sh",
"//scripts:ci/gofmt-bin.sh",
],
deps = ["//internal/testutil/bazeltest"],
)

View file

@ -0,0 +1,184 @@
package prlintmake
import (
"bufio"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// The regression tests for be-gx8.
//
// gofmt's output is not stable across Go releases, and the repo's formatting
// gate is judged by whichever binary runs. CI installs exactly go.mod's version
// (actions/setup-go with go-version-file), so any resolution that can land on a
// different Go silently disagrees with the gate that blocks merges -- and the
// gate's own advice, "run make fmt", then rewrites files into a form CI
// rejects.
//
// These pin the resolution itself rather than fmt-check.sh's reporting, because
// the shipped bug was in the resolution: a bare `gofmt` reached PATH, and every
// output assertion around it stayed green.
func TestGofmtBinMatchesGoModToolchain(t *testing.T) {
goBin := testGo(t)
want := "go" + goModToolchainVersion(t)
resolved, stderr := runGofmtBin(t, nil, nil)
output, err := exec.Command(goBin, "version", resolved).CombinedOutput()
if err != nil {
t.Fatalf("go version %s: %v\n%s\nresolver stderr:\n%s", resolved, err, output, stderr)
}
fields := strings.Fields(string(output))
if len(fields) == 0 {
t.Fatalf("go version %s printed no fields\nresolver stderr:\n%s", resolved, stderr)
}
got := fields[len(fields)-1]
if got != want {
t.Fatalf("gofmt-bin.sh resolved %s (built with %s), want a %s gofmt.\n"+
"CI and every make target format with the toolchain go.mod selects, "+
"so this host's `make fmt` would rewrite files CI then rejects.\n"+
"resolver stderr:\n%s",
resolved, got, want, stderr)
}
}
func TestGofmtBinIgnoresPathGofmt(t *testing.T) {
testGo(t)
bash := testBash(t)
shimDir := filepath.Join(t.TempDir(), "path shims")
if err := os.MkdirAll(shimDir, 0o755); err != nil {
t.Fatal(err)
}
shim := filepath.Join(shimDir, "gofmt")
writeShellExecutable(t, bash, shim, "#!/usr/bin/env bash\nexit 0\n")
path := shimDir + string(os.PathListSeparator) + os.Getenv("PATH")
resolved, stderr := runGofmtBin(t, map[string]string{"PATH": path}, nil)
if resolved == shellVisiblePath(shim) {
t.Fatalf("gofmt-bin.sh returned the PATH shim %s; it must resolve from "+
"go.mod's toolchain instead.\nresolver stderr:\n%s", resolved, stderr)
}
}
func TestGofmtBinHonorsGOFMTOverride(t *testing.T) {
want := shellVisiblePath(filepath.Join(t.TempDir(), "explicit gofmt"))
resolved, stderr := runGofmtBin(t, map[string]string{"GOFMT": want}, nil)
if resolved != want {
t.Fatalf("gofmt-bin.sh = %q, want the GOFMT override %q\nresolver stderr:\n%s",
resolved, want, stderr)
}
}
// runGofmtBin runs scripts/ci/gofmt-bin.sh and returns its stdout (the resolved
// path) and stderr separately. Fallback warnings go to stderr, so keeping them
// apart is what lets a failure report why the resolution went the way it did.
func runGofmtBin(t *testing.T, overrides map[string]string, args []string) (string, string) {
t.Helper()
bash := testBash(t)
env := map[string]string{
"BASH_ENV": "",
"BASHOPTS": "",
"ENV": "",
"GOFMT": "",
"LANG": "C",
"LC_ALL": "C",
"SHELLOPTS": "",
}
for key, value := range overrides {
env[key] = value
}
// GOFMT is exported empty rather than deleted from the map. environment()
// starts from the ambient environment, so deleting the key here would leave
// an ambient GOFMT in place -- and that short-circuits the very resolution
// these tests exist to pin, failing one of them with a message blaming the
// script and passing the other vacuously. gofmt-bin.sh reads GOFMT with
// [[ -n "${GOFMT:-}" ]], so empty already is its "not set" case, and the
// override test stays distinguishable by setting a non-empty value.
script := shellVisiblePath(filepath.Join(sourceRepoRoot(), "scripts", "ci", "gofmt-bin.sh"))
cmd := exec.Command(bash, append([]string{"--noprofile", "--norc", "--", script}, args...)...)
cmd.Dir = sourceRepoRoot()
cmd.Env = environment(env)
var stderr strings.Builder
cmd.Stderr = &stderr
stdout, err := cmd.Output()
if err != nil {
t.Fatalf("gofmt-bin.sh failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr.String())
}
return strings.TrimSpace(normalizeNewlines(string(stdout))), stderr.String()
}
// goModToolchainVersion returns the Go version go.mod selects, in GOTOOLCHAIN
// form: the toolchain directive when present, otherwise the go directive, with
// the patch component a bare "go 1.26" directive omits.
//
// Toolchain-first is the repo's precedence, not this test's: Makefile:85-90
// exports GOTOOLCHAIN from the same pair for every make target, and
// scripts/bazel_policy_test.go's goModToolchainVersion is the same rule in Go.
// `go` is the floor promised to importers; `toolchain` is what this repo is
// built and formatted with, so it is what the formatting gate must agree with.
func goModToolchainVersion(t *testing.T) string {
t.Helper()
file, err := os.Open(filepath.Join(sourceRepoRoot(), "go.mod"))
if err != nil {
t.Fatal(err)
}
defer file.Close()
goDirective := ""
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) != 2 {
continue
}
switch fields[0] {
case "toolchain":
// `toolchain default` is legal and names no version, so it must fall
// through to the `go` directive exactly as gofmt-bin.sh does -- the
// script's awk requires the same literal `go` prefix. Returning the
// bare value here would make this helper agree with a buggy resolver
// instead of detecting it.
if version, ok := strings.CutPrefix(fields[1], "go"); ok {
return withPatchComponent(version)
}
case "go":
if goDirective == "" {
goDirective = fields[1]
}
}
}
if err := scanner.Err(); err != nil {
t.Fatal(err)
}
if goDirective != "" {
return withPatchComponent(goDirective)
}
t.Fatal("no toolchain or go directive in go.mod")
return ""
}
// withPatchComponent returns a GOTOOLCHAIN-shaped version: names there carry
// the patch component that a bare "go 1.26" directive is allowed to omit.
func withPatchComponent(version string) string {
if strings.Count(version, ".") == 1 {
return version + ".0"
}
return version
}
func testGo(t *testing.T) string {
t.Helper()
path, err := exec.LookPath("go")
if err != nil {
t.Skipf("go is not on PATH: %v", err)
}
return path
}

View file

@ -13,22 +13,23 @@ import (
)
func TestFmtCheckClean(t *testing.T) {
output, err := runFmtCheck(t, "exit 0\n")
gofmt, output, err := runFmtCheck(t, "exit 0\n")
if err != nil {
t.Fatalf("fmt-check failed: %v\n%s", err, output)
}
want := "Checking Go formatting...\nAll Go files are properly formatted\n"
want := "Checking Go formatting...\nUsing gofmt " + gofmt + "\nAll Go files are properly formatted\n"
if output != want {
t.Fatalf("output = %q, want %q", output, want)
}
}
func TestFmtCheckReportsUnformattedFiles(t *testing.T) {
output, err := runFmtCheck(t, "printf '%s\\n' cmd/bd/main.go internal/config/config.go\n")
gofmt, output, err := runFmtCheck(t, "printf '%s\\n' cmd/bd/main.go internal/config/config.go\n")
if got := processExitCode(err); got != 1 {
t.Fatalf("exit = %d, want 1; error=%v\n%s", got, err, output)
}
want := "Checking Go formatting...\n" +
"Using gofmt " + gofmt + "\n" +
"The following files are not properly formatted:\n" +
"cmd/bd/main.go\n" +
"internal/config/config.go\n\n" +
@ -38,8 +39,31 @@ func TestFmtCheckReportsUnformattedFiles(t *testing.T) {
}
}
// TestFmtCheckReportsGofmtVersion pins describe_gofmt's version-bearing arm,
// the "<version> (<path>)" form.
//
// The cases above inject a bash script, for which `go version` errors and the
// version is always empty, so only the bare-path else arm is exercised there --
// deleting the whole version block leaves all three of them green. The version
// is the half that makes a toolchain skew legible as a skew, which is the whole
// justification for the reporting change, so it needs a real Go-built binary.
func TestFmtCheckReportsGofmtVersion(t *testing.T) {
goBin := testGo(t)
shim := buildNoopGoBinary(t, goBin, "gofmt")
want := goBuildVersion(t, goBin, shim)
output, err := runFmtCheckWithGofmt(t, shim)
if err != nil {
t.Fatalf("fmt-check failed: %v\n%s", err, output)
}
line := "Using gofmt " + want + " (" + shim + ")\n"
if !strings.Contains(output, line) {
t.Fatalf("missing %q in output:\n%s", line, output)
}
}
func TestFmtCheckPreservesGofmtFailure(t *testing.T) {
output, err := runFmtCheck(t, "printf 'synthetic gofmt failure\\n' >&2\nexit 42\n")
_, output, err := runFmtCheck(t, "printf 'synthetic gofmt failure\\n' >&2\nexit 42\n")
if got := processExitCode(err); got != 42 {
t.Fatalf("exit = %d, want 42; error=%v\n%s", got, err, output)
}
@ -54,7 +78,14 @@ func TestFmtCheckPreservesGofmtFailure(t *testing.T) {
}
}
func runFmtCheck(t *testing.T, gofmtBody string) (string, error) {
// runFmtCheck runs scripts/ci/fmt-check.sh against a gofmt shim with the given
// body, and returns the shim path fmt-check.sh is expected to report.
//
// The shim is injected through GOFMT rather than PATH. fmt-check.sh deliberately
// ignores a PATH gofmt -- that is the whole of be-gx8 -- so a PATH shim would be
// silently bypassed and these tests would grade the real toolchain instead of
// the case they name. TestGofmtBinIgnoresPathGofmt covers the resolution itself.
func runFmtCheck(t *testing.T, gofmtBody string) (string, string, error) {
t.Helper()
bash := testBash(t)
testRoot := t.TempDir()
@ -62,12 +93,19 @@ func runFmtCheck(t *testing.T, gofmtBody string) (string, error) {
if err := os.MkdirAll(shimDir, 0o755); err != nil {
t.Fatal(err)
}
writeShellExecutable(t, bash, filepath.Join(shimDir, "gofmt"), "#!/usr/bin/env bash\nset -euo pipefail\n"+gofmtBody)
shim := filepath.Join(shimDir, "gofmt")
writeShellExecutable(t, bash, shim, "#!/usr/bin/env bash\nset -euo pipefail\n"+gofmtBody)
gofmt := shellVisiblePath(shim)
path := shimDir + string(os.PathListSeparator) + os.Getenv("PATH")
if runtime.GOOS == "windows" {
path = msysPath(shimDir) + ":/usr/bin:/bin"
}
output, err := runFmtCheckWithGofmt(t, gofmt)
return gofmt, output, err
}
// runFmtCheckWithGofmt runs scripts/ci/fmt-check.sh with GOFMT pointing at an
// already-built binary, and returns its combined output.
func runFmtCheckWithGofmt(t *testing.T, gofmt string) (string, error) {
t.Helper()
bash := testBash(t)
cmd := exec.Command(
bash,
"--noprofile",
@ -80,15 +118,55 @@ func runFmtCheck(t *testing.T, gofmtBody string) (string, error) {
"BASH_ENV": "",
"BASHOPTS": "",
"ENV": "",
"GOFMT": gofmt,
"LANG": "C",
"LC_ALL": "C",
"PATH": path,
"SHELLOPTS": "",
})
output, err := cmd.CombinedOutput()
return normalizeNewlines(string(output)), err
}
// buildNoopGoBinary compiles a do-nothing program under the given name and
// returns its shell-visible path. `go version` reports the toolchain that built
// it, which is what the caller needs and what a shell shim can never provide.
func buildNoopGoBinary(t *testing.T, goBin, name string) string {
t.Helper()
dir := t.TempDir()
write := func(base, content string) {
if err := os.WriteFile(filepath.Join(dir, base), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
write("go.mod", "module noopgobinary\n")
write("main.go", "package main\n\nfunc main() {}\n")
if runtime.GOOS == "windows" {
name += ".exe"
}
binary := filepath.Join(dir, name)
cmd := exec.Command(goBin, "build", "-o", binary, ".")
cmd.Dir = dir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("go build a no-op %s: %v\n%s", name, err, output)
}
return shellVisiblePath(binary)
}
// goBuildVersion returns the "goX.Y.Z" that `go version <binary>` reports.
func goBuildVersion(t *testing.T, goBin, binary string) string {
t.Helper()
output, err := exec.Command(goBin, "version", binary).CombinedOutput()
if err != nil {
t.Fatalf("go version %s: %v\n%s", binary, err, output)
}
fields := strings.Fields(string(output))
if len(fields) == 0 {
t.Fatalf("go version %s printed no fields", binary)
}
return fields[len(fields)-1]
}
func writeShellExecutable(t *testing.T, bash, path, body string) {
t.Helper()
if err := os.WriteFile(path, []byte(strings.ReplaceAll(body, "\r\n", "\n")), 0o755); err != nil {