1 // Copyright 2011 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.
5 // Package load loads packages.
32 "cmd/go/internal/base"
34 "cmd/go/internal/fsys"
35 "cmd/go/internal/imports"
36 "cmd/go/internal/modfetch"
37 "cmd/go/internal/modinfo"
38 "cmd/go/internal/modload"
40 "cmd/go/internal/search"
42 "cmd/go/internal/trace"
46 "golang.org/x/mod/modfile"
47 "golang.org/x/mod/module"
50 // A Package describes a single package found in a directory.
52 PackagePublic // visible in 'go list'
53 Internal PackageInternal // for use inside go command only
56 type PackagePublic struct {
57 // Note: These fields are part of the go command's public API.
58 // See list.go. It is okay to add fields, but not to change or
59 // remove existing ones. Keep in sync with list.go
60 Dir string `json:",omitempty"` // directory containing package sources
61 ImportPath string `json:",omitempty"` // import path of package in dir
62 ImportComment string `json:",omitempty"` // path in import comment on package statement
63 Name string `json:",omitempty"` // package name
64 Doc string `json:",omitempty"` // package documentation string
65 Target string `json:",omitempty"` // installed target for this package (may be executable)
66 Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
67 Root string `json:",omitempty"` // Go root, Go path dir, or module root dir containing this package
68 ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory
69 ForTest string `json:",omitempty"` // package is only for use in named test
70 Export string `json:",omitempty"` // file containing export data (set by go list -export)
71 BuildID string `json:",omitempty"` // build ID of the compiled package (set by go list -export)
72 Module *modinfo.ModulePublic `json:",omitempty"` // info about package's module, if any
73 Match []string `json:",omitempty"` // command-line patterns matching this package
74 Goroot bool `json:",omitempty"` // is this package found in the Go root?
75 Standard bool `json:",omitempty"` // is this package part of the standard Go library?
76 DepOnly bool `json:",omitempty"` // package is only as a dependency, not explicitly listed
77 BinaryOnly bool `json:",omitempty"` // package cannot be recompiled
78 Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies?
80 // Stale and StaleReason remain here *only* for the list command.
81 // They are only initialized in preparation for list execution.
82 // The regular build determines staleness on the fly during action execution.
83 Stale bool `json:",omitempty"` // would 'go install' do anything for this package?
84 StaleReason string `json:",omitempty"` // why is Stale true?
87 // If you add to this list you MUST add to p.AllFiles (below) too.
88 // Otherwise file name security lists will not apply to any new additions.
89 GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
90 CgoFiles []string `json:",omitempty"` // .go source files that import "C"
91 CompiledGoFiles []string `json:",omitempty"` // .go output from running cgo on CgoFiles
92 IgnoredGoFiles []string `json:",omitempty"` // .go source files ignored due to build constraints
93 InvalidGoFiles []string `json:",omitempty"` // .go source files with detected problems (parse error, wrong package name, and so on)
94 IgnoredOtherFiles []string `json:",omitempty"` // non-.go source files ignored due to build constraints
95 CFiles []string `json:",omitempty"` // .c source files
96 CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files
97 MFiles []string `json:",omitempty"` // .m source files
98 HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
99 FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
100 SFiles []string `json:",omitempty"` // .s source files
101 SwigFiles []string `json:",omitempty"` // .swig files
102 SwigCXXFiles []string `json:",omitempty"` // .swigcxx files
103 SysoFiles []string `json:",omitempty"` // .syso system object files added to package
106 EmbedPatterns []string `json:",omitempty"` // //go:embed patterns
107 EmbedFiles []string `json:",omitempty"` // files matched by EmbedPatterns
110 CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler
111 CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor
112 CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler
113 CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler
114 CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker
115 CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
117 // Dependency information
118 Imports []string `json:",omitempty"` // import paths used by this package
119 ImportMap map[string]string `json:",omitempty"` // map from source import to ImportPath (identity entries omitted)
120 Deps []string `json:",omitempty"` // all (recursively) imported dependencies
123 // Incomplete is above, packed into the other bools
124 Error *PackageError `json:",omitempty"` // error loading this package (not dependencies)
125 DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
128 // If you add to this list you MUST add to p.AllFiles (below) too.
129 // Otherwise file name security lists will not apply to any new additions.
130 TestGoFiles []string `json:",omitempty"` // _test.go files in package
131 TestImports []string `json:",omitempty"` // imports from TestGoFiles
132 TestEmbedPatterns []string `json:",omitempty"` // //go:embed patterns
133 TestEmbedFiles []string `json:",omitempty"` // files matched by TestEmbedPatterns
134 XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
135 XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
136 XTestEmbedPatterns []string `json:",omitempty"` // //go:embed patterns
137 XTestEmbedFiles []string `json:",omitempty"` // files matched by XTestEmbedPatterns
140 // AllFiles returns the names of all the files considered for the package.
141 // This is used for sanity and security checks, so we include all files,
142 // even IgnoredGoFiles, because some subcommands consider them.
143 // The go/build package filtered others out (like foo_wrongGOARCH.s)
145 func (p *Package) AllFiles() []string {
146 files := str.StringList(
149 // no p.CompiledGoFiles, because they are from GoFiles or generated by us
151 // no p.InvalidGoFiles, because they are from GoFiles
166 // EmbedFiles may overlap with the other files.
167 // Dedup, but delay building the map as long as possible.
168 // Only files in the current directory (no slash in name)
169 // need to be checked against the files variable above.
170 var have map[string]bool
171 for _, file := range p.EmbedFiles {
172 if !strings.Contains(file, "/") {
174 have = make(map[string]bool)
175 for _, file := range files {
183 files = append(files, file)
188 // Desc returns the package "description", for use in b.showOutput.
189 func (p *Package) Desc() string {
191 return p.ImportPath + " [" + p.ForTest + ".test]"
196 type PackageInternal struct {
197 // Unexported fields are not part of the public API.
199 Imports []*Package // this package's direct imports
200 CompiledImports []string // additional Imports necessary when using CompiledGoFiles (all from standard library); 1:1 with the end of PackagePublic.Imports
201 RawImports []string // this package's original imports as they appear in the text of the program; 1:1 with the end of PackagePublic.Imports
202 ForceLibrary bool // this package is a library (even if named "main")
203 CmdlineFiles bool // package built from files listed on command line
204 CmdlinePkg bool // package listed on command line
205 CmdlinePkgLiteral bool // package listed as literal on command line (not via wildcard)
206 Local bool // imported via local path (./ or ../)
207 LocalPrefix string // interpret ./ and ../ imports relative to this prefix
208 ExeName string // desired name for temporary executable
209 FuzzInstrument bool // package should be instrumented for fuzzing
210 CoverMode string // preprocess Go source files with the coverage tool in this mode
211 CoverVars map[string]*CoverVar // variables created by coverage analysis
212 OmitDebug bool // tell linker not to write debug information
213 GobinSubdir bool // install target would be subdir of GOBIN
214 BuildInfo string // add this info to package main
215 TestmainGo *[]byte // content for _testmain.go
216 Embed map[string][]string // //go:embed comment mapping
217 OrigImportPath string // original import path before adding '_test' suffix
219 Asmflags []string // -asmflags for this package
220 Gcflags []string // -gcflags for this package
221 Ldflags []string // -ldflags for this package
222 Gccgoflags []string // -gccgoflags for this package
225 // A NoGoError indicates that no Go files for the package were applicable to the
226 // build for that package.
228 // That may be because there were no files whatsoever, or because all files were
229 // excluded, or because all non-excluded files were test sources.
230 type NoGoError struct {
234 func (e *NoGoError) Error() string {
235 if len(e.Package.IgnoredGoFiles) > 0 {
236 // Go files exist, but they were ignored due to build constraints.
237 return "build constraints exclude all Go files in " + e.Package.Dir
239 if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
240 // Test Go files exist, but we're not interested in them.
241 // The double-negative is unfortunate but we want e.Package.Dir
242 // to appear at the end of error message.
243 return "no non-test Go files in " + e.Package.Dir
245 return "no Go files in " + e.Package.Dir
248 // setLoadPackageDataError presents an error found when loading package data
249 // as a *PackageError. It has special cases for some common errors to improve
250 // messages shown to users and reduce redundancy.
252 // setLoadPackageDataError returns true if it's safe to load information about
253 // imported packages, for example, if there was a parse error loading imports
254 // in one file, but other files are okay.
255 func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportStack, importPos []token.Position) {
256 matchErr, isMatchErr := err.(*search.MatchError)
257 if isMatchErr && matchErr.Match.Pattern() == path {
258 if matchErr.Match.IsLiteral() {
259 // The error has a pattern has a pattern similar to the import path.
260 // It may be slightly different (./foo matching example.com/foo),
261 // but close enough to seem redundant.
262 // Unwrap the error so we don't show the pattern.
267 // Replace (possibly wrapped) *build.NoGoError with *load.NoGoError.
268 // The latter is more specific about the cause.
269 var nogoErr *build.NoGoError
270 if errors.As(err, &nogoErr) {
271 if p.Dir == "" && nogoErr.Dir != "" {
274 err = &NoGoError{Package: p}
277 // Take only the first error from a scanner.ErrorList. PackageError only
278 // has room for one position, so we report the first error with a position
279 // instead of all of the errors without a position.
282 if scanErr, ok := err.(scanner.ErrorList); ok && len(scanErr) > 0 {
283 isScanErr = true // For stack push/pop below.
285 scanPos := scanErr[0].Pos
286 scanPos.Filename = base.ShortPath(scanPos.Filename)
287 pos = scanPos.String()
288 err = errors.New(scanErr[0].Msg)
291 // Report the error on the importing package if the problem is with the import declaration
292 // for example, if the package doesn't exist or if the import path is malformed.
293 // On the other hand, don't include a position if the problem is with the imported package,
294 // for example there are no Go files (NoGoError), or there's a problem in the imported
295 // package's source files themselves (scanner errors).
297 // TODO(matloob): Perhaps make each of those the errors in the first group
298 // (including modload.ImportMissingError, ImportMissingSumError, and the
299 // corresponding "cannot find package %q in any of" GOPATH-mode error
300 // produced in build.(*Context).Import; modload.AmbiguousImportError,
301 // and modload.PackageNotInModuleError; and the malformed module path errors
302 // produced in golang.org/x/mod/module.CheckMod) implement an interface
303 // to make it easier to check for them? That would save us from having to
304 // move the modload errors into this package to avoid a package import cycle,
305 // and from having to export an error type for the errors produced in build.
306 if !isMatchErr && (nogoErr != nil || isScanErr) {
311 p.Error = &PackageError{
312 ImportStack: stk.Copy(),
317 if path != stk.Top() {
318 p.Error.setPos(importPos)
322 // Resolve returns the resolved version of imports,
323 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
324 // The imports in p.TestImports and p.XTestImports are not recursively
325 // loaded during the initial load of p, so they list the imports found in
326 // the source file, but most processing should be over the vendor-resolved
327 // import paths. We do this resolution lazily both to avoid file system work
328 // and because the eventual real load of the test imports (during 'go test')
329 // can produce better error messages if it starts with the original paths.
330 // The initial load of p loads all the non-test imports and rewrites
331 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
332 func (p *Package) Resolve(imports []string) []string {
333 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
334 panic("internal error: p.Resolve(p.Imports) called")
336 seen := make(map[string]bool)
338 for _, path := range imports {
339 path = ResolveImportPath(p, path)
342 all = append(all, path)
349 // CoverVar holds the name of the generated coverage variables targeting the named file.
350 type CoverVar struct {
351 File string // local file name
352 Var string // name of count struct
355 func (p *Package) copyBuild(opts PackageOpts, pp *build.Package) {
356 p.Internal.Build = pp
358 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
359 old := pp.PkgTargetRoot
360 pp.PkgRoot = cfg.BuildPkgdir
361 pp.PkgTargetRoot = cfg.BuildPkgdir
362 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
366 p.ImportPath = pp.ImportPath
367 p.ImportComment = pp.ImportComment
371 p.ConflictDir = pp.ConflictDir
372 p.BinaryOnly = pp.BinaryOnly
376 p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
377 p.GoFiles = pp.GoFiles
378 p.CgoFiles = pp.CgoFiles
379 p.IgnoredGoFiles = pp.IgnoredGoFiles
380 p.InvalidGoFiles = pp.InvalidGoFiles
381 p.IgnoredOtherFiles = pp.IgnoredOtherFiles
383 p.CXXFiles = pp.CXXFiles
388 p.SwigFiles = pp.SwigFiles
389 p.SwigCXXFiles = pp.SwigCXXFiles
390 p.SysoFiles = pp.SysoFiles
392 // There's no way for .syso files to be built both with and without
393 // support for memory sanitizer. Assume they are built without,
397 p.CgoCFLAGS = pp.CgoCFLAGS
398 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
399 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
400 p.CgoFFLAGS = pp.CgoFFLAGS
401 p.CgoLDFLAGS = pp.CgoLDFLAGS
402 p.CgoPkgConfig = pp.CgoPkgConfig
403 // We modify p.Imports in place, so make copy now.
404 p.Imports = make([]string, len(pp.Imports))
405 copy(p.Imports, pp.Imports)
406 p.Internal.RawImports = pp.Imports
407 p.TestGoFiles = pp.TestGoFiles
408 p.TestImports = pp.TestImports
409 p.XTestGoFiles = pp.XTestGoFiles
410 p.XTestImports = pp.XTestImports
411 if opts.IgnoreImports {
413 p.Internal.RawImports = nil
417 p.EmbedPatterns = pp.EmbedPatterns
418 p.TestEmbedPatterns = pp.TestEmbedPatterns
419 p.XTestEmbedPatterns = pp.XTestEmbedPatterns
420 p.Internal.OrigImportPath = pp.ImportPath
423 // A PackageError describes an error loading information about a package.
424 type PackageError struct {
425 ImportStack []string // shortest path from package named on command line to this one
426 Pos string // position of error
427 Err error // the error itself
428 IsImportCycle bool // the error is an import cycle
429 Hard bool // whether the error is soft or hard; soft errors are ignored in some places
430 alwaysPrintStack bool // whether to always print the ImportStack
433 func (p *PackageError) Error() string {
434 // TODO(#43696): decide when to print the stack or the position based on
435 // the error type and whether the package is in the main module.
436 // Document the rationale.
437 if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
438 // Omit import stack. The full path to the file where the error
439 // is the most important thing.
440 return p.Pos + ": " + p.Err.Error()
443 // If the error is an ImportPathError, and the last path on the stack appears
444 // in the error message, omit that path from the stack to avoid repetition.
445 // If an ImportPathError wraps another ImportPathError that matches the
446 // last path on the stack, we don't omit the path. An error like
447 // "package A imports B: error loading C caused by B" would not be clearer
448 // if "imports B" were omitted.
449 if len(p.ImportStack) == 0 {
454 optpos = "\n\t" + p.Pos
456 return "package " + strings.Join(p.ImportStack, "\n\timports ") + optpos + ": " + p.Err.Error()
459 func (p *PackageError) Unwrap() error { return p.Err }
461 // PackageError implements MarshalJSON so that Err is marshaled as a string
462 // and non-essential fields are omitted.
463 func (p *PackageError) MarshalJSON() ([]byte, error) {
468 }{p.ImportStack, p.Pos, p.Err.Error()}
469 return json.Marshal(perr)
472 func (p *PackageError) setPos(posList []token.Position) {
473 if len(posList) == 0 {
477 pos.Filename = base.ShortPath(pos.Filename)
481 // ImportPathError is a type of error that prevents a package from being loaded
482 // for a given import path. When such a package is loaded, a *Package is
483 // returned with Err wrapping an ImportPathError: the error is attached to
484 // the imported package, not the importing package.
486 // The string returned by ImportPath must appear in the string returned by
487 // Error. Errors that wrap ImportPathError (such as PackageError) may omit
489 type ImportPathError interface {
495 _ ImportPathError = (*importError)(nil)
496 _ ImportPathError = (*mainPackageError)(nil)
497 _ ImportPathError = (*modload.ImportMissingError)(nil)
498 _ ImportPathError = (*modload.ImportMissingSumError)(nil)
499 _ ImportPathError = (*modload.DirectImportFromImplicitDependencyError)(nil)
502 type importError struct {
504 err error // created with fmt.Errorf
507 func ImportErrorf(path, format string, args ...interface{}) ImportPathError {
508 err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
509 if errStr := err.Error(); !strings.Contains(errStr, path) {
510 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
515 func (e *importError) Error() string {
519 func (e *importError) Unwrap() error {
520 // Don't return e.err directly, since we're only wrapping an error if %w
521 // was passed to ImportErrorf.
522 return errors.Unwrap(e.err)
525 func (e *importError) ImportPath() string {
529 // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
530 // The import path of a test package is the import path of the corresponding
531 // non-test package with the suffix "_test" added.
532 type ImportStack []string
534 func (s *ImportStack) Push(p string) {
538 func (s *ImportStack) Pop() {
539 *s = (*s)[0 : len(*s)-1]
542 func (s *ImportStack) Copy() []string {
543 return append([]string{}, *s...)
546 func (s *ImportStack) Top() string {
550 return (*s)[len(*s)-1]
553 // shorterThan reports whether sp is shorter than t.
554 // We use this to record the shortest import sequence
555 // that leads to a particular package.
556 func (sp *ImportStack) shorterThan(t []string) bool {
558 if len(s) != len(t) {
559 return len(s) < len(t)
561 // If they are the same length, settle ties using string ordering.
567 return false // they are equal
570 // packageCache is a lookup cache for LoadImport,
571 // so that if we look up a package multiple times
572 // we return the same pointer each time.
573 var packageCache = map[string]*Package{}
575 // ClearPackageCache clears the in-memory package cache and the preload caches.
576 // It is only for use by GOPATH-based "go get".
577 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
578 func ClearPackageCache() {
579 for name := range packageCache {
580 delete(packageCache, name)
582 resolvedImportCache.Clear()
583 packageDataCache.Clear()
586 // ClearPackageCachePartial clears packages with the given import paths from the
587 // in-memory package cache and the preload caches. It is only for use by
588 // GOPATH-based "go get".
589 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
590 func ClearPackageCachePartial(args []string) {
591 shouldDelete := make(map[string]bool)
592 for _, arg := range args {
593 shouldDelete[arg] = true
594 if p := packageCache[arg]; p != nil {
595 delete(packageCache, arg)
598 resolvedImportCache.DeleteIf(func(key interface{}) bool {
599 return shouldDelete[key.(importSpec).path]
601 packageDataCache.DeleteIf(func(key interface{}) bool {
602 return shouldDelete[key.(string)]
606 // ReloadPackageNoFlags is like LoadImport but makes sure
607 // not to use the package cache.
608 // It is only for use by GOPATH-based "go get".
609 // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
610 func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
611 p := packageCache[arg]
613 delete(packageCache, arg)
614 resolvedImportCache.DeleteIf(func(key interface{}) bool {
615 return key.(importSpec).path == p.ImportPath
617 packageDataCache.Delete(p.ImportPath)
619 return LoadImport(context.TODO(), PackageOpts{}, arg, base.Cwd(), nil, stk, nil, 0)
622 // dirToImportPath returns the pseudo-import path we use for a package
623 // outside the Go path. It begins with _/ and then contains the full path
624 // to the directory. If the package lives in c:\home\gopher\my\pkg then
625 // the pseudo-import path is _/c_/home/gopher/my/pkg.
626 // Using a pseudo-import path like this makes the ./ imports no longer
627 // a special case, so that all the code to deal with ordinary imports works
629 func dirToImportPath(dir string) string {
630 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
633 func makeImportValid(r rune) rune {
634 // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
635 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
636 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
642 // Mode flags for loadImport and download (in get.go).
644 // ResolveImport means that loadImport should do import path expansion.
645 // That is, ResolveImport means that the import path came from
646 // a source file and has not been expanded yet to account for
647 // vendoring or possible module adjustment.
648 // Every import path should be loaded initially with ResolveImport,
649 // and then the expanded version (for example with the /vendor/ in it)
650 // gets recorded as the canonical import path. At that point, future loads
651 // of that package must not pass ResolveImport, because
652 // disallowVendor will reject direct use of paths containing /vendor/.
653 ResolveImport = 1 << iota
655 // ResolveModule is for download (part of "go get") and indicates
656 // that the module adjustment should be done, but not vendor adjustment.
659 // GetTestDeps is for download (part of "go get") and indicates
660 // that test dependencies should be fetched too.
664 // LoadImport scans the directory named by path, which must be an import path,
665 // but possibly a local import path (an absolute file system path or one beginning
666 // with ./ or ../). A local relative path is interpreted relative to srcDir.
667 // It returns a *Package describing the package found in that directory.
668 // LoadImport does not set tool flags and should only be used by
669 // this package, as part of a bigger load operation, and by GOPATH-based "go get".
670 // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
671 func LoadImport(ctx context.Context, opts PackageOpts, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
672 return loadImport(ctx, opts, nil, path, srcDir, parent, stk, importPos, mode)
675 func loadImport(ctx context.Context, opts PackageOpts, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
677 panic("LoadImport called with empty package path")
680 var parentPath, parentRoot string
683 parentPath = parent.ImportPath
684 parentRoot = parent.Root
685 parentIsStd = parent.Standard
687 bp, loaded, err := loadPackageData(ctx, path, parentPath, srcDir, parentRoot, parentIsStd, mode)
688 if loaded && pre != nil && !opts.IgnoreImports {
689 pre.preloadImports(ctx, opts, bp.Imports, bp)
693 PackagePublic: PackagePublic{
698 if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
699 // Only add path to the error's import stack if it's not already present
702 // TODO(bcmills): setLoadPackageDataError itself has a similar Push / Pop
703 // sequence that empirically doesn't trigger for these errors, guarded by
704 // a somewhat complex condition. Figure out how to generalize that
705 // condition and eliminate the explicit calls here.
709 p.setLoadPackageDataError(err, path, stk, nil)
713 importPath := bp.ImportPath
714 p := packageCache[importPath]
717 p = reusePackage(p, stk)
721 p.Internal.Local = build.IsLocalImport(path)
722 p.ImportPath = importPath
723 packageCache[importPath] = p
726 // loadPackageData may return bp != nil even if an error occurs,
727 // in order to return partial information.
728 p.load(ctx, opts, path, stk, importPos, bp, err)
730 if !cfg.ModulesEnabled && path != cleanImport(path) {
731 p.Error = &PackageError{
732 ImportStack: stk.Copy(),
733 Err: ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
736 p.Error.setPos(importPos)
740 // Checked on every import because the rules depend on the code doing the importing.
741 if perr := disallowInternal(ctx, srcDir, parent, parentPath, p, stk); perr != p {
742 perr.Error.setPos(importPos)
745 if mode&ResolveImport != 0 {
746 if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != p {
747 perr.Error.setPos(importPos)
752 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
754 perr.Error = &PackageError{
755 ImportStack: stk.Copy(),
756 Err: ImportErrorf(path, "import %q is a program, not an importable package", path),
758 perr.Error.setPos(importPos)
762 if p.Internal.Local && parent != nil && !parent.Internal.Local {
766 err = ImportErrorf(path, "%s: cannot import current directory", path)
768 err = ImportErrorf(path, "local import %q in non-local package", path)
770 perr.Error = &PackageError{
771 ImportStack: stk.Copy(),
774 perr.Error.setPos(importPos)
781 // loadPackageData loads information needed to construct a *Package. The result
782 // is cached, and later calls to loadPackageData for the same package will return
785 // loadPackageData returns a non-nil package even if err is non-nil unless
786 // the package path is malformed (for example, the path contains "mod/" or "@").
788 // loadPackageData returns a boolean, loaded, which is true if this is the
789 // first time the package was loaded. Callers may preload imports in this case.
790 func loadPackageData(ctx context.Context, path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
792 panic("loadPackageData called with empty package path")
795 if strings.HasPrefix(path, "mod/") {
796 // Paths beginning with "mod/" might accidentally
797 // look in the module cache directory tree in $GOPATH/pkg/mod/.
798 // This prefix is owned by the Go core for possible use in the
799 // standard library (since it does not begin with a domain name),
800 // so it's OK to disallow entirely.
801 return nil, false, fmt.Errorf("disallowed import path %q", path)
804 if strings.Contains(path, "@") {
805 return nil, false, errors.New("can only use path@version syntax with 'go get' and 'go install' in module-aware mode")
808 // Determine canonical package path and directory.
809 // For a local import the identifier is the pseudo-import path
810 // we create from the full directory to the package.
811 // Otherwise it is the usual import path.
812 // For vendored imports, it is the expanded form.
814 // Note that when modules are enabled, local import paths are normally
815 // canonicalized by modload.LoadPackages before now. However, if there's an
816 // error resolving a local path, it will be returned untransformed
817 // so that 'go list -e' reports something useful.
818 importKey := importSpec{
820 parentPath: parentPath,
821 parentDir: parentDir,
822 parentRoot: parentRoot,
823 parentIsStd: parentIsStd,
826 r := resolvedImportCache.Do(importKey, func() interface{} {
828 if build.IsLocalImport(path) {
829 r.dir = filepath.Join(parentDir, path)
830 r.path = dirToImportPath(r.dir)
831 } else if cfg.ModulesEnabled {
832 r.dir, r.path, r.err = modload.Lookup(parentPath, parentIsStd, path)
833 } else if mode&ResolveImport != 0 {
834 // We do our own path resolution, because we want to
835 // find out the key to use in packageCache without the
836 // overhead of repeated calls to buildContext.Import.
837 // The code is also needed in a few other places anyway.
838 r.path = resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
839 } else if mode&ResolveModule != 0 {
840 r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
847 // Invariant: r.path is set to the resolved import path. If the path cannot
848 // be resolved, r.path is set to path, the source import path.
849 // r.path is never empty.
851 // Load the package from its directory. If we already found the package's
852 // directory when resolving its import path, use that.
853 data := packageDataCache.Do(r.path, func() interface{} {
857 var buildMode build.ImportMode
858 if !cfg.ModulesEnabled {
859 buildMode = build.ImportComment
861 data.p, data.err = cfg.BuildContext.ImportDir(r.dir, buildMode)
862 if cfg.ModulesEnabled {
863 // Override data.p.Root, since ImportDir sets it to $GOPATH, if
864 // the module is inside $GOPATH/src.
865 if info := modload.PackageModuleInfo(ctx, path); info != nil {
866 data.p.Root = info.Dir
871 // ImportDir gave us one error, and the module loader gave us another.
872 // We arbitrarily choose to keep the error from ImportDir because
873 // that's what our tests already expect, and it seems to provide a bit
874 // more detail in most cases.
875 } else if errors.Is(r.err, imports.ErrNoGo) {
876 // ImportDir said there were files in the package, but the module
877 // loader said there weren't. Which one is right?
878 // Without this special-case hack, the TestScript/test_vet case fails
879 // on the vetfail/p1 package (added in CL 83955).
880 // Apparently, imports.ShouldBuild biases toward rejecting files
881 // with invalid build constraints, whereas ImportDir biases toward
884 // TODO(#41410: Figure out how this actually ought to work and fix
890 } else if r.err != nil {
891 data.p = new(build.Package)
893 } else if cfg.ModulesEnabled && path != "unsafe" {
894 data.p = new(build.Package)
895 data.err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", r.path)
897 buildMode := build.ImportComment
898 if mode&ResolveImport == 0 || r.path != path {
899 // Not vendoring, or we already found the vendored path.
900 buildMode |= build.IgnoreVendor
902 data.p, data.err = cfg.BuildContext.Import(r.path, parentDir, buildMode)
904 data.p.ImportPath = r.path
906 // Set data.p.BinDir in cases where go/build.Context.Import
907 // may give us a path we don't want.
910 data.p.BinDir = cfg.GOBIN
911 } else if cfg.ModulesEnabled {
912 data.p.BinDir = modload.BinDir()
916 if !cfg.ModulesEnabled && data.err == nil &&
917 data.p.ImportComment != "" && data.p.ImportComment != path &&
918 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
919 data.err = fmt.Errorf("code in directory %s expects import %q", data.p.Dir, data.p.ImportComment)
924 return data.p, loaded, data.err
927 // importSpec describes an import declaration in source code. It is used as a
928 // cache key for resolvedImportCache.
929 type importSpec struct {
931 parentPath, parentDir, parentRoot string
936 // resolvedImport holds a canonical identifier for a package. It may also contain
937 // a path to the package's directory and an error if one occurred. resolvedImport
938 // is the value type in resolvedImportCache.
939 type resolvedImport struct {
944 // packageData holds information loaded from a package. It is the value type
945 // in packageDataCache.
946 type packageData struct {
951 // resolvedImportCache maps import strings (importSpec) to canonical package names
953 var resolvedImportCache par.Cache
955 // packageDataCache maps canonical package names (string) to package metadata
957 var packageDataCache par.Cache
959 // preloadWorkerCount is the number of concurrent goroutines that can load
960 // packages. Experimentally, there are diminishing returns with more than
961 // 4 workers. This was measured on the following machines.
963 // * MacBookPro with a 4-core Intel Core i7 CPU
964 // * Linux workstation with 6-core Intel Xeon CPU
965 // * Linux workstation with 24-core Intel Xeon CPU
967 // It is very likely (though not confirmed) that this workload is limited
968 // by memory bandwidth. We don't have a good way to determine the number of
969 // workers that would saturate the bus though, so runtime.GOMAXPROCS
970 // seems like a reasonable default.
971 var preloadWorkerCount = runtime.GOMAXPROCS(0)
973 // preload holds state for managing concurrent preloading of package data.
975 // A preload should be created with newPreload before loading a large
976 // package graph. flush must be called when package loading is complete
977 // to ensure preload goroutines are no longer active. This is necessary
978 // because of global mutable state that cannot safely be read and written
979 // concurrently. In particular, packageDataCache may be cleared by "go get"
980 // in GOPATH mode, and modload.loaded (accessed via modload.Lookup) may be
981 // modified by modload.LoadPackages.
982 type preload struct {
987 // newPreload creates a new preloader. flush must be called later to avoid
988 // accessing global state while it is being modified.
989 func newPreload() *preload {
991 cancel: make(chan struct{}),
992 sema: make(chan struct{}, preloadWorkerCount),
997 // preloadMatches loads data for package paths matched by patterns.
998 // When preloadMatches returns, some packages may not be loaded yet, but
999 // loadPackageData and loadImport are always safe to call.
1000 func (pre *preload) preloadMatches(ctx context.Context, opts PackageOpts, matches []*search.Match) {
1001 for _, m := range matches {
1002 for _, pkg := range m.Pkgs {
1006 case pre.sema <- struct{}{}:
1007 go func(pkg string) {
1008 mode := 0 // don't use vendoring or module import resolution
1009 bp, loaded, err := loadPackageData(ctx, pkg, "", base.Cwd(), "", false, mode)
1011 if bp != nil && loaded && err == nil && !opts.IgnoreImports {
1012 pre.preloadImports(ctx, opts, bp.Imports, bp)
1020 // preloadImports queues a list of imports for preloading.
1021 // When preloadImports returns, some packages may not be loaded yet,
1022 // but loadPackageData and loadImport are always safe to call.
1023 func (pre *preload) preloadImports(ctx context.Context, opts PackageOpts, imports []string, parent *build.Package) {
1024 parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
1025 for _, path := range imports {
1026 if path == "C" || path == "unsafe" {
1032 case pre.sema <- struct{}{}:
1033 go func(path string) {
1034 bp, loaded, err := loadPackageData(ctx, path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
1036 if bp != nil && loaded && err == nil && !opts.IgnoreImports {
1037 pre.preloadImports(ctx, opts, bp.Imports, bp)
1044 // flush stops pending preload operations. flush blocks until preload calls to
1045 // loadPackageData have completed. The preloader will not make any new calls
1046 // to loadPackageData.
1047 func (pre *preload) flush() {
1048 // flush is usually deferred.
1049 // Don't hang program waiting for workers on panic.
1050 if v := recover(); v != nil {
1055 for i := 0; i < preloadWorkerCount; i++ {
1056 pre.sema <- struct{}{}
1060 func cleanImport(path string) string {
1062 path = pathpkg.Clean(path)
1063 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
1069 var isDirCache par.Cache
1071 func isDir(path string) bool {
1072 return isDirCache.Do(path, func() interface{} {
1073 fi, err := fsys.Stat(path)
1074 return err == nil && fi.IsDir()
1078 // ResolveImportPath returns the true meaning of path when it appears in parent.
1079 // There are two different resolutions applied.
1080 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
1081 // If vendor expansion doesn't trigger, then the path is also subject to
1082 // Go 1.11 module legacy conversion (golang.org/issue/25069).
1083 func ResolveImportPath(parent *Package, path string) (found string) {
1084 var parentPath, parentDir, parentRoot string
1085 parentIsStd := false
1087 parentPath = parent.ImportPath
1088 parentDir = parent.Dir
1089 parentRoot = parent.Root
1090 parentIsStd = parent.Standard
1092 return resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
1095 func resolveImportPath(path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
1096 if cfg.ModulesEnabled {
1097 if _, p, e := modload.Lookup(parentPath, parentIsStd, path); e == nil {
1102 found = vendoredImportPath(path, parentPath, parentDir, parentRoot)
1106 return moduleImportPath(path, parentPath, parentDir, parentRoot)
1109 // dirAndRoot returns the source directory and workspace root
1110 // for the package p, guaranteeing that root is a path prefix of dir.
1111 func dirAndRoot(path string, dir, root string) (string, string) {
1112 origDir, origRoot := dir, root
1113 dir = filepath.Clean(dir)
1114 root = filepath.Join(root, "src")
1115 if !str.HasFilePathPrefix(dir, root) || path != "command-line-arguments" && filepath.Join(root, path) != dir {
1116 // Look for symlinks before reporting error.
1117 dir = expandPath(dir)
1118 root = expandPath(root)
1121 if !str.HasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || path != "command-line-arguments" && !build.IsLocalImport(path) && filepath.Join(root, path) != dir {
1122 base.Fatalf("unexpected directory layout:\n"+
1123 " import path: %s\n"+
1126 " expand root: %s\n"+
1127 " expand dir: %s\n"+
1130 filepath.Join(origRoot, "src"),
1131 filepath.Clean(origDir),
1134 string(filepath.Separator))
1140 // vendoredImportPath returns the vendor-expansion of path when it appears in parent.
1141 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
1142 // x/vendor/path, vendor/path, or else stay path if none of those exist.
1143 // vendoredImportPath returns the expanded path or, if no expansion is found, the original.
1144 func vendoredImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1145 if parentRoot == "" {
1149 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1151 vpath := "vendor/" + path
1152 for i := len(dir); i >= len(root); i-- {
1153 if i < len(dir) && dir[i] != filepath.Separator {
1156 // Note: checking for the vendor directory before checking
1157 // for the vendor/path directory helps us hit the
1158 // isDir cache more often. It also helps us prepare a more useful
1159 // list of places we looked, to report when an import is not found.
1160 if !isDir(filepath.Join(dir[:i], "vendor")) {
1163 targ := filepath.Join(dir[:i], vpath)
1164 if isDir(targ) && hasGoFiles(targ) {
1165 importPath := parentPath
1166 if importPath == "command-line-arguments" {
1167 // If parent.ImportPath is 'command-line-arguments'.
1168 // set to relative directory to root (also chopped root directory)
1169 importPath = dir[len(root)+1:]
1171 // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
1172 // We know the import path for parent's dir.
1173 // We chopped off some number of path elements and
1174 // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
1175 // Now we want to know the import path for that directory.
1176 // Construct it by chopping the same number of path elements
1177 // (actually the same number of bytes) from parent's import path
1178 // and then append /vendor/path.
1179 chopped := len(dir) - i
1180 if chopped == len(importPath)+1 {
1181 // We walked up from c:\gopath\src\foo\bar
1182 // and found c:\gopath\src\vendor\path.
1183 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
1184 // Use "vendor/path" without any prefix.
1187 return importPath[:len(importPath)-chopped] + "/" + vpath
1194 modulePrefix = []byte("\nmodule ")
1195 goModPathCache par.Cache
1198 // goModPath returns the module path in the go.mod in dir, if any.
1199 func goModPath(dir string) (path string) {
1200 return goModPathCache.Do(dir, func() interface{} {
1201 data, err := os.ReadFile(filepath.Join(dir, "go.mod"))
1206 if bytes.HasPrefix(data, modulePrefix[1:]) {
1209 i = bytes.Index(data, modulePrefix)
1217 // Cut line at \n, drop trailing \r if present.
1218 if j := bytes.IndexByte(line, '\n'); j >= 0 {
1221 if line[len(line)-1] == '\r' {
1222 line = line[:len(line)-1]
1224 line = line[len("module "):]
1226 // If quoted, unquote.
1227 path = strings.TrimSpace(string(line))
1228 if path != "" && path[0] == '"' {
1229 s, err := strconv.Unquote(path)
1239 // findVersionElement returns the slice indices of the final version element /vN in path.
1240 // If there is no such element, it returns -1, -1.
1241 func findVersionElement(path string) (i, j int) {
1243 for i = len(path) - 1; i >= 0; i-- {
1245 if isVersionElement(path[i+1 : j]) {
1254 // isVersionElement reports whether s is a well-formed path version element:
1255 // v2, v3, v10, etc, but not v0, v05, v1.
1256 func isVersionElement(s string) bool {
1257 if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
1260 for i := 1; i < len(s); i++ {
1261 if s[i] < '0' || '9' < s[i] {
1268 // moduleImportPath translates import paths found in go modules
1269 // back down to paths that can be resolved in ordinary builds.
1271 // Define “new” code as code with a go.mod file in the same directory
1272 // or a parent directory. If an import in new code says x/y/v2/z but
1273 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
1274 // then go build will read the import as x/y/z instead.
1275 // See golang.org/issue/25069.
1276 func moduleImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1277 if parentRoot == "" {
1281 // If there are no vN elements in path, leave it alone.
1282 // (The code below would do the same, but only after
1283 // some other file system accesses that we can avoid
1284 // here by returning early.)
1285 if i, _ := findVersionElement(path); i < 0 {
1289 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1291 // Consider dir and parents, up to and including root.
1292 for i := len(dir); i >= len(root); i-- {
1293 if i < len(dir) && dir[i] != filepath.Separator {
1296 if goModPath(dir[:i]) != "" {
1300 // This code is not in a tree with a go.mod,
1301 // so apply no changes to the path.
1305 // This import is in a tree with a go.mod.
1306 // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
1307 // if GOPATH/src/x/y/go.mod says module "x/y/v2",
1309 // If x/y/v2/z exists, use it unmodified.
1310 if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
1314 // Otherwise look for a go.mod supplying a version element.
1315 // Some version-like elements may appear in paths but not
1316 // be module versions; we skip over those to look for module
1317 // versions. For example the module m/v2 might have a
1318 // package m/v2/api/v1/foo.
1321 i, j := findVersionElement(path[:limit])
1325 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
1326 if mpath := goModPath(bp.Dir); mpath != "" {
1327 // Found a valid go.mod file, so we're stopping the search.
1328 // If the path is m/v2/p and we found m/go.mod that says
1329 // "module m/v2", then we return "m/p".
1330 if mpath == path[:j] {
1331 return path[:i] + path[j:]
1333 // Otherwise just return the original path.
1334 // We didn't find anything worth rewriting,
1335 // and the go.mod indicates that we should
1336 // not consider parent directories.
1345 // hasGoFiles reports whether dir contains any files with names ending in .go.
1346 // For a vendor check we must exclude directories that contain no .go files.
1347 // Otherwise it is not possible to vendor just a/b/c and still import the
1348 // non-vendored a/b. See golang.org/issue/13832.
1349 func hasGoFiles(dir string) bool {
1350 files, _ := os.ReadDir(dir)
1351 for _, f := range files {
1352 if !f.IsDir() && strings.HasSuffix(f.Name(), ".go") {
1359 // reusePackage reuses package p to satisfy the import at the top
1360 // of the import stack stk. If this use causes an import loop,
1361 // reusePackage updates p's error information to record the loop.
1362 func reusePackage(p *Package, stk *ImportStack) *Package {
1363 // We use p.Internal.Imports==nil to detect a package that
1364 // is in the midst of its own loadPackage call
1365 // (all the recursion below happens before p.Internal.Imports gets set).
1366 if p.Internal.Imports == nil {
1368 p.Error = &PackageError{
1369 ImportStack: stk.Copy(),
1370 Err: errors.New("import cycle not allowed"),
1371 IsImportCycle: true,
1373 } else if !p.Error.IsImportCycle {
1374 // If the error is already set, but it does not indicate that
1375 // we are in an import cycle, set IsImportCycle so that we don't
1376 // end up stuck in a loop down the road.
1377 p.Error.IsImportCycle = true
1381 // Don't rewrite the import stack in the error if we have an import cycle.
1382 // If we do, we'll lose the path that describes the cycle.
1383 if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
1384 p.Error.ImportStack = stk.Copy()
1389 // disallowInternal checks that srcDir (containing package importerPath, if non-empty)
1390 // is allowed to import p.
1391 // If the import is allowed, disallowInternal returns the original package p.
1392 // If not, it returns a new package containing just an appropriate error.
1393 func disallowInternal(ctx context.Context, srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package {
1394 // golang.org/s/go14internal:
1395 // An import of a path containing the element “internal”
1396 // is disallowed if the importing code is outside the tree
1397 // rooted at the parent of the “internal” directory.
1399 // There was an error loading the package; stop here.
1404 // The generated 'testmain' package is allowed to access testing/internal/...,
1405 // as if it were generated into the testing directory tree
1406 // (it's actually in a temporary directory outside any Go tree).
1407 // This cleans up a former kludge in passing functionality to the testing package.
1408 if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
1412 // We can't check standard packages with gccgo.
1413 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
1417 // The sort package depends on internal/reflectlite, but during bootstrap
1418 // the path rewriting causes the normal internal checks to fail.
1419 // Instead, just ignore the internal rules during bootstrap.
1420 if p.Standard && strings.HasPrefix(importerPath, "bootstrap/") {
1424 // importerPath is empty: we started
1425 // with a name given on the command line, not an
1426 // import. Anything listed on the command line is fine.
1427 if importerPath == "" {
1431 // Check for "internal" element: three cases depending on begin of string and/or end of string.
1432 i, ok := findInternal(p.ImportPath)
1437 // Internal is present.
1438 // Map import path back to directory corresponding to parent of internal.
1440 i-- // rewind over slash in ".../internal"
1443 if p.Module == nil {
1444 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
1446 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1450 // Look for symlinks before reporting error.
1451 srcDir = expandPath(srcDir)
1452 parent = expandPath(parent)
1453 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1457 // p is in a module, so make it available based on the importer's import path instead
1458 // of the file path (https://golang.org/issue/23970).
1459 if importer.Internal.CmdlineFiles {
1460 // The importer is a list of command-line files.
1461 // Pretend that the import path is the import path of the
1462 // directory containing them.
1463 // If the directory is outside the main modules, this will resolve to ".",
1464 // which is not a prefix of any valid module.
1465 importerPath, _ = modload.MainModules.DirImportPath(ctx, importer.Dir)
1467 parentOfInternal := p.ImportPath[:i]
1468 if str.HasPathPrefix(importerPath, parentOfInternal) {
1473 // Internal is present, and srcDir is outside parent's tree. Not allowed.
1475 perr.Error = &PackageError{
1476 alwaysPrintStack: true,
1477 ImportStack: stk.Copy(),
1478 Err: ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
1480 perr.Incomplete = true
1484 // findInternal looks for the final "internal" path element in the given import path.
1485 // If there isn't one, findInternal returns ok=false.
1486 // Otherwise, findInternal returns ok=true and the index of the "internal".
1487 func findInternal(path string) (index int, ok bool) {
1488 // Three cases, depending on internal at start/end of string or not.
1489 // The order matters: we must return the index of the final element,
1490 // because the final one produces the most restrictive requirement
1493 case strings.HasSuffix(path, "/internal"):
1494 return len(path) - len("internal"), true
1495 case strings.Contains(path, "/internal/"):
1496 return strings.LastIndex(path, "/internal/") + 1, true
1497 case path == "internal", strings.HasPrefix(path, "internal/"):
1503 // disallowVendor checks that srcDir is allowed to import p as path.
1504 // If the import is allowed, disallowVendor returns the original package p.
1505 // If not, it returns a new package containing just an appropriate error.
1506 func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *Package {
1507 // If the importerPath is empty, we started
1508 // with a name given on the command line, not an
1509 // import. Anything listed on the command line is fine.
1510 if importerPath == "" {
1514 if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != p {
1518 // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
1519 if i, ok := FindVendor(path); ok {
1521 perr.Error = &PackageError{
1522 ImportStack: stk.Copy(),
1523 Err: ImportErrorf(path, "%s must be imported as %s", path, path[i+len("vendor/"):]),
1525 perr.Incomplete = true
1532 // disallowVendorVisibility checks that srcDir is allowed to import p.
1533 // The rules are the same as for /internal/ except that a path ending in /vendor
1534 // is not subject to the rules, only subdirectories of vendor.
1535 // This allows people to have packages and commands named vendor,
1536 // for maximal compatibility with existing source trees.
1537 func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *Package {
1538 // The stack does not include p.ImportPath.
1539 // If there's nothing on the stack, we started
1540 // with a name given on the command line, not an
1541 // import. Anything listed on the command line is fine.
1542 if importerPath == "" {
1546 // Check for "vendor" element.
1547 i, ok := FindVendor(p.ImportPath)
1552 // Vendor is present.
1553 // Map import path back to directory corresponding to parent of vendor.
1555 i-- // rewind over slash in ".../vendor"
1557 truncateTo := i + len(p.Dir) - len(p.ImportPath)
1558 if truncateTo < 0 || len(p.Dir) < truncateTo {
1561 parent := p.Dir[:truncateTo]
1562 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1566 // Look for symlinks before reporting error.
1567 srcDir = expandPath(srcDir)
1568 parent = expandPath(parent)
1569 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1573 // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1575 perr.Error = &PackageError{
1576 ImportStack: stk.Copy(),
1577 Err: errors.New("use of vendored package not allowed"),
1579 perr.Incomplete = true
1583 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1584 // If there isn't one, FindVendor returns ok=false.
1585 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1587 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1588 // not the vendored copy of an import "" (the empty import path).
1589 // This will allow people to have packages or commands named vendor.
1590 // This may help reduce breakage, or it may just be confusing. We'll see.
1591 func FindVendor(path string) (index int, ok bool) {
1592 // Two cases, depending on internal at start of string or not.
1593 // The order matters: we must return the index of the final element,
1594 // because the final one is where the effective import path starts.
1596 case strings.Contains(path, "/vendor/"):
1597 return strings.LastIndex(path, "/vendor/") + 1, true
1598 case strings.HasPrefix(path, "vendor/"):
1607 ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1608 ToBin // to bin dir inside package root (default for non-cmd/*)
1609 StalePath // an old import path; fail to build
1612 // InstallTargetDir reports the target directory for installing the command p.
1613 func InstallTargetDir(p *Package) TargetDir {
1614 if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1617 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1618 switch p.ImportPath {
1619 case "cmd/go", "cmd/gofmt":
1627 var cgoExclude = map[string]bool{
1628 "runtime/cgo": true,
1631 var cgoSyscallExclude = map[string]bool{
1632 "runtime/cgo": true,
1633 "runtime/race": true,
1634 "runtime/msan": true,
1635 "runtime/asan": true,
1638 var foldPath = make(map[string]string)
1640 // exeFromImportPath returns an executable name
1641 // for a package using the import path.
1643 // The executable name is the last element of the import path.
1644 // In module-aware mode, an additional rule is used on import paths
1645 // consisting of two or more path elements. If the last element is
1646 // a vN path element specifying the major version, then the
1647 // second last element of the import path is used instead.
1648 func (p *Package) exeFromImportPath() string {
1649 _, elem := pathpkg.Split(p.ImportPath)
1650 if cfg.ModulesEnabled {
1651 // If this is example.com/mycmd/v2, it's more useful to
1652 // install it as mycmd than as v2. See golang.org/issue/24667.
1653 if elem != p.ImportPath && isVersionElement(elem) {
1654 _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
1660 // exeFromFiles returns an executable name for a package
1661 // using the first element in GoFiles or CgoFiles collections without the prefix.
1663 // Returns empty string in case of empty collection.
1664 func (p *Package) exeFromFiles() string {
1666 if len(p.GoFiles) > 0 {
1668 } else if len(p.CgoFiles) > 0 {
1673 _, elem := filepath.Split(src)
1674 return elem[:len(elem)-len(".go")]
1677 // DefaultExecName returns the default executable name for a package
1678 func (p *Package) DefaultExecName() string {
1679 if p.Internal.CmdlineFiles {
1680 return p.exeFromFiles()
1682 return p.exeFromImportPath()
1685 // load populates p using information from bp, err, which should
1686 // be the result of calling build.Context.Import.
1687 // stk contains the import stack, not including path itself.
1688 func (p *Package) load(ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
1689 p.copyBuild(opts, bp)
1691 // The localPrefix is the path we interpret ./ imports relative to,
1692 // if we support them at all (not in module mode!).
1693 // Synthesized main packages sometimes override this.
1694 if p.Internal.Local && !cfg.ModulesEnabled {
1695 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1698 // setError sets p.Error if it hasn't already been set. We may proceed
1699 // after encountering some errors so that 'go list -e' has more complete
1700 // output. If there's more than one error, we should report the first.
1701 setError := func(err error) {
1703 p.Error = &PackageError{
1704 ImportStack: stk.Copy(),
1708 // Add the importer's position information if the import position exists, and
1709 // the current package being examined is the importer.
1710 // If we have not yet accepted package p onto the import stack,
1711 // then the cause of the error is not within p itself: the error
1712 // must be either in an explicit command-line argument,
1713 // or on the importer side (indicated by a non-empty importPos).
1714 if path != stk.Top() && len(importPos) > 0 {
1715 p.Error.setPos(importPos)
1722 p.setLoadPackageDataError(err, path, stk, importPos)
1725 useBindir := p.Name == "main"
1727 switch cfg.BuildBuildmode {
1728 case "c-archive", "c-shared", "plugin":
1734 // Report an error when the old code.google.com/p/go.tools paths are used.
1735 if InstallTargetDir(p) == StalePath {
1736 // TODO(matloob): remove this branch, and StalePath itself. code.google.com/p/go is so
1737 // old, even this code checking for it is stale now!
1738 newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1739 e := ImportErrorf(p.ImportPath, "the %v command has moved; use %v instead.", p.ImportPath, newPath)
1743 elem := p.DefaultExecName()
1744 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1745 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1746 // Install cross-compiled binaries to subdirectories of bin.
1749 if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
1750 p.Internal.Build.BinDir = modload.BinDir()
1752 if p.Internal.Build.BinDir != "" {
1753 // Install to GOBIN or bin of GOPATH entry.
1754 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1755 if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1756 // Do not create $GOBIN/goos_goarch/elem.
1758 p.Internal.GobinSubdir = true
1761 if InstallTargetDir(p) == ToTool {
1762 // This is for 'go tool'.
1763 // Override all the usual logic and force it into the tool directory.
1764 if cfg.BuildToolchainName == "gccgo" {
1765 p.Target = filepath.Join(base.ToolDir, elem)
1767 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1770 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1773 } else if p.Internal.Local {
1774 // Local import turned into absolute path.
1775 // No permanent install target.
1778 p.Target = p.Internal.Build.PkgObj
1779 if cfg.BuildLinkshared && p.Target != "" {
1780 // TODO(bcmills): The reliance on p.Target implies that -linkshared does
1781 // not work for any package that lacks a Target — such as a non-main
1782 // package in module mode. We should probably fix that.
1783 shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1784 shlib, err := os.ReadFile(shlibnamefile)
1785 if err != nil && !os.IsNotExist(err) {
1786 base.Fatalf("reading shlibname: %v", err)
1789 libname := strings.TrimSpace(string(shlib))
1790 if cfg.BuildContext.Compiler == "gccgo" {
1791 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1793 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1799 // Build augmented import list to add implicit dependencies.
1800 // Be careful not to add imports twice, just to avoid confusion.
1801 importPaths := p.Imports
1802 addImport := func(path string, forCompiler bool) {
1803 for _, p := range importPaths {
1808 importPaths = append(importPaths, path)
1810 p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
1814 if !opts.IgnoreImports {
1815 // Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall",
1816 // except for certain packages, to avoid circular dependencies.
1818 addImport("unsafe", true)
1820 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1821 addImport("runtime/cgo", true)
1823 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1824 addImport("syscall", true)
1827 // SWIG adds imports of some standard packages.
1829 addImport("unsafe", true)
1830 if cfg.BuildContext.Compiler != "gccgo" {
1831 addImport("runtime/cgo", true)
1833 addImport("syscall", true)
1834 addImport("sync", true)
1836 // TODO: The .swig and .swigcxx files can use
1837 // %go_import directives to import other packages.
1840 // The linker loads implicit dependencies.
1841 if p.Name == "main" && !p.Internal.ForceLibrary {
1842 for _, dep := range LinkerDeps(p) {
1843 addImport(dep, false)
1848 // Check for case-insensitive collisions of import paths.
1849 fold := str.ToFold(p.ImportPath)
1850 if other := foldPath[fold]; other == "" {
1851 foldPath[fold] = p.ImportPath
1852 } else if other != p.ImportPath {
1853 setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
1857 if !SafeArg(p.ImportPath) {
1858 setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
1862 // Errors after this point are caused by this package, not the importing
1863 // package. Pushing the path here prevents us from reporting the error
1864 // with the position of the import declaration.
1868 pkgPath := p.ImportPath
1869 if p.Internal.CmdlineFiles {
1870 pkgPath = "command-line-arguments"
1872 if cfg.ModulesEnabled {
1873 p.Module = modload.PackageModuleInfo(ctx, pkgPath)
1876 p.EmbedFiles, p.Internal.Embed, err = resolveEmbed(p.Dir, p.EmbedPatterns)
1880 embedErr := err.(*EmbedError)
1881 p.Error.setPos(p.Internal.Build.EmbedPatternPos[embedErr.Pattern])
1884 // Check for case-insensitive collision of input files.
1885 // To avoid problems on case-insensitive files, we reject any package
1886 // where two different input files have equal names under a case-insensitive
1888 inputs := p.AllFiles()
1889 f1, f2 := str.FoldDup(inputs)
1891 setError(fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2))
1895 // If first letter of input file is ASCII, it must be alphanumeric.
1896 // This avoids files turning into flags when invoking commands,
1897 // and other problems we haven't thought of yet.
1898 // Also, _cgo_ files must be generated by us, not supplied.
1899 // They are allowed to have //go:cgo_ldflag directives.
1900 // The directory scan ignores files beginning with _,
1901 // so we shouldn't see any _cgo_ files anyway, but just be safe.
1902 for _, file := range inputs {
1903 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1904 setError(fmt.Errorf("invalid input file name %q", file))
1908 if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1909 setError(fmt.Errorf("invalid input directory name %q", name))
1913 // Build list of imported packages and full dependency list.
1914 imports := make([]*Package, 0, len(p.Imports))
1915 for i, path := range importPaths {
1919 p1 := LoadImport(ctx, opts, path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1921 path = p1.ImportPath
1922 importPaths[i] = path
1923 if i < len(p.Imports) {
1927 imports = append(imports, p1)
1932 p.Internal.Imports = imports
1934 if p.Error == nil && p.Name == "main" && len(p.DepsErrors) == 0 {
1938 // unsafe is a fake package.
1939 if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1943 // If cgo is not enabled, ignore cgo supporting sources
1944 // just as we ignore go files containing import "C".
1945 if !cfg.BuildContext.CgoEnabled {
1950 p.SwigCXXFiles = nil
1951 // Note that SFiles are okay (they go to the Go assembler)
1952 // and HFiles are okay (they might be used by the SFiles).
1953 // Also Sysofiles are okay (they might not contain object
1954 // code; see issue #16050).
1957 // The gc toolchain only permits C source files with cgo or SWIG.
1958 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1959 setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1963 // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1964 // regardless of toolchain.
1965 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1966 setError(fmt.Errorf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1969 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1970 setError(fmt.Errorf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1973 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1974 setError(fmt.Errorf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1979 // An EmbedError indicates a problem with a go:embed directive.
1980 type EmbedError struct {
1985 func (e *EmbedError) Error() string {
1986 return fmt.Sprintf("pattern %s: %v", e.Pattern, e.Err)
1989 func (e *EmbedError) Unwrap() error {
1993 // ResolveEmbed resolves //go:embed patterns and returns only the file list.
1994 // For use by go mod vendor to find embedded files it should copy into the
1995 // vendor directory.
1996 // TODO(#42504): Once go mod vendor uses load.PackagesAndErrors, just
1997 // call (*Package).ResolveEmbed
1998 func ResolveEmbed(dir string, patterns []string) ([]string, error) {
1999 files, _, err := resolveEmbed(dir, patterns)
2003 // resolveEmbed resolves //go:embed patterns to precise file lists.
2004 // It sets files to the list of unique files matched (for go list),
2005 // and it sets pmap to the more precise mapping from
2006 // patterns to files.
2007 func resolveEmbed(pkgdir string, patterns []string) (files []string, pmap map[string][]string, err error) {
2018 // TODO(rsc): All these messages need position information for better error reports.
2019 pmap = make(map[string][]string)
2020 have := make(map[string]int)
2021 dirOK := make(map[string]bool)
2022 pid := 0 // pattern ID, to allow reuse of have map
2023 for _, pattern = range patterns {
2026 // Check pattern is valid for //go:embed.
2027 if _, err := path.Match(pattern, ""); err != nil || !validEmbedPattern(pattern) {
2028 return nil, nil, fmt.Errorf("invalid pattern syntax")
2031 // Glob to find matches.
2032 match, err := fsys.Glob(pkgdir + string(filepath.Separator) + filepath.FromSlash(pattern))
2034 return nil, nil, err
2037 // Filter list of matches down to the ones that will still exist when
2038 // the directory is packaged up as a module. (If p.Dir is in the module cache,
2039 // only those files exist already, but if p.Dir is in the current module,
2040 // then there may be other things lying around, like symbolic links or .git directories.)
2042 for _, file := range match {
2043 rel := filepath.ToSlash(file[len(pkgdir)+1:]) // file, relative to p.Dir
2046 info, err := fsys.Lstat(file)
2048 return nil, nil, err
2054 // Check that directories along path do not begin a new module
2055 // (do not contain a go.mod).
2056 for dir := file; len(dir) > len(pkgdir)+1 && !dirOK[dir]; dir = filepath.Dir(dir) {
2057 if _, err := fsys.Stat(filepath.Join(dir, "go.mod")); err == nil {
2058 return nil, nil, fmt.Errorf("cannot embed %s %s: in different module", what, rel)
2061 if info, err := fsys.Lstat(dir); err == nil && !info.IsDir() {
2062 return nil, nil, fmt.Errorf("cannot embed %s %s: in non-directory %s", what, rel, dir[len(pkgdir)+1:])
2066 if elem := filepath.Base(dir); isBadEmbedName(elem) {
2068 return nil, nil, fmt.Errorf("cannot embed %s %s: invalid name %s", what, rel, elem)
2070 return nil, nil, fmt.Errorf("cannot embed %s %s: in invalid directory %s", what, rel, elem)
2077 return nil, nil, fmt.Errorf("cannot embed irregular file %s", rel)
2079 case info.Mode().IsRegular():
2080 if have[rel] != pid {
2082 list = append(list, rel)
2086 // Gather all files in the named directory, stopping at module boundaries
2087 // and ignoring files that wouldn't be packaged into a module.
2089 err := fsys.Walk(file, func(path string, info os.FileInfo, err error) error {
2093 rel := filepath.ToSlash(path[len(pkgdir)+1:])
2095 if path != file && (isBadEmbedName(name) || name[0] == '.' || name[0] == '_') {
2096 // Ignore bad names, assuming they won't go into modules.
2097 // Also avoid hidden files that user may not know about.
2098 // See golang.org/issue/42328.
2105 if _, err := fsys.Stat(filepath.Join(path, "go.mod")); err == nil {
2106 return filepath.SkipDir
2110 if !info.Mode().IsRegular() {
2114 if have[rel] != pid {
2116 list = append(list, rel)
2121 return nil, nil, err
2124 return nil, nil, fmt.Errorf("cannot embed directory %s: contains no embeddable files", rel)
2130 return nil, nil, fmt.Errorf("no matching files found")
2133 pmap[pattern] = list
2136 for file := range have {
2137 files = append(files, file)
2140 return files, pmap, nil
2143 func validEmbedPattern(pattern string) bool {
2144 return pattern != "." && fs.ValidPath(pattern)
2147 // isBadEmbedName reports whether name is the base name of a file that
2148 // can't or won't be included in modules and therefore shouldn't be treated
2149 // as existing for embedding.
2150 func isBadEmbedName(name string) bool {
2151 if err := module.CheckFilePath(name); err != nil {
2155 // Empty string should be impossible but make it bad.
2158 // Version control directories won't be present in module.
2159 case ".bzr", ".hg", ".git", ".svn":
2165 // collectDeps populates p.Deps and p.DepsErrors by iterating over
2166 // p.Internal.Imports.
2168 // TODO(jayconrod): collectDeps iterates over transitive imports for every
2169 // package. We should only need to visit direct imports.
2170 func (p *Package) collectDeps() {
2171 deps := make(map[string]*Package)
2173 q = append(q, p.Internal.Imports...)
2174 for i := 0; i < len(q); i++ {
2176 path := p1.ImportPath
2177 // The same import path could produce an error or not,
2178 // depending on what tries to import it.
2179 // Prefer to record entries with errors, so we can report them.
2181 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
2183 for _, p2 := range p1.Internal.Imports {
2184 if deps[p2.ImportPath] != p2 {
2191 p.Deps = make([]string, 0, len(deps))
2192 for dep := range deps {
2193 p.Deps = append(p.Deps, dep)
2195 sort.Strings(p.Deps)
2196 for _, dep := range p.Deps {
2199 panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
2201 if p1.Error != nil {
2202 p.DepsErrors = append(p.DepsErrors, p1.Error)
2207 // setBuildInfo gathers build information, formats it as a string to be
2208 // embedded in the binary, then sets p.Internal.BuildInfo to that string.
2209 // setBuildInfo should only be called on a main package with no errors.
2211 // This information can be retrieved using debug.ReadBuildInfo.
2213 // Note that the GoVersion field is not set here to avoid encoding it twice.
2214 // It is stored separately in the binary, mostly for historical reasons.
2215 func (p *Package) setBuildInfo() {
2216 // TODO: build and vcs information is not embedded for executables in GOROOT.
2217 // cmd/dist uses -gcflags=all= -ldflags=all= by default, which means these
2218 // executables always appear stale unless the user sets the same flags.
2219 // Perhaps it's safe to omit those flags when GO_GCFLAGS and GO_LDFLAGS
2221 setPkgErrorf := func(format string, args ...interface{}) {
2223 p.Error = &PackageError{Err: fmt.Errorf(format, args...)}
2227 var debugModFromModinfo func(*modinfo.ModulePublic) *debug.Module
2228 debugModFromModinfo = func(mi *modinfo.ModulePublic) *debug.Module {
2229 dm := &debug.Module{
2231 Version: mi.Version,
2233 if mi.Replace != nil {
2234 dm.Replace = debugModFromModinfo(mi.Replace)
2236 dm.Sum = modfetch.Sum(module.Version{Path: mi.Path, Version: mi.Version})
2241 var main debug.Module
2242 if p.Module != nil {
2243 main = *debugModFromModinfo(p.Module)
2246 visited := make(map[*Package]bool)
2247 mdeps := make(map[module.Version]*debug.Module)
2249 q = append(q, p.Internal.Imports...)
2257 if p1.Module != nil {
2258 m := module.Version{Path: p1.Module.Path, Version: p1.Module.Version}
2259 if p1.Module.Path != main.Path && mdeps[m] == nil {
2260 mdeps[m] = debugModFromModinfo(p1.Module)
2263 q = append(q, p1.Internal.Imports...)
2265 sortedMods := make([]module.Version, 0, len(mdeps))
2266 for mod := range mdeps {
2267 sortedMods = append(sortedMods, mod)
2269 module.Sort(sortedMods)
2270 deps := make([]*debug.Module, len(sortedMods))
2271 for i, mod := range sortedMods {
2272 deps[i] = mdeps[mod]
2275 pkgPath := p.ImportPath
2276 if p.Internal.CmdlineFiles {
2277 pkgPath = "command-line-arguments"
2279 info := &debug.BuildInfo{
2284 appendSetting := func(key, value string) {
2285 info.Settings = append(info.Settings, debug.BuildSetting{Key: key, Value: value})
2288 // Add command-line flags relevant to the build.
2289 // This is informational, not an exhaustive list.
2290 if cfg.BuildBuildinfo && !p.Standard {
2291 appendSetting("compiler", cfg.BuildContext.Compiler)
2292 if BuildAsmflags.present {
2293 appendSetting("asmflags", BuildAsmflags.String())
2295 if BuildGcflags.present && cfg.BuildContext.Compiler == "gc" {
2296 appendSetting("gcflags", BuildGcflags.String())
2298 if BuildGccgoflags.present && cfg.BuildContext.Compiler == "gccgo" {
2299 appendSetting("gccgoflags", BuildGccgoflags.String())
2301 if BuildLdflags.present {
2302 appendSetting("ldflags", BuildLdflags.String())
2304 tags := append(cfg.BuildContext.BuildTags, cfg.BuildContext.ToolTags...)
2305 appendSetting("tags", strings.Join(tags, ","))
2306 appendSetting("CGO_ENABLED", strconv.FormatBool(cfg.BuildContext.CgoEnabled))
2307 if cfg.BuildContext.CgoEnabled {
2308 for _, name := range []string{"CGO_CPPFLAGS", "CGO_CFLAGS", "CGO_CXXFLAGS", "CGO_LDFLAGS"} {
2309 appendSetting(name, cfg.Getenv(name))
2314 // Add VCS status if all conditions are true:
2316 // - -buildvcs is enabled.
2317 // - p is contained within a main module (there may be multiple main modules
2318 // in a workspace, but local replacements don't count).
2319 // - Both the current directory and p's module's root directory are contained
2320 // in the same local repository.
2321 // - We know the VCS commands needed to get the status.
2322 setVCSError := func(err error) {
2323 setPkgErrorf("error obtaining VCS status: %v\n\tUse -buildvcs=false to disable VCS stamping.", err)
2329 const allowNesting = true
2330 if cfg.BuildBuildvcs && p.Module != nil && p.Module.Version == "" && !p.Standard {
2331 repoDir, vcsCmd, err = vcs.FromDir(base.Cwd(), "", allowNesting)
2332 if err != nil && !errors.Is(err, os.ErrNotExist) {
2336 if !str.HasFilePathPrefix(p.Module.Dir, repoDir) &&
2337 !str.HasFilePathPrefix(repoDir, p.Module.Dir) {
2338 // The module containing the main package does not overlap with the
2339 // repository containing the working directory. Don't include VCS info.
2340 // If the repo contains the module or vice versa, but they are not
2341 // the same directory, it's likely an error (see below).
2342 repoDir, vcsCmd = "", nil
2345 if repoDir != "" && vcsCmd.Status != nil {
2346 // Check that the current directory, package, and module are in the same
2347 // repository. vcs.FromDir allows nested Git repositories, but nesting
2348 // is not allowed for other VCS tools. The current directory may be outside
2349 // p.Module.Dir when a workspace is used.
2350 pkgRepoDir, _, err := vcs.FromDir(p.Dir, "", allowNesting)
2355 if pkgRepoDir != repoDir {
2356 setVCSError(fmt.Errorf("main package is in repository %q but current directory is in repository %q", pkgRepoDir, repoDir))
2359 modRepoDir, _, err := vcs.FromDir(p.Module.Dir, "", allowNesting)
2364 if modRepoDir != repoDir {
2365 setVCSError(fmt.Errorf("main module is in repository %q but current directory is in repository %q", modRepoDir, repoDir))
2369 st, err := vcsCmd.Status(vcsCmd, repoDir)
2374 if st.Revision != "" {
2375 appendSetting(vcsCmd.Cmd+"revision", st.Revision)
2377 if !st.CommitTime.IsZero() {
2378 stamp := st.CommitTime.UTC().Format(time.RFC3339Nano)
2379 appendSetting(vcsCmd.Cmd+"committime", stamp)
2381 appendSetting(vcsCmd.Cmd+"uncommitted", strconv.FormatBool(st.Uncommitted))
2384 text, err := info.MarshalText()
2386 setPkgErrorf("error formatting build info: %v", err)
2389 p.Internal.BuildInfo = string(text)
2392 // SafeArg reports whether arg is a "safe" command-line argument,
2393 // meaning that when it appears in a command-line, it probably
2394 // doesn't have some special meaning other than its own name.
2395 // Obviously args beginning with - are not safe (they look like flags).
2396 // Less obviously, args beginning with @ are not safe (they look like
2397 // GNU binutils flagfile specifiers, sometimes called "response files").
2398 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
2399 // We accept leading . _ and / as likely in file system paths.
2400 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
2401 func SafeArg(name string) bool {
2406 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
2409 // LinkerDeps returns the list of linker-induced dependencies for main package p.
2410 func LinkerDeps(p *Package) []string {
2411 // Everything links runtime.
2412 deps := []string{"runtime"}
2414 // External linking mode forces an import of runtime/cgo.
2415 if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
2416 deps = append(deps, "runtime/cgo")
2418 // On ARM with GOARM=5, it forces an import of math, for soft floating point.
2419 if cfg.Goarch == "arm" {
2420 deps = append(deps, "math")
2422 // Using the race detector forces an import of runtime/race.
2424 deps = append(deps, "runtime/race")
2426 // Using memory sanitizer forces an import of runtime/msan.
2428 deps = append(deps, "runtime/msan")
2430 // Using address sanitizer forces an import of runtime/asan.
2432 deps = append(deps, "runtime/asan")
2438 // externalLinkingForced reports whether external linking is being
2439 // forced even for programs that do not use cgo.
2440 func externalLinkingForced(p *Package) bool {
2441 if !cfg.BuildContext.CgoEnabled {
2445 // Some targets must use external linking even inside GOROOT.
2446 switch cfg.BuildContext.GOOS {
2448 if cfg.BuildContext.GOARCH != "arm64" {
2455 // Currently build modes c-shared, pie (on systems that do not
2456 // support PIE with internal linking mode (currently all
2457 // systems: issue #18968)), plugin, and -linkshared force
2458 // external linking mode, as of course does
2459 // -ldflags=-linkmode=external. External linking mode forces
2460 // an import of runtime/cgo.
2461 // If there are multiple -linkmode options, the last one wins.
2462 pieCgo := cfg.BuildBuildmode == "pie" && !sys.InternalLinkPIESupported(cfg.BuildContext.GOOS, cfg.BuildContext.GOARCH)
2463 linkmodeExternal := false
2465 ldflags := BuildLdflags.For(p)
2466 for i := len(ldflags) - 1; i >= 0; i-- {
2468 if a == "-linkmode=external" ||
2469 a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
2470 linkmodeExternal = true
2472 } else if a == "-linkmode=internal" ||
2473 a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "internal" {
2479 return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
2482 // mkAbs rewrites list, which must be paths relative to p.Dir,
2483 // into a sorted list of absolute paths. It edits list in place but for
2484 // convenience also returns list back to its caller.
2485 func (p *Package) mkAbs(list []string) []string {
2486 for i, f := range list {
2487 list[i] = filepath.Join(p.Dir, f)
2493 // InternalGoFiles returns the list of Go files being built for the package,
2494 // using absolute paths.
2495 func (p *Package) InternalGoFiles() []string {
2496 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
2499 // InternalXGoFiles returns the list of Go files being built for the XTest package,
2500 // using absolute paths.
2501 func (p *Package) InternalXGoFiles() []string {
2502 return p.mkAbs(p.XTestGoFiles)
2505 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
2506 // using absolute paths. "Possibly relevant" means that files are not excluded
2507 // due to build tags, but files with names beginning with . or _ are still excluded.
2508 func (p *Package) InternalAllGoFiles() []string {
2509 return p.mkAbs(str.StringList(p.IgnoredGoFiles, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
2512 // usesSwig reports whether the package needs to run SWIG.
2513 func (p *Package) UsesSwig() bool {
2514 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
2517 // usesCgo reports whether the package needs to run cgo
2518 func (p *Package) UsesCgo() bool {
2519 return len(p.CgoFiles) > 0
2522 // PackageList returns the list of packages in the dag rooted at roots
2523 // as visited in a depth-first post-order traversal.
2524 func PackageList(roots []*Package) []*Package {
2525 seen := map[*Package]bool{}
2527 var walk func(*Package)
2528 walk = func(p *Package) {
2533 for _, p1 := range p.Internal.Imports {
2536 all = append(all, p)
2538 for _, root := range roots {
2544 // TestPackageList returns the list of packages in the dag rooted at roots
2545 // as visited in a depth-first post-order traversal, including the test
2546 // imports of the roots. This ignores errors in test packages.
2547 func TestPackageList(ctx context.Context, opts PackageOpts, roots []*Package) []*Package {
2548 seen := map[*Package]bool{}
2550 var walk func(*Package)
2551 walk = func(p *Package) {
2556 for _, p1 := range p.Internal.Imports {
2559 all = append(all, p)
2561 walkTest := func(root *Package, path string) {
2563 p1 := LoadImport(ctx, opts, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
2564 if p1.Error == nil {
2568 for _, root := range roots {
2570 for _, path := range root.TestImports {
2571 walkTest(root, path)
2573 for _, path := range root.XTestImports {
2574 walkTest(root, path)
2580 // LoadImportWithFlags loads the package with the given import path and
2581 // sets tool flags on that package. This function is useful loading implicit
2582 // dependencies (like sync/atomic for coverage).
2583 // TODO(jayconrod): delete this function and set flags automatically
2584 // in LoadImport instead.
2585 func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
2586 p := LoadImport(context.TODO(), PackageOpts{}, path, srcDir, parent, stk, importPos, mode)
2591 // PackageOpts control the behavior of PackagesAndErrors and other package
2592 // loading functions.
2593 type PackageOpts struct {
2594 // IgnoreImports controls whether we ignore explicit and implicit imports
2595 // when loading packages. Implicit imports are added when supporting Cgo
2596 // or SWIG and when linking main packages.
2599 // ModResolveTests indicates whether calls to the module loader should also
2600 // resolve test dependencies of the requested packages.
2602 // If ModResolveTests is true, then the module loader needs to resolve test
2603 // dependencies at the same time as packages; otherwise, the test dependencies
2604 // of those packages could be missing, and resolving those missing dependencies
2605 // could change the selected versions of modules that provide other packages.
2606 ModResolveTests bool
2608 // MainOnly is true if the caller only wants to load main packages.
2609 // For a literal argument matching a non-main package, a stub may be returned
2610 // with an error. For a non-literal argument (with "..."), non-main packages
2611 // are not be matched, and their dependencies may not be loaded. A warning
2612 // may be printed for non-literal arguments that match no main packages.
2616 // PackagesAndErrors returns the packages named by the command line arguments
2617 // 'patterns'. If a named package cannot be loaded, PackagesAndErrors returns
2618 // a *Package with the Error field describing the failure. If errors are found
2619 // loading imported packages, the DepsErrors field is set. The Incomplete field
2620 // may be set as well.
2622 // To obtain a flat list of packages, use PackageList.
2623 // To report errors loading packages, use ReportPackageErrors.
2624 func PackagesAndErrors(ctx context.Context, opts PackageOpts, patterns []string) []*Package {
2625 ctx, span := trace.StartSpan(ctx, "load.PackagesAndErrors")
2628 for _, p := range patterns {
2629 // Listing is only supported with all patterns referring to either:
2630 // - Files that are part of the same directory.
2631 // - Explicit package paths or patterns.
2632 if strings.HasSuffix(p, ".go") {
2633 // We need to test whether the path is an actual Go file and not a
2634 // package path or pattern ending in '.go' (see golang.org/issue/34653).
2635 if fi, err := fsys.Stat(p); err == nil && !fi.IsDir() {
2636 return []*Package{GoFilesPackage(ctx, opts, patterns)}
2641 var matches []*search.Match
2642 if modload.Init(); cfg.ModulesEnabled {
2643 modOpts := modload.PackageOpts{
2644 ResolveMissingImports: true,
2645 LoadTests: opts.ModResolveTests,
2646 SilencePackageErrors: true,
2648 matches, _ = modload.LoadPackages(ctx, modOpts, patterns...)
2650 noModRoots := []string{}
2651 matches = search.ImportPaths(patterns, noModRoots)
2657 seenPkg = make(map[*Package]bool)
2662 pre.preloadMatches(ctx, opts, matches)
2664 for _, m := range matches {
2665 for _, pkg := range m.Pkgs {
2667 panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
2669 p := loadImport(ctx, opts, pre, pkg, base.Cwd(), nil, &stk, nil, 0)
2670 p.Match = append(p.Match, m.Pattern())
2671 p.Internal.CmdlinePkg = true
2673 // Note: do not set = m.IsLiteral unconditionally
2674 // because maybe we'll see p matching both
2675 // a literal and also a non-literal pattern.
2676 p.Internal.CmdlinePkgLiteral = true
2682 pkgs = append(pkgs, p)
2685 if len(m.Errs) > 0 {
2686 // In addition to any packages that were actually resolved from the
2687 // pattern, there was some error in resolving the pattern itself.
2688 // Report it as a synthetic package.
2690 p.ImportPath = m.Pattern()
2691 // Pass an empty ImportStack and nil importPos: the error arose from a pattern, not an import.
2693 var importPos []token.Position
2694 p.setLoadPackageDataError(m.Errs[0], m.Pattern(), &stk, importPos)
2696 p.Match = append(p.Match, m.Pattern())
2697 p.Internal.CmdlinePkg = true
2699 p.Internal.CmdlinePkgLiteral = true
2701 pkgs = append(pkgs, p)
2706 pkgs = mainPackagesOnly(pkgs, matches)
2709 // Now that CmdlinePkg is set correctly,
2710 // compute the effective flags for all loaded packages
2711 // (not just the ones matching the patterns but also
2712 // their dependencies).
2713 setToolFlags(pkgs...)
2718 // CheckPackageErrors prints errors encountered loading pkgs and their
2719 // dependencies, then exits with a non-zero status if any errors were found.
2720 func CheckPackageErrors(pkgs []*Package) {
2721 printed := map[*PackageError]bool{}
2722 for _, pkg := range pkgs {
2723 if pkg.Error != nil {
2724 base.Errorf("%v", pkg.Error)
2725 printed[pkg.Error] = true
2727 for _, err := range pkg.DepsErrors {
2728 // Since these are errors in dependencies,
2729 // the same error might show up multiple times,
2730 // once in each package that depends on it.
2731 // Only print each once.
2734 base.Errorf("%v", err)
2740 // Check for duplicate loads of the same package.
2741 // That should be impossible, but if it does happen then
2742 // we end up trying to build the same package twice,
2743 // usually in parallel overwriting the same files,
2744 // which doesn't work very well.
2745 seen := map[string]bool{}
2746 reported := map[string]bool{}
2747 for _, pkg := range PackageList(pkgs) {
2748 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
2749 reported[pkg.ImportPath] = true
2750 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
2752 seen[pkg.ImportPath] = true
2757 // mainPackagesOnly filters out non-main packages matched only by arguments
2758 // containing "..." and returns the remaining main packages.
2760 // Packages with missing, invalid, or ambiguous names may be treated as
2761 // possibly-main packages.
2763 // mainPackagesOnly sets a non-main package's Error field and returns it if it
2764 // is named by a literal argument.
2766 // mainPackagesOnly prints warnings for non-literal arguments that only match
2767 // non-main packages.
2768 func mainPackagesOnly(pkgs []*Package, matches []*search.Match) []*Package {
2769 treatAsMain := map[string]bool{}
2770 for _, m := range matches {
2772 for _, path := range m.Pkgs {
2773 treatAsMain[path] = true
2778 var mains []*Package
2779 for _, pkg := range pkgs {
2780 if pkg.Name == "main" {
2781 treatAsMain[pkg.ImportPath] = true
2782 mains = append(mains, pkg)
2786 if len(pkg.InvalidGoFiles) > 0 { // TODO(#45999): && pkg.Name == "", but currently go/build sets pkg.Name arbitrarily if it is ambiguous.
2787 // The package has (or may have) conflicting names, and we can't easily
2788 // tell whether one of them is "main". So assume that it could be, and
2789 // report an error for the package.
2790 treatAsMain[pkg.ImportPath] = true
2792 if treatAsMain[pkg.ImportPath] {
2793 if pkg.Error == nil {
2794 pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
2796 mains = append(mains, pkg)
2800 for _, m := range matches {
2801 if m.IsLiteral() || len(m.Pkgs) == 0 {
2805 for _, path := range m.Pkgs {
2806 if treatAsMain[path] {
2812 fmt.Fprintf(os.Stderr, "go: warning: %q matched only non-main packages\n", m.Pattern())
2819 type mainPackageError struct {
2823 func (e *mainPackageError) Error() string {
2824 return fmt.Sprintf("package %s is not a main package", e.importPath)
2827 func (e *mainPackageError) ImportPath() string {
2831 func setToolFlags(pkgs ...*Package) {
2832 for _, p := range PackageList(pkgs) {
2833 p.Internal.Asmflags = BuildAsmflags.For(p)
2834 p.Internal.Gcflags = BuildGcflags.For(p)
2835 p.Internal.Ldflags = BuildLdflags.For(p)
2836 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
2840 // GoFilesPackage creates a package for building a collection of Go files
2841 // (typically named on the command line). The target is named p.a for
2842 // package p or named after the first Go file for package main.
2843 func GoFilesPackage(ctx context.Context, opts PackageOpts, gofiles []string) *Package {
2846 for _, f := range gofiles {
2847 if !strings.HasSuffix(f, ".go") {
2849 pkg.Internal.Local = true
2850 pkg.Internal.CmdlineFiles = true
2852 pkg.Error = &PackageError{
2853 Err: fmt.Errorf("named files must be .go files: %s", pkg.Name),
2860 ctxt := cfg.BuildContext
2861 ctxt.UseAllFiles = true
2863 // Synthesize fake "directory" that only shows the named files,
2864 // to make it look like this is a standard package or
2865 // command directory. So that local imports resolve
2866 // consistently, the files must all be in the same directory.
2867 var dirent []fs.FileInfo
2869 for _, file := range gofiles {
2870 fi, err := fsys.Stat(file)
2872 base.Fatalf("%s", err)
2875 base.Fatalf("%s is a directory, should be a Go file", file)
2877 dir1 := filepath.Dir(file)
2880 } else if dir != dir1 {
2881 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
2883 dirent = append(dirent, fi)
2885 ctxt.ReadDir = func(string) ([]fs.FileInfo, error) { return dirent, nil }
2887 if cfg.ModulesEnabled {
2888 modload.ImportFromFiles(ctx, gofiles)
2895 dir, err = filepath.Abs(dir)
2897 base.Fatalf("%s", err)
2900 bp, err := ctxt.ImportDir(dir, 0)
2902 pkg.Internal.Local = true
2903 pkg.Internal.CmdlineFiles = true
2904 pkg.load(ctx, opts, "command-line-arguments", &stk, nil, bp, err)
2905 if !cfg.ModulesEnabled {
2906 pkg.Internal.LocalPrefix = dirToImportPath(dir)
2908 pkg.ImportPath = "command-line-arguments"
2912 if pkg.Name == "main" {
2913 exe := pkg.DefaultExecName() + cfg.ExeSuffix
2915 if cfg.GOBIN != "" {
2916 pkg.Target = filepath.Join(cfg.GOBIN, exe)
2917 } else if cfg.ModulesEnabled {
2918 pkg.Target = filepath.Join(modload.BinDir(), exe)
2922 if opts.MainOnly && pkg.Name != "main" && pkg.Error == nil {
2923 pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
2930 // PackagesAndErrorsOutsideModule is like PackagesAndErrors but runs in
2931 // module-aware mode and ignores the go.mod file in the current directory or any
2932 // parent directory, if there is one. This is used in the implementation of 'go
2933 // install pkg@version' and other commands that support similar forms.
2935 // modload.ForceUseModules must be true, and modload.RootMode must be NoRoot
2936 // before calling this function.
2938 // PackagesAndErrorsOutsideModule imposes several constraints to avoid
2939 // ambiguity. All arguments must have the same version suffix (not just a suffix
2940 // that resolves to the same version). They must refer to packages in the same
2941 // module, which must not be std or cmd. That module is not considered the main
2942 // module, but its go.mod file (if it has one) must not contain directives that
2943 // would cause it to be interpreted differently if it were the main module
2944 // (replace, exclude).
2945 func PackagesAndErrorsOutsideModule(ctx context.Context, opts PackageOpts, args []string) ([]*Package, error) {
2946 if !modload.ForceUseModules {
2947 panic("modload.ForceUseModules must be true")
2949 if modload.RootMode != modload.NoRoot {
2950 panic("modload.RootMode must be NoRoot")
2953 // Check that the arguments satisfy syntactic constraints.
2955 for _, arg := range args {
2956 if i := strings.Index(arg, "@"); i >= 0 {
2959 return nil, fmt.Errorf("%s: version must not be empty", arg)
2964 patterns := make([]string, len(args))
2965 for i, arg := range args {
2966 if !strings.HasSuffix(arg, "@"+version) {
2967 return nil, fmt.Errorf("%s: all arguments must have the same version (@%s)", arg, version)
2969 p := arg[:len(arg)-len(version)-1]
2971 case build.IsLocalImport(p):
2972 return nil, fmt.Errorf("%s: argument must be a package path, not a relative path", arg)
2973 case filepath.IsAbs(p):
2974 return nil, fmt.Errorf("%s: argument must be a package path, not an absolute path", arg)
2975 case search.IsMetaPackage(p):
2976 return nil, fmt.Errorf("%s: argument must be a package path, not a meta-package", arg)
2977 case path.Clean(p) != p:
2978 return nil, fmt.Errorf("%s: argument must be a clean package path", arg)
2979 case !strings.Contains(p, "...") && search.IsStandardImportPath(p) && goroot.IsStandardPackage(cfg.GOROOT, cfg.BuildContext.Compiler, p):
2980 return nil, fmt.Errorf("%s: argument must not be a package in the standard library", arg)
2986 // Query the module providing the first argument, load its go.mod file, and
2987 // check that it doesn't contain directives that would cause it to be
2988 // interpreted differently if it were the main module.
2990 // If multiple modules match the first argument, accept the longest match
2991 // (first result). It's possible this module won't provide packages named by
2992 // later arguments, and other modules would. Let's not try to be too
2994 allowed := modload.CheckAllowed
2995 if modload.IsRevisionQuery(version) {
2996 // Don't check for retractions if a specific revision is requested.
2999 noneSelected := func(path string) (version string) { return "none" }
3000 qrs, err := modload.QueryPackages(ctx, patterns[0], version, noneSelected, allowed)
3002 return nil, fmt.Errorf("%s: %w", args[0], err)
3004 rootMod := qrs[0].Mod
3005 data, err := modfetch.GoMod(rootMod.Path, rootMod.Version)
3007 return nil, fmt.Errorf("%s: %w", args[0], err)
3009 f, err := modfile.Parse("go.mod", data, nil)
3011 return nil, fmt.Errorf("%s (in %s): %w", args[0], rootMod, err)
3013 directiveFmt := "%s (in %s):\n" +
3014 "\tThe go.mod file for the module providing named packages contains one or\n" +
3015 "\tmore %s directives. It must not contain directives that would cause\n" +
3016 "\tit to be interpreted differently than if it were the main module."
3017 if len(f.Replace) > 0 {
3018 return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "replace")
3020 if len(f.Exclude) > 0 {
3021 return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "exclude")
3024 // Since we are in NoRoot mode, the build list initially contains only
3025 // the dummy command-line-arguments module. Add a requirement on the
3026 // module that provides the packages named on the command line.
3027 if _, err := modload.EditBuildList(ctx, nil, []module.Version{rootMod}); err != nil {
3028 return nil, fmt.Errorf("%s: %w", args[0], err)
3031 // Load packages for all arguments.
3032 pkgs := PackagesAndErrors(ctx, opts, patterns)
3034 // Check that named packages are all provided by the same module.
3035 for _, pkg := range pkgs {
3037 if pkg.Module == nil {
3038 // Packages in std, cmd, and their vendored dependencies
3039 // don't have this field set.
3040 pkgErr = fmt.Errorf("package %s not provided by module %s", pkg.ImportPath, rootMod)
3041 } else if pkg.Module.Path != rootMod.Path || pkg.Module.Version != rootMod.Version {
3042 pkgErr = fmt.Errorf("package %s provided by module %s@%s\n\tAll packages must be provided by the same module (%s).", pkg.ImportPath, pkg.Module.Path, pkg.Module.Version, rootMod)
3044 if pkgErr != nil && pkg.Error == nil {
3045 pkg.Error = &PackageError{Err: pkgErr}
3049 matchers := make([]func(string) bool, len(patterns))
3050 for i, p := range patterns {
3051 if strings.Contains(p, "...") {
3052 matchers[i] = search.MatchPattern(p)