diff --git a/errcheck/errcheck.go b/errcheck/errcheck.go index 74bfaf0..163e345 100644 --- a/errcheck/errcheck.go +++ b/errcheck/errcheck.go @@ -187,6 +187,9 @@ type Checker struct { // Tags are a list of build tags to use. Tags []string + + // The mod flag for go build. + Mod string } // loadPackages is used for testing. @@ -197,10 +200,14 @@ var loadPackages = func(cfg *packages.Config, paths ...string) ([]*packages.Pack // LoadPackages loads all the packages in all the paths provided. It uses the // exclusions and build tags provided to by the user when loading the packages. func (c *Checker) LoadPackages(paths ...string) ([]*packages.Package, error) { + buildFlags := []string{fmtTags(c.Tags)} + if c.Mod != "" { + buildFlags = append(buildFlags, fmt.Sprintf("-mod=%s", c.Mod)) + } cfg := &packages.Config{ Mode: packages.LoadAllSyntax, Tests: !c.Exclusions.TestFiles, - BuildFlags: []string{fmtTags(c.Tags)}, + BuildFlags: buildFlags, } return loadPackages(cfg, paths...) } diff --git a/errcheck/errcheck_test.go b/errcheck/errcheck_test.go index 472c023..6cecc84 100644 --- a/errcheck/errcheck_test.go +++ b/errcheck/errcheck_test.go @@ -364,6 +364,7 @@ require github.com/testlog v0.0.0 cases := []struct { withoutGeneratedCode bool numExpectedErrs int + withModVendor bool }{ // basic case has one error { @@ -375,16 +376,32 @@ require github.com/testlog v0.0.0 withoutGeneratedCode: true, numExpectedErrs: 0, }, + // using checker.Mod="vendor" + { + withoutGeneratedCode: false, + numExpectedErrs: 1, + withModVendor: true, + }, } for i, test := range cases { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { var checker Checker checker.Exclusions.GeneratedFiles = test.withoutGeneratedCode + if test.withModVendor { + if os.Getenv("GO111MODULE") == "off" { + t.Skip("-mod=vendor doesn't work if modules are disabled") + } + checker.Mod = "vendor" + } loadPackages = func(cfg *packages.Config, paths ...string) ([]*packages.Package, error) { cfg.Env = append(os.Environ(), - "GOPATH="+tmpGopath, - "GOFLAGS=-mod=vendor") + "GOPATH="+tmpGopath) + + if !test.withModVendor { + cfg.Env = append(cfg.Env, + "GOFLAGS=-mod=vendor") + } cfg.Dir = testVendorDir pkgs, err := packages.Load(cfg, paths...) return pkgs, err diff --git a/main.go b/main.go index 6369927..641aa54 100644 --- a/main.go +++ b/main.go @@ -201,6 +201,8 @@ func parseFlags(checker *errcheck.Checker, args []string) ([]string, int) { var excludeOnly bool flags.BoolVar(&excludeOnly, "excludeonly", false, "Use only excludes from -exclude file") + flags.StringVar(&checker.Mod, "mod", "", "module download mode to use: readonly or vendor. See 'go help modules' for more.") + if err := flags.Parse(args[1:]); err != nil { return nil, exitFatalError }