Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ caller repo at the default PR merge ref with `fetch-depth: 0`; the action
does not fetch refs.
It needs Git 2.41 or later. Replace `<sha>` with the commit SHA to pin.

Run the action from trusted workflow code. The calling workflow sets its
inputs, so a PR that controls the workflow can change `allow-new-modules`,
`other-modules`, or `guarded-linters`.

```yaml
on:
pull_request:
Expand Down Expand Up @@ -113,11 +117,14 @@ The action rejects added symlinks.
The action also rejects new line directives and build constraints that
mention the `ignore` tag.
The action checks whether changed Go files in the selected module load on
Linux, Windows, or macOS with cgo and the base config's build tags. It skips
files whose nearest `go.mod` belongs to a different module. To check a
nested module, run the action with `working-directory` set to that module.
It accepts unimported `testdata` files. The Linux lint job does not lint files that only
load on Windows or macOS.
Linux, Windows, or macOS with cgo and the base config's build tags. By default,
it fails if a changed Go file belongs to a different module. For a repository
with several modules, either run the action once per module with
`other-modules: skip`, or keep the default to reject changes outside the
selected module.
It accepts unimported `testdata` files, including files in fixture modules
with no packages in the Go package list. The Linux lint job does not lint
files that only load on Windows or macOS.

The full-tree dead-code check runs last. It fails on any `unused` or
`unparam` finding, and the directive check rejects new suppressions for
Expand Down
26 changes: 20 additions & 6 deletions internal/baseline/directives.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ import (
const (
directivesCommand = "directives"
goMod = "go.mod"
otherModulesFail = "fail"
otherModulesSkip = "skip"
)

type directiveRules struct {
root, goList, moduleDir string
guarded map[string]bool
allowGenerated, allowNewModules bool
root, goList, moduleDir, otherModules string
guarded map[string]bool
allowGenerated, allowNewModules bool
}

func executeDirectives(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
Expand Down Expand Up @@ -54,6 +56,12 @@ func parseDirectiveFlags(args []string) (directiveRules, error) {
flags.StringVar(&rules.root, "root", "", "destination source tree")
flags.StringVar(&rules.goList, "go-list", "", "go list -e -json -deps -test package stream")
flags.StringVar(&rules.moduleDir, "module-dir", ".", "module directory relative to root")
flags.StringVar(
&rules.otherModules,
"other-modules",
otherModulesFail,
"fail or skip Go files in other modules",
)
flags.BoolVar(&rules.allowGenerated, "allow-generated", false, "allow generated headers")
flags.BoolVar(
&rules.allowNewModules,
Expand All @@ -79,6 +87,9 @@ func parseDirectiveFlags(args []string) (directiveRules, error) {
return rules, errors.New("expected --module-dir relative to --root")
}
rules.moduleDir = filepath.ToSlash(filepath.Clean(rules.moduleDir))
if !slices.Contains([]string{otherModulesFail, otherModulesSkip}, rules.otherModules) {
return rules, errors.New("expected --other-modules to be fail or skip")
}
return rules, nil
}

Expand Down Expand Up @@ -120,9 +131,12 @@ func (r directiveRules) findings(name string, c *fileChange, l loadedGo) (map[in
if err != nil {
return nil, err
}
rejected, err := l.rejects(name)
if rejected && findings[1] == "" {
findings[1] = "not loaded by any GOOS build"
reason, err := l.reason(name)
if reason != "" {
if findings[1] != "" {
reason = findings[1] + "; " + reason
}
findings[1] = reason
}
return findings, err
}
Expand Down
100 changes: 77 additions & 23 deletions internal/baseline/loaded.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ import (
const goExtension = ".go"

type loadedGo struct {
tree *os.Root
root, moduleDir string
files, allowed map[string]bool
imports map[packageImport]bool
tree *os.Root
root, moduleDir string
files, allowed map[string]bool
listedModules map[string]bool
imports map[packageImport]bool
skipOtherModules bool
}

type packageImport struct{ importer, imported string }
Expand All @@ -32,13 +34,18 @@ type listedPackage struct {
}

type listedModule struct {
Path string
Main bool
Path, Dir string
Main bool
}

func readLoaded(tree *os.Root, rules directiveRules) (loadedGo, error) {
loaded := loadedGo{
tree: tree,
moduleDir: rules.moduleDir,
skipOtherModules: rules.otherModules == otherModulesSkip,
}
if rules.goList == "" {
return loadedGo{tree: tree}, nil
return loaded, nil
}
root, err := physicalPath(rules.root)
if err != nil {
Expand All @@ -48,11 +55,10 @@ func readLoaded(tree *os.Root, rules directiveRules) (loadedGo, error) {
if err != nil {
return loadedGo{}, fmt.Errorf("open go list stream: %w", err)
}
loaded := loadedGo{
tree: tree, root: root, moduleDir: rules.moduleDir,
files: map[string]bool{}, allowed: map[string]bool{},
imports: map[packageImport]bool{},
}
loaded.root = root
loaded.files, loaded.allowed = map[string]bool{}, map[string]bool{}
loaded.listedModules = map[string]bool{}
loaded.imports = map[packageImport]bool{}
return loaded, errors.Join(loaded.decode(file), file.Close())
}

Expand All @@ -67,6 +73,9 @@ func (loaded loadedGo) decode(input io.Reader) error {
if err != nil {
return fmt.Errorf("read go list stream: decode package: %w", err)
}
if err := loaded.indexModule(pkg.Module); err != nil {
return err
}
if err := loaded.index(pkg); err != nil {
return err
}
Expand Down Expand Up @@ -95,6 +104,19 @@ func (loaded loadedGo) index(pkg listedPackage) error {
return nil
}

func (loaded loadedGo) indexModule(module *listedModule) error {
if module == nil || module.Dir == "" || loaded.listedModules[module.Dir] {
return nil
}
dir, err := physicalPath(module.Dir)
if err != nil {
return fmt.Errorf("resolve listed module directory: %w", err)
}
loaded.listedModules[module.Dir] = true
loaded.listedModules[dir] = true
return nil
}

func (loaded loadedGo) indexImports(pkg listedPackage) {
if pkg.Module == nil || !pkg.Module.Main {
return
Expand All @@ -118,27 +140,59 @@ func physicalPath(name string) (string, error) {
return resolved, nil
}

func (loaded loadedGo) rejects(name string) (bool, error) {
func (loaded loadedGo) reason(name string) (string, error) {
name = filepath.FromSlash(name)
if loaded.files == nil || filepath.Ext(name) != goExtension ||
loaded.files[filepath.Join(loaded.root, name)] ||
slices.Contains(strings.Split(filepath.ToSlash(name), "/"), "testdata") {
return false, nil
if filepath.Ext(name) != goExtension {
return "", nil
}
return belongsToModule(loaded.tree, filepath.Dir(name), filepath.FromSlash(loaded.moduleDir))
dir, err := nearestModule(loaded.tree, filepath.Dir(name))
if err != nil {
return "", err
}
if dir != filepath.FromSlash(loaded.moduleDir) {
return loaded.otherModuleReason(dir)
}
if loaded.files != nil && !loaded.files[filepath.Join(loaded.root, name)] &&
!isTestdataPath(name) {
return "not loaded by any GOOS build", nil
}
return "", nil
}

func (loaded loadedGo) otherModuleReason(dir string) (string, error) {
if loaded.skipOtherModules {
return "", nil
}
if loaded.listedModules != nil && isTestdataPath(dir) {
physical, err := physicalPath(filepath.Join(loaded.root, dir))
if err != nil {
return "", fmt.Errorf("resolve testdata module directory: %w", err)
}
if !loaded.listedModules[physical] {
return "", nil
}
}
return fmt.Sprintf(
"belongs to module %q, which this run does not lint",
filepath.ToSlash(dir),
), nil
}

func isTestdataPath(name string) bool {
return slices.Contains(strings.Split(filepath.ToSlash(name), "/"), "testdata")
}

func belongsToModule(root *os.Root, dir, module string) (bool, error) {
for ; dir != module && dir != "."; dir = filepath.Dir(dir) {
func nearestModule(root *os.Root, dir string) (string, error) {
for ; dir != "."; dir = filepath.Dir(dir) {
info, err := root.Stat(filepath.Join(dir, goMod))
if err == nil && info.Mode().IsRegular() {
return false, nil
return dir, nil
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
return false, fmt.Errorf("stat nearest go.mod: %w", err)
return "", fmt.Errorf("stat nearest go.mod: %w", err)
}
}
return dir == module, nil
return dir, nil
}

func (loaded loadedGo) reportImports(log *strings.Builder) int {
Expand Down
57 changes: 57 additions & 0 deletions internal/baseline/loaded_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,14 @@ func TestDirectiveModuleDirectory(t *testing.T) {
args: []string{rootFlag, root, guardFlag, goListFlag, list},
diff: "--- a/b/x.go\n+++ b/b/x.go\n@@ -1,0 +2 @@\n+var x int\n",
}
const otherModuleFlag = "--other-modules"
assertDirectives(
t,
input,
`"b/x.go" 1: belongs to module "b", which this run does not lint`+"\n"+failed,
1,
)
input.args = append(input.args, otherModuleFlag, otherModulesSkip)
assertDirectives(t, input, passed, 0)
input.args = append(input.args, modDirFlag, "b")
assertDirectives(t, input, `"b/x.go" 1: `+missingGo+"\n"+failed, 1)
Expand All @@ -160,6 +168,55 @@ func TestDirectiveModuleDirectory(t *testing.T) {
assertDirectives(t, input, `"b/x.go" 2: `+bare+"\n"+failed, 1)
}

func TestNestedRunRejectsRootEdit(t *testing.T) {
t.Parallel()
root := t.TempDir()
fixtureFile(t, root, moduleFile, productMod)
fixtureFile(t, root, "new.go", sourcePkg)
directiveFixture(t, root, "nested/go.mod", "module example.com/nested\n")
input := directiveTest{
args: []string{rootFlag, root, guardFlag, modDirFlag, "nested"},
diff: addedHunk + "+package main\n",
}
assertDirectives(
t,
input,
`"new.go" 1: belongs to module ".", which this run does not lint`+"\n"+failed,
1,
)
input.args = append(input.args, "--other-modules", "warn")
assertDirectiveError(t, input, "expected --other-modules to be fail or skip")
}

func TestDirectiveTestdataModule(t *testing.T) {
t.Parallel()
root := t.TempDir()
const moduleDir = "fixtures/testdata/fixture"
const file = moduleDir + "/x.go"
fixtureFile(t, root, moduleFile, productMod)
directiveFixture(t, root, moduleDir+"/go.mod", "module example.com/fixture\n")
directiveFixture(t, root, file, sourcePkg)
input := directiveTest{
args: []string{rootFlag, root, guardFlag, goListFlag},
diff: "--- /dev/null\n+++ b/" + file + "\n@@ -0,0 +1 @@\n+package main\n",
}
emptyList := fixtureFile(t, root, "empty.json", "")
input.args = append(input.args, emptyList)
assertDirectives(t, input, passed, 0)

record := fmt.Sprintf(
`{"ImportPath":"example.com/fixture/dep","Module":{"Path":"example.com/fixture","Dir":%q}}`,
filepath.Join(root, moduleDir),
)
input.args[len(input.args)-1] = fixtureFile(t, root, "dependency.json", record)
want := fmt.Sprintf(
"%q 1: belongs to module %q, which this run does not lint\n",
file,
moduleDir,
)
assertDirectives(t, input, want+failed, 1)
}

func TestDirectiveAddedSymlink(t *testing.T) {
t.Parallel()
root := t.TempDir()
Expand Down
6 changes: 5 additions & 1 deletion lint-baseline/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ inputs:
working-directory:
description: Directory containing the caller's go.mod.
default: .
other-modules:
description: Fail or skip when changed Go files belong to another module.
default: fail
guarded-linters:
description: Comma-separated linters that new nolint directives may not suppress.
default: cyclop,funlen,gocognit,gocyclo,nestif,maintidx,revive
Expand Down Expand Up @@ -138,6 +141,7 @@ runs:
ALLOW_GENERATED: ${{ inputs.allow-generated }}
ALLOW_NEW_MODULES: ${{ inputs.allow-new-modules }}
MODULE_DIR: ${{ inputs.working-directory }}
OTHER_MODULES: ${{ inputs.other-modules }}
DEAD_CODE: ${{ inputs.dead-code }}
run: |
tags=$("$RUNNER_TEMP/lint-baseline" config-check --config "$CONFIG" --linters "$BASELINE_LINTERS")
Expand All @@ -156,7 +160,7 @@ runs:
"$PR_MERGE_BASE...HEAD" -- . |
"$RUNNER_TEMP/lint-baseline" directives --root "$GITHUB_WORKSPACE" --guarded "$GUARDED_LINTERS" \
--allow-generated="$ALLOW_GENERATED" --allow-new-modules="$ALLOW_NEW_MODULES" \
--go-list "$RUNNER_TEMP/golist.json" --module-dir "$MODULE_DIR"
--go-list "$RUNNER_TEMP/golist.json" --module-dir "$MODULE_DIR" --other-modules "$OTHER_MODULES"

probe=$(mktemp -d /tmp/lint-baseline.XXXXXX)
trap 'rm -rf -- "$probe"' EXIT
Expand Down