Skip to content

Commit dc76c47

Browse files
author
Jay Conrod
committed
cmd/go/internal/load: convert two global flags to an options struct
PackageOpts is a new struct type accepted by package loading functions. It initially has two fields: IgnoreImports, and ModResolveTests. Previously, these were global variables set by clients. We'll add more to this in the future. For #40775 Change-Id: I6956e56502de836d3815ce788bdf16fc5f3e5338 Reviewed-on: https://go-review.googlesource.com/c/go/+/310669 Trust: Jay Conrod <[email protected]> Run-TryBot: Jay Conrod <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Bryan C. Mills <[email protected]>
1 parent cde9284 commit dc76c47

File tree

14 files changed

+85
-84
lines changed

14 files changed

+85
-84
lines changed

src/cmd/go/internal/clean/clean.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ func runClean(ctx context.Context, cmd *base.Command, args []string) {
117117
}
118118

119119
if cleanPkg {
120-
for _, pkg := range load.PackagesAndErrors(ctx, args) {
120+
for _, pkg := range load.PackagesAndErrors(ctx, load.PackageOpts{}, args) {
121121
clean(pkg)
122122
}
123123
}

src/cmd/go/internal/fix/fix.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ See also: go fmt, go vet.
3333
}
3434

3535
func runFix(ctx context.Context, cmd *base.Command, args []string) {
36-
pkgs := load.PackagesAndErrors(ctx, args)
36+
pkgs := load.PackagesAndErrors(ctx, load.PackageOpts{}, args)
3737
w := 0
3838
for _, pkg := range pkgs {
3939
if pkg.Error != nil {

src/cmd/go/internal/fmtcmd/fmt.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func runFmt(ctx context.Context, cmd *base.Command, args []string) {
6565
}
6666
}()
6767
}
68-
for _, pkg := range load.PackagesAndErrors(ctx, args) {
68+
for _, pkg := range load.PackagesAndErrors(ctx, load.PackageOpts{}, args) {
6969
if modload.Enabled() && pkg.Module != nil && !pkg.Module.Main {
7070
if !printed {
7171
fmt.Fprintf(os.Stderr, "go: not formatting packages in dependency modules\n")

src/cmd/go/internal/generate/generate.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,6 @@ func init() {
161161
}
162162

163163
func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
164-
load.IgnoreImports = true
165-
166164
if generateRunFlag != "" {
167165
var err error
168166
generateRunRE, err = regexp.Compile(generateRunFlag)
@@ -175,7 +173,8 @@ func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
175173

176174
// Even if the arguments are .go files, this loop suffices.
177175
printed := false
178-
for _, pkg := range load.PackagesAndErrors(ctx, args) {
176+
pkgOpts := load.PackageOpts{IgnoreImports: true}
177+
for _, pkg := range load.PackagesAndErrors(ctx, pkgOpts, args) {
179178
if modload.Enabled() && pkg.Module != nil && !pkg.Module.Main {
180179
if !printed {
181180
fmt.Fprintf(os.Stderr, "go: not generating in packages in dependency modules\n")

src/cmd/go/internal/get/get.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) {
173173
// everything.
174174
load.ClearPackageCache()
175175

176-
pkgs := load.PackagesAndErrors(ctx, args)
176+
pkgs := load.PackagesAndErrors(ctx, load.PackageOpts{}, args)
177177
load.CheckPackageErrors(pkgs)
178178

179179
// Phase 3. Install.
@@ -248,9 +248,9 @@ func download(arg string, parent *load.Package, stk *load.ImportStack, mode int)
248248
load1 := func(path string, mode int) *load.Package {
249249
if parent == nil {
250250
mode := 0 // don't do module or vendor resolution
251-
return load.LoadImport(context.TODO(), path, base.Cwd, nil, stk, nil, mode)
251+
return load.LoadImport(context.TODO(), load.PackageOpts{}, path, base.Cwd, nil, stk, nil, mode)
252252
}
253-
return load.LoadImport(context.TODO(), path, parent.Dir, parent, stk, nil, mode|load.ResolveModule)
253+
return load.LoadImport(context.TODO(), load.PackageOpts{}, path, parent.Dir, parent, stk, nil, mode|load.ResolveModule)
254254
}
255255

256256
p := load1(arg, mode)

src/cmd/go/internal/list/list.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,6 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
339339
base.Fatalf("go list -f cannot be used with -json")
340340
}
341341

342-
load.ModResolveTests = *listTest
343342
work.BuildInit()
344343
out := newTrackingWriter(os.Stdout)
345344
defer out.w.Flush()
@@ -498,8 +497,11 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
498497
base.Fatalf("go list -test cannot be used with -find")
499498
}
500499

501-
load.IgnoreImports = *listFind
502-
pkgs := load.PackagesAndErrors(ctx, args)
500+
pkgOpts := load.PackageOpts{
501+
IgnoreImports: *listFind,
502+
ModResolveTests: *listTest,
503+
}
504+
pkgs := load.PackagesAndErrors(ctx, pkgOpts, args)
503505
if !*listE {
504506
w := 0
505507
for _, pkg := range pkgs {
@@ -536,9 +538,9 @@ func runList(ctx context.Context, cmd *base.Command, args []string) {
536538
var pmain, ptest, pxtest *load.Package
537539
var err error
538540
if *listE {
539-
pmain, ptest, pxtest = load.TestPackagesAndErrors(ctx, p, nil)
541+
pmain, ptest, pxtest = load.TestPackagesAndErrors(ctx, pkgOpts, p, nil)
540542
} else {
541-
pmain, ptest, pxtest, err = load.TestPackagesFor(ctx, p, nil)
543+
pmain, ptest, pxtest, err = load.TestPackagesFor(ctx, pkgOpts, p, nil)
542544
if err != nil {
543545
base.Errorf("can't load test package: %s", err)
544546
}

src/cmd/go/internal/load/pkg.go

+45-43
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,6 @@ import (
4141
"golang.org/x/mod/module"
4242
)
4343

44-
var IgnoreImports bool // control whether we ignore imports in packages
45-
4644
// A Package describes a single package found in a directory.
4745
type Package struct {
4846
PackagePublic // visible in 'go list'
@@ -345,7 +343,7 @@ type CoverVar struct {
345343
Var string // name of count struct
346344
}
347345

348-
func (p *Package) copyBuild(pp *build.Package) {
346+
func (p *Package) copyBuild(opts PackageOpts, pp *build.Package) {
349347
p.Internal.Build = pp
350348

351349
if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
@@ -394,7 +392,7 @@ func (p *Package) copyBuild(pp *build.Package) {
394392
p.TestImports = pp.TestImports
395393
p.XTestGoFiles = pp.XTestGoFiles
396394
p.XTestImports = pp.XTestImports
397-
if IgnoreImports {
395+
if opts.IgnoreImports {
398396
p.Imports = nil
399397
p.Internal.RawImports = nil
400398
p.TestImports = nil
@@ -601,7 +599,7 @@ func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
601599
})
602600
packageDataCache.Delete(p.ImportPath)
603601
}
604-
return LoadImport(context.TODO(), arg, base.Cwd, nil, stk, nil, 0)
602+
return LoadImport(context.TODO(), PackageOpts{}, arg, base.Cwd, nil, stk, nil, 0)
605603
}
606604

607605
// dirToImportPath returns the pseudo-import path we use for a package
@@ -653,11 +651,11 @@ const (
653651
// LoadImport does not set tool flags and should only be used by
654652
// this package, as part of a bigger load operation, and by GOPATH-based "go get".
655653
// TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
656-
func LoadImport(ctx context.Context, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
657-
return loadImport(ctx, nil, path, srcDir, parent, stk, importPos, mode)
654+
func LoadImport(ctx context.Context, opts PackageOpts, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
655+
return loadImport(ctx, opts, nil, path, srcDir, parent, stk, importPos, mode)
658656
}
659657

660-
func loadImport(ctx context.Context, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
658+
func loadImport(ctx context.Context, opts PackageOpts, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
661659
if path == "" {
662660
panic("LoadImport called with empty package path")
663661
}
@@ -670,8 +668,8 @@ func loadImport(ctx context.Context, pre *preload, path, srcDir string, parent *
670668
parentIsStd = parent.Standard
671669
}
672670
bp, loaded, err := loadPackageData(ctx, path, parentPath, srcDir, parentRoot, parentIsStd, mode)
673-
if loaded && pre != nil && !IgnoreImports {
674-
pre.preloadImports(ctx, bp.Imports, bp)
671+
if loaded && pre != nil && !opts.IgnoreImports {
672+
pre.preloadImports(ctx, opts, bp.Imports, bp)
675673
}
676674
if bp == nil {
677675
p := &Package{
@@ -710,7 +708,7 @@ func loadImport(ctx context.Context, pre *preload, path, srcDir string, parent *
710708
// Load package.
711709
// loadPackageData may return bp != nil even if an error occurs,
712710
// in order to return partial information.
713-
p.load(ctx, path, stk, importPos, bp, err)
711+
p.load(ctx, opts, path, stk, importPos, bp, err)
714712

715713
if !cfg.ModulesEnabled && path != cleanImport(path) {
716714
p.Error = &PackageError{
@@ -980,7 +978,7 @@ func newPreload() *preload {
980978
// preloadMatches loads data for package paths matched by patterns.
981979
// When preloadMatches returns, some packages may not be loaded yet, but
982980
// loadPackageData and loadImport are always safe to call.
983-
func (pre *preload) preloadMatches(ctx context.Context, matches []*search.Match) {
981+
func (pre *preload) preloadMatches(ctx context.Context, opts PackageOpts, matches []*search.Match) {
984982
for _, m := range matches {
985983
for _, pkg := range m.Pkgs {
986984
select {
@@ -991,8 +989,8 @@ func (pre *preload) preloadMatches(ctx context.Context, matches []*search.Match)
991989
mode := 0 // don't use vendoring or module import resolution
992990
bp, loaded, err := loadPackageData(ctx, pkg, "", base.Cwd, "", false, mode)
993991
<-pre.sema
994-
if bp != nil && loaded && err == nil && !IgnoreImports {
995-
pre.preloadImports(ctx, bp.Imports, bp)
992+
if bp != nil && loaded && err == nil && !opts.IgnoreImports {
993+
pre.preloadImports(ctx, opts, bp.Imports, bp)
996994
}
997995
}(pkg)
998996
}
@@ -1003,7 +1001,7 @@ func (pre *preload) preloadMatches(ctx context.Context, matches []*search.Match)
10031001
// preloadImports queues a list of imports for preloading.
10041002
// When preloadImports returns, some packages may not be loaded yet,
10051003
// but loadPackageData and loadImport are always safe to call.
1006-
func (pre *preload) preloadImports(ctx context.Context, imports []string, parent *build.Package) {
1004+
func (pre *preload) preloadImports(ctx context.Context, opts PackageOpts, imports []string, parent *build.Package) {
10071005
parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
10081006
for _, path := range imports {
10091007
if path == "C" || path == "unsafe" {
@@ -1016,8 +1014,8 @@ func (pre *preload) preloadImports(ctx context.Context, imports []string, parent
10161014
go func(path string) {
10171015
bp, loaded, err := loadPackageData(ctx, path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
10181016
<-pre.sema
1019-
if bp != nil && loaded && err == nil && !IgnoreImports {
1020-
pre.preloadImports(ctx, bp.Imports, bp)
1017+
if bp != nil && loaded && err == nil && !opts.IgnoreImports {
1018+
pre.preloadImports(ctx, opts, bp.Imports, bp)
10211019
}
10221020
}(path)
10231021
}
@@ -1667,8 +1665,8 @@ func (p *Package) DefaultExecName() string {
16671665
// load populates p using information from bp, err, which should
16681666
// be the result of calling build.Context.Import.
16691667
// stk contains the import stack, not including path itself.
1670-
func (p *Package) load(ctx context.Context, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
1671-
p.copyBuild(bp)
1668+
func (p *Package) load(ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
1669+
p.copyBuild(opts, bp)
16721670

16731671
// The localPrefix is the path we interpret ./ imports relative to.
16741672
// Synthesized main packages sometimes override this.
@@ -1887,7 +1885,7 @@ func (p *Package) load(ctx context.Context, path string, stk *ImportStack, impor
18871885
if path == "C" {
18881886
continue
18891887
}
1890-
p1 := LoadImport(ctx, path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1888+
p1 := LoadImport(ctx, opts, path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
18911889

18921890
path = p1.ImportPath
18931891
importPaths[i] = path
@@ -2334,7 +2332,7 @@ func PackageList(roots []*Package) []*Package {
23342332
// TestPackageList returns the list of packages in the dag rooted at roots
23352333
// as visited in a depth-first post-order traversal, including the test
23362334
// imports of the roots. This ignores errors in test packages.
2337-
func TestPackageList(ctx context.Context, roots []*Package) []*Package {
2335+
func TestPackageList(ctx context.Context, opts PackageOpts, roots []*Package) []*Package {
23382336
seen := map[*Package]bool{}
23392337
all := []*Package{}
23402338
var walk func(*Package)
@@ -2350,7 +2348,7 @@ func TestPackageList(ctx context.Context, roots []*Package) []*Package {
23502348
}
23512349
walkTest := func(root *Package, path string) {
23522350
var stk ImportStack
2353-
p1 := LoadImport(ctx, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
2351+
p1 := LoadImport(ctx, opts, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
23542352
if p1.Error == nil {
23552353
walk(p1)
23562354
}
@@ -2373,22 +2371,26 @@ func TestPackageList(ctx context.Context, roots []*Package) []*Package {
23732371
// TODO(jayconrod): delete this function and set flags automatically
23742372
// in LoadImport instead.
23752373
func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
2376-
p := LoadImport(context.TODO(), path, srcDir, parent, stk, importPos, mode)
2374+
p := LoadImport(context.TODO(), PackageOpts{}, path, srcDir, parent, stk, importPos, mode)
23772375
setToolFlags(p)
23782376
return p
23792377
}
23802378

2381-
// ModResolveTests indicates whether calls to the module loader should also
2382-
// resolve test dependencies of the requested packages.
2383-
//
2384-
// If ModResolveTests is true, then the module loader needs to resolve test
2385-
// dependencies at the same time as packages; otherwise, the test dependencies
2386-
// of those packages could be missing, and resolving those missing dependencies
2387-
// could change the selected versions of modules that provide other packages.
2388-
//
2389-
// TODO(#40775): Change this from a global variable to an explicit function
2390-
// argument where needed.
2391-
var ModResolveTests bool
2379+
// PackageOpts control the behavior of PackagesAndErrors and other package
2380+
// loading functions.
2381+
type PackageOpts struct {
2382+
// IgnoreImports controls whether we ignore imports when loading packages.
2383+
IgnoreImports bool
2384+
2385+
// ModResolveTests indicates whether calls to the module loader should also
2386+
// resolve test dependencies of the requested packages.
2387+
//
2388+
// If ModResolveTests is true, then the module loader needs to resolve test
2389+
// dependencies at the same time as packages; otherwise, the test dependencies
2390+
// of those packages could be missing, and resolving those missing dependencies
2391+
// could change the selected versions of modules that provide other packages.
2392+
ModResolveTests bool
2393+
}
23922394

23932395
// PackagesAndErrors returns the packages named by the command line arguments
23942396
// 'patterns'. If a named package cannot be loaded, PackagesAndErrors returns
@@ -2398,7 +2400,7 @@ var ModResolveTests bool
23982400
//
23992401
// To obtain a flat list of packages, use PackageList.
24002402
// To report errors loading packages, use ReportPackageErrors.
2401-
func PackagesAndErrors(ctx context.Context, patterns []string) []*Package {
2403+
func PackagesAndErrors(ctx context.Context, opts PackageOpts, patterns []string) []*Package {
24022404
ctx, span := trace.StartSpan(ctx, "load.PackagesAndErrors")
24032405
defer span.Done()
24042406

@@ -2410,19 +2412,19 @@ func PackagesAndErrors(ctx context.Context, patterns []string) []*Package {
24102412
// We need to test whether the path is an actual Go file and not a
24112413
// package path or pattern ending in '.go' (see golang.org/issue/34653).
24122414
if fi, err := fsys.Stat(p); err == nil && !fi.IsDir() {
2413-
return []*Package{GoFilesPackage(ctx, patterns)}
2415+
return []*Package{GoFilesPackage(ctx, opts, patterns)}
24142416
}
24152417
}
24162418
}
24172419

24182420
var matches []*search.Match
24192421
if modload.Init(); cfg.ModulesEnabled {
2420-
loadOpts := modload.PackageOpts{
2422+
modOpts := modload.PackageOpts{
24212423
ResolveMissingImports: true,
2422-
LoadTests: ModResolveTests,
2424+
LoadTests: opts.ModResolveTests,
24232425
SilenceErrors: true,
24242426
}
2425-
matches, _ = modload.LoadPackages(ctx, loadOpts, patterns...)
2427+
matches, _ = modload.LoadPackages(ctx, modOpts, patterns...)
24262428
} else {
24272429
matches = search.ImportPaths(patterns)
24282430
}
@@ -2435,14 +2437,14 @@ func PackagesAndErrors(ctx context.Context, patterns []string) []*Package {
24352437

24362438
pre := newPreload()
24372439
defer pre.flush()
2438-
pre.preloadMatches(ctx, matches)
2440+
pre.preloadMatches(ctx, opts, matches)
24392441

24402442
for _, m := range matches {
24412443
for _, pkg := range m.Pkgs {
24422444
if pkg == "" {
24432445
panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
24442446
}
2445-
p := loadImport(ctx, pre, pkg, base.Cwd, nil, &stk, nil, 0)
2447+
p := loadImport(ctx, opts, pre, pkg, base.Cwd, nil, &stk, nil, 0)
24462448
p.Match = append(p.Match, m.Pattern())
24472449
p.Internal.CmdlinePkg = true
24482450
if m.IsLiteral() {
@@ -2538,7 +2540,7 @@ func setToolFlags(pkgs ...*Package) {
25382540
// GoFilesPackage creates a package for building a collection of Go files
25392541
// (typically named on the command line). The target is named p.a for
25402542
// package p or named after the first Go file for package main.
2541-
func GoFilesPackage(ctx context.Context, gofiles []string) *Package {
2543+
func GoFilesPackage(ctx context.Context, opts PackageOpts, gofiles []string) *Package {
25422544
modload.Init()
25432545

25442546
for _, f := range gofiles {
@@ -2602,7 +2604,7 @@ func GoFilesPackage(ctx context.Context, gofiles []string) *Package {
26022604
pkg := new(Package)
26032605
pkg.Internal.Local = true
26042606
pkg.Internal.CmdlineFiles = true
2605-
pkg.load(ctx, "command-line-arguments", &stk, nil, bp, err)
2607+
pkg.load(ctx, opts, "command-line-arguments", &stk, nil, bp, err)
26062608
pkg.Internal.LocalPrefix = dirToImportPath(dir)
26072609
pkg.ImportPath = "command-line-arguments"
26082610
pkg.Target = ""

0 commit comments

Comments
 (0)