Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/go/internal/modload/load.go

Documentation: cmd/go/internal/modload

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package modload
     6  
     7  // This file contains the module-mode package loader, as well as some accessory
     8  // functions pertaining to the package import graph.
     9  //
    10  // There are two exported entry points into package loading — LoadPackages and
    11  // ImportFromFiles — both implemented in terms of loadFromRoots, which itself
    12  // manipulates an instance of the loader struct.
    13  //
    14  // Although most of the loading state is maintained in the loader struct,
    15  // one key piece - the build list - is a global, so that it can be modified
    16  // separate from the loading operation, such as during "go get"
    17  // upgrades/downgrades or in "go mod" operations.
    18  // TODO(#40775): It might be nice to make the loader take and return
    19  // a buildList rather than hard-coding use of the global.
    20  //
    21  // Loading is an iterative process. On each iteration, we try to load the
    22  // requested packages and their transitive imports, then try to resolve modules
    23  // for any imported packages that are still missing.
    24  //
    25  // The first step of each iteration identifies a set of “root” packages.
    26  // Normally the root packages are exactly those matching the named pattern
    27  // arguments. However, for the "all" meta-pattern, the final set of packages is
    28  // computed from the package import graph, and therefore cannot be an initial
    29  // input to loading that graph. Instead, the root packages for the "all" pattern
    30  // are those contained in the main module, and allPatternIsRoot parameter to the
    31  // loader instructs it to dynamically expand those roots to the full "all"
    32  // pattern as loading progresses.
    33  //
    34  // The pkgInAll flag on each loadPkg instance tracks whether that
    35  // package is known to match the "all" meta-pattern.
    36  // A package matches the "all" pattern if:
    37  // 	- it is in the main module, or
    38  // 	- it is imported by any test in the main module, or
    39  // 	- it is imported by another package in "all", or
    40  // 	- the main module specifies a go version ≤ 1.15, and the package is imported
    41  // 	  by a *test of* another package in "all".
    42  //
    43  // When we implement lazy loading, we will record the modules providing packages
    44  // in "all" even when we are only loading individual packages, so we set the
    45  // pkgInAll flag regardless of the whether the "all" pattern is a root.
    46  // (This is necessary to maintain the “import invariant” described in
    47  // https://golang.org/design/36460-lazy-module-loading.)
    48  //
    49  // Because "go mod vendor" prunes out the tests of vendored packages, the
    50  // behavior of the "all" pattern with -mod=vendor in Go 1.11–1.15 is the same
    51  // as the "all" pattern (regardless of the -mod flag) in 1.16+.
    52  // The allClosesOverTests parameter to the loader indicates whether the "all"
    53  // pattern should close over tests (as in Go 1.11–1.15) or stop at only those
    54  // packages transitively imported by the packages and tests in the main module
    55  // ("all" in Go 1.16+ and "go mod vendor" in Go 1.11+).
    56  //
    57  // Note that it is possible for a loaded package NOT to be in "all" even when we
    58  // are loading the "all" pattern. For example, packages that are transitive
    59  // dependencies of other roots named on the command line must be loaded, but are
    60  // not in "all". (The mod_notall test illustrates this behavior.)
    61  // Similarly, if the LoadTests flag is set but the "all" pattern does not close
    62  // over test dependencies, then when we load the test of a package that is in
    63  // "all" but outside the main module, the dependencies of that test will not
    64  // necessarily themselves be in "all". (That configuration does not arise in Go
    65  // 1.11–1.15, but it will be possible in Go 1.16+.)
    66  //
    67  // Loading proceeds from the roots, using a parallel work-queue with a limit on
    68  // the amount of active work (to avoid saturating disks, CPU cores, and/or
    69  // network connections). Each package is added to the queue the first time it is
    70  // imported by another package. When we have finished identifying the imports of
    71  // a package, we add the test for that package if it is needed. A test may be
    72  // needed if:
    73  // 	- the package matches a root pattern and tests of the roots were requested, or
    74  // 	- the package is in the main module and the "all" pattern is requested
    75  // 	  (because the "all" pattern includes the dependencies of tests in the main
    76  // 	  module), or
    77  // 	- the package is in "all" and the definition of "all" we are using includes
    78  // 	  dependencies of tests (as is the case in Go ≤1.15).
    79  //
    80  // After all available packages have been loaded, we examine the results to
    81  // identify any requested or imported packages that are still missing, and if
    82  // so, which modules we could add to the module graph in order to make the
    83  // missing packages available. We add those to the module graph and iterate,
    84  // until either all packages resolve successfully or we cannot identify any
    85  // module that would resolve any remaining missing package.
    86  //
    87  // If the main module is “tidy” (that is, if "go mod tidy" is a no-op for it)
    88  // and all requested packages are in "all", then loading completes in a single
    89  // iteration.
    90  // TODO(bcmills): We should also be able to load in a single iteration if the
    91  // requested packages all come from modules that are themselves tidy, regardless
    92  // of whether those packages are in "all". Today, that requires two iterations
    93  // if those packages are not found in existing dependencies of the main module.
    94  
    95  import (
    96  	"bytes"
    97  	"context"
    98  	"errors"
    99  	"fmt"
   100  	"go/build"
   101  	"io/fs"
   102  	"os"
   103  	"path"
   104  	pathpkg "path"
   105  	"path/filepath"
   106  	"reflect"
   107  	"runtime"
   108  	"sort"
   109  	"strings"
   110  	"sync"
   111  	"sync/atomic"
   112  
   113  	"cmd/go/internal/base"
   114  	"cmd/go/internal/cfg"
   115  	"cmd/go/internal/fsys"
   116  	"cmd/go/internal/imports"
   117  	"cmd/go/internal/modfetch"
   118  	"cmd/go/internal/mvs"
   119  	"cmd/go/internal/par"
   120  	"cmd/go/internal/search"
   121  	"cmd/go/internal/str"
   122  
   123  	"golang.org/x/mod/module"
   124  )
   125  
   126  // loaded is the most recently-used package loader.
   127  // It holds details about individual packages.
   128  var loaded *loader
   129  
   130  // PackageOpts control the behavior of the LoadPackages function.
   131  type PackageOpts struct {
   132  	// Tags are the build tags in effect (as interpreted by the
   133  	// cmd/go/internal/imports package).
   134  	// If nil, treated as equivalent to imports.Tags().
   135  	Tags map[string]bool
   136  
   137  	// ResolveMissingImports indicates that we should attempt to add module
   138  	// dependencies as needed to resolve imports of packages that are not found.
   139  	//
   140  	// For commands that support the -mod flag, resolving imports may still fail
   141  	// if the flag is set to "readonly" (the default) or "vendor".
   142  	ResolveMissingImports bool
   143  
   144  	// AllowPackage, if non-nil, is called after identifying the module providing
   145  	// each package. If AllowPackage returns a non-nil error, that error is set
   146  	// for the package, and the imports and test of that package will not be
   147  	// loaded.
   148  	//
   149  	// AllowPackage may be invoked concurrently by multiple goroutines,
   150  	// and may be invoked multiple times for a given package path.
   151  	AllowPackage func(ctx context.Context, path string, mod module.Version) error
   152  
   153  	// LoadTests loads the test dependencies of each package matching a requested
   154  	// pattern. If ResolveMissingImports is also true, test dependencies will be
   155  	// resolved if missing.
   156  	LoadTests bool
   157  
   158  	// UseVendorAll causes the "all" package pattern to be interpreted as if
   159  	// running "go mod vendor" (or building with "-mod=vendor").
   160  	//
   161  	// This is a no-op for modules that declare 'go 1.16' or higher, for which this
   162  	// is the default (and only) interpretation of the "all" pattern in module mode.
   163  	UseVendorAll bool
   164  
   165  	// AllowErrors indicates that LoadPackages should not terminate the process if
   166  	// an error occurs.
   167  	AllowErrors bool
   168  
   169  	// SilenceErrors indicates that LoadPackages should not print errors
   170  	// that occur while loading packages. SilenceErrors implies AllowErrors.
   171  	SilenceErrors bool
   172  
   173  	// SilenceUnmatchedWarnings suppresses the warnings normally emitted for
   174  	// patterns that did not match any packages.
   175  	SilenceUnmatchedWarnings bool
   176  }
   177  
   178  // LoadPackages identifies the set of packages matching the given patterns and
   179  // loads the packages in the import graph rooted at that set.
   180  func LoadPackages(ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string) {
   181  	LoadModFile(ctx)
   182  	if opts.Tags == nil {
   183  		opts.Tags = imports.Tags()
   184  	}
   185  
   186  	patterns = search.CleanPatterns(patterns)
   187  	matches = make([]*search.Match, 0, len(patterns))
   188  	allPatternIsRoot := false
   189  	for _, pattern := range patterns {
   190  		matches = append(matches, search.NewMatch(pattern))
   191  		if pattern == "all" {
   192  			allPatternIsRoot = true
   193  		}
   194  	}
   195  
   196  	updateMatches := func(ld *loader) {
   197  		for _, m := range matches {
   198  			switch {
   199  			case m.IsLocal():
   200  				// Evaluate list of file system directories on first iteration.
   201  				if m.Dirs == nil {
   202  					matchLocalDirs(m)
   203  				}
   204  
   205  				// Make a copy of the directory list and translate to import paths.
   206  				// Note that whether a directory corresponds to an import path
   207  				// changes as the build list is updated, and a directory can change
   208  				// from not being in the build list to being in it and back as
   209  				// the exact version of a particular module increases during
   210  				// the loader iterations.
   211  				m.Pkgs = m.Pkgs[:0]
   212  				for _, dir := range m.Dirs {
   213  					pkg, err := resolveLocalPackage(dir)
   214  					if err != nil {
   215  						if !m.IsLiteral() && (err == errPkgIsBuiltin || err == errPkgIsGorootSrc) {
   216  							continue // Don't include "builtin" or GOROOT/src in wildcard patterns.
   217  						}
   218  
   219  						// If we're outside of a module, ensure that the failure mode
   220  						// indicates that.
   221  						ModRoot()
   222  
   223  						if ld != nil {
   224  							m.AddError(err)
   225  						}
   226  						continue
   227  					}
   228  					m.Pkgs = append(m.Pkgs, pkg)
   229  				}
   230  
   231  			case m.IsLiteral():
   232  				m.Pkgs = []string{m.Pattern()}
   233  
   234  			case strings.Contains(m.Pattern(), "..."):
   235  				m.Errs = m.Errs[:0]
   236  				matchPackages(ctx, m, opts.Tags, includeStd, buildList)
   237  
   238  			case m.Pattern() == "all":
   239  				if ld == nil {
   240  					// The initial roots are the packages in the main module.
   241  					// loadFromRoots will expand that to "all".
   242  					m.Errs = m.Errs[:0]
   243  					matchPackages(ctx, m, opts.Tags, omitStd, []module.Version{Target})
   244  				} else {
   245  					// Starting with the packages in the main module,
   246  					// enumerate the full list of "all".
   247  					m.Pkgs = ld.computePatternAll()
   248  				}
   249  
   250  			case m.Pattern() == "std" || m.Pattern() == "cmd":
   251  				if m.Pkgs == nil {
   252  					m.MatchPackages() // Locate the packages within GOROOT/src.
   253  				}
   254  
   255  			default:
   256  				panic(fmt.Sprintf("internal error: modload missing case for pattern %s", m.Pattern()))
   257  			}
   258  		}
   259  	}
   260  
   261  	loaded = loadFromRoots(loaderParams{
   262  		PackageOpts: opts,
   263  
   264  		allClosesOverTests: index.allPatternClosesOverTests() && !opts.UseVendorAll,
   265  		allPatternIsRoot:   allPatternIsRoot,
   266  
   267  		listRoots: func() (roots []string) {
   268  			updateMatches(nil)
   269  			for _, m := range matches {
   270  				roots = append(roots, m.Pkgs...)
   271  			}
   272  			return roots
   273  		},
   274  	})
   275  
   276  	// One last pass to finalize wildcards.
   277  	updateMatches(loaded)
   278  
   279  	// Report errors, if any.
   280  	checkMultiplePaths()
   281  	for _, pkg := range loaded.pkgs {
   282  		if pkg.err != nil {
   283  			if sumErr := (*ImportMissingSumError)(nil); errors.As(pkg.err, &sumErr) {
   284  				if importer := pkg.stack; importer != nil {
   285  					sumErr.importer = importer.path
   286  					sumErr.importerVersion = importer.mod.Version
   287  					sumErr.importerIsTest = importer.testOf != nil
   288  				}
   289  			}
   290  
   291  			if !opts.SilenceErrors {
   292  				if opts.AllowErrors {
   293  					fmt.Fprintf(os.Stderr, "%s: %v\n", pkg.stackText(), pkg.err)
   294  				} else {
   295  					base.Errorf("%s: %v", pkg.stackText(), pkg.err)
   296  				}
   297  			}
   298  		}
   299  		if !pkg.isTest() {
   300  			loadedPackages = append(loadedPackages, pkg.path)
   301  		}
   302  	}
   303  	if !opts.SilenceErrors {
   304  		// Also list errors in matching patterns (such as directory permission
   305  		// errors for wildcard patterns).
   306  		for _, match := range matches {
   307  			for _, err := range match.Errs {
   308  				if opts.AllowErrors {
   309  					fmt.Fprintf(os.Stderr, "%v\n", err)
   310  				} else {
   311  					base.Errorf("%v", err)
   312  				}
   313  			}
   314  		}
   315  	}
   316  	base.ExitIfErrors()
   317  
   318  	if !opts.SilenceUnmatchedWarnings {
   319  		search.WarnUnmatched(matches)
   320  	}
   321  
   322  	// Success! Update go.mod (if needed) and return the results.
   323  	WriteGoMod()
   324  	sort.Strings(loadedPackages)
   325  	return matches, loadedPackages
   326  }
   327  
   328  // matchLocalDirs is like m.MatchDirs, but tries to avoid scanning directories
   329  // outside of the standard library and active modules.
   330  func matchLocalDirs(m *search.Match) {
   331  	if !m.IsLocal() {
   332  		panic(fmt.Sprintf("internal error: resolveLocalDirs on non-local pattern %s", m.Pattern()))
   333  	}
   334  
   335  	if i := strings.Index(m.Pattern(), "..."); i >= 0 {
   336  		// The pattern is local, but it is a wildcard. Its packages will
   337  		// only resolve to paths if they are inside of the standard
   338  		// library, the main module, or some dependency of the main
   339  		// module. Verify that before we walk the filesystem: a filesystem
   340  		// walk in a directory like /var or /etc can be very expensive!
   341  		dir := filepath.Dir(filepath.Clean(m.Pattern()[:i+3]))
   342  		absDir := dir
   343  		if !filepath.IsAbs(dir) {
   344  			absDir = filepath.Join(base.Cwd, dir)
   345  		}
   346  		if search.InDir(absDir, cfg.GOROOTsrc) == "" && search.InDir(absDir, ModRoot()) == "" && pathInModuleCache(absDir) == "" {
   347  			m.Dirs = []string{}
   348  			m.AddError(fmt.Errorf("directory prefix %s outside available modules", base.ShortPath(absDir)))
   349  			return
   350  		}
   351  	}
   352  
   353  	m.MatchDirs()
   354  }
   355  
   356  // resolveLocalPackage resolves a filesystem path to a package path.
   357  func resolveLocalPackage(dir string) (string, error) {
   358  	var absDir string
   359  	if filepath.IsAbs(dir) {
   360  		absDir = filepath.Clean(dir)
   361  	} else {
   362  		absDir = filepath.Join(base.Cwd, dir)
   363  	}
   364  
   365  	bp, err := cfg.BuildContext.ImportDir(absDir, 0)
   366  	if err != nil && (bp == nil || len(bp.IgnoredGoFiles) == 0) {
   367  		// golang.org/issue/32917: We should resolve a relative path to a
   368  		// package path only if the relative path actually contains the code
   369  		// for that package.
   370  		//
   371  		// If the named directory does not exist or contains no Go files,
   372  		// the package does not exist.
   373  		// Other errors may affect package loading, but not resolution.
   374  		if _, err := fsys.Stat(absDir); err != nil {
   375  			if os.IsNotExist(err) {
   376  				// Canonicalize OS-specific errors to errDirectoryNotFound so that error
   377  				// messages will be easier for users to search for.
   378  				return "", &fs.PathError{Op: "stat", Path: absDir, Err: errDirectoryNotFound}
   379  			}
   380  			return "", err
   381  		}
   382  		if _, noGo := err.(*build.NoGoError); noGo {
   383  			// A directory that does not contain any Go source files — even ignored
   384  			// ones! — is not a Go package, and we can't resolve it to a package
   385  			// path because that path could plausibly be provided by some other
   386  			// module.
   387  			//
   388  			// Any other error indicates that the package “exists” (at least in the
   389  			// sense that it cannot exist in any other module), but has some other
   390  			// problem (such as a syntax error).
   391  			return "", err
   392  		}
   393  	}
   394  
   395  	if modRoot != "" && absDir == modRoot {
   396  		if absDir == cfg.GOROOTsrc {
   397  			return "", errPkgIsGorootSrc
   398  		}
   399  		return targetPrefix, nil
   400  	}
   401  
   402  	// Note: The checks for @ here are just to avoid misinterpreting
   403  	// the module cache directories (formerly GOPATH/src/mod/foo@v1.5.2/bar).
   404  	// It's not strictly necessary but helpful to keep the checks.
   405  	if modRoot != "" && strings.HasPrefix(absDir, modRoot+string(filepath.Separator)) && !strings.Contains(absDir[len(modRoot):], "@") {
   406  		suffix := filepath.ToSlash(absDir[len(modRoot):])
   407  		if strings.HasPrefix(suffix, "/vendor/") {
   408  			if cfg.BuildMod != "vendor" {
   409  				return "", fmt.Errorf("without -mod=vendor, directory %s has no package path", absDir)
   410  			}
   411  
   412  			readVendorList()
   413  			pkg := strings.TrimPrefix(suffix, "/vendor/")
   414  			if _, ok := vendorPkgModule[pkg]; !ok {
   415  				return "", fmt.Errorf("directory %s is not a package listed in vendor/modules.txt", absDir)
   416  			}
   417  			return pkg, nil
   418  		}
   419  
   420  		if targetPrefix == "" {
   421  			pkg := strings.TrimPrefix(suffix, "/")
   422  			if pkg == "builtin" {
   423  				// "builtin" is a pseudo-package with a real source file.
   424  				// It's not included in "std", so it shouldn't resolve from "."
   425  				// within module "std" either.
   426  				return "", errPkgIsBuiltin
   427  			}
   428  			return pkg, nil
   429  		}
   430  
   431  		pkg := targetPrefix + suffix
   432  		if _, ok, err := dirInModule(pkg, targetPrefix, modRoot, true); err != nil {
   433  			return "", err
   434  		} else if !ok {
   435  			return "", &PackageNotInModuleError{Mod: Target, Pattern: pkg}
   436  		}
   437  		return pkg, nil
   438  	}
   439  
   440  	if sub := search.InDir(absDir, cfg.GOROOTsrc); sub != "" && sub != "." && !strings.Contains(sub, "@") {
   441  		pkg := filepath.ToSlash(sub)
   442  		if pkg == "builtin" {
   443  			return "", errPkgIsBuiltin
   444  		}
   445  		return pkg, nil
   446  	}
   447  
   448  	pkg := pathInModuleCache(absDir)
   449  	if pkg == "" {
   450  		return "", fmt.Errorf("directory %s outside available modules", base.ShortPath(absDir))
   451  	}
   452  	return pkg, nil
   453  }
   454  
   455  var (
   456  	errDirectoryNotFound = errors.New("directory not found")
   457  	errPkgIsGorootSrc    = errors.New("GOROOT/src is not an importable package")
   458  	errPkgIsBuiltin      = errors.New(`"builtin" is a pseudo-package, not an importable package`)
   459  )
   460  
   461  // pathInModuleCache returns the import path of the directory dir,
   462  // if dir is in the module cache copy of a module in our build list.
   463  func pathInModuleCache(dir string) string {
   464  	tryMod := func(m module.Version) (string, bool) {
   465  		var root string
   466  		var err error
   467  		if repl := Replacement(m); repl.Path != "" && repl.Version == "" {
   468  			root = repl.Path
   469  			if !filepath.IsAbs(root) {
   470  				root = filepath.Join(ModRoot(), root)
   471  			}
   472  		} else if repl.Path != "" {
   473  			root, err = modfetch.DownloadDir(repl)
   474  		} else {
   475  			root, err = modfetch.DownloadDir(m)
   476  		}
   477  		if err != nil {
   478  			return "", false
   479  		}
   480  
   481  		sub := search.InDir(dir, root)
   482  		if sub == "" {
   483  			return "", false
   484  		}
   485  		sub = filepath.ToSlash(sub)
   486  		if strings.Contains(sub, "/vendor/") || strings.HasPrefix(sub, "vendor/") || strings.Contains(sub, "@") {
   487  			return "", false
   488  		}
   489  
   490  		return path.Join(m.Path, filepath.ToSlash(sub)), true
   491  	}
   492  
   493  	for _, m := range buildList[1:] {
   494  		if importPath, ok := tryMod(m); ok {
   495  			// checkMultiplePaths ensures that a module can be used for at most one
   496  			// requirement, so this must be it.
   497  			return importPath
   498  		}
   499  	}
   500  	return ""
   501  }
   502  
   503  // ImportFromFiles adds modules to the build list as needed
   504  // to satisfy the imports in the named Go source files.
   505  func ImportFromFiles(ctx context.Context, gofiles []string) {
   506  	LoadModFile(ctx)
   507  
   508  	tags := imports.Tags()
   509  	imports, testImports, err := imports.ScanFiles(gofiles, tags)
   510  	if err != nil {
   511  		base.Fatalf("go: %v", err)
   512  	}
   513  
   514  	loaded = loadFromRoots(loaderParams{
   515  		PackageOpts: PackageOpts{
   516  			Tags:                  tags,
   517  			ResolveMissingImports: true,
   518  		},
   519  		allClosesOverTests: index.allPatternClosesOverTests(),
   520  		listRoots: func() (roots []string) {
   521  			roots = append(roots, imports...)
   522  			roots = append(roots, testImports...)
   523  			return roots
   524  		},
   525  	})
   526  	WriteGoMod()
   527  }
   528  
   529  // DirImportPath returns the effective import path for dir,
   530  // provided it is within the main module, or else returns ".".
   531  func DirImportPath(dir string) string {
   532  	if !HasModRoot() {
   533  		return "."
   534  	}
   535  	LoadModFile(context.TODO())
   536  
   537  	if !filepath.IsAbs(dir) {
   538  		dir = filepath.Join(base.Cwd, dir)
   539  	} else {
   540  		dir = filepath.Clean(dir)
   541  	}
   542  
   543  	if dir == modRoot {
   544  		return targetPrefix
   545  	}
   546  	if strings.HasPrefix(dir, modRoot+string(filepath.Separator)) {
   547  		suffix := filepath.ToSlash(dir[len(modRoot):])
   548  		if strings.HasPrefix(suffix, "/vendor/") {
   549  			return strings.TrimPrefix(suffix, "/vendor/")
   550  		}
   551  		return targetPrefix + suffix
   552  	}
   553  	return "."
   554  }
   555  
   556  // TargetPackages returns the list of packages in the target (top-level) module
   557  // matching pattern, which may be relative to the working directory, under all
   558  // build tag settings.
   559  func TargetPackages(ctx context.Context, pattern string) *search.Match {
   560  	// TargetPackages is relative to the main module, so ensure that the main
   561  	// module is a thing that can contain packages.
   562  	LoadModFile(ctx)
   563  	ModRoot()
   564  
   565  	m := search.NewMatch(pattern)
   566  	matchPackages(ctx, m, imports.AnyTags(), omitStd, []module.Version{Target})
   567  	return m
   568  }
   569  
   570  // ImportMap returns the actual package import path
   571  // for an import path found in source code.
   572  // If the given import path does not appear in the source code
   573  // for the packages that have been loaded, ImportMap returns the empty string.
   574  func ImportMap(path string) string {
   575  	pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
   576  	if !ok {
   577  		return ""
   578  	}
   579  	return pkg.path
   580  }
   581  
   582  // PackageDir returns the directory containing the source code
   583  // for the package named by the import path.
   584  func PackageDir(path string) string {
   585  	pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
   586  	if !ok {
   587  		return ""
   588  	}
   589  	return pkg.dir
   590  }
   591  
   592  // PackageModule returns the module providing the package named by the import path.
   593  func PackageModule(path string) module.Version {
   594  	pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
   595  	if !ok {
   596  		return module.Version{}
   597  	}
   598  	return pkg.mod
   599  }
   600  
   601  // PackageImports returns the imports for the package named by the import path.
   602  // Test imports will be returned as well if tests were loaded for the package
   603  // (i.e., if "all" was loaded or if LoadTests was set and the path was matched
   604  // by a command line argument). PackageImports will return nil for
   605  // unknown package paths.
   606  func PackageImports(path string) (imports, testImports []string) {
   607  	pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
   608  	if !ok {
   609  		return nil, nil
   610  	}
   611  	imports = make([]string, len(pkg.imports))
   612  	for i, p := range pkg.imports {
   613  		imports[i] = p.path
   614  	}
   615  	if pkg.test != nil {
   616  		testImports = make([]string, len(pkg.test.imports))
   617  		for i, p := range pkg.test.imports {
   618  			testImports[i] = p.path
   619  		}
   620  	}
   621  	return imports, testImports
   622  }
   623  
   624  // Lookup returns the source directory, import path, and any loading error for
   625  // the package at path as imported from the package in parentDir.
   626  // Lookup requires that one of the Load functions in this package has already
   627  // been called.
   628  func Lookup(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) {
   629  	if path == "" {
   630  		panic("Lookup called with empty package path")
   631  	}
   632  
   633  	if parentIsStd {
   634  		path = loaded.stdVendor(parentPath, path)
   635  	}
   636  	pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
   637  	if !ok {
   638  		// The loader should have found all the relevant paths.
   639  		// There are a few exceptions, though:
   640  		//	- during go list without -test, the p.Resolve calls to process p.TestImports and p.XTestImports
   641  		//	  end up here to canonicalize the import paths.
   642  		//	- during any load, non-loaded packages like "unsafe" end up here.
   643  		//	- during any load, build-injected dependencies like "runtime/cgo" end up here.
   644  		//	- because we ignore appengine/* in the module loader,
   645  		//	  the dependencies of any actual appengine/* library end up here.
   646  		dir := findStandardImportPath(path)
   647  		if dir != "" {
   648  			return dir, path, nil
   649  		}
   650  		return "", "", errMissing
   651  	}
   652  	return pkg.dir, pkg.path, pkg.err
   653  }
   654  
   655  // A loader manages the process of loading information about
   656  // the required packages for a particular build,
   657  // checking that the packages are available in the module set,
   658  // and updating the module set if needed.
   659  type loader struct {
   660  	loaderParams
   661  
   662  	work *par.Queue
   663  
   664  	// reset on each iteration
   665  	roots    []*loadPkg
   666  	pkgCache *par.Cache // package path (string) → *loadPkg
   667  	pkgs     []*loadPkg // transitive closure of loaded packages and tests; populated in buildStacks
   668  
   669  	// computed at end of iterations
   670  	direct map[string]bool // imported directly by main module
   671  }
   672  
   673  // loaderParams configure the packages loaded by, and the properties reported
   674  // by, a loader instance.
   675  type loaderParams struct {
   676  	PackageOpts
   677  
   678  	allClosesOverTests bool // Does the "all" pattern include the transitive closure of tests of packages in "all"?
   679  	allPatternIsRoot   bool // Is the "all" pattern an additional root?
   680  
   681  	listRoots func() []string
   682  }
   683  
   684  func (ld *loader) reset() {
   685  	select {
   686  	case <-ld.work.Idle():
   687  	default:
   688  		panic("loader.reset when not idle")
   689  	}
   690  
   691  	ld.roots = nil
   692  	ld.pkgCache = new(par.Cache)
   693  	ld.pkgs = nil
   694  }
   695  
   696  // A loadPkg records information about a single loaded package.
   697  type loadPkg struct {
   698  	// Populated at construction time:
   699  	path   string // import path
   700  	testOf *loadPkg
   701  
   702  	// Populated at construction time and updated by (*loader).applyPkgFlags:
   703  	flags atomicLoadPkgFlags
   704  
   705  	// Populated by (*loader).load:
   706  	mod         module.Version // module providing package
   707  	dir         string         // directory containing source code
   708  	err         error          // error loading package
   709  	imports     []*loadPkg     // packages imported by this one
   710  	testImports []string       // test-only imports, saved for use by pkg.test.
   711  	inStd       bool
   712  
   713  	// Populated by (*loader).pkgTest:
   714  	testOnce sync.Once
   715  	test     *loadPkg
   716  
   717  	// Populated by postprocessing in (*loader).buildStacks:
   718  	stack *loadPkg // package importing this one in minimal import stack for this pkg
   719  }
   720  
   721  // loadPkgFlags is a set of flags tracking metadata about a package.
   722  type loadPkgFlags int8
   723  
   724  const (
   725  	// pkgInAll indicates that the package is in the "all" package pattern,
   726  	// regardless of whether we are loading the "all" package pattern.
   727  	//
   728  	// When the pkgInAll flag and pkgImportsLoaded flags are both set, the caller
   729  	// who set the last of those flags must propagate the pkgInAll marking to all
   730  	// of the imports of the marked package.
   731  	//
   732  	// A test is marked with pkgInAll if that test would promote the packages it
   733  	// imports to be in "all" (such as when the test is itself within the main
   734  	// module, or when ld.allClosesOverTests is true).
   735  	pkgInAll loadPkgFlags = 1 << iota
   736  
   737  	// pkgIsRoot indicates that the package matches one of the root package
   738  	// patterns requested by the caller.
   739  	//
   740  	// If LoadTests is set, then when pkgIsRoot and pkgImportsLoaded are both set,
   741  	// the caller who set the last of those flags must populate a test for the
   742  	// package (in the pkg.test field).
   743  	//
   744  	// If the "all" pattern is included as a root, then non-test packages in "all"
   745  	// are also roots (and must be marked pkgIsRoot).
   746  	pkgIsRoot
   747  
   748  	// pkgImportsLoaded indicates that the imports and testImports fields of a
   749  	// loadPkg have been populated.
   750  	pkgImportsLoaded
   751  )
   752  
   753  // has reports whether all of the flags in cond are set in f.
   754  func (f loadPkgFlags) has(cond loadPkgFlags) bool {
   755  	return f&cond == cond
   756  }
   757  
   758  // An atomicLoadPkgFlags stores a loadPkgFlags for which individual flags can be
   759  // added atomically.
   760  type atomicLoadPkgFlags struct {
   761  	bits int32
   762  }
   763  
   764  // update sets the given flags in af (in addition to any flags already set).
   765  //
   766  // update returns the previous flag state so that the caller may determine which
   767  // flags were newly-set.
   768  func (af *atomicLoadPkgFlags) update(flags loadPkgFlags) (old loadPkgFlags) {
   769  	for {
   770  		old := atomic.LoadInt32(&af.bits)
   771  		new := old | int32(flags)
   772  		if new == old || atomic.CompareAndSwapInt32(&af.bits, old, new) {
   773  			return loadPkgFlags(old)
   774  		}
   775  	}
   776  }
   777  
   778  // has reports whether all of the flags in cond are set in af.
   779  func (af *atomicLoadPkgFlags) has(cond loadPkgFlags) bool {
   780  	return loadPkgFlags(atomic.LoadInt32(&af.bits))&cond == cond
   781  }
   782  
   783  // isTest reports whether pkg is a test of another package.
   784  func (pkg *loadPkg) isTest() bool {
   785  	return pkg.testOf != nil
   786  }
   787  
   788  var errMissing = errors.New("cannot find package")
   789  
   790  // loadFromRoots attempts to load the build graph needed to process a set of
   791  // root packages and their dependencies.
   792  //
   793  // The set of root packages is returned by the params.listRoots function, and
   794  // expanded to the full set of packages by tracing imports (and possibly tests)
   795  // as needed.
   796  func loadFromRoots(params loaderParams) *loader {
   797  	ld := &loader{
   798  		loaderParams: params,
   799  		work:         par.NewQueue(runtime.GOMAXPROCS(0)),
   800  	}
   801  
   802  	var err error
   803  	reqs := &mvsReqs{buildList: buildList}
   804  	buildList, err = mvs.BuildList(Target, reqs)
   805  	if err != nil {
   806  		base.Fatalf("go: %v", err)
   807  	}
   808  
   809  	addedModuleFor := make(map[string]bool)
   810  	for {
   811  		ld.reset()
   812  
   813  		// Load the root packages and their imports.
   814  		// Note: the returned roots can change on each iteration,
   815  		// since the expansion of package patterns depends on the
   816  		// build list we're using.
   817  		inRoots := map[*loadPkg]bool{}
   818  		for _, path := range ld.listRoots() {
   819  			root := ld.pkg(path, pkgIsRoot)
   820  			if !inRoots[root] {
   821  				ld.roots = append(ld.roots, root)
   822  				inRoots[root] = true
   823  			}
   824  		}
   825  
   826  		// ld.pkg adds imported packages to the work queue and calls applyPkgFlags,
   827  		// which adds tests (and test dependencies) as needed.
   828  		//
   829  		// When all of the work in the queue has completed, we'll know that the
   830  		// transitive closure of dependencies has been loaded.
   831  		<-ld.work.Idle()
   832  
   833  		ld.buildStacks()
   834  
   835  		if !ld.ResolveMissingImports || (!HasModRoot() && !allowMissingModuleImports) {
   836  			// We've loaded as much as we can without resolving missing imports.
   837  			break
   838  		}
   839  		modAddedBy := ld.resolveMissingImports(addedModuleFor)
   840  		if len(modAddedBy) == 0 {
   841  			break
   842  		}
   843  
   844  		// Recompute buildList with all our additions.
   845  		reqs = &mvsReqs{buildList: buildList}
   846  		buildList, err = mvs.BuildList(Target, reqs)
   847  		if err != nil {
   848  			// If an error was found in a newly added module, report the package
   849  			// import stack instead of the module requirement stack. Packages
   850  			// are more descriptive.
   851  			if err, ok := err.(*mvs.BuildListError); ok {
   852  				if pkg := modAddedBy[err.Module()]; pkg != nil {
   853  					base.Fatalf("go: %s: %v", pkg.stackText(), err.Err)
   854  				}
   855  			}
   856  			base.Fatalf("go: %v", err)
   857  		}
   858  	}
   859  	base.ExitIfErrors()
   860  
   861  	// Compute directly referenced dependency modules.
   862  	ld.direct = make(map[string]bool)
   863  	for _, pkg := range ld.pkgs {
   864  		if pkg.mod == Target {
   865  			for _, dep := range pkg.imports {
   866  				if dep.mod.Path != "" && dep.mod.Path != Target.Path && index != nil {
   867  					_, explicit := index.require[dep.mod]
   868  					if allowWriteGoMod && cfg.BuildMod == "readonly" && !explicit {
   869  						// TODO(#40775): attach error to package instead of using
   870  						// base.Errorf. Ideally, 'go list' should not fail because of this,
   871  						// but today, LoadPackages calls WriteGoMod unconditionally, which
   872  						// would fail with a less clear message.
   873  						base.Errorf("go: %[1]s: package %[2]s imported from implicitly required module; to add missing requirements, run:\n\tgo get %[2]s@%[3]s", pkg.path, dep.path, dep.mod.Version)
   874  					}
   875  					ld.direct[dep.mod.Path] = true
   876  				}
   877  			}
   878  		}
   879  	}
   880  	base.ExitIfErrors()
   881  
   882  	// If we didn't scan all of the imports from the main module, or didn't use
   883  	// imports.AnyTags, then we didn't necessarily load every package that
   884  	// contributes “direct” imports — so we can't safely mark existing
   885  	// dependencies as indirect-only.
   886  	// Conservatively mark those dependencies as direct.
   887  	if modFile != nil && (!ld.allPatternIsRoot || !reflect.DeepEqual(ld.Tags, imports.AnyTags())) {
   888  		for _, r := range modFile.Require {
   889  			if !r.Indirect {
   890  				ld.direct[r.Mod.Path] = true
   891  			}
   892  		}
   893  	}
   894  
   895  	return ld
   896  }
   897  
   898  // resolveMissingImports adds module dependencies to the global build list
   899  // in order to resolve missing packages from pkgs.
   900  //
   901  // The newly-resolved packages are added to the addedModuleFor map, and
   902  // resolveMissingImports returns a map from each newly-added module version to
   903  // the first package for which that module was added.
   904  func (ld *loader) resolveMissingImports(addedModuleFor map[string]bool) (modAddedBy map[module.Version]*loadPkg) {
   905  	var needPkgs []*loadPkg
   906  	for _, pkg := range ld.pkgs {
   907  		if pkg.err == nil {
   908  			continue
   909  		}
   910  		if pkg.isTest() {
   911  			// If we are missing a test, we are also missing its non-test version, and
   912  			// we should only add the missing import once.
   913  			continue
   914  		}
   915  		if !errors.As(pkg.err, new(*ImportMissingError)) {
   916  			// Leave other errors for Import or load.Packages to report.
   917  			continue
   918  		}
   919  
   920  		needPkgs = append(needPkgs, pkg)
   921  
   922  		pkg := pkg
   923  		ld.work.Add(func() {
   924  			pkg.mod, pkg.err = queryImport(context.TODO(), pkg.path)
   925  		})
   926  	}
   927  	<-ld.work.Idle()
   928  
   929  	modAddedBy = map[module.Version]*loadPkg{}
   930  	for _, pkg := range needPkgs {
   931  		if pkg.err != nil {
   932  			continue
   933  		}
   934  
   935  		fmt.Fprintf(os.Stderr, "go: found %s in %s %s\n", pkg.path, pkg.mod.Path, pkg.mod.Version)
   936  		if addedModuleFor[pkg.path] {
   937  			// TODO(bcmills): This should only be an error if pkg.mod is the same
   938  			// version we already tried to add previously.
   939  			base.Fatalf("go: %s: looping trying to add package", pkg.stackText())
   940  		}
   941  		if modAddedBy[pkg.mod] == nil {
   942  			modAddedBy[pkg.mod] = pkg
   943  			buildList = append(buildList, pkg.mod)
   944  		}
   945  	}
   946  
   947  	return modAddedBy
   948  }
   949  
   950  // pkg locates the *loadPkg for path, creating and queuing it for loading if
   951  // needed, and updates its state to reflect the given flags.
   952  //
   953  // The imports of the returned *loadPkg will be loaded asynchronously in the
   954  // ld.work queue, and its test (if requested) will also be populated once
   955  // imports have been resolved. When ld.work goes idle, all transitive imports of
   956  // the requested package (and its test, if requested) will have been loaded.
   957  func (ld *loader) pkg(path string, flags loadPkgFlags) *loadPkg {
   958  	if flags.has(pkgImportsLoaded) {
   959  		panic("internal error: (*loader).pkg called with pkgImportsLoaded flag set")
   960  	}
   961  
   962  	pkg := ld.pkgCache.Do(path, func() interface{} {
   963  		pkg := &loadPkg{
   964  			path: path,
   965  		}
   966  		ld.applyPkgFlags(pkg, flags)
   967  
   968  		ld.work.Add(func() { ld.load(pkg) })
   969  		return pkg
   970  	}).(*loadPkg)
   971  
   972  	ld.applyPkgFlags(pkg, flags)
   973  	return pkg
   974  }
   975  
   976  // applyPkgFlags updates pkg.flags to set the given flags and propagate the
   977  // (transitive) effects of those flags, possibly loading or enqueueing further
   978  // packages as a result.
   979  func (ld *loader) applyPkgFlags(pkg *loadPkg, flags loadPkgFlags) {
   980  	if flags == 0 {
   981  		return
   982  	}
   983  
   984  	if flags.has(pkgInAll) && ld.allPatternIsRoot && !pkg.isTest() {
   985  		// This package matches a root pattern by virtue of being in "all".
   986  		flags |= pkgIsRoot
   987  	}
   988  
   989  	old := pkg.flags.update(flags)
   990  	new := old | flags
   991  	if new == old || !new.has(pkgImportsLoaded) {
   992  		// We either didn't change the state of pkg, or we don't know anything about
   993  		// its dependencies yet. Either way, we can't usefully load its test or
   994  		// update its dependencies.
   995  		return
   996  	}
   997  
   998  	if !pkg.isTest() {
   999  		// Check whether we should add (or update the flags for) a test for pkg.
  1000  		// ld.pkgTest is idempotent and extra invocations are inexpensive,
  1001  		// so it's ok if we call it more than is strictly necessary.
  1002  		wantTest := false
  1003  		switch {
  1004  		case ld.allPatternIsRoot && pkg.mod == Target:
  1005  			// We are loading the "all" pattern, which includes packages imported by
  1006  			// tests in the main module. This package is in the main module, so we
  1007  			// need to identify the imports of its test even if LoadTests is not set.
  1008  			//
  1009  			// (We will filter out the extra tests explicitly in computePatternAll.)
  1010  			wantTest = true
  1011  
  1012  		case ld.allPatternIsRoot && ld.allClosesOverTests && new.has(pkgInAll):
  1013  			// This variant of the "all" pattern includes imports of tests of every
  1014  			// package that is itself in "all", and pkg is in "all", so its test is
  1015  			// also in "all" (as above).
  1016  			wantTest = true
  1017  
  1018  		case ld.LoadTests && new.has(pkgIsRoot):
  1019  			// LoadTest explicitly requests tests of “the root packages”.
  1020  			wantTest = true
  1021  		}
  1022  
  1023  		if wantTest {
  1024  			var testFlags loadPkgFlags
  1025  			if pkg.mod == Target || (ld.allClosesOverTests && new.has(pkgInAll)) {
  1026  				// Tests of packages in the main module are in "all", in the sense that
  1027  				// they cause the packages they import to also be in "all". So are tests
  1028  				// of packages in "all" if "all" closes over test dependencies.
  1029  				testFlags |= pkgInAll
  1030  			}
  1031  			ld.pkgTest(pkg, testFlags)
  1032  		}
  1033  	}
  1034  
  1035  	if new.has(pkgInAll) && !old.has(pkgInAll|pkgImportsLoaded) {
  1036  		// We have just marked pkg with pkgInAll, or we have just loaded its
  1037  		// imports, or both. Now is the time to propagate pkgInAll to the imports.
  1038  		for _, dep := range pkg.imports {
  1039  			ld.applyPkgFlags(dep, pkgInAll)
  1040  		}
  1041  	}
  1042  }
  1043  
  1044  // load loads an individual package.
  1045  func (ld *loader) load(pkg *loadPkg) {
  1046  	if strings.Contains(pkg.path, "@") {
  1047  		// Leave for error during load.
  1048  		return
  1049  	}
  1050  	if build.IsLocalImport(pkg.path) || filepath.IsAbs(pkg.path) {
  1051  		// Leave for error during load.
  1052  		// (Module mode does not allow local imports.)
  1053  		return
  1054  	}
  1055  
  1056  	if search.IsMetaPackage(pkg.path) {
  1057  		pkg.err = &invalidImportError{
  1058  			importPath: pkg.path,
  1059  			err:        fmt.Errorf("%q is not an importable package; see 'go help packages'", pkg.path),
  1060  		}
  1061  		return
  1062  	}
  1063  
  1064  	pkg.mod, pkg.dir, pkg.err = importFromBuildList(context.TODO(), pkg.path, buildList)
  1065  	if pkg.dir == "" {
  1066  		return
  1067  	}
  1068  	if pkg.mod == Target {
  1069  		// Go ahead and mark pkg as in "all". This provides the invariant that a
  1070  		// package that is *only* imported by other packages in "all" is always
  1071  		// marked as such before loading its imports.
  1072  		//
  1073  		// We don't actually rely on that invariant at the moment, but it may
  1074  		// improve efficiency somewhat and makes the behavior a bit easier to reason
  1075  		// about (by reducing churn on the flag bits of dependencies), and costs
  1076  		// essentially nothing (these atomic flag ops are essentially free compared
  1077  		// to scanning source code for imports).
  1078  		ld.applyPkgFlags(pkg, pkgInAll)
  1079  	}
  1080  	if ld.AllowPackage != nil {
  1081  		if err := ld.AllowPackage(context.TODO(), pkg.path, pkg.mod); err != nil {
  1082  			pkg.err = err
  1083  		}
  1084  	}
  1085  
  1086  	pkg.inStd = (search.IsStandardImportPath(pkg.path) && search.InDir(pkg.dir, cfg.GOROOTsrc) != "")
  1087  
  1088  	var imports, testImports []string
  1089  
  1090  	if cfg.BuildContext.Compiler == "gccgo" && pkg.inStd {
  1091  		// We can't scan standard packages for gccgo.
  1092  	} else {
  1093  		var err error
  1094  		imports, testImports, err = scanDir(pkg.dir, ld.Tags)
  1095  		if err != nil {
  1096  			pkg.err = err
  1097  			return
  1098  		}
  1099  	}
  1100  
  1101  	pkg.imports = make([]*loadPkg, 0, len(imports))
  1102  	var importFlags loadPkgFlags
  1103  	if pkg.flags.has(pkgInAll) {
  1104  		importFlags = pkgInAll
  1105  	}
  1106  	for _, path := range imports {
  1107  		if pkg.inStd {
  1108  			// Imports from packages in "std" and "cmd" should resolve using
  1109  			// GOROOT/src/vendor even when "std" is not the main module.
  1110  			path = ld.stdVendor(pkg.path, path)
  1111  		}
  1112  		pkg.imports = append(pkg.imports, ld.pkg(path, importFlags))
  1113  	}
  1114  	pkg.testImports = testImports
  1115  
  1116  	ld.applyPkgFlags(pkg, pkgImportsLoaded)
  1117  }
  1118  
  1119  // pkgTest locates the test of pkg, creating it if needed, and updates its state
  1120  // to reflect the given flags.
  1121  //
  1122  // pkgTest requires that the imports of pkg have already been loaded (flagged
  1123  // with pkgImportsLoaded).
  1124  func (ld *loader) pkgTest(pkg *loadPkg, testFlags loadPkgFlags) *loadPkg {
  1125  	if pkg.isTest() {
  1126  		panic("pkgTest called on a test package")
  1127  	}
  1128  
  1129  	createdTest := false
  1130  	pkg.testOnce.Do(func() {
  1131  		pkg.test = &loadPkg{
  1132  			path:   pkg.path,
  1133  			testOf: pkg,
  1134  			mod:    pkg.mod,
  1135  			dir:    pkg.dir,
  1136  			err:    pkg.err,
  1137  			inStd:  pkg.inStd,
  1138  		}
  1139  		ld.applyPkgFlags(pkg.test, testFlags)
  1140  		createdTest = true
  1141  	})
  1142  
  1143  	test := pkg.test
  1144  	if createdTest {
  1145  		test.imports = make([]*loadPkg, 0, len(pkg.testImports))
  1146  		var importFlags loadPkgFlags
  1147  		if test.flags.has(pkgInAll) {
  1148  			importFlags = pkgInAll
  1149  		}
  1150  		for _, path := range pkg.testImports {
  1151  			if pkg.inStd {
  1152  				path = ld.stdVendor(test.path, path)
  1153  			}
  1154  			test.imports = append(test.imports, ld.pkg(path, importFlags))
  1155  		}
  1156  		pkg.testImports = nil
  1157  		ld.applyPkgFlags(test, pkgImportsLoaded)
  1158  	} else {
  1159  		ld.applyPkgFlags(test, testFlags)
  1160  	}
  1161  
  1162  	return test
  1163  }
  1164  
  1165  // stdVendor returns the canonical import path for the package with the given
  1166  // path when imported from the standard-library package at parentPath.
  1167  func (ld *loader) stdVendor(parentPath, path string) string {
  1168  	if search.IsStandardImportPath(path) {
  1169  		return path
  1170  	}
  1171  
  1172  	if str.HasPathPrefix(parentPath, "cmd") {
  1173  		if Target.Path != "cmd" {
  1174  			vendorPath := pathpkg.Join("cmd", "vendor", path)
  1175  			if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
  1176  				return vendorPath
  1177  			}
  1178  		}
  1179  	} else if Target.Path != "std" || str.HasPathPrefix(parentPath, "vendor") {
  1180  		// If we are outside of the 'std' module, resolve imports from within 'std'
  1181  		// to the vendor directory.
  1182  		//
  1183  		// Do the same for importers beginning with the prefix 'vendor/' even if we
  1184  		// are *inside* of the 'std' module: the 'vendor/' packages that resolve
  1185  		// globally from GOROOT/src/vendor (and are listed as part of 'go list std')
  1186  		// are distinct from the real module dependencies, and cannot import
  1187  		// internal packages from the real module.
  1188  		//
  1189  		// (Note that although the 'vendor/' packages match the 'std' *package*
  1190  		// pattern, they are not part of the std *module*, and do not affect
  1191  		// 'go mod tidy' and similar module commands when working within std.)
  1192  		vendorPath := pathpkg.Join("vendor", path)
  1193  		if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
  1194  			return vendorPath
  1195  		}
  1196  	}
  1197  
  1198  	// Not vendored: resolve from modules.
  1199  	return path
  1200  }
  1201  
  1202  // computePatternAll returns the list of packages matching pattern "all",
  1203  // starting with a list of the import paths for the packages in the main module.
  1204  func (ld *loader) computePatternAll() (all []string) {
  1205  	for _, pkg := range ld.pkgs {
  1206  		if pkg.flags.has(pkgInAll) && !pkg.isTest() {
  1207  			all = append(all, pkg.path)
  1208  		}
  1209  	}
  1210  	sort.Strings(all)
  1211  	return all
  1212  }
  1213  
  1214  // scanDir is like imports.ScanDir but elides known magic imports from the list,
  1215  // so that we do not go looking for packages that don't really exist.
  1216  //
  1217  // The standard magic import is "C", for cgo.
  1218  //
  1219  // The only other known magic imports are appengine and appengine/*.
  1220  // These are so old that they predate "go get" and did not use URL-like paths.
  1221  // Most code today now uses google.golang.org/appengine instead,
  1222  // but not all code has been so updated. When we mostly ignore build tags
  1223  // during "go vendor", we look into "// +build appengine" files and
  1224  // may see these legacy imports. We drop them so that the module
  1225  // search does not look for modules to try to satisfy them.
  1226  func scanDir(dir string, tags map[string]bool) (imports_, testImports []string, err error) {
  1227  	imports_, testImports, err = imports.ScanDir(dir, tags)
  1228  
  1229  	filter := func(x []string) []string {
  1230  		w := 0
  1231  		for _, pkg := range x {
  1232  			if pkg != "C" && pkg != "appengine" && !strings.HasPrefix(pkg, "appengine/") &&
  1233  				pkg != "appengine_internal" && !strings.HasPrefix(pkg, "appengine_internal/") {
  1234  				x[w] = pkg
  1235  				w++
  1236  			}
  1237  		}
  1238  		return x[:w]
  1239  	}
  1240  
  1241  	return filter(imports_), filter(testImports), err
  1242  }
  1243  
  1244  // buildStacks computes minimal import stacks for each package,
  1245  // for use in error messages. When it completes, packages that
  1246  // are part of the original root set have pkg.stack == nil,
  1247  // and other packages have pkg.stack pointing at the next
  1248  // package up the import stack in their minimal chain.
  1249  // As a side effect, buildStacks also constructs ld.pkgs,
  1250  // the list of all packages loaded.
  1251  func (ld *loader) buildStacks() {
  1252  	if len(ld.pkgs) > 0 {
  1253  		panic("buildStacks")
  1254  	}
  1255  	for _, pkg := range ld.roots {
  1256  		pkg.stack = pkg // sentinel to avoid processing in next loop
  1257  		ld.pkgs = append(ld.pkgs, pkg)
  1258  	}
  1259  	for i := 0; i < len(ld.pkgs); i++ { // not range: appending to ld.pkgs in loop
  1260  		pkg := ld.pkgs[i]
  1261  		for _, next := range pkg.imports {
  1262  			if next.stack == nil {
  1263  				next.stack = pkg
  1264  				ld.pkgs = append(ld.pkgs, next)
  1265  			}
  1266  		}
  1267  		if next := pkg.test; next != nil && next.stack == nil {
  1268  			next.stack = pkg
  1269  			ld.pkgs = append(ld.pkgs, next)
  1270  		}
  1271  	}
  1272  	for _, pkg := range ld.roots {
  1273  		pkg.stack = nil
  1274  	}
  1275  }
  1276  
  1277  // stackText builds the import stack text to use when
  1278  // reporting an error in pkg. It has the general form
  1279  //
  1280  //	root imports
  1281  //		other imports
  1282  //		other2 tested by
  1283  //		other2.test imports
  1284  //		pkg
  1285  //
  1286  func (pkg *loadPkg) stackText() string {
  1287  	var stack []*loadPkg
  1288  	for p := pkg; p != nil; p = p.stack {
  1289  		stack = append(stack, p)
  1290  	}
  1291  
  1292  	var buf bytes.Buffer
  1293  	for i := len(stack) - 1; i >= 0; i-- {
  1294  		p := stack[i]
  1295  		fmt.Fprint(&buf, p.path)
  1296  		if p.testOf != nil {
  1297  			fmt.Fprint(&buf, ".test")
  1298  		}
  1299  		if i > 0 {
  1300  			if stack[i-1].testOf == p {
  1301  				fmt.Fprint(&buf, " tested by\n\t")
  1302  			} else {
  1303  				fmt.Fprint(&buf, " imports\n\t")
  1304  			}
  1305  		}
  1306  	}
  1307  	return buf.String()
  1308  }
  1309  
  1310  // why returns the text to use in "go mod why" output about the given package.
  1311  // It is less ornate than the stackText but contains the same information.
  1312  func (pkg *loadPkg) why() string {
  1313  	var buf strings.Builder
  1314  	var stack []*loadPkg
  1315  	for p := pkg; p != nil; p = p.stack {
  1316  		stack = append(stack, p)
  1317  	}
  1318  
  1319  	for i := len(stack) - 1; i >= 0; i-- {
  1320  		p := stack[i]
  1321  		if p.testOf != nil {
  1322  			fmt.Fprintf(&buf, "%s.test\n", p.testOf.path)
  1323  		} else {
  1324  			fmt.Fprintf(&buf, "%s\n", p.path)
  1325  		}
  1326  	}
  1327  	return buf.String()
  1328  }
  1329  
  1330  // Why returns the "go mod why" output stanza for the given package,
  1331  // without the leading # comment.
  1332  // The package graph must have been loaded already, usually by LoadPackages.
  1333  // If there is no reason for the package to be in the current build,
  1334  // Why returns an empty string.
  1335  func Why(path string) string {
  1336  	pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
  1337  	if !ok {
  1338  		return ""
  1339  	}
  1340  	return pkg.why()
  1341  }
  1342  
  1343  // WhyDepth returns the number of steps in the Why listing.
  1344  // If there is no reason for the package to be in the current build,
  1345  // WhyDepth returns 0.
  1346  func WhyDepth(path string) int {
  1347  	n := 0
  1348  	pkg, _ := loaded.pkgCache.Get(path).(*loadPkg)
  1349  	for p := pkg; p != nil; p = p.stack {
  1350  		n++
  1351  	}
  1352  	return n
  1353  }
  1354  

View as plain text