From 2e7db0af2a409e15df8f4bf4f14c16f038de07b3 Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 16:28:51 +0400 Subject: [PATCH 1/8] fix(lint): lint and test each Go module from its own directory --- docs/commands.md | 13 +- docs/domains.md | 7 + internal/gomod/gomod.go | 56 ++++++ internal/lint/gomod.go | 73 +++++++ internal/lint/gomod_test.go | 355 +++++++++++++++++++++++++++++++++ internal/lint/lint.go | 65 +++--- internal/testrun/gomod_test.go | 62 ++++++ internal/testrun/testrun.go | 72 +++++++ 8 files changed, 674 insertions(+), 29 deletions(-) create mode 100644 internal/gomod/gomod.go create mode 100644 internal/lint/gomod.go create mode 100644 internal/lint/gomod_test.go create mode 100644 internal/testrun/gomod_test.go diff --git a/docs/commands.md b/docs/commands.md index 14af074e..679c76fe 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -254,8 +254,12 @@ merely parsed. A linter that could not run is BLOCKING: a green gate has to mean the code was checked, not that the machine was empty. Go repositories without a golangci config get Procoder's curated baseline (standard set plus gosec, gocritic, errorlint, unparam, copyloopvar, nilerr) — the repo's own golangci config always wins, -whichever of `.golangci.yml`/`.yaml`/`.toml`/`.json` it uses. Report -by default; `[lint] policy = "block"` makes findings block. +whichever of `.golangci.yml`/`.yaml`/`.toml`/`.json` it uses. golangci-lint runs +once per Go module, from the module's directory: a changed file in a nested +module (its own `go.mod`, such as a `bench/` with `replace => ../`) is linted +as that module, and a repository config at the root is passed to a nested +module that has none. A `go.work` at the root keeps the single run from the +root. Report by default; `[lint] policy = "block"` makes findings block. `--types` adds the type-checker where the canonical linter does not compile the code: `tsc --noEmit` for TypeScript (grouped under each @@ -647,7 +651,10 @@ so a failure is attributed to the test the framework failed rather than to a line that merely looks like one; a package that failed outside any test (a build error, a crash) is named by package, and each Go failure carries a bounded excerpt of its own output — the assertion, panic or -build error — under the FAIL line, in the gate's finding as well. `--coverage` adds the +build error — under the FAIL line, in the gate's finding as well. When the +narrowed packages sit in a nested Go module (its own `go.mod`), `go test` runs +once per module from that module's directory, and the detail is prefixed with +the module. `--coverage` adds the percentage where the runner measures it natively (Go; pytest with pytest-cov); a number is reported, never enforced. With `--name ` narrows the run to matching tests — `-run` for Go, diff --git a/docs/domains.md b/docs/domains.md index 73b97abb..6dccd8b0 100644 --- a/docs/domains.md +++ b/docs/domains.md @@ -54,6 +54,13 @@ complexity check alike. Its lock is machine-wide, so a run from another worktree or agent makes this one wait instead of failing. The lint deadline still bounds the wait. +Go files are grouped by their nearest `go.mod` and golangci-lint runs once +per module, from the module's directory, with package patterns relative to +it; findings are mapped back to repo-root paths. golangci-lint resolves +packages against the module it runs in, so a file in a nested module named +from the root used to fail as NOT checked ("main module ... does not contain +package"). A `go.work` at the root keeps one run from the root. + The commit gate runs SAST and blocks on findings in the files the commit carries. semgrep is pointed at the tree and narrowed with one `--include` per changed file, never handed the files as targets — naming files diff --git a/internal/gomod/gomod.go b/internal/gomod/gomod.go new file mode 100644 index 00000000..19d8a69c --- /dev/null +++ b/internal/gomod/gomod.go @@ -0,0 +1,56 @@ +// Package gomod answers which Go module owns a file. golangci-lint and +// `go test` both resolve packages against the module of their working +// directory, so a file in a nested module (its own go.mod, e.g. a bench/ +// with `replace => ../`) cannot be named from the repository root: the run +// fails with "main module ... does not contain package". Callers group +// files by module and run once per group from the module's directory. +package gomod + +import ( + "os" + "path/filepath" +) + +func exists(p string) bool { + _, err := os.Stat(p) + return err == nil +} + +// Workspace reports whether root carries a go.work. A workspace resolves +// every member module from the root, so such a repository needs no split. +func Workspace(root string) bool { + return exists(filepath.Join(root, "go.work")) +} + +// ModuleDir is the directory of the go.mod nearest to file, ascending from +// the file's directory and stopping at root. A file under no go.mod belongs +// to root: the repository is then taken to be one module, as it was before +// nested modules were understood. +func ModuleDir(root, file string) string { + dir := filepath.Dir(file) + for { + if exists(filepath.Join(dir, "go.mod")) { + return dir + } + parent := filepath.Dir(dir) + if dir == root || parent == dir { + return root + } + dir = parent + } +} + +// Group splits absolute paths by owning module directory. Under a go.work +// at root everything stays one group at root. +func Group(root string, paths []string) map[string][]string { + out := map[string][]string{} + work := Workspace(root) + for _, p := range paths { + dir := root + if !work { + dir = ModuleDir(root, p) + } + out[dir] = append(out[dir], p) + } + return out +} diff --git a/internal/lint/gomod.go b/internal/lint/gomod.go new file mode 100644 index 00000000..893ce477 --- /dev/null +++ b/internal/lint/gomod.go @@ -0,0 +1,73 @@ +package lint + +import ( + "os" + "path/filepath" + "sort" + "strings" +) + +// golangciConfigNames are the config files golangci-lint itself accepts. +var golangciConfigNames = []string{".golangci.yml", ".golangci.yaml", ".golangci.toml", ".golangci.json"} + +// sortedKeys gives the module directories in a stable order, so the order +// of findings does not depend on map iteration. +func sortedKeys(m map[string][]string) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// goPatterns are the package patterns for files, relative to modDir: +// "./" for the module root, "./x" for a subpackage. Sorted and unique. +func goPatterns(modDir string, files []string) []string { + seen := map[string]bool{} + var out []string + for _, f := range files { + rel, err := filepath.Rel(modDir, filepath.Dir(f)) + if err != nil { + continue + } + pat := "./" + if rel != "." { + pat = "./" + filepath.ToSlash(rel) + } + if !seen[pat] { + seen[pat] = true + out = append(out, pat) + } + } + sort.Strings(out) + return out +} + +// repoRelPath maps a path golangci-lint printed — relative to the +// directory it ran in, or absolute — to a slash path relative to root, +// which is what the wanted filter and gitx.Finding carry. A path outside +// root is returned as printed. +func repoRelPath(root, modDir, p string) string { + abs := p + if !filepath.IsAbs(abs) { + abs = filepath.Join(modDir, p) + } + rel, err := filepath.Rel(root, abs) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return filepath.ToSlash(p) + } + return filepath.ToSlash(rel) +} + +// golangciConfigIn is the golangci config file sitting directly in dir, or +// "" when there is none. +func golangciConfigIn(dir string) string { + for _, name := range golangciConfigNames { + p := filepath.Join(dir, name) + if _, err := os.Stat(p); err == nil { + return p + } + } + return "" +} diff --git a/internal/lint/gomod_test.go b/internal/lint/gomod_test.go new file mode 100644 index 00000000..4c6a6097 --- /dev/null +++ b/internal/lint/gomod_test.go @@ -0,0 +1,355 @@ +package lint + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "procoder/internal/gomod" + "procoder/internal/tools" +) + +// goCall is one golangci-lint invocation the stub recorded. +type goCall struct { + dir string + args []string +} + +// stubGolangci puts a fake golangci-lint on PATH that records its working +// directory and arguments and answers every package pattern with one finding +// in that package's x.go, with the path relative to the directory it ran in +// — which is what the real binary prints. It returns a reader for the calls. +func stubGolangci(t *testing.T) func() []goCall { + t.Helper() + dir := t.TempDir() + log := filepath.Join(dir, "calls.txt") + script := `#!/bin/sh +printf 'CALL\n' >> ` + log + ` +printf 'pwd=%s\n' "$(pwd -P)" >> ` + log + ` +for a in "$@"; do printf 'arg=%s\n' "$a" >> ` + log + `; done +rc=0 +for a in "$@"; do + case "$a" in + ./*) p=${a#./}; p=${p%/} + if [ -z "$p" ]; then f=x.go; else f=$p/x.go; fi + printf '%s:3:1: boom (stub)\n' "$f"; rc=1 ;; + esac +done +exit $rc +` + if err := os.WriteFile(filepath.Join(dir, "golangci-lint"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + t.Setenv("HOME", dir) + return func() []goCall { + raw, err := os.ReadFile(log) + if err != nil { + return nil + } + var calls []goCall + for _, chunk := range strings.Split(string(raw), "CALL\n")[1:] { + var c goCall + for _, line := range strings.Split(strings.TrimSpace(chunk), "\n") { + switch { + case strings.HasPrefix(line, "pwd="): + c.dir = strings.TrimPrefix(line, "pwd=") + case strings.HasPrefix(line, "arg="): + c.args = append(c.args, strings.TrimPrefix(line, "arg=")) + } + } + calls = append(calls, c) + } + return calls + } +} + +// moduleRepo lays out a root module and a nested one (momo's bench/ shape): +// its own go.mod, `replace => ../`, files that the root module does not own. +func moduleRepo(t *testing.T, workFile bool) string { + t.Helper() + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + put := func(rel, body string) { + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + put("go.mod", "module example.com/root\n\ngo 1.22\n") + put("pkg/x.go", "package pkg\n") + put("sub/go.mod", "module example.com/root/sub\n\ngo 1.22\n\nrequire example.com/root v0.0.0\n\nreplace example.com/root => ../\n") + put("sub/x/x.go", "package x\n") + if workFile { + put("go.work", "go 1.22\n\nuse (\n\t.\n\t./sub\n)\n") + } + return root +} + +func hasArg(c goCall, want string) bool { + for _, a := range c.args { + if a == want { + return true + } + } + return false +} + +func argAfter(c goCall, flag string) string { + for i, a := range c.args { + if a == flag && i+1 < len(c.args) { + return c.args[i+1] + } + } + return "" +} + +// A file in a nested module must be linted FROM that module, with patterns +// relative to it, and its findings must come back repo-root-relative. +// Run from the repo root golangci-lint fails with "main module (...) does +// not contain package ...", and the gate reports the file NOT checked — so +// every commit touching a nested module was blocked while correct. +// +// proved by: leave cmd.Dir at the repo root in lintGo — the call's dir is +// the root and the pattern is ./sub/x, so this fails on both. +func TestLintGoRunsANestedModuleFromItsOwnDirectory(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, false) + file := filepath.Join(root, "sub", "x", "x.go") + + got := lintGo(root, []string{file}, false) + + cs := calls() + if len(cs) != 1 { + t.Fatalf("want exactly one golangci-lint run, got %d: %+v", len(cs), cs) + } + if want := filepath.Join(root, "sub"); cs[0].dir != want { + t.Errorf("ran in %s, want the nested module directory %s", cs[0].dir, want) + } + if !hasArg(cs[0], "./x") || hasArg(cs[0], "./sub/x") { + t.Errorf("patterns must be relative to the module dir (./x, not ./sub/x): %v", cs[0].args) + } + if len(got) != 1 || got[0].File != "sub/x/x.go" || got[0].Line != 3 { + t.Errorf("the finding must map back to the repo-root path sub/x/x.go, got %+v", got) + } +} + +// Files from two modules in one commit get one run each, none from the +// wrong directory, and each module's findings keep their own prefix. +// +// proved by: collapse the groups into one run — one call, not two. +func TestLintGoRunsOncePerModule(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, false) + files := []string{filepath.Join(root, "pkg", "x.go"), filepath.Join(root, "sub", "x", "x.go")} + + got := lintGo(root, files, false) + + cs := calls() + if len(cs) != 2 { + t.Fatalf("want one run per module (2), got %d: %+v", len(cs), cs) + } + dirs := map[string]goCall{} + for _, c := range cs { + dirs[c.dir] = c + } + if c, ok := dirs[root]; !ok || !hasArg(c, "./pkg") { + t.Errorf("root module run missing or wrong: %+v", dirs) + } + if c, ok := dirs[filepath.Join(root, "sub")]; !ok || !hasArg(c, "./x") { + t.Errorf("nested module run missing or wrong: %+v", dirs) + } + seen := map[string]bool{} + for _, f := range got { + seen[f.File] = true + } + if !seen["pkg/x.go"] || !seen["sub/x/x.go"] { + t.Errorf("want findings in pkg/x.go and sub/x/x.go, got %+v", got) + } +} + +// A go.work at the root makes golangci-lint resolve the nested module +// itself, so today's single run from the root must stay exactly that. +// This is the regression guard for the fix, not a test of the bug. +// +// proved by: group by go.mod unconditionally — the go.work repo then gets +// a run from sub/ and this fails on the call count and directory. +func TestLintGoKeepsOneRootRunUnderGoWork(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, true) + files := []string{filepath.Join(root, "pkg", "x.go"), filepath.Join(root, "sub", "x", "x.go")} + + got := lintGo(root, files, false) + + cs := calls() + if len(cs) != 1 || cs[0].dir != root { + t.Fatalf("a go.work repo keeps one run from the root, got %+v", cs) + } + if !hasArg(cs[0], "./pkg") || !hasArg(cs[0], "./sub/x") { + t.Errorf("root-relative patterns expected under go.work: %v", cs[0].args) + } + seen := map[string]bool{} + for _, f := range got { + seen[f.File] = true + } + if !seen["pkg/x.go"] || !seen["sub/x/x.go"] { + t.Errorf("findings must stay root-relative, got %+v", got) + } +} + +// The project's golangci config wins: a nested module without its own file +// inherits the ROOT config explicitly (it now runs from a directory the +// root file is not in), one with its own is left to find it, and a repo +// with neither gets the procoder baseline as before. +// +// proved by: drop the --config pass-through for the root file — the first +// case then runs without it and silently loses the project's linters. +func TestLintGoConfigSelectionPerModule(t *testing.T) { + t.Run("root config reaches a nested module that has none", func(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, false) + cfg := filepath.Join(root, ".golangci.yml") + if err := os.WriteFile(cfg, []byte("version: \"2\"\n"), 0o644); err != nil { + t.Fatal(err) + } + lintGo(root, []string{filepath.Join(root, "sub", "x", "x.go")}, false) + cs := calls() + if len(cs) != 1 || argAfter(cs[0], "--config") != cfg { + t.Errorf("want --config %s, got %+v", cfg, cs) + } + }) + t.Run("the nested module's own config is not overridden", func(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, false) + for _, p := range []string{filepath.Join(root, ".golangci.yml"), filepath.Join(root, "sub", ".golangci.yml")} { + if err := os.WriteFile(p, []byte("version: \"2\"\n"), 0o644); err != nil { + t.Fatal(err) + } + } + lintGo(root, []string{filepath.Join(root, "sub", "x", "x.go")}, false) + cs := calls() + if len(cs) != 1 || hasArg(cs[0], "--config") { + t.Errorf("the module's own config must be found by golangci-lint, not overridden: %+v", cs) + } + }) + t.Run("no project config means the baseline", func(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, false) + lintGo(root, []string{filepath.Join(root, "sub", "x", "x.go")}, false) + cs := calls() + if len(cs) != 1 || !strings.Contains(argAfter(cs[0], "--config"), "procoder-golangci-") { + t.Errorf("want the procoder baseline config, got %+v", cs) + } + }) +} + +// The real binary, where one is installed: a nested module's file used to +// come back NOT checked ("main module ... does not contain package"). Here +// it must be checked and the finding must carry the repo-root path. +// +// proved by: revert the fix — the finding is the NOT-checked refusal, whose +// message names golangci-lint failing, not an errcheck on sub/x/x.go. +func TestGolangciFindsARealProblemInANestedModule(t *testing.T) { + if tools.Resolve(GolangciLint, "") == "" { + t.Skip("golangci-lint not installed; the stub tests carry the logic") + } + root := moduleRepo(t, false) + src := "package x\n\nimport \"os\"\n\nfunc F() { os.Remove(\"nope\") }\n" + file := filepath.Join(root, "sub", "x", "x.go") + if err := os.WriteFile(file, []byte(src), 0o644); err != nil { + t.Fatal(err) + } + got := lintGo(root, []string{file}, true) + if len(got) == 0 { + t.Fatal("an unchecked error in the nested module produced no finding") + } + for _, f := range got { + if strings.Contains(f.Message, "NOT checked") { + t.Fatalf("the nested module's file was not checked: %+v", f) + } + if f.File != "sub/x/x.go" { + t.Errorf("finding path %q, want sub/x/x.go", f.File) + } + } +} + +// The nearest go.mod decides the module, ascending from the file and +// stopping at the root; a file under none belongs to the root. +// +// proved by: make gomod.ModuleDir return root unconditionally — sub/x/x.go +// groups under the root module and the nested-module bug is back. +func TestModuleDirIsTheNearestGoMod(t *testing.T) { + root := moduleRepo(t, false) + deep := filepath.Join(root, "sub", "x", "y") + if err := os.MkdirAll(deep, 0o755); err != nil { + t.Fatal(err) + } + for file, want := range map[string]string{ + filepath.Join(root, "pkg", "x.go"): root, + filepath.Join(root, "main.go"): root, + filepath.Join(root, "sub", "x", "x.go"): filepath.Join(root, "sub"), + filepath.Join(deep, "y.go"): filepath.Join(root, "sub"), + filepath.Join(root, "nomod", "z", "z.go"): root, + } { + if got := gomod.ModuleDir(root, file); got != want { + t.Errorf("ModuleDir(%s) = %s, want %s", file, got, want) + } + } +} + +// proved by: key groups by the root instead of the module — one group, so +// the nested file would again be named from the wrong module; and drop the +// go.work branch — a workspace repo then splits into two groups. +func TestGroupSplitsByModuleUnlessAWorkspace(t *testing.T) { + root := moduleRepo(t, false) + a, b := filepath.Join(root, "pkg", "x.go"), filepath.Join(root, "sub", "x", "x.go") + g := gomod.Group(root, []string{a, b}) + if len(g) != 2 || len(g[root]) != 1 || len(g[filepath.Join(root, "sub")]) != 1 { + t.Errorf("want one group per module, got %v", g) + } + ws := moduleRepo(t, true) + g = gomod.Group(ws, []string{filepath.Join(ws, "pkg", "x.go"), filepath.Join(ws, "sub", "x", "x.go")}) + if len(g) != 1 || len(g[ws]) != 2 { + t.Errorf("a go.work repo is one group at the root, got %v", g) + } +} + +// proved by: compute patterns relative to the root — ./sub/x leaks into the +// nested module's run; drop the dedupe — ./x appears twice. +func TestGoPatternsAreRelativeToTheModule(t *testing.T) { + mod := filepath.Join(string(filepath.Separator), "r", "sub") + got := goPatterns(mod, []string{ + filepath.Join(mod, "main.go"), + filepath.Join(mod, "x", "a.go"), + filepath.Join(mod, "x", "b.go"), + filepath.Join(mod, "x", "y", "c.go"), + }) + want := []string{"./", "./x", "./x/y"} + if strings.Join(got, " ") != strings.Join(want, " ") { + t.Errorf("goPatterns = %v, want %v", got, want) + } +} + +// proved by: return the path unchanged — a finding printed as x/x.go in the +// sub module no longer matches the wanted sub/x/x.go and is silently dropped. +func TestRepoRelPathMapsModuleRelativeFindingsToTheRoot(t *testing.T) { + root := filepath.Join(string(filepath.Separator), "r") + sub := filepath.Join(root, "sub") + for _, c := range []struct{ modDir, in, want string }{ + {sub, "x/x.go", "sub/x/x.go"}, + {sub, "x.go", "sub/x.go"}, + {root, "pkg/x.go", "pkg/x.go"}, + {sub, filepath.Join(sub, "x", "x.go"), "sub/x/x.go"}, + {sub, "../other/x.go", "other/x.go"}, + } { + if got := repoRelPath(root, c.modDir, c.in); got != c.want { + t.Errorf("repoRelPath(%s, %s, %q) = %q, want %q", root, c.modDir, c.in, got, c.want) + } + } +} diff --git a/internal/lint/lint.go b/internal/lint/lint.go index 53bde683..c853fafc 100644 --- a/internal/lint/lint.go +++ b/internal/lint/lint.go @@ -24,6 +24,7 @@ import ( "procoder/internal/config" "procoder/internal/gitx" + "procoder/internal/gomod" "procoder/internal/textutil" "procoder/internal/tools" ) @@ -271,19 +272,22 @@ func lintGo(root string, files []string, block bool) []gitx.Finding { if bin == "" { return notChecked(files[0], "golangci-lint") } - dirs := map[string]bool{} - for _, f := range files { - rel, err := filepath.Rel(root, f) - if err != nil { - continue - } - d := filepath.Dir(rel) - if d == "." { - dirs["./"] = true - } else { - dirs["./"+filepath.ToSlash(d)] = true - } + // One run per Go module: golangci-lint resolves packages against the + // module of its working directory, so a nested module's files cannot be + // linted from the repo root (see gomod.Group). + groups := gomod.Group(root, files) + var out []gitx.Finding + for _, modDir := range sortedKeys(groups) { + out = append(out, lintGoModule(root, bin, modDir, groups[modDir], block)...) } + return out +} + +// lintGoModule runs golangci-lint once from modDir over the packages +// holding files (all inside that module) and keeps only the findings that +// land in them, with paths mapped back to repo-root-relative. +func lintGoModule(root, bin, modDir string, files []string, block bool) []gitx.Finding { + patterns := goPatterns(modDir, files) // No issue caps. golangci-lint defaults to --max-issues-per-linter 50 // and --max-same-issues 3, and it lints packages concurrently — so // WHICH issues survive those caps depends on which package finished @@ -302,13 +306,23 @@ func lintGo(root string, files []string, block bool) []gitx.Finding { // the lock is the honest answer; the lint deadline still bounds it. args := []string{"run", "--allow-serial-runners", "--output.text.path=stdout", "--show-stats=false", "--max-issues-per-linter=0", "--max-same-issues=0"} - // the project's own config always wins; without one, procoder supplies - // a curated baseline strong enough to catch the bug classes reviewers + // the project's own config always wins: the module's own file is found + // by golangci-lint from modDir; the repo root's file is passed + // explicitly to a nested module that has none, since it now runs from a + // directory that file is not in. Without either, procoder supplies a + // curated baseline strong enough to catch the bug classes reviewers // keep finding (security edges, error handling, loop allocations) — // the file lives in the temp dir, nothing is imposed on the repo // (requires golangci-lint v2, the version doctor installs) var baselineNote []gitx.Finding - if !hasGolangciConfig(root) { + switch { + case golangciConfigIn(modDir) != "": + // found by golangci-lint itself + case golangciConfigIn(root) != "": + if modDir != root { + args = append(args, "--config", golangciConfigIn(root)) + } + default: cfgFile, err := os.CreateTemp("", "procoder-golangci-*.yml") if err == nil { _, err = cfgFile.WriteString(golangciBaseline) @@ -328,20 +342,24 @@ func lintGo(root string, files []string, block bool) []gitx.Finding { Message: "go lint ran WITHOUT the procoder baseline (cannot write temp config: " + err.Error() + ") (lint)"}) } } - for d := range dirs { - args = append(args, d) - } + args = append(args, patterns...) wanted := map[string]bool{} for _, f := range files { if rel, err := filepath.Rel(root, f); err == nil { wanted[filepath.ToSlash(rel)] = true } } - raw, err := execute(root, bin, args) + raw, err := execute(modDir, bin, args) findings := finishParse(raw, err, files[0], "golangci-lint", block) out := baselineNote for _, f := range findings { - if wanted[filepath.ToSlash(f.File)] || f.File == files[0] { + if f.File == files[0] { + // the run-failed refusal already names the absolute file + out = append(out, f) + continue + } + f.File = repoRelPath(root, modDir, f.File) + if wanted[f.File] { out = append(out, f) } } @@ -368,12 +386,7 @@ linters: // hasGolangciConfig reports whether the project carries its own golangci // config — the repo's file always wins over the baseline (D-OVERRIDE). func hasGolangciConfig(root string) bool { - for _, name := range []string{".golangci.yml", ".golangci.yaml", ".golangci.toml", ".golangci.json"} { - if _, err := os.Stat(filepath.Join(root, name)); err == nil { - return true - } - } - return false + return golangciConfigIn(root) != "" } // lintJS runs eslint. The project's config always wins and is resolved the diff --git a/internal/testrun/gomod_test.go b/internal/testrun/gomod_test.go new file mode 100644 index 00000000..12b01d7b --- /dev/null +++ b/internal/testrun/gomod_test.go @@ -0,0 +1,62 @@ +package testrun + +import ( + "strings" + "testing" +) + +// nestedModuleFixture is a root module plus a nested one (its own go.mod, +// `replace => ../`), each with one package and one test. +func nestedModuleFixture(t *testing.T, nestedPasses bool) string { + t.Helper() + root := t.TempDir() + write(t, root, "go.mod", "module demo\n\ngo 1.22\n") + write(t, root, "a/a.go", "package a\n") + write(t, root, "a/a_test.go", "package a\n\nimport \"testing\"\n\nfunc TestA(t *testing.T) {}\n") + write(t, root, "sub/go.mod", "module demo/sub\n\ngo 1.22\n\nrequire demo v0.0.0\n\nreplace demo => ../\n") + write(t, root, "sub/x/x.go", "package x\n") + body := "t.Fatal(\"deliberately red\")" + if nestedPasses { + body = "_ = t" + } + write(t, root, "sub/x/x_test.go", "package x\n\nimport \"testing\"\n\nfunc TestX(t *testing.T) { "+body+" }\n") + return root +} + +// A package in a nested module used to be named from the repo root and +// came back as "[setup failed] main module does not contain package": a +// correct commit blocked. Narrowed to it, the suite must run from the +// module's own directory. +// +// proved by: have runGo always run from root — the nested package fails to +// set up and this reads Fail with "does not contain package". +func TestGoNestedModulePackageIsTestedFromItsModule(t *testing.T) { + requireGo(t) + root := nestedModuleFixture(t, true) + r := runGo(root, []string{"sub/x"}, false, "") + if r.Verdict != Pass { + t.Fatalf("nested module package must pass from its own dir, got %s: %s", r.Verdict, r.Detail) + } + if !strings.Contains(r.Detail, "sub: pass") { + t.Errorf("the detail must say which module ran: %q", r.Detail) + } +} + +// Both modules in one commit run, and a red test in either one is red. +// +// proved by: drop the Fail branch of the merge in runGoModules — a failing +// nested module is reported as a pass. +func TestGoMixedModulesRunBothAndFailIfEitherFails(t *testing.T) { + requireGo(t) + root := nestedModuleFixture(t, false) + r := runGo(root, []string{"a", "sub/x"}, false, "") + if r.Verdict != Fail { + t.Fatalf("a red test in the nested module must fail the run, got %s: %s", r.Verdict, r.Detail) + } + if !strings.Contains(r.Detail, ".: pass") || !strings.Contains(r.Detail, "sub: ") { + t.Errorf("both modules must be reported: %q", r.Detail) + } + if !strings.Contains(r.Output+r.Detail, "TestX") { + t.Errorf("the failing test must be named: %q / %q", r.Detail, r.Output) + } +} diff --git a/internal/testrun/testrun.go b/internal/testrun/testrun.go index b99545dc..3bafc59a 100644 --- a/internal/testrun/testrun.go +++ b/internal/testrun/testrun.go @@ -16,10 +16,12 @@ import ( "os/exec" "path/filepath" "regexp" + "sort" "strconv" "strings" "time" + "procoder/internal/gomod" "procoder/internal/textutil" ) @@ -195,6 +197,76 @@ func goArgs(root string, paths []string, coverage bool, name string) []string { } func runGo(root string, paths []string, coverage bool, name string) Result { + // `go test` resolves packages against the module of its working + // directory, so a package in a nested module (its own go.mod) cannot be + // named from the root: "main module ... does not contain package". Paths + // are grouped by owning module and each group runs from its module's + // directory. With no paths the whole root module runs, as before — a + // nested module is its own module and `./...` has never reached it. + if len(paths) > 0 { + abs := make([]string, 0, len(paths)) + for _, p := range paths { + if !filepath.IsAbs(p) { + p = filepath.Join(root, p) + } + abs = append(abs, p) + } + groups := gomod.Group(root, abs) + if _, onlyRoot := groups[root]; !(onlyRoot && len(groups) == 1) { + return runGoModules(root, groups, coverage, name) + } + } + return runGoIn(root, paths, coverage, name) +} + +// runGoModules runs one `go test` per module and folds the answers into +// one Result: any failure fails, otherwise any run that could not happen +// is NOT run, otherwise it passes. Each module's detail is prefixed with +// its directory so a red line says where it came from. +func runGoModules(root string, groups map[string][]string, coverage bool, name string) Result { + dirs := make([]string, 0, len(groups)) + for d := range groups { + dirs = append(dirs, d) + } + sort.Strings(dirs) + merged := Result{Ecosystem: "go", Coverage: -1, Verdict: Pass} + var details, outputs []string + var covSum float64 + var covN int + for _, dir := range dirs { + r := runGoIn(dir, groups[dir], coverage, name) + label := "." + if rel, err := filepath.Rel(root, dir); err == nil && rel != "." { + label = filepath.ToSlash(rel) + } + details = append(details, label+": "+r.Detail) + if r.Output != "" { + outputs = append(outputs, r.Output) + } + merged.Passed += r.Passed + merged.Failed += r.Failed + merged.Filtered = merged.Filtered || r.Filtered + if r.Coverage >= 0 { + covSum += r.Coverage + covN++ + } + switch { + case r.Verdict == Fail: + merged.Verdict = Fail + case r.Verdict == NotRun && merged.Verdict == Pass: + merged.Verdict = NotRun + } + } + if covN > 0 { + merged.Coverage = covSum / float64(covN) + } + merged.Detail = strings.Join(details, "; ") + merged.Output = strings.Join(outputs, "\n") + return merged +} + +// runGoIn runs `go test` from dir; paths are targets inside that module. +func runGoIn(root string, paths []string, coverage bool, name string) Result { r := Result{Ecosystem: "go", Coverage: -1, Filtered: name != ""} bin, err := exec.LookPath("go") if err != nil { From 27c8c8f5eef2147d790c3de99f559d17da187429 Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 16:33:56 +0400 Subject: [PATCH 2/8] docs(changelog): nested Go modules are checked from their own directory --- CHANGELOG.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e495318f..13a8e2f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,25 @@ Rules that earn their place: handle opened none of what its paragraph cites. --> +## Unreleased + +_The commit gate lints and tests a Go file that lives in a nested Go +module instead of refusing it as not checked._ + +**Fixed — a file in a nested Go module is checked from its own module.** +([#340](https://github.com/azrtydxb/procoder/pull/340)) The gate ran one +golangci-lint from the repository root over every changed Go package, so a +changed file in a directory with its own `go.mod` (a `bench/` module with +`replace => ../`, say) failed with "main module does not contain package" +and was reported NOT checked, blocking a commit whose code was correct. +`go test` narrowed to such a package failed the same way with "setup +failed". procoder now groups the changed Go files by their nearest +`go.mod` and runs golangci-lint and `go test` once per module, from that +module's directory, then maps each finding back to its path in the +repository. The project's golangci config applies to every module (a +nested module without its own file gets the root one), and a `go.work` at +the root keeps the single run it always had. + ## 3.9.3 — 2026-11-07 _procoder no longer floods a CI container with formatter processes when From c55c07dc67ac570c9fcaf6c55a001bc8a7b47906 Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 17:05:37 +0400 Subject: [PATCH 3/8] docs(changelog): leave the entry to the release commit --- CHANGELOG.md | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13a8e2f1..e495318f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,25 +51,6 @@ Rules that earn their place: handle opened none of what its paragraph cites. --> -## Unreleased - -_The commit gate lints and tests a Go file that lives in a nested Go -module instead of refusing it as not checked._ - -**Fixed — a file in a nested Go module is checked from its own module.** -([#340](https://github.com/azrtydxb/procoder/pull/340)) The gate ran one -golangci-lint from the repository root over every changed Go package, so a -changed file in a directory with its own `go.mod` (a `bench/` module with -`replace => ../`, say) failed with "main module does not contain package" -and was reported NOT checked, blocking a commit whose code was correct. -`go test` narrowed to such a package failed the same way with "setup -failed". procoder now groups the changed Go files by their nearest -`go.mod` and runs golangci-lint and `go test` once per module, from that -module's directory, then maps each finding back to its path in the -repository. The project's golangci config applies to every module (a -nested module without its own file gets the root one), and a `go.work` at -the root keeps the single run it always had. - ## 3.9.3 — 2026-11-07 _procoder no longer floods a CI container with formatter processes when From fed059aa0762e012f972b207b3120adee57ea484 Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 17:05:38 +0400 Subject: [PATCH 4/8] docs(commands): the test runner covers the root module only without paths --- docs/commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/commands.md b/docs/commands.md index 679c76fe..361aeec2 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -654,7 +654,7 @@ carries a bounded excerpt of its own output — the assertion, panic or build error — under the FAIL line, in the gate's finding as well. When the narrowed packages sit in a nested Go module (its own `go.mod`), `go test` runs once per module from that module's directory, and the detail is prefixed with -the module. `--coverage` adds the +the module; with no narrowed paths it covers the root module only. `--coverage` adds the percentage where the runner measures it natively (Go; pytest with pytest-cov); a number is reported, never enforced. With `--name ` narrows the run to matching tests — `-run` for Go, From 77e2267e63f6a92c284b2b2a1537b9c58c30df63 Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 17:05:38 +0400 Subject: [PATCH 5/8] fix(lint): ask golangci-lint for absolute paths so the config location cannot shift them --- internal/lint/gomod.go | 22 ++++++++++++++++++---- internal/lint/lint.go | 14 +++++++++++--- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/internal/lint/gomod.go b/internal/lint/gomod.go index 893ce477..7acdbe02 100644 --- a/internal/lint/gomod.go +++ b/internal/lint/gomod.go @@ -53,11 +53,16 @@ func repoRelPath(root, modDir, p string) string { if !filepath.IsAbs(abs) { abs = filepath.Join(modDir, p) } - rel, err := filepath.Rel(root, abs) - if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - return filepath.ToSlash(p) + if rel, ok := under(root, abs); ok { + return rel + } + // the tool may print a symlink-resolved path (macOS /var -> /private/var) + if real, err := filepath.EvalSymlinks(root); err == nil { + if rel, ok := under(real, abs); ok { + return rel + } } - return filepath.ToSlash(rel) + return filepath.ToSlash(p) } // golangciConfigIn is the golangci config file sitting directly in dir, or @@ -71,3 +76,12 @@ func golangciConfigIn(dir string) string { } return "" } + +// under is abs relative to base as a slash path, false when it is outside. +func under(base, abs string) (string, bool) { + rel, err := filepath.Rel(base, abs) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false + } + return filepath.ToSlash(rel), true +} diff --git a/internal/lint/lint.go b/internal/lint/lint.go index c853fafc..141144ae 100644 --- a/internal/lint/lint.go +++ b/internal/lint/lint.go @@ -305,7 +305,14 @@ func lintGoModule(root, bin, modDir string, files []string, block bool) []gitx.F // worktree, agent, or the write hook was mid-run (#324). Waiting for // the lock is the honest answer; the lint deadline still bounds it. args := []string{"run", "--allow-serial-runners", "--output.text.path=stdout", "--show-stats=false", - "--max-issues-per-linter=0", "--max-same-issues=0"} + "--max-issues-per-linter=0", "--max-same-issues=0", + // golangci-lint v2 prints paths relative to the CONFIG file's + // directory by default. The baseline lives in the temp dir and a + // root config is passed from outside the module, so every path + // arrived as ../../elsewhere/x.go and the wanted filter dropped + // the finding. Absolute paths do not depend on where the config + // is; repoRelPath maps them to the repo root. + "--path-mode=abs"} // the project's own config always wins: the module's own file is found // by golangci-lint from modDir; the repo root's file is passed // explicitly to a nested module that has none, since it now runs from a @@ -353,8 +360,9 @@ func lintGoModule(root, bin, modDir string, files []string, block bool) []gitx.F findings := finishParse(raw, err, files[0], "golangci-lint", block) out := baselineNote for _, f := range findings { - if f.File == files[0] { - // the run-failed refusal already names the absolute file + if strings.HasPrefix(f.Message, "NOT checked") { + // the run-failed refusal already names the absolute file; a + // real finding in that same file has a path to map instead out = append(out, f) continue } From a61f6e0355398b0abba2702921532841ab88e0c2 Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 17:05:38 +0400 Subject: [PATCH 6/8] fix(gomod): resolve a package directory from itself, clamp to the root, ignore testdata and vendor go.mod --- internal/gomod/gomod.go | 40 +++++++++++++++---- internal/gomod/gomod_test.go | 64 ++++++++++++++++++++++++++++++ internal/lint/gomod_test.go | 35 +++++++++++++++- internal/testrun/gomod_dir_test.go | 29 ++++++++++++++ 4 files changed, 160 insertions(+), 8 deletions(-) create mode 100644 internal/gomod/gomod_test.go create mode 100644 internal/testrun/gomod_dir_test.go diff --git a/internal/gomod/gomod.go b/internal/gomod/gomod.go index 19d8a69c..3ef84411 100644 --- a/internal/gomod/gomod.go +++ b/internal/gomod/gomod.go @@ -9,6 +9,7 @@ package gomod import ( "os" "path/filepath" + "strings" ) func exists(p string) bool { @@ -22,14 +23,24 @@ func Workspace(root string) bool { return exists(filepath.Join(root, "go.work")) } -// ModuleDir is the directory of the go.mod nearest to file, ascending from -// the file's directory and stopping at root. A file under no go.mod belongs -// to root: the repository is then taken to be one module, as it was before -// nested modules were understood. -func ModuleDir(root, file string) string { - dir := filepath.Dir(file) +// ModuleDir is the directory of the go.mod nearest to p, ascending from p +// when it is a directory (the gate passes package directories) or from its +// parent when it is a file, and stopping at root. A path under no go.mod, or +// outside root, belongs to root: the repository is then taken to be one +// module, as it was before nested modules were understood. A go.mod under a +// testdata or vendor directory is ignored, as the go command ignores it, so +// a file there belongs to the enclosing real module. +func ModuleDir(root, p string) string { + rel, err := filepath.Rel(root, p) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return root + } + dir := p + if info, err := os.Stat(p); err != nil || !info.IsDir() { + dir = filepath.Dir(p) + } for { - if exists(filepath.Join(dir, "go.mod")) { + if exists(filepath.Join(dir, "go.mod")) && !ignoredDir(root, dir) { return dir } parent := filepath.Dir(dir) @@ -40,6 +51,21 @@ func ModuleDir(root, file string) string { } } +// ignoredDir reports whether dir sits at or under a testdata or vendor +// directory below root. +func ignoredDir(root, dir string) bool { + rel, err := filepath.Rel(root, dir) + if err != nil { + return false + } + for _, part := range strings.Split(filepath.ToSlash(rel), "/") { + if part == "testdata" || part == "vendor" { + return true + } + } + return false +} + // Group splits absolute paths by owning module directory. Under a go.work // at root everything stays one group at root. func Group(root string, paths []string) map[string][]string { diff --git a/internal/gomod/gomod_test.go b/internal/gomod/gomod_test.go new file mode 100644 index 00000000..a8f7d98a --- /dev/null +++ b/internal/gomod/gomod_test.go @@ -0,0 +1,64 @@ +package gomod + +import ( + "os" + "path/filepath" + "testing" +) + +func layout(t *testing.T, files ...string) string { + t.Helper() + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + for _, f := range files { + p := filepath.Join(root, filepath.FromSlash(f)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("x\n"), 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +// proved by: start the ascent at filepath.Dir(p) for a directory too — +// sub (a package directory at the nested module's root) resolves to the +// root module, and the "dir input" row fails. +func TestModuleDir(t *testing.T) { + root := layout(t, "go.mod", "a/a.go", "sub/go.mod", "sub/main.go", "sub/x/x.go", + "sub/testdata/go.mod", "sub/testdata/t.go", "vendor/go.mod", "vendor/v/v.go") + sub := filepath.Join(root, "sub") + for name, c := range map[string]struct{ in, want string }{ + "file in root module": {filepath.Join(root, "a", "a.go"), root}, + "file in module root": {filepath.Join(sub, "main.go"), sub}, + "file below module root": {filepath.Join(sub, "x", "x.go"), sub}, + "dir input is its own start": {sub, sub}, + "dir input below": {filepath.Join(sub, "x"), sub}, + "outside root": {filepath.Join(filepath.Dir(root), "elsewhere", "e.go"), root}, + "testdata go.mod ignored": {filepath.Join(sub, "testdata", "t.go"), sub}, + "vendor go.mod ignored": {filepath.Join(root, "vendor", "v", "v.go"), root}, + "no go.mod anywhere": {filepath.Join(root, "nomod", "z.go"), root}, + } { + if got := ModuleDir(root, c.in); got != c.want { + t.Errorf("%s: ModuleDir(%s) = %s, want %s", name, c.in, got, c.want) + } + } +} + +// proved by: drop the go.work branch of Group — the workspace splits in two. +func TestGroup(t *testing.T) { + root := layout(t, "go.mod", "a/a.go", "sub/go.mod", "sub/x/x.go") + a, b := filepath.Join(root, "a", "a.go"), filepath.Join(root, "sub", "x", "x.go") + if g := Group(root, []string{a, b}); len(g) != 2 { + t.Errorf("want a group per module, got %v", g) + } + if err := os.WriteFile(filepath.Join(root, "go.work"), []byte("go 1.22\n"), 0o644); err != nil { + t.Fatal(err) + } + if g := Group(root, []string{a, b}); len(g) != 1 || len(g[root]) != 2 { + t.Errorf("a go.work repo is one group at the root, got %v", g) + } +} diff --git a/internal/lint/gomod_test.go b/internal/lint/gomod_test.go index 4c6a6097..d5dc1082 100644 --- a/internal/lint/gomod_test.go +++ b/internal/lint/gomod_test.go @@ -3,6 +3,7 @@ package lint import ( "os" "path/filepath" + "runtime" "strings" "testing" @@ -22,6 +23,9 @@ type goCall struct { // — which is what the real binary prints. It returns a reader for the calls. func stubGolangci(t *testing.T) func() []goCall { t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the stub is a /bin/sh script; the logic it checks is not platform-specific") + } dir := t.TempDir() log := filepath.Join(dir, "calls.txt") script := `#!/bin/sh @@ -116,7 +120,8 @@ func argAfter(c goCall, flag string) string { // not contain package ...", and the gate reports the file NOT checked — so // every commit touching a nested module was blocked while correct. // -// proved by: leave cmd.Dir at the repo root in lintGo — the call's dir is +// proved by: leave cmd.Dir at the repo root in lintGo, or drop +// --path-mode=abs — the call's dir is // the root and the pattern is ./sub/x, so this fails on both. func TestLintGoRunsANestedModuleFromItsOwnDirectory(t *testing.T) { calls := stubGolangci(t) @@ -132,6 +137,12 @@ func TestLintGoRunsANestedModuleFromItsOwnDirectory(t *testing.T) { if want := filepath.Join(root, "sub"); cs[0].dir != want { t.Errorf("ran in %s, want the nested module directory %s", cs[0].dir, want) } + // golangci-lint v2 prints paths relative to the CONFIG file's directory + // by default; with the baseline in the temp dir every path came back + // as ../../tmp/... and was dropped by the wanted filter. + if !hasArg(cs[0], "--path-mode=abs") { + t.Errorf("paths must be absolute, independent of the config file's directory: %v", cs[0].args) + } if !hasArg(cs[0], "./x") || hasArg(cs[0], "./sub/x") { t.Errorf("patterns must be relative to the module dir (./x, not ./sub/x): %v", cs[0].args) } @@ -353,3 +364,25 @@ func TestRepoRelPathMapsModuleRelativeFindingsToTheRoot(t *testing.T) { } } } + +// A file directly in the nested module's root (sub/x.go) is the module's +// "./" package: the run is from sub with the pattern "./", never ./sub. +// +// proved by: resolve the module from the repo root — the run happens in +// root with ./sub, and this fails on the directory. +func TestLintGoFileAtTheNestedModuleRoot(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, false) + file := filepath.Join(root, "sub", "x.go") + if err := os.WriteFile(file, []byte("package main\n"), 0o644); err != nil { + t.Fatal(err) + } + got := lintGo(root, []string{file}, false) + cs := calls() + if len(cs) != 1 || cs[0].dir != filepath.Join(root, "sub") || !hasArg(cs[0], "./") { + t.Fatalf("want one run in sub with ./, got %+v", cs) + } + if len(got) != 1 || got[0].File != "sub/x.go" { + t.Errorf("finding must map to sub/x.go (the stub's file for ./), got %+v", got) + } +} diff --git a/internal/testrun/gomod_dir_test.go b/internal/testrun/gomod_dir_test.go new file mode 100644 index 00000000..114d0609 --- /dev/null +++ b/internal/testrun/gomod_dir_test.go @@ -0,0 +1,29 @@ +package testrun + +import ( + "strings" + "testing" +) + +// The gate hands runGo package DIRECTORIES (changedPackages maps a changed +// file to path.Dir(rel)). A changed sub/main.go arrives as "sub", the root +// of the nested module; the module lookup used to treat it as a file, start +// its ascent at the repo root, and pick the root module — which then failed +// with "main module does not contain package demo/sub". +// +// proved by: make gomod.ModuleDir start at filepath.Dir(path) for a +// directory too — "sub" resolves to the root module and this fails with +// "does not contain package". +func TestGoDirectoryAtANestedModuleRootIsTestedFromThatModule(t *testing.T) { + requireGo(t) + root := nestedModuleFixture(t, true) + write(t, root, "sub/s.go", "package sub\n") + write(t, root, "sub/s_test.go", "package sub\n\nimport \"testing\"\n\nfunc TestS(t *testing.T) {}\n") + r := runGo(root, []string{"sub"}, false, "") + if r.Verdict != Pass { + t.Fatalf("a package at the nested module's root must pass from that module, got %s: %s", r.Verdict, r.Detail) + } + if !strings.Contains(r.Detail, "sub: pass") { + t.Errorf("the detail must say the nested module ran: %q", r.Detail) + } +} From d0e6219ebfefff08b9f9707cfefd0ba1156d600e Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 17:09:37 +0400 Subject: [PATCH 7/8] ci: install the pinned golangci-lint in the test job so the real-binary lint test runs --- .github/workflows/ci.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2321ae1c..3dd1e9a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,6 +68,19 @@ jobs: # failure. Otherwise a broken install would restore the silent # skip and the suite would stay green over the guard it disabled. echo "PROCODER_PHP_PLUGIN_REQUIRED=1" >> "$GITHUB_ENV" + - name: golangci-lint, so the real-binary lint test runs instead of skipping + # TestGolangciFindsARealProblemInANestedModule is the only test that + # checks procoder's golangci-lint flags and path handling against the + # real tool; the stub tests cannot catch a flag it rejects. Pinned + # from the same file the gate reads. Linux only, once. + if: runner.os == 'Linux' + run: | + eval "$(grep -E '^[A-Z][A-Z0-9_]*=' .github/tool-versions.env)" + cd /tmp + curl -sSfL "https://github.com/golangci/golangci-lint/releases/download/v${GOLANGCI_LINT}/golangci-lint-${GOLANGCI_LINT}-linux-amd64.tar.gz" | tar xz + sudo install -m 0755 "golangci-lint-${GOLANGCI_LINT}-linux-amd64/golangci-lint" /usr/local/bin/golangci-lint + golangci-lint --version + echo "PROCODER_GOLANGCI_REQUIRED=1" >> "$GITHUB_ENV" - run: go test ./internal/... - name: the binary builds run: go build ./cmd/procoder From 65dc731552a4535ce829d837abebdc2a364c1a8b Mon Sep 17 00:00:00 2001 From: Pascal Watteel Date: Mon, 9 Nov 2026 17:09:37 +0400 Subject: [PATCH 8/8] fix(lint): pass --path-mode only to a golangci-lint that knows it; test absolute output and symlinked roots --- internal/lint/gomod.go | 18 +++++++ internal/lint/gomod_test.go | 97 +++++++++++++++++++++++++++++++++++++ internal/lint/lint.go | 22 ++++++--- 3 files changed, 129 insertions(+), 8 deletions(-) diff --git a/internal/lint/gomod.go b/internal/lint/gomod.go index 7acdbe02..d3febd1a 100644 --- a/internal/lint/gomod.go +++ b/internal/lint/gomod.go @@ -5,6 +5,7 @@ import ( "path/filepath" "sort" "strings" + "sync" ) // golangciConfigNames are the config files golangci-lint itself accepts. @@ -85,3 +86,20 @@ func under(base, abs string) (string, bool) { } return filepath.ToSlash(rel), true } + +// pathModeSupport caches, per binary, whether `golangci-lint run` knows +// --path-mode: asked once per process, not once per module. +var pathModeSupport sync.Map // bin path -> bool + +// supportsPathMode reports whether bin's `run --help` lists --path-mode. +// A binary that cannot even print its help is treated as not supporting it; +// the real run then fails (or not) on its own terms and says so. +func supportsPathMode(bin string) bool { + if v, ok := pathModeSupport.Load(bin); ok { + return v.(bool) + } + raw, _ := execute(filepath.Dir(bin), bin, []string{"run", "--help"}) + ok := strings.Contains(raw, "--path-mode") + pathModeSupport.Store(bin, ok) + return ok +} diff --git a/internal/lint/gomod_test.go b/internal/lint/gomod_test.go index d5dc1082..f0d76d9e 100644 --- a/internal/lint/gomod_test.go +++ b/internal/lint/gomod_test.go @@ -22,21 +22,51 @@ type goCall struct { // in that package's x.go, with the path relative to the directory it ran in // — which is what the real binary prints. It returns a reader for the calls. func stubGolangci(t *testing.T) func() []goCall { + return stubGolangciMode(t, stubModern) +} + +// stubMode says how the fake binary behaves. +type stubMode int + +const ( + // stubModern knows --path-mode and, given it, prints absolute paths. + stubModern stubMode = iota + // stubOld lacks --path-mode: its help does not list it and it errors + // if given the flag; it prints paths relative to its working directory. + stubOld +) + +func stubGolangciMode(t *testing.T, mode stubMode) func() []goCall { t.Helper() if runtime.GOOS == "windows" { t.Skip("the stub is a /bin/sh script; the logic it checks is not platform-specific") } dir := t.TempDir() log := filepath.Join(dir, "calls.txt") + help := "Usage:\n --allow-serial-runners\n --path-mode string\n" + if mode == stubOld { + help = "Usage:\n --allow-serial-runners\n" + } script := `#!/bin/sh +for a in "$@"; do + if [ "$a" = "--help" ]; then printf '` + help + `'; exit 0; fi +done printf 'CALL\n' >> ` + log + ` printf 'pwd=%s\n' "$(pwd -P)" >> ` + log + ` for a in "$@"; do printf 'arg=%s\n' "$a" >> ` + log + `; done +abs=0 +for a in "$@"; do + case "$a" in + --path-mode=abs) abs=1 +` + map[bool]string{true: " printf 'Error: unknown flag: --path-mode\n'; exit 3\n", false: ""}[mode == stubOld] + `;; + esac +done rc=0 for a in "$@"; do case "$a" in ./*) p=${a#./}; p=${p%/} if [ -z "$p" ]; then f=x.go; else f=$p/x.go; fi + if [ $abs = 1 ]; then f="$(pwd -P)/$f"; fi printf '%s:3:1: boom (stub)\n' "$f"; rc=1 ;; esac done @@ -268,6 +298,11 @@ func TestLintGoConfigSelectionPerModule(t *testing.T) { // message names golangci-lint failing, not an errcheck on sub/x/x.go. func TestGolangciFindsARealProblemInANestedModule(t *testing.T) { if tools.Resolve(GolangciLint, "") == "" { + // where CI promises the binary, skipping is a failure: otherwise a + // broken install restores the silent skip over the guard + if os.Getenv("PROCODER_GOLANGCI_REQUIRED") != "" { + t.Fatal("golangci-lint is required here and was not found") + } t.Skip("golangci-lint not installed; the stub tests carry the logic") } root := moduleRepo(t, false) @@ -386,3 +421,65 @@ func TestLintGoFileAtTheNestedModuleRoot(t *testing.T) { t.Errorf("finding must map to sub/x.go (the stub's file for ./), got %+v", got) } } + +// golangci-lint v2 prints absolute paths under --path-mode=abs. A finding +// in the FIRST linted file arrives as that file's absolute path — exactly +// what the old `File == files[0]` shortcut mistook for the run-failed +// refusal and passed through unmapped, so the gate printed an absolute path +// and the wanted filter was never applied. +// +// proved by: restore `if f.File == files[0]` in lintGoModule in place of the +// NOT checked prefix test — the finding keeps its absolute path. +func TestLintGoMapsAbsoluteFindingInTheFirstFile(t *testing.T) { + calls := stubGolangci(t) + root := moduleRepo(t, false) + file := filepath.Join(root, "sub", "x", "x.go") + got := lintGo(root, []string{file}, false) + cs := calls() + if len(cs) != 1 || !hasArg(cs[0], "--path-mode=abs") { + t.Fatalf("a binary that knows --path-mode must be given it: %+v", cs) + } + if len(got) != 1 || got[0].File != "sub/x/x.go" { + t.Errorf("an absolute finding in files[0] must be mapped to sub/x/x.go, got %+v", got) + } +} + +// A golangci-lint v2 too old to know --path-mode rejects the flag, which +// would turn every Go file into NOT checked. Support is read from the +// binary's own help, the flag is withheld, and its working-directory +// relative output is still mapped and kept. +// +// proved by: pass --path-mode=abs unconditionally — the stub exits 3 and +// the file reads NOT checked. +func TestLintGoWithholdsPathModeFromABinaryThatLacksIt(t *testing.T) { + calls := stubGolangciMode(t, stubOld) + root := moduleRepo(t, false) + got := lintGo(root, []string{filepath.Join(root, "sub", "x", "x.go")}, false) + cs := calls() + if len(cs) != 1 || hasArg(cs[0], "--path-mode=abs") { + t.Fatalf("the unknown flag must not be passed: %+v", cs) + } + if len(got) != 1 || got[0].File != "sub/x/x.go" || strings.Contains(got[0].Message, "NOT checked") { + t.Errorf("the file must be linted and mapped, got %+v", got) + } +} + +// proved by: drop the symlink fallback in repoRelPath — the resolved path +// the tool prints is outside the symlinked root and comes back unmapped. +func TestRepoRelPathMapsAResolvedPathUnderASymlinkedRoot(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation needs privileges on Windows") + } + resolved, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + link := filepath.Join(t.TempDir(), "link") + if err := os.Symlink(resolved, link); err != nil { + t.Skipf("cannot symlink: %v", err) + } + got := repoRelPath(link, filepath.Join(link, "sub"), filepath.Join(resolved, "sub", "x", "x.go")) + if got != "sub/x/x.go" { + t.Errorf("repoRelPath = %q, want sub/x/x.go", got) + } +} diff --git a/internal/lint/lint.go b/internal/lint/lint.go index 141144ae..8619cd8e 100644 --- a/internal/lint/lint.go +++ b/internal/lint/lint.go @@ -305,14 +305,20 @@ func lintGoModule(root, bin, modDir string, files []string, block bool) []gitx.F // worktree, agent, or the write hook was mid-run (#324). Waiting for // the lock is the honest answer; the lint deadline still bounds it. args := []string{"run", "--allow-serial-runners", "--output.text.path=stdout", "--show-stats=false", - "--max-issues-per-linter=0", "--max-same-issues=0", - // golangci-lint v2 prints paths relative to the CONFIG file's - // directory by default. The baseline lives in the temp dir and a - // root config is passed from outside the module, so every path - // arrived as ../../elsewhere/x.go and the wanted filter dropped - // the finding. Absolute paths do not depend on where the config - // is; repoRelPath maps them to the repo root. - "--path-mode=abs"} + "--max-issues-per-linter=0", "--max-same-issues=0"} + // golangci-lint v2 prints paths relative to the CONFIG file's directory + // by default. The baseline lives in the temp dir and a root config is + // passed from outside the module, so every path arrived as + // ../../elsewhere/x.go and the wanted filter dropped the finding. + // Absolute paths do not depend on where the config is; repoRelPath maps + // them to the repo root. Only where the binary knows the flag: an older + // v2 rejects it, which would turn every Go file into NOT checked. As far + // as is known, versions without the flag also predate config-relative + // output and print paths relative to the working directory, which + // repoRelPath maps too. + if supportsPathMode(bin) { + args = append(args, "--path-mode=abs") + } // the project's own config always wins: the module's own file is found // by golangci-lint from modDir; the repo root's file is passed // explicitly to a nested module that has none, since it now runs from a