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 // IsTestOnly reports whether p is a test-only package.
198 // A “test-only” package is one that:
199 // - is a test-only variant of an ordinary package, or
200 // - is a synthesized "main" package for a test binary, or
201 // - contains only _test.go files.
202 func (p *Package) IsTestOnly() bool {
203 return p.ForTest != "" ||
204 p.Internal.TestmainGo != nil ||
205 len(p.TestGoFiles)+len(p.XTestGoFiles) > 0 && len(p.GoFiles)+len(p.CgoFiles) == 0
208 type PackageInternal struct {
209 // Unexported fields are not part of the public API.
211 Imports []*Package // this package's direct imports
212 CompiledImports []string // additional Imports necessary when using CompiledGoFiles (all from standard library); 1:1 with the end of PackagePublic.Imports
213 RawImports []string // this package's original imports as they appear in the text of the program; 1:1 with the end of PackagePublic.Imports
214 ForceLibrary bool // this package is a library (even if named "main")
215 CmdlineFiles bool // package built from files listed on command line
216 CmdlinePkg bool // package listed on command line
217 CmdlinePkgLiteral bool // package listed as literal on command line (not via wildcard)
218 Local bool // imported via local path (./ or ../)
219 LocalPrefix string // interpret ./ and ../ imports relative to this prefix
220 ExeName string // desired name for temporary executable
221 FuzzInstrument bool // package should be instrumented for fuzzing
222 CoverMode string // preprocess Go source files with the coverage tool in this mode
223 CoverVars map[string]*CoverVar // variables created by coverage analysis
224 OmitDebug bool // tell linker not to write debug information
225 GobinSubdir bool // install target would be subdir of GOBIN
226 BuildInfo string // add this info to package main
227 TestmainGo *[]byte // content for _testmain.go
228 Embed map[string][]string // //go:embed comment mapping
229 OrigImportPath string // original import path before adding '_test' suffix
231 Asmflags []string // -asmflags for this package
232 Gcflags []string // -gcflags for this package
233 Ldflags []string // -ldflags for this package
234 Gccgoflags []string // -gccgoflags for this package
237 // A NoGoError indicates that no Go files for the package were applicable to the
238 // build for that package.
240 // That may be because there were no files whatsoever, or because all files were
241 // excluded, or because all non-excluded files were test sources.
242 type NoGoError struct {
246 func (e *NoGoError) Error() string {
247 if len(e.Package.IgnoredGoFiles) > 0 {
248 // Go files exist, but they were ignored due to build constraints.
249 return "build constraints exclude all Go files in " + e.Package.Dir
251 if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
252 // Test Go files exist, but we're not interested in them.
253 // The double-negative is unfortunate but we want e.Package.Dir
254 // to appear at the end of error message.
255 return "no non-test Go files in " + e.Package.Dir
257 return "no Go files in " + e.Package.Dir
260 // setLoadPackageDataError presents an error found when loading package data
261 // as a *PackageError. It has special cases for some common errors to improve
262 // messages shown to users and reduce redundancy.
264 // setLoadPackageDataError returns true if it's safe to load information about
265 // imported packages, for example, if there was a parse error loading imports
266 // in one file, but other files are okay.
267 func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportStack, importPos []token.Position) {
268 matchErr, isMatchErr := err.(*search.MatchError)
269 if isMatchErr && matchErr.Match.Pattern() == path {
270 if matchErr.Match.IsLiteral() {
271 // The error has a pattern has a pattern similar to the import path.
272 // It may be slightly different (./foo matching example.com/foo),
273 // but close enough to seem redundant.
274 // Unwrap the error so we don't show the pattern.
279 // Replace (possibly wrapped) *build.NoGoError with *load.NoGoError.
280 // The latter is more specific about the cause.
281 var nogoErr *build.NoGoError
282 if errors.As(err, &nogoErr) {
283 if p.Dir == "" && nogoErr.Dir != "" {
286 err = &NoGoError{Package: p}
289 // Take only the first error from a scanner.ErrorList. PackageError only
290 // has room for one position, so we report the first error with a position
291 // instead of all of the errors without a position.
294 if scanErr, ok := err.(scanner.ErrorList); ok && len(scanErr) > 0 {
295 isScanErr = true // For stack push/pop below.
297 scanPos := scanErr[0].Pos
298 scanPos.Filename = base.ShortPath(scanPos.Filename)
299 pos = scanPos.String()
300 err = errors.New(scanErr[0].Msg)
303 // Report the error on the importing package if the problem is with the import declaration
304 // for example, if the package doesn't exist or if the import path is malformed.
305 // On the other hand, don't include a position if the problem is with the imported package,
306 // for example there are no Go files (NoGoError), or there's a problem in the imported
307 // package's source files themselves (scanner errors).
309 // TODO(matloob): Perhaps make each of those the errors in the first group
310 // (including modload.ImportMissingError, ImportMissingSumError, and the
311 // corresponding "cannot find package %q in any of" GOPATH-mode error
312 // produced in build.(*Context).Import; modload.AmbiguousImportError,
313 // and modload.PackageNotInModuleError; and the malformed module path errors
314 // produced in golang.org/x/mod/module.CheckMod) implement an interface
315 // to make it easier to check for them? That would save us from having to
316 // move the modload errors into this package to avoid a package import cycle,
317 // and from having to export an error type for the errors produced in build.
318 if !isMatchErr && (nogoErr != nil || isScanErr) {
323 p.Error = &PackageError{
324 ImportStack: stk.Copy(),
329 if path != stk.Top() {
330 p.Error.setPos(importPos)
334 // Resolve returns the resolved version of imports,
335 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
336 // The imports in p.TestImports and p.XTestImports are not recursively
337 // loaded during the initial load of p, so they list the imports found in
338 // the source file, but most processing should be over the vendor-resolved
339 // import paths. We do this resolution lazily both to avoid file system work
340 // and because the eventual real load of the test imports (during 'go test')
341 // can produce better error messages if it starts with the original paths.
342 // The initial load of p loads all the non-test imports and rewrites
343 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
344 func (p *Package) Resolve(imports []string) []string {
345 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
346 panic("internal error: p.Resolve(p.Imports) called")
348 seen := make(map[string]bool)
350 for _, path := range imports {
351 path = ResolveImportPath(p, path)
354 all = append(all, path)
361 // CoverVar holds the name of the generated coverage variables targeting the named file.
362 type CoverVar struct {
363 File string // local file name
364 Var string // name of count struct
367 func (p *Package) copyBuild(opts PackageOpts, pp *build.Package) {
368 p.Internal.Build = pp
370 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
371 old := pp.PkgTargetRoot
372 pp.PkgRoot = cfg.BuildPkgdir
373 pp.PkgTargetRoot = cfg.BuildPkgdir
374 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
378 p.ImportPath = pp.ImportPath
379 p.ImportComment = pp.ImportComment
383 p.ConflictDir = pp.ConflictDir
384 p.BinaryOnly = pp.BinaryOnly
388 p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
389 p.GoFiles = pp.GoFiles
390 p.CgoFiles = pp.CgoFiles
391 p.IgnoredGoFiles = pp.IgnoredGoFiles
392 p.InvalidGoFiles = pp.InvalidGoFiles
393 p.IgnoredOtherFiles = pp.IgnoredOtherFiles
395 p.CXXFiles = pp.CXXFiles
400 p.SwigFiles = pp.SwigFiles
401 p.SwigCXXFiles = pp.SwigCXXFiles
402 p.SysoFiles = pp.SysoFiles
404 // There's no way for .syso files to be built both with and without
405 // support for memory sanitizer. Assume they are built without,
409 p.CgoCFLAGS = pp.CgoCFLAGS
410 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
411 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
412 p.CgoFFLAGS = pp.CgoFFLAGS
413 p.CgoLDFLAGS = pp.CgoLDFLAGS
414 p.CgoPkgConfig = pp.CgoPkgConfig
415 // We modify p.Imports in place, so make copy now.
416 p.Imports = make([]string, len(pp.Imports))
417 copy(p.Imports, pp.Imports)
418 p.Internal.RawImports = pp.Imports
419 p.TestGoFiles = pp.TestGoFiles
420 p.TestImports = pp.TestImports
421 p.XTestGoFiles = pp.XTestGoFiles
422 p.XTestImports = pp.XTestImports
423 if opts.IgnoreImports {
425 p.Internal.RawImports = nil
429 p.EmbedPatterns = pp.EmbedPatterns
430 p.TestEmbedPatterns = pp.TestEmbedPatterns
431 p.XTestEmbedPatterns = pp.XTestEmbedPatterns
432 p.Internal.OrigImportPath = pp.ImportPath
435 // A PackageError describes an error loading information about a package.
436 type PackageError struct {
437 ImportStack []string // shortest path from package named on command line to this one
438 Pos string // position of error
439 Err error // the error itself
440 IsImportCycle bool // the error is an import cycle
441 Hard bool // whether the error is soft or hard; soft errors are ignored in some places
442 alwaysPrintStack bool // whether to always print the ImportStack
445 func (p *PackageError) Error() string {
446 // TODO(#43696): decide when to print the stack or the position based on
447 // the error type and whether the package is in the main module.
448 // Document the rationale.
449 if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
450 // Omit import stack. The full path to the file where the error
451 // is the most important thing.
452 return p.Pos + ": " + p.Err.Error()
455 // If the error is an ImportPathError, and the last path on the stack appears
456 // in the error message, omit that path from the stack to avoid repetition.
457 // If an ImportPathError wraps another ImportPathError that matches the
458 // last path on the stack, we don't omit the path. An error like
459 // "package A imports B: error loading C caused by B" would not be clearer
460 // if "imports B" were omitted.
461 if len(p.ImportStack) == 0 {
466 optpos = "\n\t" + p.Pos
468 return "package " + strings.Join(p.ImportStack, "\n\timports ") + optpos + ": " + p.Err.Error()
471 func (p *PackageError) Unwrap() error { return p.Err }
473 // PackageError implements MarshalJSON so that Err is marshaled as a string
474 // and non-essential fields are omitted.
475 func (p *PackageError) MarshalJSON() ([]byte, error) {
480 }{p.ImportStack, p.Pos, p.Err.Error()}
481 return json.Marshal(perr)
484 func (p *PackageError) setPos(posList []token.Position) {
485 if len(posList) == 0 {
489 pos.Filename = base.ShortPath(pos.Filename)
493 // ImportPathError is a type of error that prevents a package from being loaded
494 // for a given import path. When such a package is loaded, a *Package is
495 // returned with Err wrapping an ImportPathError: the error is attached to
496 // the imported package, not the importing package.
498 // The string returned by ImportPath must appear in the string returned by
499 // Error. Errors that wrap ImportPathError (such as PackageError) may omit
501 type ImportPathError interface {
507 _ ImportPathError = (*importError)(nil)
508 _ ImportPathError = (*mainPackageError)(nil)
509 _ ImportPathError = (*modload.ImportMissingError)(nil)
510 _ ImportPathError = (*modload.ImportMissingSumError)(nil)
511 _ ImportPathError = (*modload.DirectImportFromImplicitDependencyError)(nil)
514 type importError struct {
516 err error // created with fmt.Errorf
519 func ImportErrorf(path, format string, args ...any) ImportPathError {
520 err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
521 if errStr := err.Error(); !strings.Contains(errStr, path) {
522 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
527 func (e *importError) Error() string {
531 func (e *importError) Unwrap() error {
532 // Don't return e.err directly, since we're only wrapping an error if %w
533 // was passed to ImportErrorf.
534 return errors.Unwrap(e.err)
537 func (e *importError) ImportPath() string {
541 // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
542 // The import path of a test package is the import path of the corresponding
543 // non-test package with the suffix "_test" added.
544 type ImportStack []string
546 func (s *ImportStack) Push(p string) {
550 func (s *ImportStack) Pop() {
551 *s = (*s)[0 : len(*s)-1]
554 func (s *ImportStack) Copy() []string {
555 return append([]string{}, *s...)
558 func (s *ImportStack) Top() string {
562 return (*s)[len(*s)-1]
565 // shorterThan reports whether sp is shorter than t.
566 // We use this to record the shortest import sequence
567 // that leads to a particular package.
568 func (sp *ImportStack) shorterThan(t []string) bool {
570 if len(s) != len(t) {
571 return len(s) < len(t)
573 // If they are the same length, settle ties using string ordering.
579 return false // they are equal
582 // packageCache is a lookup cache for LoadImport,
583 // so that if we look up a package multiple times
584 // we return the same pointer each time.
585 var packageCache = map[string]*Package{}
587 // ClearPackageCache clears the in-memory package cache and the preload caches.
588 // It is only for use by GOPATH-based "go get".
589 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
590 func ClearPackageCache() {
591 for name := range packageCache {
592 delete(packageCache, name)
594 resolvedImportCache.Clear()
595 packageDataCache.Clear()
598 // ClearPackageCachePartial clears packages with the given import paths from the
599 // in-memory package cache and the preload caches. It is only for use by
600 // GOPATH-based "go get".
601 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
602 func ClearPackageCachePartial(args []string) {
603 shouldDelete := make(map[string]bool)
604 for _, arg := range args {
605 shouldDelete[arg] = true
606 if p := packageCache[arg]; p != nil {
607 delete(packageCache, arg)
610 resolvedImportCache.DeleteIf(func(key any) bool {
611 return shouldDelete[key.(importSpec).path]
613 packageDataCache.DeleteIf(func(key any) bool {
614 return shouldDelete[key.(string)]
618 // ReloadPackageNoFlags is like LoadImport but makes sure
619 // not to use the package cache.
620 // It is only for use by GOPATH-based "go get".
621 // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
622 func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
623 p := packageCache[arg]
625 delete(packageCache, arg)
626 resolvedImportCache.DeleteIf(func(key any) bool {
627 return key.(importSpec).path == p.ImportPath
629 packageDataCache.Delete(p.ImportPath)
631 return LoadImport(context.TODO(), PackageOpts{}, arg, base.Cwd(), nil, stk, nil, 0)
634 // dirToImportPath returns the pseudo-import path we use for a package
635 // outside the Go path. It begins with _/ and then contains the full path
636 // to the directory. If the package lives in c:\home\gopher\my\pkg then
637 // the pseudo-import path is _/c_/home/gopher/my/pkg.
638 // Using a pseudo-import path like this makes the ./ imports no longer
639 // a special case, so that all the code to deal with ordinary imports works
641 func dirToImportPath(dir string) string {
642 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
645 func makeImportValid(r rune) rune {
646 // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
647 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
648 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
654 // Mode flags for loadImport and download (in get.go).
656 // ResolveImport means that loadImport should do import path expansion.
657 // That is, ResolveImport means that the import path came from
658 // a source file and has not been expanded yet to account for
659 // vendoring or possible module adjustment.
660 // Every import path should be loaded initially with ResolveImport,
661 // and then the expanded version (for example with the /vendor/ in it)
662 // gets recorded as the canonical import path. At that point, future loads
663 // of that package must not pass ResolveImport, because
664 // disallowVendor will reject direct use of paths containing /vendor/.
665 ResolveImport = 1 << iota
667 // ResolveModule is for download (part of "go get") and indicates
668 // that the module adjustment should be done, but not vendor adjustment.
671 // GetTestDeps is for download (part of "go get") and indicates
672 // that test dependencies should be fetched too.
676 // LoadImport scans the directory named by path, which must be an import path,
677 // but possibly a local import path (an absolute file system path or one beginning
678 // with ./ or ../). A local relative path is interpreted relative to srcDir.
679 // It returns a *Package describing the package found in that directory.
680 // LoadImport does not set tool flags and should only be used by
681 // this package, as part of a bigger load operation, and by GOPATH-based "go get".
682 // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
683 func LoadImport(ctx context.Context, opts PackageOpts, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
684 return loadImport(ctx, opts, nil, path, srcDir, parent, stk, importPos, mode)
687 func loadImport(ctx context.Context, opts PackageOpts, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
689 panic("LoadImport called with empty package path")
692 var parentPath, parentRoot string
695 parentPath = parent.ImportPath
696 parentRoot = parent.Root
697 parentIsStd = parent.Standard
699 bp, loaded, err := loadPackageData(ctx, path, parentPath, srcDir, parentRoot, parentIsStd, mode)
700 if loaded && pre != nil && !opts.IgnoreImports {
701 pre.preloadImports(ctx, opts, bp.Imports, bp)
705 PackagePublic: PackagePublic{
710 if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
711 // Only add path to the error's import stack if it's not already present
714 // TODO(bcmills): setLoadPackageDataError itself has a similar Push / Pop
715 // sequence that empirically doesn't trigger for these errors, guarded by
716 // a somewhat complex condition. Figure out how to generalize that
717 // condition and eliminate the explicit calls here.
721 p.setLoadPackageDataError(err, path, stk, nil)
725 importPath := bp.ImportPath
726 p := packageCache[importPath]
729 p = reusePackage(p, stk)
733 p.Internal.Local = build.IsLocalImport(path)
734 p.ImportPath = importPath
735 packageCache[importPath] = p
738 // loadPackageData may return bp != nil even if an error occurs,
739 // in order to return partial information.
740 p.load(ctx, opts, path, stk, importPos, bp, err)
742 if !cfg.ModulesEnabled && path != cleanImport(path) {
743 p.Error = &PackageError{
744 ImportStack: stk.Copy(),
745 Err: ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
748 p.Error.setPos(importPos)
752 // Checked on every import because the rules depend on the code doing the importing.
753 if perr := disallowInternal(ctx, srcDir, parent, parentPath, p, stk); perr != p {
754 perr.Error.setPos(importPos)
757 if mode&ResolveImport != 0 {
758 if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != p {
759 perr.Error.setPos(importPos)
764 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
766 perr.Error = &PackageError{
767 ImportStack: stk.Copy(),
768 Err: ImportErrorf(path, "import %q is a program, not an importable package", path),
770 perr.Error.setPos(importPos)
774 if p.Internal.Local && parent != nil && !parent.Internal.Local {
778 err = ImportErrorf(path, "%s: cannot import current directory", path)
780 err = ImportErrorf(path, "local import %q in non-local package", path)
782 perr.Error = &PackageError{
783 ImportStack: stk.Copy(),
786 perr.Error.setPos(importPos)
793 // loadPackageData loads information needed to construct a *Package. The result
794 // is cached, and later calls to loadPackageData for the same package will return
797 // loadPackageData returns a non-nil package even if err is non-nil unless
798 // the package path is malformed (for example, the path contains "mod/" or "@").
800 // loadPackageData returns a boolean, loaded, which is true if this is the
801 // first time the package was loaded. Callers may preload imports in this case.
802 func loadPackageData(ctx context.Context, path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
804 panic("loadPackageData called with empty package path")
807 if strings.HasPrefix(path, "mod/") {
808 // Paths beginning with "mod/" might accidentally
809 // look in the module cache directory tree in $GOPATH/pkg/mod/.
810 // This prefix is owned by the Go core for possible use in the
811 // standard library (since it does not begin with a domain name),
812 // so it's OK to disallow entirely.
813 return nil, false, fmt.Errorf("disallowed import path %q", path)
816 if strings.Contains(path, "@") {
817 return nil, false, errors.New("can only use path@version syntax with 'go get' and 'go install' in module-aware mode")
820 // Determine canonical package path and directory.
821 // For a local import the identifier is the pseudo-import path
822 // we create from the full directory to the package.
823 // Otherwise it is the usual import path.
824 // For vendored imports, it is the expanded form.
826 // Note that when modules are enabled, local import paths are normally
827 // canonicalized by modload.LoadPackages before now. However, if there's an
828 // error resolving a local path, it will be returned untransformed
829 // so that 'go list -e' reports something useful.
830 importKey := importSpec{
832 parentPath: parentPath,
833 parentDir: parentDir,
834 parentRoot: parentRoot,
835 parentIsStd: parentIsStd,
838 r := resolvedImportCache.Do(importKey, func() any {
840 if cfg.ModulesEnabled {
841 r.dir, r.path, r.err = modload.Lookup(parentPath, parentIsStd, path)
842 } else if build.IsLocalImport(path) {
843 r.dir = filepath.Join(parentDir, path)
844 r.path = dirToImportPath(r.dir)
845 } else if mode&ResolveImport != 0 {
846 // We do our own path resolution, because we want to
847 // find out the key to use in packageCache without the
848 // overhead of repeated calls to buildContext.Import.
849 // The code is also needed in a few other places anyway.
850 r.path = resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
851 } else if mode&ResolveModule != 0 {
852 r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
859 // Invariant: r.path is set to the resolved import path. If the path cannot
860 // be resolved, r.path is set to path, the source import path.
861 // r.path is never empty.
863 // Load the package from its directory. If we already found the package's
864 // directory when resolving its import path, use that.
865 data := packageDataCache.Do(r.path, func() any {
869 var buildMode build.ImportMode
870 if !cfg.ModulesEnabled {
871 buildMode = build.ImportComment
873 data.p, data.err = cfg.BuildContext.ImportDir(r.dir, buildMode)
874 if cfg.ModulesEnabled {
875 // Override data.p.Root, since ImportDir sets it to $GOPATH, if
876 // the module is inside $GOPATH/src.
877 if info := modload.PackageModuleInfo(ctx, path); info != nil {
878 data.p.Root = info.Dir
883 // ImportDir gave us one error, and the module loader gave us another.
884 // We arbitrarily choose to keep the error from ImportDir because
885 // that's what our tests already expect, and it seems to provide a bit
886 // more detail in most cases.
887 } else if errors.Is(r.err, imports.ErrNoGo) {
888 // ImportDir said there were files in the package, but the module
889 // loader said there weren't. Which one is right?
890 // Without this special-case hack, the TestScript/test_vet case fails
891 // on the vetfail/p1 package (added in CL 83955).
892 // Apparently, imports.ShouldBuild biases toward rejecting files
893 // with invalid build constraints, whereas ImportDir biases toward
896 // TODO(#41410: Figure out how this actually ought to work and fix
902 } else if r.err != nil {
903 data.p = new(build.Package)
905 } else if cfg.ModulesEnabled && path != "unsafe" {
906 data.p = new(build.Package)
907 data.err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", r.path)
909 buildMode := build.ImportComment
910 if mode&ResolveImport == 0 || r.path != path {
911 // Not vendoring, or we already found the vendored path.
912 buildMode |= build.IgnoreVendor
914 data.p, data.err = cfg.BuildContext.Import(r.path, parentDir, buildMode)
916 data.p.ImportPath = r.path
918 // Set data.p.BinDir in cases where go/build.Context.Import
919 // may give us a path we don't want.
922 data.p.BinDir = cfg.GOBIN
923 } else if cfg.ModulesEnabled {
924 data.p.BinDir = modload.BinDir()
928 if !cfg.ModulesEnabled && data.err == nil &&
929 data.p.ImportComment != "" && data.p.ImportComment != path &&
930 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
931 data.err = fmt.Errorf("code in directory %s expects import %q", data.p.Dir, data.p.ImportComment)
936 return data.p, loaded, data.err
939 // importSpec describes an import declaration in source code. It is used as a
940 // cache key for resolvedImportCache.
941 type importSpec struct {
943 parentPath, parentDir, parentRoot string
948 // resolvedImport holds a canonical identifier for a package. It may also contain
949 // a path to the package's directory and an error if one occurred. resolvedImport
950 // is the value type in resolvedImportCache.
951 type resolvedImport struct {
956 // packageData holds information loaded from a package. It is the value type
957 // in packageDataCache.
958 type packageData struct {
963 // resolvedImportCache maps import strings (importSpec) to canonical package names
965 var resolvedImportCache par.Cache
967 // packageDataCache maps canonical package names (string) to package metadata
969 var packageDataCache par.Cache
971 // preloadWorkerCount is the number of concurrent goroutines that can load
972 // packages. Experimentally, there are diminishing returns with more than
973 // 4 workers. This was measured on the following machines.
975 // * MacBookPro with a 4-core Intel Core i7 CPU
976 // * Linux workstation with 6-core Intel Xeon CPU
977 // * Linux workstation with 24-core Intel Xeon CPU
979 // It is very likely (though not confirmed) that this workload is limited
980 // by memory bandwidth. We don't have a good way to determine the number of
981 // workers that would saturate the bus though, so runtime.GOMAXPROCS
982 // seems like a reasonable default.
983 var preloadWorkerCount = runtime.GOMAXPROCS(0)
985 // preload holds state for managing concurrent preloading of package data.
987 // A preload should be created with newPreload before loading a large
988 // package graph. flush must be called when package loading is complete
989 // to ensure preload goroutines are no longer active. This is necessary
990 // because of global mutable state that cannot safely be read and written
991 // concurrently. In particular, packageDataCache may be cleared by "go get"
992 // in GOPATH mode, and modload.loaded (accessed via modload.Lookup) may be
993 // modified by modload.LoadPackages.
994 type preload struct {
999 // newPreload creates a new preloader. flush must be called later to avoid
1000 // accessing global state while it is being modified.
1001 func newPreload() *preload {
1003 cancel: make(chan struct{}),
1004 sema: make(chan struct{}, preloadWorkerCount),
1009 // preloadMatches loads data for package paths matched by patterns.
1010 // When preloadMatches returns, some packages may not be loaded yet, but
1011 // loadPackageData and loadImport are always safe to call.
1012 func (pre *preload) preloadMatches(ctx context.Context, opts PackageOpts, matches []*search.Match) {
1013 for _, m := range matches {
1014 for _, pkg := range m.Pkgs {
1018 case pre.sema <- struct{}{}:
1019 go func(pkg string) {
1020 mode := 0 // don't use vendoring or module import resolution
1021 bp, loaded, err := loadPackageData(ctx, pkg, "", base.Cwd(), "", false, mode)
1023 if bp != nil && loaded && err == nil && !opts.IgnoreImports {
1024 pre.preloadImports(ctx, opts, bp.Imports, bp)
1032 // preloadImports queues a list of imports for preloading.
1033 // When preloadImports returns, some packages may not be loaded yet,
1034 // but loadPackageData and loadImport are always safe to call.
1035 func (pre *preload) preloadImports(ctx context.Context, opts PackageOpts, imports []string, parent *build.Package) {
1036 parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
1037 for _, path := range imports {
1038 if path == "C" || path == "unsafe" {
1044 case pre.sema <- struct{}{}:
1045 go func(path string) {
1046 bp, loaded, err := loadPackageData(ctx, path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
1048 if bp != nil && loaded && err == nil && !opts.IgnoreImports {
1049 pre.preloadImports(ctx, opts, bp.Imports, bp)
1056 // flush stops pending preload operations. flush blocks until preload calls to
1057 // loadPackageData have completed. The preloader will not make any new calls
1058 // to loadPackageData.
1059 func (pre *preload) flush() {
1060 // flush is usually deferred.
1061 // Don't hang program waiting for workers on panic.
1062 if v := recover(); v != nil {
1067 for i := 0; i < preloadWorkerCount; i++ {
1068 pre.sema <- struct{}{}
1072 func cleanImport(path string) string {
1074 path = pathpkg.Clean(path)
1075 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
1081 var isDirCache par.Cache
1083 func isDir(path string) bool {
1084 return isDirCache.Do(path, func() any {
1085 fi, err := fsys.Stat(path)
1086 return err == nil && fi.IsDir()
1090 // ResolveImportPath returns the true meaning of path when it appears in parent.
1091 // There are two different resolutions applied.
1092 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
1093 // If vendor expansion doesn't trigger, then the path is also subject to
1094 // Go 1.11 module legacy conversion (golang.org/issue/25069).
1095 func ResolveImportPath(parent *Package, path string) (found string) {
1096 var parentPath, parentDir, parentRoot string
1097 parentIsStd := false
1099 parentPath = parent.ImportPath
1100 parentDir = parent.Dir
1101 parentRoot = parent.Root
1102 parentIsStd = parent.Standard
1104 return resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
1107 func resolveImportPath(path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
1108 if cfg.ModulesEnabled {
1109 if _, p, e := modload.Lookup(parentPath, parentIsStd, path); e == nil {
1114 found = vendoredImportPath(path, parentPath, parentDir, parentRoot)
1118 return moduleImportPath(path, parentPath, parentDir, parentRoot)
1121 // dirAndRoot returns the source directory and workspace root
1122 // for the package p, guaranteeing that root is a path prefix of dir.
1123 func dirAndRoot(path string, dir, root string) (string, string) {
1124 origDir, origRoot := dir, root
1125 dir = filepath.Clean(dir)
1126 root = filepath.Join(root, "src")
1127 if !str.HasFilePathPrefix(dir, root) || path != "command-line-arguments" && filepath.Join(root, path) != dir {
1128 // Look for symlinks before reporting error.
1129 dir = expandPath(dir)
1130 root = expandPath(root)
1133 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 {
1135 base.Fatalf("unexpected directory layout:\n"+
1136 " import path: %s\n"+
1139 " expand root: %s\n"+
1140 " expand dir: %s\n"+
1143 filepath.Join(origRoot, "src"),
1144 filepath.Clean(origDir),
1147 string(filepath.Separator))
1153 // vendoredImportPath returns the vendor-expansion of path when it appears in parent.
1154 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
1155 // x/vendor/path, vendor/path, or else stay path if none of those exist.
1156 // vendoredImportPath returns the expanded path or, if no expansion is found, the original.
1157 func vendoredImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1158 if parentRoot == "" {
1162 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1164 vpath := "vendor/" + path
1165 for i := len(dir); i >= len(root); i-- {
1166 if i < len(dir) && dir[i] != filepath.Separator {
1169 // Note: checking for the vendor directory before checking
1170 // for the vendor/path directory helps us hit the
1171 // isDir cache more often. It also helps us prepare a more useful
1172 // list of places we looked, to report when an import is not found.
1173 if !isDir(filepath.Join(dir[:i], "vendor")) {
1176 targ := filepath.Join(dir[:i], vpath)
1177 if isDir(targ) && hasGoFiles(targ) {
1178 importPath := parentPath
1179 if importPath == "command-line-arguments" {
1180 // If parent.ImportPath is 'command-line-arguments'.
1181 // set to relative directory to root (also chopped root directory)
1182 importPath = dir[len(root)+1:]
1184 // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
1185 // We know the import path for parent's dir.
1186 // We chopped off some number of path elements and
1187 // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
1188 // Now we want to know the import path for that directory.
1189 // Construct it by chopping the same number of path elements
1190 // (actually the same number of bytes) from parent's import path
1191 // and then append /vendor/path.
1192 chopped := len(dir) - i
1193 if chopped == len(importPath)+1 {
1194 // We walked up from c:\gopath\src\foo\bar
1195 // and found c:\gopath\src\vendor\path.
1196 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
1197 // Use "vendor/path" without any prefix.
1200 return importPath[:len(importPath)-chopped] + "/" + vpath
1207 modulePrefix = []byte("\nmodule ")
1208 goModPathCache par.Cache
1211 // goModPath returns the module path in the go.mod in dir, if any.
1212 func goModPath(dir string) (path string) {
1213 return goModPathCache.Do(dir, func() any {
1214 data, err := os.ReadFile(filepath.Join(dir, "go.mod"))
1219 if bytes.HasPrefix(data, modulePrefix[1:]) {
1222 i = bytes.Index(data, modulePrefix)
1230 // Cut line at \n, drop trailing \r if present.
1231 if j := bytes.IndexByte(line, '\n'); j >= 0 {
1234 if line[len(line)-1] == '\r' {
1235 line = line[:len(line)-1]
1237 line = line[len("module "):]
1239 // If quoted, unquote.
1240 path = strings.TrimSpace(string(line))
1241 if path != "" && path[0] == '"' {
1242 s, err := strconv.Unquote(path)
1252 // findVersionElement returns the slice indices of the final version element /vN in path.
1253 // If there is no such element, it returns -1, -1.
1254 func findVersionElement(path string) (i, j int) {
1256 for i = len(path) - 1; i >= 0; i-- {
1258 if isVersionElement(path[i+1 : j]) {
1267 // isVersionElement reports whether s is a well-formed path version element:
1268 // v2, v3, v10, etc, but not v0, v05, v1.
1269 func isVersionElement(s string) bool {
1270 if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
1273 for i := 1; i < len(s); i++ {
1274 if s[i] < '0' || '9' < s[i] {
1281 // moduleImportPath translates import paths found in go modules
1282 // back down to paths that can be resolved in ordinary builds.
1284 // Define “new” code as code with a go.mod file in the same directory
1285 // or a parent directory. If an import in new code says x/y/v2/z but
1286 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
1287 // then go build will read the import as x/y/z instead.
1288 // See golang.org/issue/25069.
1289 func moduleImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1290 if parentRoot == "" {
1294 // If there are no vN elements in path, leave it alone.
1295 // (The code below would do the same, but only after
1296 // some other file system accesses that we can avoid
1297 // here by returning early.)
1298 if i, _ := findVersionElement(path); i < 0 {
1302 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1304 // Consider dir and parents, up to and including root.
1305 for i := len(dir); i >= len(root); i-- {
1306 if i < len(dir) && dir[i] != filepath.Separator {
1309 if goModPath(dir[:i]) != "" {
1313 // This code is not in a tree with a go.mod,
1314 // so apply no changes to the path.
1318 // This import is in a tree with a go.mod.
1319 // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
1320 // if GOPATH/src/x/y/go.mod says module "x/y/v2",
1322 // If x/y/v2/z exists, use it unmodified.
1323 if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
1327 // Otherwise look for a go.mod supplying a version element.
1328 // Some version-like elements may appear in paths but not
1329 // be module versions; we skip over those to look for module
1330 // versions. For example the module m/v2 might have a
1331 // package m/v2/api/v1/foo.
1334 i, j := findVersionElement(path[:limit])
1338 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
1339 if mpath := goModPath(bp.Dir); mpath != "" {
1340 // Found a valid go.mod file, so we're stopping the search.
1341 // If the path is m/v2/p and we found m/go.mod that says
1342 // "module m/v2", then we return "m/p".
1343 if mpath == path[:j] {
1344 return path[:i] + path[j:]
1346 // Otherwise just return the original path.
1347 // We didn't find anything worth rewriting,
1348 // and the go.mod indicates that we should
1349 // not consider parent directories.
1358 // hasGoFiles reports whether dir contains any files with names ending in .go.
1359 // For a vendor check we must exclude directories that contain no .go files.
1360 // Otherwise it is not possible to vendor just a/b/c and still import the
1361 // non-vendored a/b. See golang.org/issue/13832.
1362 func hasGoFiles(dir string) bool {
1363 files, _ := os.ReadDir(dir)
1364 for _, f := range files {
1365 if !f.IsDir() && strings.HasSuffix(f.Name(), ".go") {
1372 // reusePackage reuses package p to satisfy the import at the top
1373 // of the import stack stk. If this use causes an import loop,
1374 // reusePackage updates p's error information to record the loop.
1375 func reusePackage(p *Package, stk *ImportStack) *Package {
1376 // We use p.Internal.Imports==nil to detect a package that
1377 // is in the midst of its own loadPackage call
1378 // (all the recursion below happens before p.Internal.Imports gets set).
1379 if p.Internal.Imports == nil {
1381 p.Error = &PackageError{
1382 ImportStack: stk.Copy(),
1383 Err: errors.New("import cycle not allowed"),
1384 IsImportCycle: true,
1386 } else if !p.Error.IsImportCycle {
1387 // If the error is already set, but it does not indicate that
1388 // we are in an import cycle, set IsImportCycle so that we don't
1389 // end up stuck in a loop down the road.
1390 p.Error.IsImportCycle = true
1394 // Don't rewrite the import stack in the error if we have an import cycle.
1395 // If we do, we'll lose the path that describes the cycle.
1396 if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
1397 p.Error.ImportStack = stk.Copy()
1402 // disallowInternal checks that srcDir (containing package importerPath, if non-empty)
1403 // is allowed to import p.
1404 // If the import is allowed, disallowInternal returns the original package p.
1405 // If not, it returns a new package containing just an appropriate error.
1406 func disallowInternal(ctx context.Context, srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package {
1407 // golang.org/s/go14internal:
1408 // An import of a path containing the element “internal”
1409 // is disallowed if the importing code is outside the tree
1410 // rooted at the parent of the “internal” directory.
1412 // There was an error loading the package; stop here.
1417 // The generated 'testmain' package is allowed to access testing/internal/...,
1418 // as if it were generated into the testing directory tree
1419 // (it's actually in a temporary directory outside any Go tree).
1420 // This cleans up a former kludge in passing functionality to the testing package.
1421 if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
1425 // We can't check standard packages with gccgo.
1426 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
1430 // The sort package depends on internal/reflectlite, but during bootstrap
1431 // the path rewriting causes the normal internal checks to fail.
1432 // Instead, just ignore the internal rules during bootstrap.
1433 if p.Standard && strings.HasPrefix(importerPath, "bootstrap/") {
1437 // importerPath is empty: we started
1438 // with a name given on the command line, not an
1439 // import. Anything listed on the command line is fine.
1440 if importerPath == "" {
1444 // Check for "internal" element: three cases depending on begin of string and/or end of string.
1445 i, ok := findInternal(p.ImportPath)
1450 // Internal is present.
1451 // Map import path back to directory corresponding to parent of internal.
1453 i-- // rewind over slash in ".../internal"
1456 if p.Module == nil {
1457 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
1459 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1463 // Look for symlinks before reporting error.
1464 srcDir = expandPath(srcDir)
1465 parent = expandPath(parent)
1466 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1470 // p is in a module, so make it available based on the importer's import path instead
1471 // of the file path (https://golang.org/issue/23970).
1472 if importer.Internal.CmdlineFiles {
1473 // The importer is a list of command-line files.
1474 // Pretend that the import path is the import path of the
1475 // directory containing them.
1476 // If the directory is outside the main modules, this will resolve to ".",
1477 // which is not a prefix of any valid module.
1478 importerPath, _ = modload.MainModules.DirImportPath(ctx, importer.Dir)
1480 parentOfInternal := p.ImportPath[:i]
1481 if str.HasPathPrefix(importerPath, parentOfInternal) {
1486 // Internal is present, and srcDir is outside parent's tree. Not allowed.
1488 perr.Error = &PackageError{
1489 alwaysPrintStack: true,
1490 ImportStack: stk.Copy(),
1491 Err: ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
1493 perr.Incomplete = true
1497 // findInternal looks for the final "internal" path element in the given import path.
1498 // If there isn't one, findInternal returns ok=false.
1499 // Otherwise, findInternal returns ok=true and the index of the "internal".
1500 func findInternal(path string) (index int, ok bool) {
1501 // Three cases, depending on internal at start/end of string or not.
1502 // The order matters: we must return the index of the final element,
1503 // because the final one produces the most restrictive requirement
1506 case strings.HasSuffix(path, "/internal"):
1507 return len(path) - len("internal"), true
1508 case strings.Contains(path, "/internal/"):
1509 return strings.LastIndex(path, "/internal/") + 1, true
1510 case path == "internal", strings.HasPrefix(path, "internal/"):
1516 // disallowVendor checks that srcDir is allowed to import p as path.
1517 // If the import is allowed, disallowVendor returns the original package p.
1518 // If not, it returns a new package containing just an appropriate error.
1519 func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *Package {
1520 // If the importerPath is empty, we started
1521 // with a name given on the command line, not an
1522 // import. Anything listed on the command line is fine.
1523 if importerPath == "" {
1527 if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != p {
1531 // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
1532 if i, ok := FindVendor(path); ok {
1534 perr.Error = &PackageError{
1535 ImportStack: stk.Copy(),
1536 Err: ImportErrorf(path, "%s must be imported as %s", path, path[i+len("vendor/"):]),
1538 perr.Incomplete = true
1545 // disallowVendorVisibility checks that srcDir is allowed to import p.
1546 // The rules are the same as for /internal/ except that a path ending in /vendor
1547 // is not subject to the rules, only subdirectories of vendor.
1548 // This allows people to have packages and commands named vendor,
1549 // for maximal compatibility with existing source trees.
1550 func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *Package {
1551 // The stack does not include p.ImportPath.
1552 // If there's nothing on the stack, we started
1553 // with a name given on the command line, not an
1554 // import. Anything listed on the command line is fine.
1555 if importerPath == "" {
1559 // Check for "vendor" element.
1560 i, ok := FindVendor(p.ImportPath)
1565 // Vendor is present.
1566 // Map import path back to directory corresponding to parent of vendor.
1568 i-- // rewind over slash in ".../vendor"
1570 truncateTo := i + len(p.Dir) - len(p.ImportPath)
1571 if truncateTo < 0 || len(p.Dir) < truncateTo {
1574 parent := p.Dir[:truncateTo]
1575 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1579 // Look for symlinks before reporting error.
1580 srcDir = expandPath(srcDir)
1581 parent = expandPath(parent)
1582 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1586 // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1588 perr.Error = &PackageError{
1589 ImportStack: stk.Copy(),
1590 Err: errors.New("use of vendored package not allowed"),
1592 perr.Incomplete = true
1596 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1597 // If there isn't one, FindVendor returns ok=false.
1598 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1600 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1601 // not the vendored copy of an import "" (the empty import path).
1602 // This will allow people to have packages or commands named vendor.
1603 // This may help reduce breakage, or it may just be confusing. We'll see.
1604 func FindVendor(path string) (index int, ok bool) {
1605 // Two cases, depending on internal at start of string or not.
1606 // The order matters: we must return the index of the final element,
1607 // because the final one is where the effective import path starts.
1609 case strings.Contains(path, "/vendor/"):
1610 return strings.LastIndex(path, "/vendor/") + 1, true
1611 case strings.HasPrefix(path, "vendor/"):
1620 ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1621 ToBin // to bin dir inside package root (default for non-cmd/*)
1622 StalePath // an old import path; fail to build
1625 // InstallTargetDir reports the target directory for installing the command p.
1626 func InstallTargetDir(p *Package) TargetDir {
1627 if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1630 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1631 switch p.ImportPath {
1632 case "cmd/go", "cmd/gofmt":
1640 var cgoExclude = map[string]bool{
1641 "runtime/cgo": true,
1644 var cgoSyscallExclude = map[string]bool{
1645 "runtime/cgo": true,
1646 "runtime/race": true,
1647 "runtime/msan": true,
1648 "runtime/asan": true,
1651 var foldPath = make(map[string]string)
1653 // exeFromImportPath returns an executable name
1654 // for a package using the import path.
1656 // The executable name is the last element of the import path.
1657 // In module-aware mode, an additional rule is used on import paths
1658 // consisting of two or more path elements. If the last element is
1659 // a vN path element specifying the major version, then the
1660 // second last element of the import path is used instead.
1661 func (p *Package) exeFromImportPath() string {
1662 _, elem := pathpkg.Split(p.ImportPath)
1663 if cfg.ModulesEnabled {
1664 // If this is example.com/mycmd/v2, it's more useful to
1665 // install it as mycmd than as v2. See golang.org/issue/24667.
1666 if elem != p.ImportPath && isVersionElement(elem) {
1667 _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
1673 // exeFromFiles returns an executable name for a package
1674 // using the first element in GoFiles or CgoFiles collections without the prefix.
1676 // Returns empty string in case of empty collection.
1677 func (p *Package) exeFromFiles() string {
1679 if len(p.GoFiles) > 0 {
1681 } else if len(p.CgoFiles) > 0 {
1686 _, elem := filepath.Split(src)
1687 return elem[:len(elem)-len(".go")]
1690 // DefaultExecName returns the default executable name for a package
1691 func (p *Package) DefaultExecName() string {
1692 if p.Internal.CmdlineFiles {
1693 return p.exeFromFiles()
1695 return p.exeFromImportPath()
1698 // load populates p using information from bp, err, which should
1699 // be the result of calling build.Context.Import.
1700 // stk contains the import stack, not including path itself.
1701 func (p *Package) load(ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
1702 p.copyBuild(opts, bp)
1704 // The localPrefix is the path we interpret ./ imports relative to,
1705 // if we support them at all (not in module mode!).
1706 // Synthesized main packages sometimes override this.
1707 if p.Internal.Local && !cfg.ModulesEnabled {
1708 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1711 // setError sets p.Error if it hasn't already been set. We may proceed
1712 // after encountering some errors so that 'go list -e' has more complete
1713 // output. If there's more than one error, we should report the first.
1714 setError := func(err error) {
1716 p.Error = &PackageError{
1717 ImportStack: stk.Copy(),
1721 // Add the importer's position information if the import position exists, and
1722 // the current package being examined is the importer.
1723 // If we have not yet accepted package p onto the import stack,
1724 // then the cause of the error is not within p itself: the error
1725 // must be either in an explicit command-line argument,
1726 // or on the importer side (indicated by a non-empty importPos).
1727 if path != stk.Top() && len(importPos) > 0 {
1728 p.Error.setPos(importPos)
1735 p.setLoadPackageDataError(err, path, stk, importPos)
1738 useBindir := p.Name == "main"
1740 switch cfg.BuildBuildmode {
1741 case "c-archive", "c-shared", "plugin":
1747 // Report an error when the old code.google.com/p/go.tools paths are used.
1748 if InstallTargetDir(p) == StalePath {
1749 // TODO(matloob): remove this branch, and StalePath itself. code.google.com/p/go is so
1750 // old, even this code checking for it is stale now!
1751 newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1752 e := ImportErrorf(p.ImportPath, "the %v command has moved; use %v instead.", p.ImportPath, newPath)
1756 elem := p.DefaultExecName()
1757 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1758 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1759 // Install cross-compiled binaries to subdirectories of bin.
1762 if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
1763 p.Internal.Build.BinDir = modload.BinDir()
1765 if p.Internal.Build.BinDir != "" {
1766 // Install to GOBIN or bin of GOPATH entry.
1767 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1768 if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1769 // Do not create $GOBIN/goos_goarch/elem.
1771 p.Internal.GobinSubdir = true
1774 if InstallTargetDir(p) == ToTool {
1775 // This is for 'go tool'.
1776 // Override all the usual logic and force it into the tool directory.
1777 if cfg.BuildToolchainName == "gccgo" {
1778 p.Target = filepath.Join(base.ToolDir, elem)
1780 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1783 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1786 } else if p.Internal.Local {
1787 // Local import turned into absolute path.
1788 // No permanent install target.
1791 p.Target = p.Internal.Build.PkgObj
1792 if cfg.BuildLinkshared && p.Target != "" {
1793 // TODO(bcmills): The reliance on p.Target implies that -linkshared does
1794 // not work for any package that lacks a Target — such as a non-main
1795 // package in module mode. We should probably fix that.
1796 shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1797 shlib, err := os.ReadFile(shlibnamefile)
1798 if err != nil && !os.IsNotExist(err) {
1799 base.Fatalf("reading shlibname: %v", err)
1802 libname := strings.TrimSpace(string(shlib))
1803 if cfg.BuildContext.Compiler == "gccgo" {
1804 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1806 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1812 // Build augmented import list to add implicit dependencies.
1813 // Be careful not to add imports twice, just to avoid confusion.
1814 importPaths := p.Imports
1815 addImport := func(path string, forCompiler bool) {
1816 for _, p := range importPaths {
1821 importPaths = append(importPaths, path)
1823 p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
1827 if !opts.IgnoreImports {
1828 // Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall",
1829 // except for certain packages, to avoid circular dependencies.
1831 addImport("unsafe", true)
1833 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1834 addImport("runtime/cgo", true)
1836 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1837 addImport("syscall", true)
1840 // SWIG adds imports of some standard packages.
1842 addImport("unsafe", true)
1843 if cfg.BuildContext.Compiler != "gccgo" {
1844 addImport("runtime/cgo", true)
1846 addImport("syscall", true)
1847 addImport("sync", true)
1849 // TODO: The .swig and .swigcxx files can use
1850 // %go_import directives to import other packages.
1853 // The linker loads implicit dependencies.
1854 if p.Name == "main" && !p.Internal.ForceLibrary {
1855 for _, dep := range LinkerDeps(p) {
1856 addImport(dep, false)
1861 // Check for case-insensitive collisions of import paths.
1862 fold := str.ToFold(p.ImportPath)
1863 if other := foldPath[fold]; other == "" {
1864 foldPath[fold] = p.ImportPath
1865 } else if other != p.ImportPath {
1866 setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
1870 if !SafeArg(p.ImportPath) {
1871 setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
1875 // Errors after this point are caused by this package, not the importing
1876 // package. Pushing the path here prevents us from reporting the error
1877 // with the position of the import declaration.
1881 pkgPath := p.ImportPath
1882 if p.Internal.CmdlineFiles {
1883 pkgPath = "command-line-arguments"
1885 if cfg.ModulesEnabled {
1886 p.Module = modload.PackageModuleInfo(ctx, pkgPath)
1889 p.EmbedFiles, p.Internal.Embed, err = resolveEmbed(p.Dir, p.EmbedPatterns)
1893 embedErr := err.(*EmbedError)
1894 p.Error.setPos(p.Internal.Build.EmbedPatternPos[embedErr.Pattern])
1897 // Check for case-insensitive collision of input files.
1898 // To avoid problems on case-insensitive files, we reject any package
1899 // where two different input files have equal names under a case-insensitive
1901 inputs := p.AllFiles()
1902 f1, f2 := str.FoldDup(inputs)
1904 setError(fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2))
1908 // If first letter of input file is ASCII, it must be alphanumeric.
1909 // This avoids files turning into flags when invoking commands,
1910 // and other problems we haven't thought of yet.
1911 // Also, _cgo_ files must be generated by us, not supplied.
1912 // They are allowed to have //go:cgo_ldflag directives.
1913 // The directory scan ignores files beginning with _,
1914 // so we shouldn't see any _cgo_ files anyway, but just be safe.
1915 for _, file := range inputs {
1916 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1917 setError(fmt.Errorf("invalid input file name %q", file))
1921 if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1922 setError(fmt.Errorf("invalid input directory name %q", name))
1926 // Build list of imported packages and full dependency list.
1927 imports := make([]*Package, 0, len(p.Imports))
1928 for i, path := range importPaths {
1932 p1 := LoadImport(ctx, opts, path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1934 path = p1.ImportPath
1935 importPaths[i] = path
1936 if i < len(p.Imports) {
1940 imports = append(imports, p1)
1945 p.Internal.Imports = imports
1947 if p.Error == nil && p.Name == "main" && !p.Internal.ForceLibrary && len(p.DepsErrors) == 0 {
1948 // TODO(bcmills): loading VCS metadata can be fairly slow.
1949 // Consider starting this as a background goroutine and retrieving the result
1950 // asynchronously when we're actually ready to build the package, or when we
1951 // actually need to evaluate whether the package's metadata is stale.
1952 p.setBuildInfo(opts.LoadVCS)
1955 // unsafe is a fake package.
1956 if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1960 // If cgo is not enabled, ignore cgo supporting sources
1961 // just as we ignore go files containing import "C".
1962 if !cfg.BuildContext.CgoEnabled {
1967 p.SwigCXXFiles = nil
1968 // Note that SFiles are okay (they go to the Go assembler)
1969 // and HFiles are okay (they might be used by the SFiles).
1970 // Also Sysofiles are okay (they might not contain object
1971 // code; see issue #16050).
1974 // The gc toolchain only permits C source files with cgo or SWIG.
1975 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1976 setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1980 // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1981 // regardless of toolchain.
1982 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1983 setError(fmt.Errorf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1986 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1987 setError(fmt.Errorf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1990 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1991 setError(fmt.Errorf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1996 // An EmbedError indicates a problem with a go:embed directive.
1997 type EmbedError struct {
2002 func (e *EmbedError) Error() string {
2003 return fmt.Sprintf("pattern %s: %v", e.Pattern, e.Err)
2006 func (e *EmbedError) Unwrap() error {
2010 // ResolveEmbed resolves //go:embed patterns and returns only the file list.
2011 // For use by go mod vendor to find embedded files it should copy into the
2012 // vendor directory.
2013 // TODO(#42504): Once go mod vendor uses load.PackagesAndErrors, just
2014 // call (*Package).ResolveEmbed
2015 func ResolveEmbed(dir string, patterns []string) ([]string, error) {
2016 files, _, err := resolveEmbed(dir, patterns)
2020 // resolveEmbed resolves //go:embed patterns to precise file lists.
2021 // It sets files to the list of unique files matched (for go list),
2022 // and it sets pmap to the more precise mapping from
2023 // patterns to files.
2024 func resolveEmbed(pkgdir string, patterns []string) (files []string, pmap map[string][]string, err error) {
2035 // TODO(rsc): All these messages need position information for better error reports.
2036 pmap = make(map[string][]string)
2037 have := make(map[string]int)
2038 dirOK := make(map[string]bool)
2039 pid := 0 // pattern ID, to allow reuse of have map
2040 for _, pattern = range patterns {
2044 all := strings.HasPrefix(pattern, "all:")
2046 glob = pattern[len("all:"):]
2048 // Check pattern is valid for //go:embed.
2049 if _, err := path.Match(glob, ""); err != nil || !validEmbedPattern(glob) {
2050 return nil, nil, fmt.Errorf("invalid pattern syntax")
2053 // Glob to find matches.
2054 match, err := fsys.Glob(pkgdir + string(filepath.Separator) + filepath.FromSlash(glob))
2056 return nil, nil, err
2059 // Filter list of matches down to the ones that will still exist when
2060 // the directory is packaged up as a module. (If p.Dir is in the module cache,
2061 // only those files exist already, but if p.Dir is in the current module,
2062 // then there may be other things lying around, like symbolic links or .git directories.)
2064 for _, file := range match {
2065 rel := filepath.ToSlash(file[len(pkgdir)+1:]) // file, relative to p.Dir
2068 info, err := fsys.Lstat(file)
2070 return nil, nil, err
2076 // Check that directories along path do not begin a new module
2077 // (do not contain a go.mod).
2078 for dir := file; len(dir) > len(pkgdir)+1 && !dirOK[dir]; dir = filepath.Dir(dir) {
2079 if _, err := fsys.Stat(filepath.Join(dir, "go.mod")); err == nil {
2080 return nil, nil, fmt.Errorf("cannot embed %s %s: in different module", what, rel)
2083 if info, err := fsys.Lstat(dir); err == nil && !info.IsDir() {
2084 return nil, nil, fmt.Errorf("cannot embed %s %s: in non-directory %s", what, rel, dir[len(pkgdir)+1:])
2088 if elem := filepath.Base(dir); isBadEmbedName(elem) {
2090 return nil, nil, fmt.Errorf("cannot embed %s %s: invalid name %s", what, rel, elem)
2092 return nil, nil, fmt.Errorf("cannot embed %s %s: in invalid directory %s", what, rel, elem)
2099 return nil, nil, fmt.Errorf("cannot embed irregular file %s", rel)
2101 case info.Mode().IsRegular():
2102 if have[rel] != pid {
2104 list = append(list, rel)
2108 // Gather all files in the named directory, stopping at module boundaries
2109 // and ignoring files that wouldn't be packaged into a module.
2111 err := fsys.Walk(file, func(path string, info os.FileInfo, err error) error {
2115 rel := filepath.ToSlash(path[len(pkgdir)+1:])
2117 if path != file && (isBadEmbedName(name) || ((name[0] == '.' || name[0] == '_') && !all)) {
2118 // Ignore bad names, assuming they won't go into modules.
2119 // Also avoid hidden files that user may not know about.
2120 // See golang.org/issue/42328.
2127 if _, err := fsys.Stat(filepath.Join(path, "go.mod")); err == nil {
2128 return filepath.SkipDir
2132 if !info.Mode().IsRegular() {
2136 if have[rel] != pid {
2138 list = append(list, rel)
2143 return nil, nil, err
2146 return nil, nil, fmt.Errorf("cannot embed directory %s: contains no embeddable files", rel)
2152 return nil, nil, fmt.Errorf("no matching files found")
2155 pmap[pattern] = list
2158 for file := range have {
2159 files = append(files, file)
2162 return files, pmap, nil
2165 func validEmbedPattern(pattern string) bool {
2166 return pattern != "." && fs.ValidPath(pattern)
2169 // isBadEmbedName reports whether name is the base name of a file that
2170 // can't or won't be included in modules and therefore shouldn't be treated
2171 // as existing for embedding.
2172 func isBadEmbedName(name string) bool {
2173 if err := module.CheckFilePath(name); err != nil {
2177 // Empty string should be impossible but make it bad.
2180 // Version control directories won't be present in module.
2181 case ".bzr", ".hg", ".git", ".svn":
2187 // collectDeps populates p.Deps and p.DepsErrors by iterating over
2188 // p.Internal.Imports.
2190 // TODO(jayconrod): collectDeps iterates over transitive imports for every
2191 // package. We should only need to visit direct imports.
2192 func (p *Package) collectDeps() {
2193 deps := make(map[string]*Package)
2195 q = append(q, p.Internal.Imports...)
2196 for i := 0; i < len(q); i++ {
2198 path := p1.ImportPath
2199 // The same import path could produce an error or not,
2200 // depending on what tries to import it.
2201 // Prefer to record entries with errors, so we can report them.
2203 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
2205 for _, p2 := range p1.Internal.Imports {
2206 if deps[p2.ImportPath] != p2 {
2213 p.Deps = make([]string, 0, len(deps))
2214 for dep := range deps {
2215 p.Deps = append(p.Deps, dep)
2217 sort.Strings(p.Deps)
2218 for _, dep := range p.Deps {
2221 panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
2223 if p1.Error != nil {
2224 p.DepsErrors = append(p.DepsErrors, p1.Error)
2229 // vcsStatusCache maps repository directories (string)
2230 // to their VCS information (vcsStatusError).
2231 var vcsStatusCache par.Cache
2233 // setBuildInfo gathers build information, formats it as a string to be
2234 // embedded in the binary, then sets p.Internal.BuildInfo to that string.
2235 // setBuildInfo should only be called on a main package with no errors.
2237 // This information can be retrieved using debug.ReadBuildInfo.
2239 // Note that the GoVersion field is not set here to avoid encoding it twice.
2240 // It is stored separately in the binary, mostly for historical reasons.
2241 func (p *Package) setBuildInfo(includeVCS bool) {
2242 setPkgErrorf := func(format string, args ...any) {
2244 p.Error = &PackageError{Err: fmt.Errorf(format, args...)}
2248 var debugModFromModinfo func(*modinfo.ModulePublic) *debug.Module
2249 debugModFromModinfo = func(mi *modinfo.ModulePublic) *debug.Module {
2250 version := mi.Version
2254 dm := &debug.Module{
2258 if mi.Replace != nil {
2259 dm.Replace = debugModFromModinfo(mi.Replace)
2260 } else if mi.Version != "" {
2261 dm.Sum = modfetch.Sum(module.Version{Path: mi.Path, Version: mi.Version})
2266 var main debug.Module
2267 if p.Module != nil {
2268 main = *debugModFromModinfo(p.Module)
2271 visited := make(map[*Package]bool)
2272 mdeps := make(map[module.Version]*debug.Module)
2274 q = append(q, p.Internal.Imports...)
2282 if p1.Module != nil {
2283 m := module.Version{Path: p1.Module.Path, Version: p1.Module.Version}
2284 if p1.Module.Path != main.Path && mdeps[m] == nil {
2285 mdeps[m] = debugModFromModinfo(p1.Module)
2288 q = append(q, p1.Internal.Imports...)
2290 sortedMods := make([]module.Version, 0, len(mdeps))
2291 for mod := range mdeps {
2292 sortedMods = append(sortedMods, mod)
2294 module.Sort(sortedMods)
2295 deps := make([]*debug.Module, len(sortedMods))
2296 for i, mod := range sortedMods {
2297 deps[i] = mdeps[mod]
2300 pkgPath := p.ImportPath
2301 if p.Internal.CmdlineFiles {
2302 pkgPath = "command-line-arguments"
2304 info := &debug.BuildInfo{
2309 appendSetting := func(key, value string) {
2310 value = strings.ReplaceAll(value, "\n", " ") // make value safe
2311 info.Settings = append(info.Settings, debug.BuildSetting{Key: key, Value: value})
2314 // Add command-line flags relevant to the build.
2315 // This is informational, not an exhaustive list.
2316 // Please keep the list sorted.
2318 appendSetting("-asan", "true")
2320 if BuildAsmflags.present {
2321 appendSetting("-asmflags", BuildAsmflags.String())
2323 appendSetting("-compiler", cfg.BuildContext.Compiler)
2324 if gccgoflags := BuildGccgoflags.String(); gccgoflags != "" && cfg.BuildContext.Compiler == "gccgo" {
2325 appendSetting("-gccgoflags", gccgoflags)
2327 if gcflags := BuildGcflags.String(); gcflags != "" && cfg.BuildContext.Compiler == "gc" {
2328 appendSetting("-gcflags", gcflags)
2330 if ldflags := BuildLdflags.String(); ldflags != "" {
2331 appendSetting("-ldflags", ldflags)
2334 appendSetting("-msan", "true")
2337 appendSetting("-race", "true")
2339 if tags := cfg.BuildContext.BuildTags; len(tags) > 0 {
2340 appendSetting("-tags", strings.Join(tags, ","))
2342 if cfg.BuildTrimpath {
2343 appendSetting("-trimpath", "true")
2346 if cfg.BuildContext.CgoEnabled {
2349 appendSetting("CGO_ENABLED", cgo)
2350 if cfg.BuildContext.CgoEnabled {
2351 for _, name := range []string{"CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_CXXFLAGS", "CGO_LDFLAGS"} {
2352 appendSetting(name, cfg.Getenv(name))
2355 appendSetting("GOARCH", cfg.BuildContext.GOARCH)
2356 if cfg.RawGOEXPERIMENT != "" {
2357 appendSetting("GOEXPERIMENT", cfg.RawGOEXPERIMENT)
2359 appendSetting("GOOS", cfg.BuildContext.GOOS)
2360 if key, val := cfg.GetArchEnv(); key != "" && val != "" {
2361 appendSetting(key, val)
2364 // Add VCS status if all conditions are true:
2366 // - -buildvcs is enabled.
2367 // - p is a non-test contained within a main module (there may be multiple
2368 // main modules in a workspace, but local replacements don't count).
2369 // - Both the current directory and p's module's root directory are contained
2370 // in the same local repository.
2371 // - We know the VCS commands needed to get the status.
2372 setVCSError := func(err error) {
2373 setPkgErrorf("error obtaining VCS status: %v\n\tUse -buildvcs=false to disable VCS stamping.", err)
2379 const allowNesting = true
2380 if includeVCS && p.Module != nil && p.Module.Version == "" && !p.Standard && !p.IsTestOnly() {
2381 repoDir, vcsCmd, err = vcs.FromDir(base.Cwd(), "", allowNesting)
2382 if err != nil && !errors.Is(err, os.ErrNotExist) {
2386 if !str.HasFilePathPrefix(p.Module.Dir, repoDir) &&
2387 !str.HasFilePathPrefix(repoDir, p.Module.Dir) {
2388 // The module containing the main package does not overlap with the
2389 // repository containing the working directory. Don't include VCS info.
2390 // If the repo contains the module or vice versa, but they are not
2391 // the same directory, it's likely an error (see below).
2392 repoDir, vcsCmd = "", nil
2395 if repoDir != "" && vcsCmd.Status != nil {
2396 // Check that the current directory, package, and module are in the same
2397 // repository. vcs.FromDir allows nested Git repositories, but nesting
2398 // is not allowed for other VCS tools. The current directory may be outside
2399 // p.Module.Dir when a workspace is used.
2400 pkgRepoDir, _, err := vcs.FromDir(p.Dir, "", allowNesting)
2405 if pkgRepoDir != repoDir {
2406 setVCSError(fmt.Errorf("main package is in repository %q but current directory is in repository %q", pkgRepoDir, repoDir))
2409 modRepoDir, _, err := vcs.FromDir(p.Module.Dir, "", allowNesting)
2414 if modRepoDir != repoDir {
2415 setVCSError(fmt.Errorf("main module is in repository %q but current directory is in repository %q", modRepoDir, repoDir))
2419 type vcsStatusError struct {
2423 cached := vcsStatusCache.Do(repoDir, func() any {
2424 st, err := vcsCmd.Status(vcsCmd, repoDir)
2425 return vcsStatusError{st, err}
2427 if err := cached.Err; err != nil {
2433 appendSetting("vcs", vcsCmd.Cmd)
2434 if st.Revision != "" {
2435 appendSetting("vcs.revision", st.Revision)
2437 if !st.CommitTime.IsZero() {
2438 stamp := st.CommitTime.UTC().Format(time.RFC3339Nano)
2439 appendSetting("vcs.time", stamp)
2441 appendSetting("vcs.modified", strconv.FormatBool(st.Uncommitted))
2444 p.Internal.BuildInfo = info.String()
2447 // SafeArg reports whether arg is a "safe" command-line argument,
2448 // meaning that when it appears in a command-line, it probably
2449 // doesn't have some special meaning other than its own name.
2450 // Obviously args beginning with - are not safe (they look like flags).
2451 // Less obviously, args beginning with @ are not safe (they look like
2452 // GNU binutils flagfile specifiers, sometimes called "response files").
2453 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
2454 // We accept leading . _ and / as likely in file system paths.
2455 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
2456 func SafeArg(name string) bool {
2461 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
2464 // LinkerDeps returns the list of linker-induced dependencies for main package p.
2465 func LinkerDeps(p *Package) []string {
2466 // Everything links runtime.
2467 deps := []string{"runtime"}
2469 // External linking mode forces an import of runtime/cgo.
2470 if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
2471 deps = append(deps, "runtime/cgo")
2473 // On ARM with GOARM=5, it forces an import of math, for soft floating point.
2474 if cfg.Goarch == "arm" {
2475 deps = append(deps, "math")
2477 // Using the race detector forces an import of runtime/race.
2479 deps = append(deps, "runtime/race")
2481 // Using memory sanitizer forces an import of runtime/msan.
2483 deps = append(deps, "runtime/msan")
2485 // Using address sanitizer forces an import of runtime/asan.
2487 deps = append(deps, "runtime/asan")
2493 // externalLinkingForced reports whether external linking is being
2494 // forced even for programs that do not use cgo.
2495 func externalLinkingForced(p *Package) bool {
2496 if !cfg.BuildContext.CgoEnabled {
2500 // Some targets must use external linking even inside GOROOT.
2501 switch cfg.BuildContext.GOOS {
2503 if cfg.BuildContext.GOARCH != "arm64" {
2510 // Currently build modes c-shared, pie (on systems that do not
2511 // support PIE with internal linking mode (currently all
2512 // systems: issue #18968)), plugin, and -linkshared force
2513 // external linking mode, as of course does
2514 // -ldflags=-linkmode=external. External linking mode forces
2515 // an import of runtime/cgo.
2516 // If there are multiple -linkmode options, the last one wins.
2517 pieCgo := cfg.BuildBuildmode == "pie" && !sys.InternalLinkPIESupported(cfg.BuildContext.GOOS, cfg.BuildContext.GOARCH)
2518 linkmodeExternal := false
2520 ldflags := BuildLdflags.For(p)
2521 for i := len(ldflags) - 1; i >= 0; i-- {
2523 if a == "-linkmode=external" ||
2524 a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
2525 linkmodeExternal = true
2527 } else if a == "-linkmode=internal" ||
2528 a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "internal" {
2534 return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
2537 // mkAbs rewrites list, which must be paths relative to p.Dir,
2538 // into a sorted list of absolute paths. It edits list in place but for
2539 // convenience also returns list back to its caller.
2540 func (p *Package) mkAbs(list []string) []string {
2541 for i, f := range list {
2542 list[i] = filepath.Join(p.Dir, f)
2548 // InternalGoFiles returns the list of Go files being built for the package,
2549 // using absolute paths.
2550 func (p *Package) InternalGoFiles() []string {
2551 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
2554 // InternalXGoFiles returns the list of Go files being built for the XTest package,
2555 // using absolute paths.
2556 func (p *Package) InternalXGoFiles() []string {
2557 return p.mkAbs(p.XTestGoFiles)
2560 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
2561 // using absolute paths. "Possibly relevant" means that files are not excluded
2562 // due to build tags, but files with names beginning with . or _ are still excluded.
2563 func (p *Package) InternalAllGoFiles() []string {
2564 return p.mkAbs(str.StringList(p.IgnoredGoFiles, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
2567 // usesSwig reports whether the package needs to run SWIG.
2568 func (p *Package) UsesSwig() bool {
2569 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
2572 // usesCgo reports whether the package needs to run cgo
2573 func (p *Package) UsesCgo() bool {
2574 return len(p.CgoFiles) > 0
2577 // PackageList returns the list of packages in the dag rooted at roots
2578 // as visited in a depth-first post-order traversal.
2579 func PackageList(roots []*Package) []*Package {
2580 seen := map[*Package]bool{}
2582 var walk func(*Package)
2583 walk = func(p *Package) {
2588 for _, p1 := range p.Internal.Imports {
2591 all = append(all, p)
2593 for _, root := range roots {
2599 // TestPackageList returns the list of packages in the dag rooted at roots
2600 // as visited in a depth-first post-order traversal, including the test
2601 // imports of the roots. This ignores errors in test packages.
2602 func TestPackageList(ctx context.Context, opts PackageOpts, roots []*Package) []*Package {
2603 seen := map[*Package]bool{}
2605 var walk func(*Package)
2606 walk = func(p *Package) {
2611 for _, p1 := range p.Internal.Imports {
2614 all = append(all, p)
2616 walkTest := func(root *Package, path string) {
2618 p1 := LoadImport(ctx, opts, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
2619 if p1.Error == nil {
2623 for _, root := range roots {
2625 for _, path := range root.TestImports {
2626 walkTest(root, path)
2628 for _, path := range root.XTestImports {
2629 walkTest(root, path)
2635 // LoadImportWithFlags loads the package with the given import path and
2636 // sets tool flags on that package. This function is useful loading implicit
2637 // dependencies (like sync/atomic for coverage).
2638 // TODO(jayconrod): delete this function and set flags automatically
2639 // in LoadImport instead.
2640 func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
2641 p := LoadImport(context.TODO(), PackageOpts{}, path, srcDir, parent, stk, importPos, mode)
2646 // PackageOpts control the behavior of PackagesAndErrors and other package
2647 // loading functions.
2648 type PackageOpts struct {
2649 // IgnoreImports controls whether we ignore explicit and implicit imports
2650 // when loading packages. Implicit imports are added when supporting Cgo
2651 // or SWIG and when linking main packages.
2654 // ModResolveTests indicates whether calls to the module loader should also
2655 // resolve test dependencies of the requested packages.
2657 // If ModResolveTests is true, then the module loader needs to resolve test
2658 // dependencies at the same time as packages; otherwise, the test dependencies
2659 // of those packages could be missing, and resolving those missing dependencies
2660 // could change the selected versions of modules that provide other packages.
2661 ModResolveTests bool
2663 // MainOnly is true if the caller only wants to load main packages.
2664 // For a literal argument matching a non-main package, a stub may be returned
2665 // with an error. For a non-literal argument (with "..."), non-main packages
2666 // are not be matched, and their dependencies may not be loaded. A warning
2667 // may be printed for non-literal arguments that match no main packages.
2670 // LoadVCS controls whether we also load version-control metadata for main packages.
2674 // PackagesAndErrors returns the packages named by the command line arguments
2675 // 'patterns'. If a named package cannot be loaded, PackagesAndErrors returns
2676 // a *Package with the Error field describing the failure. If errors are found
2677 // loading imported packages, the DepsErrors field is set. The Incomplete field
2678 // may be set as well.
2680 // To obtain a flat list of packages, use PackageList.
2681 // To report errors loading packages, use ReportPackageErrors.
2682 func PackagesAndErrors(ctx context.Context, opts PackageOpts, patterns []string) []*Package {
2683 ctx, span := trace.StartSpan(ctx, "load.PackagesAndErrors")
2686 for _, p := range patterns {
2687 // Listing is only supported with all patterns referring to either:
2688 // - Files that are part of the same directory.
2689 // - Explicit package paths or patterns.
2690 if strings.HasSuffix(p, ".go") {
2691 // We need to test whether the path is an actual Go file and not a
2692 // package path or pattern ending in '.go' (see golang.org/issue/34653).
2693 if fi, err := fsys.Stat(p); err == nil && !fi.IsDir() {
2694 return []*Package{GoFilesPackage(ctx, opts, patterns)}
2699 var matches []*search.Match
2700 if modload.Init(); cfg.ModulesEnabled {
2701 modOpts := modload.PackageOpts{
2702 ResolveMissingImports: true,
2703 LoadTests: opts.ModResolveTests,
2704 SilencePackageErrors: true,
2706 matches, _ = modload.LoadPackages(ctx, modOpts, patterns...)
2708 noModRoots := []string{}
2709 matches = search.ImportPaths(patterns, noModRoots)
2715 seenPkg = make(map[*Package]bool)
2720 pre.preloadMatches(ctx, opts, matches)
2722 for _, m := range matches {
2723 for _, pkg := range m.Pkgs {
2725 panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
2727 p := loadImport(ctx, opts, pre, pkg, base.Cwd(), nil, &stk, nil, 0)
2728 p.Match = append(p.Match, m.Pattern())
2729 p.Internal.CmdlinePkg = true
2731 // Note: do not set = m.IsLiteral unconditionally
2732 // because maybe we'll see p matching both
2733 // a literal and also a non-literal pattern.
2734 p.Internal.CmdlinePkgLiteral = true
2740 pkgs = append(pkgs, p)
2743 if len(m.Errs) > 0 {
2744 // In addition to any packages that were actually resolved from the
2745 // pattern, there was some error in resolving the pattern itself.
2746 // Report it as a synthetic package.
2748 p.ImportPath = m.Pattern()
2749 // Pass an empty ImportStack and nil importPos: the error arose from a pattern, not an import.
2751 var importPos []token.Position
2752 p.setLoadPackageDataError(m.Errs[0], m.Pattern(), &stk, importPos)
2754 p.Match = append(p.Match, m.Pattern())
2755 p.Internal.CmdlinePkg = true
2757 p.Internal.CmdlinePkgLiteral = true
2759 pkgs = append(pkgs, p)
2764 pkgs = mainPackagesOnly(pkgs, matches)
2767 // Now that CmdlinePkg is set correctly,
2768 // compute the effective flags for all loaded packages
2769 // (not just the ones matching the patterns but also
2770 // their dependencies).
2771 setToolFlags(pkgs...)
2776 // CheckPackageErrors prints errors encountered loading pkgs and their
2777 // dependencies, then exits with a non-zero status if any errors were found.
2778 func CheckPackageErrors(pkgs []*Package) {
2779 printed := map[*PackageError]bool{}
2780 for _, pkg := range pkgs {
2781 if pkg.Error != nil {
2782 base.Errorf("%v", pkg.Error)
2783 printed[pkg.Error] = true
2785 for _, err := range pkg.DepsErrors {
2786 // Since these are errors in dependencies,
2787 // the same error might show up multiple times,
2788 // once in each package that depends on it.
2789 // Only print each once.
2792 base.Errorf("%v", err)
2798 // Check for duplicate loads of the same package.
2799 // That should be impossible, but if it does happen then
2800 // we end up trying to build the same package twice,
2801 // usually in parallel overwriting the same files,
2802 // which doesn't work very well.
2803 seen := map[string]bool{}
2804 reported := map[string]bool{}
2805 for _, pkg := range PackageList(pkgs) {
2806 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
2807 reported[pkg.ImportPath] = true
2808 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
2810 seen[pkg.ImportPath] = true
2815 // mainPackagesOnly filters out non-main packages matched only by arguments
2816 // containing "..." and returns the remaining main packages.
2818 // Packages with missing, invalid, or ambiguous names may be treated as
2819 // possibly-main packages.
2821 // mainPackagesOnly sets a non-main package's Error field and returns it if it
2822 // is named by a literal argument.
2824 // mainPackagesOnly prints warnings for non-literal arguments that only match
2825 // non-main packages.
2826 func mainPackagesOnly(pkgs []*Package, matches []*search.Match) []*Package {
2827 treatAsMain := map[string]bool{}
2828 for _, m := range matches {
2830 for _, path := range m.Pkgs {
2831 treatAsMain[path] = true
2836 var mains []*Package
2837 for _, pkg := range pkgs {
2838 if pkg.Name == "main" {
2839 treatAsMain[pkg.ImportPath] = true
2840 mains = append(mains, pkg)
2844 if len(pkg.InvalidGoFiles) > 0 { // TODO(#45999): && pkg.Name == "", but currently go/build sets pkg.Name arbitrarily if it is ambiguous.
2845 // The package has (or may have) conflicting names, and we can't easily
2846 // tell whether one of them is "main". So assume that it could be, and
2847 // report an error for the package.
2848 treatAsMain[pkg.ImportPath] = true
2850 if treatAsMain[pkg.ImportPath] {
2851 if pkg.Error == nil {
2852 pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
2854 mains = append(mains, pkg)
2858 for _, m := range matches {
2859 if m.IsLiteral() || len(m.Pkgs) == 0 {
2863 for _, path := range m.Pkgs {
2864 if treatAsMain[path] {
2870 fmt.Fprintf(os.Stderr, "go: warning: %q matched only non-main packages\n", m.Pattern())
2877 type mainPackageError struct {
2881 func (e *mainPackageError) Error() string {
2882 return fmt.Sprintf("package %s is not a main package", e.importPath)
2885 func (e *mainPackageError) ImportPath() string {
2889 func setToolFlags(pkgs ...*Package) {
2890 for _, p := range PackageList(pkgs) {
2891 p.Internal.Asmflags = BuildAsmflags.For(p)
2892 p.Internal.Gcflags = BuildGcflags.For(p)
2893 p.Internal.Ldflags = BuildLdflags.For(p)
2894 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
2898 // GoFilesPackage creates a package for building a collection of Go files
2899 // (typically named on the command line). The target is named p.a for
2900 // package p or named after the first Go file for package main.
2901 func GoFilesPackage(ctx context.Context, opts PackageOpts, gofiles []string) *Package {
2904 for _, f := range gofiles {
2905 if !strings.HasSuffix(f, ".go") {
2907 pkg.Internal.Local = true
2908 pkg.Internal.CmdlineFiles = true
2910 pkg.Error = &PackageError{
2911 Err: fmt.Errorf("named files must be .go files: %s", pkg.Name),
2918 ctxt := cfg.BuildContext
2919 ctxt.UseAllFiles = true
2921 // Synthesize fake "directory" that only shows the named files,
2922 // to make it look like this is a standard package or
2923 // command directory. So that local imports resolve
2924 // consistently, the files must all be in the same directory.
2925 var dirent []fs.FileInfo
2927 for _, file := range gofiles {
2928 fi, err := fsys.Stat(file)
2930 base.Fatalf("%s", err)
2933 base.Fatalf("%s is a directory, should be a Go file", file)
2935 dir1 := filepath.Dir(file)
2938 } else if dir != dir1 {
2939 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
2941 dirent = append(dirent, fi)
2943 ctxt.ReadDir = func(string) ([]fs.FileInfo, error) { return dirent, nil }
2945 if cfg.ModulesEnabled {
2946 modload.ImportFromFiles(ctx, gofiles)
2953 dir, err = filepath.Abs(dir)
2955 base.Fatalf("%s", err)
2958 bp, err := ctxt.ImportDir(dir, 0)
2960 pkg.Internal.Local = true
2961 pkg.Internal.CmdlineFiles = true
2962 pkg.load(ctx, opts, "command-line-arguments", &stk, nil, bp, err)
2963 if !cfg.ModulesEnabled {
2964 pkg.Internal.LocalPrefix = dirToImportPath(dir)
2966 pkg.ImportPath = "command-line-arguments"
2970 if pkg.Name == "main" {
2971 exe := pkg.DefaultExecName() + cfg.ExeSuffix
2973 if cfg.GOBIN != "" {
2974 pkg.Target = filepath.Join(cfg.GOBIN, exe)
2975 } else if cfg.ModulesEnabled {
2976 pkg.Target = filepath.Join(modload.BinDir(), exe)
2980 if opts.MainOnly && pkg.Name != "main" && pkg.Error == nil {
2981 pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
2988 // PackagesAndErrorsOutsideModule is like PackagesAndErrors but runs in
2989 // module-aware mode and ignores the go.mod file in the current directory or any
2990 // parent directory, if there is one. This is used in the implementation of 'go
2991 // install pkg@version' and other commands that support similar forms.
2993 // modload.ForceUseModules must be true, and modload.RootMode must be NoRoot
2994 // before calling this function.
2996 // PackagesAndErrorsOutsideModule imposes several constraints to avoid
2997 // ambiguity. All arguments must have the same version suffix (not just a suffix
2998 // that resolves to the same version). They must refer to packages in the same
2999 // module, which must not be std or cmd. That module is not considered the main
3000 // module, but its go.mod file (if it has one) must not contain directives that
3001 // would cause it to be interpreted differently if it were the main module
3002 // (replace, exclude).
3003 func PackagesAndErrorsOutsideModule(ctx context.Context, opts PackageOpts, args []string) ([]*Package, error) {
3004 if !modload.ForceUseModules {
3005 panic("modload.ForceUseModules must be true")
3007 if modload.RootMode != modload.NoRoot {
3008 panic("modload.RootMode must be NoRoot")
3011 // Check that the arguments satisfy syntactic constraints.
3013 for _, arg := range args {
3014 if i := strings.Index(arg, "@"); i >= 0 {
3017 return nil, fmt.Errorf("%s: version must not be empty", arg)
3022 patterns := make([]string, len(args))
3023 for i, arg := range args {
3024 if !strings.HasSuffix(arg, "@"+version) {
3025 return nil, fmt.Errorf("%s: all arguments must refer to packages in the same module at the same version (@%s)", arg, version)
3027 p := arg[:len(arg)-len(version)-1]
3029 case build.IsLocalImport(p):
3030 return nil, fmt.Errorf("%s: argument must be a package path, not a relative path", arg)
3031 case filepath.IsAbs(p):
3032 return nil, fmt.Errorf("%s: argument must be a package path, not an absolute path", arg)
3033 case search.IsMetaPackage(p):
3034 return nil, fmt.Errorf("%s: argument must be a package path, not a meta-package", arg)
3035 case path.Clean(p) != p:
3036 return nil, fmt.Errorf("%s: argument must be a clean package path", arg)
3037 case !strings.Contains(p, "...") && search.IsStandardImportPath(p) && goroot.IsStandardPackage(cfg.GOROOT, cfg.BuildContext.Compiler, p):
3038 return nil, fmt.Errorf("%s: argument must not be a package in the standard library", arg)
3044 // Query the module providing the first argument, load its go.mod file, and
3045 // check that it doesn't contain directives that would cause it to be
3046 // interpreted differently if it were the main module.
3048 // If multiple modules match the first argument, accept the longest match
3049 // (first result). It's possible this module won't provide packages named by
3050 // later arguments, and other modules would. Let's not try to be too
3052 allowed := modload.CheckAllowed
3053 if modload.IsRevisionQuery(version) {
3054 // Don't check for retractions if a specific revision is requested.
3057 noneSelected := func(path string) (version string) { return "none" }
3058 qrs, err := modload.QueryPackages(ctx, patterns[0], version, noneSelected, allowed)
3060 return nil, fmt.Errorf("%s: %w", args[0], err)
3062 rootMod := qrs[0].Mod
3063 data, err := modfetch.GoMod(rootMod.Path, rootMod.Version)
3065 return nil, fmt.Errorf("%s: %w", args[0], err)
3067 f, err := modfile.Parse("go.mod", data, nil)
3069 return nil, fmt.Errorf("%s (in %s): %w", args[0], rootMod, err)
3071 directiveFmt := "%s (in %s):\n" +
3072 "\tThe go.mod file for the module providing named packages contains one or\n" +
3073 "\tmore %s directives. It must not contain directives that would cause\n" +
3074 "\tit to be interpreted differently than if it were the main module."
3075 if len(f.Replace) > 0 {
3076 return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "replace")
3078 if len(f.Exclude) > 0 {
3079 return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "exclude")
3082 // Since we are in NoRoot mode, the build list initially contains only
3083 // the dummy command-line-arguments module. Add a requirement on the
3084 // module that provides the packages named on the command line.
3085 if _, err := modload.EditBuildList(ctx, nil, []module.Version{rootMod}); err != nil {
3086 return nil, fmt.Errorf("%s: %w", args[0], err)
3089 // Load packages for all arguments.
3090 pkgs := PackagesAndErrors(ctx, opts, patterns)
3092 // Check that named packages are all provided by the same module.
3093 for _, pkg := range pkgs {
3095 if pkg.Module == nil {
3096 // Packages in std, cmd, and their vendored dependencies
3097 // don't have this field set.
3098 pkgErr = fmt.Errorf("package %s not provided by module %s", pkg.ImportPath, rootMod)
3099 } else if pkg.Module.Path != rootMod.Path || pkg.Module.Version != rootMod.Version {
3100 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)
3102 if pkgErr != nil && pkg.Error == nil {
3103 pkg.Error = &PackageError{Err: pkgErr}
3107 matchers := make([]func(string) bool, len(patterns))
3108 for i, p := range patterns {
3109 if strings.Contains(p, "...") {
3110 matchers[i] = search.MatchPattern(p)