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.
27 "cmd/go/internal/base"
29 "cmd/go/internal/modinfo"
31 "cmd/go/internal/search"
36 // module initialization hook; never nil, no-op if module use is disabled
39 // module hooks; nil if module use is disabled
40 ModBinDir func() string // return effective bin directory
41 ModLookup func(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) // lookup effective meaning of import
42 ModPackageModuleInfo func(path string) *modinfo.ModulePublic // return module info for Package struct
43 ModImportPaths func(args []string) []*search.Match // expand import paths
44 ModPackageBuildInfo func(main string, deps []string) string // return module info to embed in binary
45 ModInfoProg func(info string, isgccgo bool) []byte // wrap module info in .go code for binary
46 ModImportFromFiles func([]string) // update go.mod to add modules for imports in these files
47 ModDirImportPath func(string) string // return effective import path for directory
50 var IgnoreImports bool // control whether we ignore imports in packages
52 // A Package describes a single package found in a directory.
54 PackagePublic // visible in 'go list'
55 Internal PackageInternal // for use inside go command only
58 type PackagePublic struct {
59 // Note: These fields are part of the go command's public API.
60 // See list.go. It is okay to add fields, but not to change or
61 // remove existing ones. Keep in sync with list.go
62 Dir string `json:",omitempty"` // directory containing package sources
63 ImportPath string `json:",omitempty"` // import path of package in dir
64 ImportComment string `json:",omitempty"` // path in import comment on package statement
65 Name string `json:",omitempty"` // package name
66 Doc string `json:",omitempty"` // package documentation string
67 Target string `json:",omitempty"` // installed target for this package (may be executable)
68 Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
69 Root string `json:",omitempty"` // Go root, Go path dir, or module root dir containing this package
70 ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory
71 ForTest string `json:",omitempty"` // package is only for use in named test
72 Export string `json:",omitempty"` // file containing export data (set by go list -export)
73 Module *modinfo.ModulePublic `json:",omitempty"` // info about package's module, if any
74 Match []string `json:",omitempty"` // command-line patterns matching this package
75 Goroot bool `json:",omitempty"` // is this package found in the Go root?
76 Standard bool `json:",omitempty"` // is this package part of the standard Go library?
77 DepOnly bool `json:",omitempty"` // package is only as a dependency, not explicitly listed
78 BinaryOnly bool `json:",omitempty"` // package cannot be recompiled
79 Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies?
81 // Stale and StaleReason remain here *only* for the list command.
82 // They are only initialized in preparation for list execution.
83 // The regular build determines staleness on the fly during action execution.
84 Stale bool `json:",omitempty"` // would 'go install' do anything for this package?
85 StaleReason string `json:",omitempty"` // why is Stale true?
88 // If you add to this list you MUST add to p.AllFiles (below) too.
89 // Otherwise file name security lists will not apply to any new additions.
90 GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
91 CgoFiles []string `json:",omitempty"` // .go source files that import "C"
92 CompiledGoFiles []string `json:",omitempty"` // .go output from running cgo on CgoFiles
93 IgnoredGoFiles []string `json:",omitempty"` // .go source files ignored due to build constraints
94 CFiles []string `json:",omitempty"` // .c source files
95 CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files
96 MFiles []string `json:",omitempty"` // .m source files
97 HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
98 FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
99 SFiles []string `json:",omitempty"` // .s source files
100 SwigFiles []string `json:",omitempty"` // .swig files
101 SwigCXXFiles []string `json:",omitempty"` // .swigcxx files
102 SysoFiles []string `json:",omitempty"` // .syso system object files added to package
105 CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler
106 CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor
107 CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler
108 CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler
109 CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker
110 CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
112 // Dependency information
113 Imports []string `json:",omitempty"` // import paths used by this package
114 ImportMap map[string]string `json:",omitempty"` // map from source import to ImportPath (identity entries omitted)
115 Deps []string `json:",omitempty"` // all (recursively) imported dependencies
118 // Incomplete is above, packed into the other bools
119 Error *PackageError `json:",omitempty"` // error loading this package (not dependencies)
120 DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
123 // If you add to this list you MUST add to p.AllFiles (below) too.
124 // Otherwise file name security lists will not apply to any new additions.
125 TestGoFiles []string `json:",omitempty"` // _test.go files in package
126 TestImports []string `json:",omitempty"` // imports from TestGoFiles
127 XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
128 XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
131 // AllFiles returns the names of all the files considered for the package.
132 // This is used for sanity and security checks, so we include all files,
133 // even IgnoredGoFiles, because some subcommands consider them.
134 // The go/build package filtered others out (like foo_wrongGOARCH.s)
136 func (p *Package) AllFiles() []string {
137 return str.StringList(
140 // no p.CompiledGoFiles, because they are from GoFiles or generated by us
156 // Desc returns the package "description", for use in b.showOutput.
157 func (p *Package) Desc() string {
159 return p.ImportPath + " [" + p.ForTest + ".test]"
164 type PackageInternal struct {
165 // Unexported fields are not part of the public API.
167 Imports []*Package // this package's direct imports
168 CompiledImports []string // additional Imports necessary when using CompiledGoFiles (all from standard library)
169 RawImports []string // this package's original imports as they appear in the text of the program
170 ForceLibrary bool // this package is a library (even if named "main")
171 CmdlineFiles bool // package built from files listed on command line
172 CmdlinePkg bool // package listed on command line
173 CmdlinePkgLiteral bool // package listed as literal on command line (not via wildcard)
174 Local bool // imported via local path (./ or ../)
175 LocalPrefix string // interpret ./ and ../ imports relative to this prefix
176 ExeName string // desired name for temporary executable
177 CoverMode string // preprocess Go source files with the coverage tool in this mode
178 CoverVars map[string]*CoverVar // variables created by coverage analysis
179 OmitDebug bool // tell linker not to write debug information
180 GobinSubdir bool // install target would be subdir of GOBIN
181 BuildInfo string // add this info to package main
182 TestmainGo *[]byte // content for _testmain.go
184 Asmflags []string // -asmflags for this package
185 Gcflags []string // -gcflags for this package
186 Ldflags []string // -ldflags for this package
187 Gccgoflags []string // -gccgoflags for this package
190 // A NoGoError indicates that no Go files for the package were applicable to the
191 // build for that package.
193 // That may be because there were no files whatsoever, or because all files were
194 // excluded, or because all non-excluded files were test sources.
195 type NoGoError struct {
199 func (e *NoGoError) Error() string {
200 if len(e.Package.constraintIgnoredGoFiles()) > 0 {
201 // Go files exist, but they were ignored due to build constraints.
202 return "build constraints exclude all Go files in " + e.Package.Dir
204 if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
205 // Test Go files exist, but we're not interested in them.
206 // The double-negative is unfortunate but we want e.Package.Dir
207 // to appear at the end of error message.
208 return "no non-test Go files in " + e.Package.Dir
210 return "no Go files in " + e.Package.Dir
213 // setLoadPackageDataError presents an error found when loading package data
214 // as a *PackageError. It has special cases for some common errors to improve
215 // messages shown to users and reduce redundancy.
217 // setLoadPackageDataError returns true if it's safe to load information about
218 // imported packages, for example, if there was a parse error loading imports
219 // in one file, but other files are okay.
220 func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportStack, importPos []token.Position) {
221 matchErr, isMatchErr := err.(*search.MatchError)
222 if isMatchErr && matchErr.Match.Pattern() == path {
223 if matchErr.Match.IsLiteral() {
224 // The error has a pattern has a pattern similar to the import path.
225 // It may be slightly different (./foo matching example.com/foo),
226 // but close enough to seem redundant.
227 // Unwrap the error so we don't show the pattern.
232 // Replace (possibly wrapped) *build.NoGoError with *load.NoGoError.
233 // The latter is more specific about the cause.
234 var nogoErr *build.NoGoError
235 if errors.As(err, &nogoErr) {
236 if p.Dir == "" && nogoErr.Dir != "" {
239 err = &NoGoError{Package: p}
242 // Report the error on the importing package if the problem is with the import declaration
243 // for example, if the package doesn't exist or if the import path is malformed.
244 // On the other hand, don't include a position if the problem is with the imported package,
245 // for example there are no Go files (NoGoError), or there's a problem in the imported
246 // package's source files themselves.
248 // TODO(matloob): Perhaps make each of those the errors in the first group
249 // (including modload.ImportMissingError, and the corresponding
250 // "cannot find package %q in any of" GOPATH-mode error
251 // produced in build.(*Context).Import; modload.AmbiguousImportError,
252 // and modload.PackageNotInModuleError; and the malformed module path errors
253 // produced in golang.org/x/mod/module.CheckMod) implement an interface
254 // to make it easier to check for them? That would save us from having to
255 // move the modload errors into this package to avoid a package import cycle,
256 // and from having to export an error type for the errors produced in build.
257 if !isMatchErr && nogoErr != nil {
262 // Take only the first error from a scanner.ErrorList. PackageError only
263 // has room for one position, so we report the first error with a position
264 // instead of all of the errors without a position.
266 if scanErr, ok := err.(scanner.ErrorList); ok && len(scanErr) > 0 {
267 scanPos := scanErr[0].Pos
268 scanPos.Filename = base.ShortPath(scanPos.Filename)
269 pos = scanPos.String()
270 err = errors.New(scanErr[0].Msg)
273 p.Error = &PackageError{
274 ImportStack: stk.Copy(),
279 if path != stk.Top() {
280 p = setErrorPos(p, importPos)
284 // Resolve returns the resolved version of imports,
285 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
286 // The imports in p.TestImports and p.XTestImports are not recursively
287 // loaded during the initial load of p, so they list the imports found in
288 // the source file, but most processing should be over the vendor-resolved
289 // import paths. We do this resolution lazily both to avoid file system work
290 // and because the eventual real load of the test imports (during 'go test')
291 // can produce better error messages if it starts with the original paths.
292 // The initial load of p loads all the non-test imports and rewrites
293 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
294 func (p *Package) Resolve(imports []string) []string {
295 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
296 panic("internal error: p.Resolve(p.Imports) called")
298 seen := make(map[string]bool)
300 for _, path := range imports {
301 path = ResolveImportPath(p, path)
304 all = append(all, path)
311 // CoverVar holds the name of the generated coverage variables targeting the named file.
312 type CoverVar struct {
313 File string // local file name
314 Var string // name of count struct
317 func (p *Package) copyBuild(pp *build.Package) {
318 p.Internal.Build = pp
320 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
321 old := pp.PkgTargetRoot
322 pp.PkgRoot = cfg.BuildPkgdir
323 pp.PkgTargetRoot = cfg.BuildPkgdir
324 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
328 p.ImportPath = pp.ImportPath
329 p.ImportComment = pp.ImportComment
333 p.ConflictDir = pp.ConflictDir
334 p.BinaryOnly = pp.BinaryOnly
338 p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
339 p.GoFiles = pp.GoFiles
340 p.CgoFiles = pp.CgoFiles
341 p.IgnoredGoFiles = pp.IgnoredGoFiles
343 p.CXXFiles = pp.CXXFiles
348 p.SwigFiles = pp.SwigFiles
349 p.SwigCXXFiles = pp.SwigCXXFiles
350 p.SysoFiles = pp.SysoFiles
352 // There's no way for .syso files to be built both with and without
353 // support for memory sanitizer. Assume they are built without,
357 p.CgoCFLAGS = pp.CgoCFLAGS
358 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
359 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
360 p.CgoFFLAGS = pp.CgoFFLAGS
361 p.CgoLDFLAGS = pp.CgoLDFLAGS
362 p.CgoPkgConfig = pp.CgoPkgConfig
363 // We modify p.Imports in place, so make copy now.
364 p.Imports = make([]string, len(pp.Imports))
365 copy(p.Imports, pp.Imports)
366 p.Internal.RawImports = pp.Imports
367 p.TestGoFiles = pp.TestGoFiles
368 p.TestImports = pp.TestImports
369 p.XTestGoFiles = pp.XTestGoFiles
370 p.XTestImports = pp.XTestImports
373 p.Internal.RawImports = nil
379 // A PackageError describes an error loading information about a package.
380 type PackageError struct {
381 ImportStack []string // shortest path from package named on command line to this one
382 Pos string // position of error
383 Err error // the error itself
384 IsImportCycle bool // the error is an import cycle
385 Hard bool // whether the error is soft or hard; soft errors are ignored in some places
386 alwaysPrintStack bool // whether to always print the ImportStack
389 func (p *PackageError) Error() string {
390 if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
391 // Omit import stack. The full path to the file where the error
392 // is the most important thing.
393 return p.Pos + ": " + p.Err.Error()
396 // If the error is an ImportPathError, and the last path on the stack appears
397 // in the error message, omit that path from the stack to avoid repetition.
398 // If an ImportPathError wraps another ImportPathError that matches the
399 // last path on the stack, we don't omit the path. An error like
400 // "package A imports B: error loading C caused by B" would not be clearer
401 // if "imports B" were omitted.
402 if len(p.ImportStack) == 0 {
407 optpos = "\n\t" + p.Pos
409 return "package " + strings.Join(p.ImportStack, "\n\timports ") + optpos + ": " + p.Err.Error()
412 func (p *PackageError) Unwrap() error { return p.Err }
414 // PackageError implements MarshalJSON so that Err is marshaled as a string
415 // and non-essential fields are omitted.
416 func (p *PackageError) MarshalJSON() ([]byte, error) {
421 }{p.ImportStack, p.Pos, p.Err.Error()}
422 return json.Marshal(perr)
425 // ImportPathError is a type of error that prevents a package from being loaded
426 // for a given import path. When such a package is loaded, a *Package is
427 // returned with Err wrapping an ImportPathError: the error is attached to
428 // the imported package, not the importing package.
430 // The string returned by ImportPath must appear in the string returned by
431 // Error. Errors that wrap ImportPathError (such as PackageError) may omit
433 type ImportPathError interface {
438 type importError struct {
440 err error // created with fmt.Errorf
443 var _ ImportPathError = (*importError)(nil)
445 func ImportErrorf(path, format string, args ...interface{}) ImportPathError {
446 err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
447 if errStr := err.Error(); !strings.Contains(errStr, path) {
448 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
453 func (e *importError) Error() string {
457 func (e *importError) Unwrap() error {
458 // Don't return e.err directly, since we're only wrapping an error if %w
459 // was passed to ImportErrorf.
460 return errors.Unwrap(e.err)
463 func (e *importError) ImportPath() string {
467 // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
468 // The import path of a test package is the import path of the corresponding
469 // non-test package with the suffix "_test" added.
470 type ImportStack []string
472 func (s *ImportStack) Push(p string) {
476 func (s *ImportStack) Pop() {
477 *s = (*s)[0 : len(*s)-1]
480 func (s *ImportStack) Copy() []string {
481 return append([]string{}, *s...)
484 func (s *ImportStack) Top() string {
488 return (*s)[len(*s)-1]
491 // shorterThan reports whether sp is shorter than t.
492 // We use this to record the shortest import sequence
493 // that leads to a particular package.
494 func (sp *ImportStack) shorterThan(t []string) bool {
496 if len(s) != len(t) {
497 return len(s) < len(t)
499 // If they are the same length, settle ties using string ordering.
505 return false // they are equal
508 // packageCache is a lookup cache for LoadImport,
509 // so that if we look up a package multiple times
510 // we return the same pointer each time.
511 var packageCache = map[string]*Package{}
513 // ClearPackageCache clears the in-memory package cache and the preload caches.
514 // It is only for use by GOPATH-based "go get".
515 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
516 func ClearPackageCache() {
517 for name := range packageCache {
518 delete(packageCache, name)
520 resolvedImportCache.Clear()
521 packageDataCache.Clear()
524 // ClearPackageCachePartial clears packages with the given import paths from the
525 // in-memory package cache and the preload caches. It is only for use by
526 // GOPATH-based "go get".
527 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
528 func ClearPackageCachePartial(args []string) {
529 shouldDelete := make(map[string]bool)
530 for _, arg := range args {
531 shouldDelete[arg] = true
532 if p := packageCache[arg]; p != nil {
533 delete(packageCache, arg)
536 resolvedImportCache.DeleteIf(func(key interface{}) bool {
537 return shouldDelete[key.(importSpec).path]
539 packageDataCache.DeleteIf(func(key interface{}) bool {
540 return shouldDelete[key.(string)]
544 // ReloadPackageNoFlags is like LoadImport but makes sure
545 // not to use the package cache.
546 // It is only for use by GOPATH-based "go get".
547 // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
548 func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
549 p := packageCache[arg]
551 delete(packageCache, arg)
552 resolvedImportCache.DeleteIf(func(key interface{}) bool {
553 return key.(importSpec).path == p.ImportPath
555 packageDataCache.Delete(p.ImportPath)
557 return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
560 // dirToImportPath returns the pseudo-import path we use for a package
561 // outside the Go path. It begins with _/ and then contains the full path
562 // to the directory. If the package lives in c:\home\gopher\my\pkg then
563 // the pseudo-import path is _/c_/home/gopher/my/pkg.
564 // Using a pseudo-import path like this makes the ./ imports no longer
565 // a special case, so that all the code to deal with ordinary imports works
567 func dirToImportPath(dir string) string {
568 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
571 func makeImportValid(r rune) rune {
572 // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
573 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
574 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
580 // Mode flags for loadImport and download (in get.go).
582 // ResolveImport means that loadImport should do import path expansion.
583 // That is, ResolveImport means that the import path came from
584 // a source file and has not been expanded yet to account for
585 // vendoring or possible module adjustment.
586 // Every import path should be loaded initially with ResolveImport,
587 // and then the expanded version (for example with the /vendor/ in it)
588 // gets recorded as the canonical import path. At that point, future loads
589 // of that package must not pass ResolveImport, because
590 // disallowVendor will reject direct use of paths containing /vendor/.
591 ResolveImport = 1 << iota
593 // ResolveModule is for download (part of "go get") and indicates
594 // that the module adjustment should be done, but not vendor adjustment.
597 // GetTestDeps is for download (part of "go get") and indicates
598 // that test dependencies should be fetched too.
602 // LoadImport scans the directory named by path, which must be an import path,
603 // but possibly a local import path (an absolute file system path or one beginning
604 // with ./ or ../). A local relative path is interpreted relative to srcDir.
605 // It returns a *Package describing the package found in that directory.
606 // LoadImport does not set tool flags and should only be used by
607 // this package, as part of a bigger load operation, and by GOPATH-based "go get".
608 // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
609 func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
610 return loadImport(nil, path, srcDir, parent, stk, importPos, mode)
613 func loadImport(pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
615 panic("LoadImport called with empty package path")
618 var parentPath, parentRoot string
621 parentPath = parent.ImportPath
622 parentRoot = parent.Root
623 parentIsStd = parent.Standard
625 bp, loaded, err := loadPackageData(path, parentPath, srcDir, parentRoot, parentIsStd, mode)
626 if loaded && pre != nil && !IgnoreImports {
627 pre.preloadImports(bp.Imports, bp)
630 if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
631 // Only add path to the error's import stack if it's not already present on the error.
636 PackagePublic: PackagePublic{
638 Error: &PackageError{
639 ImportStack: stk.Copy(),
646 importPath := bp.ImportPath
647 p := packageCache[importPath]
650 p = reusePackage(p, stk)
654 p.Internal.Local = build.IsLocalImport(path)
655 p.ImportPath = importPath
656 packageCache[importPath] = p
659 // loadPackageData may return bp != nil even if an error occurs,
660 // in order to return partial information.
661 p.load(path, stk, importPos, bp, err)
663 if !cfg.ModulesEnabled && path != cleanImport(path) {
664 p.Error = &PackageError{
665 ImportStack: stk.Copy(),
666 Err: ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
669 setErrorPos(p, importPos)
673 // Checked on every import because the rules depend on the code doing the importing.
674 if perr := disallowInternal(srcDir, parent, parentPath, p, stk); perr != p {
675 return setErrorPos(perr, importPos)
677 if mode&ResolveImport != 0 {
678 if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != p {
679 return setErrorPos(perr, importPos)
683 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
685 perr.Error = &PackageError{
686 ImportStack: stk.Copy(),
687 Err: ImportErrorf(path, "import %q is a program, not an importable package", path),
689 return setErrorPos(&perr, importPos)
692 if p.Internal.Local && parent != nil && !parent.Internal.Local {
696 err = ImportErrorf(path, "%s: cannot import current directory", path)
698 err = ImportErrorf(path, "local import %q in non-local package", path)
700 perr.Error = &PackageError{
701 ImportStack: stk.Copy(),
704 return setErrorPos(&perr, importPos)
710 func setErrorPos(p *Package, importPos []token.Position) *Package {
711 if len(importPos) > 0 {
713 pos.Filename = base.ShortPath(pos.Filename)
714 p.Error.Pos = pos.String()
719 // loadPackageData loads information needed to construct a *Package. The result
720 // is cached, and later calls to loadPackageData for the same package will return
723 // loadPackageData returns a non-nil package even if err is non-nil unless
724 // the package path is malformed (for example, the path contains "mod/" or "@").
726 // loadPackageData returns a boolean, loaded, which is true if this is the
727 // first time the package was loaded. Callers may preload imports in this case.
728 func loadPackageData(path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
730 panic("loadPackageData called with empty package path")
733 if strings.HasPrefix(path, "mod/") {
734 // Paths beginning with "mod/" might accidentally
735 // look in the module cache directory tree in $GOPATH/pkg/mod/.
736 // This prefix is owned by the Go core for possible use in the
737 // standard library (since it does not begin with a domain name),
738 // so it's OK to disallow entirely.
739 return nil, false, fmt.Errorf("disallowed import path %q", path)
742 if strings.Contains(path, "@") {
743 if cfg.ModulesEnabled {
744 return nil, false, errors.New("can only use path@version syntax with 'go get'")
746 return nil, false, errors.New("cannot use path@version syntax in GOPATH mode")
750 // Determine canonical package path and directory.
751 // For a local import the identifier is the pseudo-import path
752 // we create from the full directory to the package.
753 // Otherwise it is the usual import path.
754 // For vendored imports, it is the expanded form.
756 // Note that when modules are enabled, local import paths are normally
757 // canonicalized by modload.ImportPaths before now. However, if there's an
758 // error resolving a local path, it will be returned untransformed
759 // so that 'go list -e' reports something useful.
760 importKey := importSpec{
762 parentPath: parentPath,
763 parentDir: parentDir,
764 parentRoot: parentRoot,
765 parentIsStd: parentIsStd,
768 r := resolvedImportCache.Do(importKey, func() interface{} {
770 if build.IsLocalImport(path) {
771 r.dir = filepath.Join(parentDir, path)
772 r.path = dirToImportPath(r.dir)
773 } else if cfg.ModulesEnabled {
774 r.dir, r.path, r.err = ModLookup(parentPath, parentIsStd, path)
775 } else if mode&ResolveImport != 0 {
776 // We do our own path resolution, because we want to
777 // find out the key to use in packageCache without the
778 // overhead of repeated calls to buildContext.Import.
779 // The code is also needed in a few other places anyway.
780 r.path = resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
781 } else if mode&ResolveModule != 0 {
782 r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
789 // Invariant: r.path is set to the resolved import path. If the path cannot
790 // be resolved, r.path is set to path, the source import path.
791 // r.path is never empty.
793 // Load the package from its directory. If we already found the package's
794 // directory when resolving its import path, use that.
795 data := packageDataCache.Do(r.path, func() interface{} {
799 var buildMode build.ImportMode
800 if !cfg.ModulesEnabled {
801 buildMode = build.ImportComment
803 data.p, data.err = cfg.BuildContext.ImportDir(r.dir, buildMode)
804 if data.p.Root == "" && cfg.ModulesEnabled {
805 if info := ModPackageModuleInfo(path); info != nil {
806 data.p.Root = info.Dir
809 } else if r.err != nil {
810 data.p = new(build.Package)
812 } else if cfg.ModulesEnabled && path != "unsafe" {
813 data.p = new(build.Package)
814 data.err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", r.path)
816 buildMode := build.ImportComment
817 if mode&ResolveImport == 0 || r.path != path {
818 // Not vendoring, or we already found the vendored path.
819 buildMode |= build.IgnoreVendor
821 data.p, data.err = cfg.BuildContext.Import(r.path, parentDir, buildMode)
823 data.p.ImportPath = r.path
825 // Set data.p.BinDir in cases where go/build.Context.Import
826 // may give us a path we don't want.
829 data.p.BinDir = cfg.GOBIN
830 } else if cfg.ModulesEnabled {
831 data.p.BinDir = ModBinDir()
835 if !cfg.ModulesEnabled && data.err == nil &&
836 data.p.ImportComment != "" && data.p.ImportComment != path &&
837 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
838 data.err = fmt.Errorf("code in directory %s expects import %q", data.p.Dir, data.p.ImportComment)
843 return data.p, loaded, data.err
846 // importSpec describes an import declaration in source code. It is used as a
847 // cache key for resolvedImportCache.
848 type importSpec struct {
850 parentPath, parentDir, parentRoot string
855 // resolvedImport holds a canonical identifier for a package. It may also contain
856 // a path to the package's directory and an error if one occurred. resolvedImport
857 // is the value type in resolvedImportCache.
858 type resolvedImport struct {
863 // packageData holds information loaded from a package. It is the value type
864 // in packageDataCache.
865 type packageData struct {
870 // resolvedImportCache maps import strings (importSpec) to canonical package names
872 var resolvedImportCache par.Cache
874 // packageDataCache maps canonical package names (string) to package metadata
876 var packageDataCache par.Cache
878 // preloadWorkerCount is the number of concurrent goroutines that can load
879 // packages. Experimentally, there are diminishing returns with more than
880 // 4 workers. This was measured on the following machines.
882 // * MacBookPro with a 4-core Intel Core i7 CPU
883 // * Linux workstation with 6-core Intel Xeon CPU
884 // * Linux workstation with 24-core Intel Xeon CPU
886 // It is very likely (though not confirmed) that this workload is limited
887 // by memory bandwidth. We don't have a good way to determine the number of
888 // workers that would saturate the bus though, so runtime.GOMAXPROCS
889 // seems like a reasonable default.
890 var preloadWorkerCount = runtime.GOMAXPROCS(0)
892 // preload holds state for managing concurrent preloading of package data.
894 // A preload should be created with newPreload before loading a large
895 // package graph. flush must be called when package loading is complete
896 // to ensure preload goroutines are no longer active. This is necessary
897 // because of global mutable state that cannot safely be read and written
898 // concurrently. In particular, packageDataCache may be cleared by "go get"
899 // in GOPATH mode, and modload.loaded (accessed via ModLookup) may be
900 // modified by modload.ImportPaths (ModImportPaths).
901 type preload struct {
906 // newPreload creates a new preloader. flush must be called later to avoid
907 // accessing global state while it is being modified.
908 func newPreload() *preload {
910 cancel: make(chan struct{}),
911 sema: make(chan struct{}, preloadWorkerCount),
916 // preloadMatches loads data for package paths matched by patterns.
917 // When preloadMatches returns, some packages may not be loaded yet, but
918 // loadPackageData and loadImport are always safe to call.
919 func (pre *preload) preloadMatches(matches []*search.Match) {
920 for _, m := range matches {
921 for _, pkg := range m.Pkgs {
925 case pre.sema <- struct{}{}:
926 go func(pkg string) {
927 mode := 0 // don't use vendoring or module import resolution
928 bp, loaded, err := loadPackageData(pkg, "", base.Cwd, "", false, mode)
930 if bp != nil && loaded && err == nil && !IgnoreImports {
931 pre.preloadImports(bp.Imports, bp)
939 // preloadImports queues a list of imports for preloading.
940 // When preloadImports returns, some packages may not be loaded yet,
941 // but loadPackageData and loadImport are always safe to call.
942 func (pre *preload) preloadImports(imports []string, parent *build.Package) {
943 parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
944 for _, path := range imports {
945 if path == "C" || path == "unsafe" {
951 case pre.sema <- struct{}{}:
952 go func(path string) {
953 bp, loaded, err := loadPackageData(path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
955 if bp != nil && loaded && err == nil && !IgnoreImports {
956 pre.preloadImports(bp.Imports, bp)
963 // flush stops pending preload operations. flush blocks until preload calls to
964 // loadPackageData have completed. The preloader will not make any new calls
965 // to loadPackageData.
966 func (pre *preload) flush() {
968 for i := 0; i < preloadWorkerCount; i++ {
969 pre.sema <- struct{}{}
973 func cleanImport(path string) string {
975 path = pathpkg.Clean(path)
976 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
982 var isDirCache par.Cache
984 func isDir(path string) bool {
985 return isDirCache.Do(path, func() interface{} {
986 fi, err := os.Stat(path)
987 return err == nil && fi.IsDir()
991 // ResolveImportPath returns the true meaning of path when it appears in parent.
992 // There are two different resolutions applied.
993 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
994 // If vendor expansion doesn't trigger, then the path is also subject to
995 // Go 1.11 module legacy conversion (golang.org/issue/25069).
996 func ResolveImportPath(parent *Package, path string) (found string) {
997 var parentPath, parentDir, parentRoot string
1000 parentPath = parent.ImportPath
1001 parentDir = parent.Dir
1002 parentRoot = parent.Root
1003 parentIsStd = parent.Standard
1005 return resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
1008 func resolveImportPath(path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
1009 if cfg.ModulesEnabled {
1010 if _, p, e := ModLookup(parentPath, parentIsStd, path); e == nil {
1015 found = vendoredImportPath(path, parentPath, parentDir, parentRoot)
1019 return moduleImportPath(path, parentPath, parentDir, parentRoot)
1022 // dirAndRoot returns the source directory and workspace root
1023 // for the package p, guaranteeing that root is a path prefix of dir.
1024 func dirAndRoot(path string, dir, root string) (string, string) {
1025 origDir, origRoot := dir, root
1026 dir = filepath.Clean(dir)
1027 root = filepath.Join(root, "src")
1028 if !str.HasFilePathPrefix(dir, root) || path != "command-line-arguments" && filepath.Join(root, path) != dir {
1029 // Look for symlinks before reporting error.
1030 dir = expandPath(dir)
1031 root = expandPath(root)
1034 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 {
1035 base.Fatalf("unexpected directory layout:\n"+
1036 " import path: %s\n"+
1039 " expand root: %s\n"+
1040 " expand dir: %s\n"+
1043 filepath.Join(origRoot, "src"),
1044 filepath.Clean(origDir),
1047 string(filepath.Separator))
1053 // vendoredImportPath returns the vendor-expansion of path when it appears in parent.
1054 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
1055 // x/vendor/path, vendor/path, or else stay path if none of those exist.
1056 // vendoredImportPath returns the expanded path or, if no expansion is found, the original.
1057 func vendoredImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1058 if parentRoot == "" {
1062 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1064 vpath := "vendor/" + path
1065 for i := len(dir); i >= len(root); i-- {
1066 if i < len(dir) && dir[i] != filepath.Separator {
1069 // Note: checking for the vendor directory before checking
1070 // for the vendor/path directory helps us hit the
1071 // isDir cache more often. It also helps us prepare a more useful
1072 // list of places we looked, to report when an import is not found.
1073 if !isDir(filepath.Join(dir[:i], "vendor")) {
1076 targ := filepath.Join(dir[:i], vpath)
1077 if isDir(targ) && hasGoFiles(targ) {
1078 importPath := parentPath
1079 if importPath == "command-line-arguments" {
1080 // If parent.ImportPath is 'command-line-arguments'.
1081 // set to relative directory to root (also chopped root directory)
1082 importPath = dir[len(root)+1:]
1084 // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
1085 // We know the import path for parent's dir.
1086 // We chopped off some number of path elements and
1087 // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
1088 // Now we want to know the import path for that directory.
1089 // Construct it by chopping the same number of path elements
1090 // (actually the same number of bytes) from parent's import path
1091 // and then append /vendor/path.
1092 chopped := len(dir) - i
1093 if chopped == len(importPath)+1 {
1094 // We walked up from c:\gopath\src\foo\bar
1095 // and found c:\gopath\src\vendor\path.
1096 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
1097 // Use "vendor/path" without any prefix.
1100 return importPath[:len(importPath)-chopped] + "/" + vpath
1107 modulePrefix = []byte("\nmodule ")
1108 goModPathCache par.Cache
1111 // goModPath returns the module path in the go.mod in dir, if any.
1112 func goModPath(dir string) (path string) {
1113 return goModPathCache.Do(dir, func() interface{} {
1114 data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
1119 if bytes.HasPrefix(data, modulePrefix[1:]) {
1122 i = bytes.Index(data, modulePrefix)
1130 // Cut line at \n, drop trailing \r if present.
1131 if j := bytes.IndexByte(line, '\n'); j >= 0 {
1134 if line[len(line)-1] == '\r' {
1135 line = line[:len(line)-1]
1137 line = line[len("module "):]
1139 // If quoted, unquote.
1140 path = strings.TrimSpace(string(line))
1141 if path != "" && path[0] == '"' {
1142 s, err := strconv.Unquote(path)
1152 // findVersionElement returns the slice indices of the final version element /vN in path.
1153 // If there is no such element, it returns -1, -1.
1154 func findVersionElement(path string) (i, j int) {
1156 for i = len(path) - 1; i >= 0; i-- {
1158 if isVersionElement(path[i+1 : j]) {
1167 // isVersionElement reports whether s is a well-formed path version element:
1168 // v2, v3, v10, etc, but not v0, v05, v1.
1169 func isVersionElement(s string) bool {
1170 if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
1173 for i := 1; i < len(s); i++ {
1174 if s[i] < '0' || '9' < s[i] {
1181 // moduleImportPath translates import paths found in go modules
1182 // back down to paths that can be resolved in ordinary builds.
1184 // Define “new” code as code with a go.mod file in the same directory
1185 // or a parent directory. If an import in new code says x/y/v2/z but
1186 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
1187 // then go build will read the import as x/y/z instead.
1188 // See golang.org/issue/25069.
1189 func moduleImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1190 if parentRoot == "" {
1194 // If there are no vN elements in path, leave it alone.
1195 // (The code below would do the same, but only after
1196 // some other file system accesses that we can avoid
1197 // here by returning early.)
1198 if i, _ := findVersionElement(path); i < 0 {
1202 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1204 // Consider dir and parents, up to and including root.
1205 for i := len(dir); i >= len(root); i-- {
1206 if i < len(dir) && dir[i] != filepath.Separator {
1209 if goModPath(dir[:i]) != "" {
1213 // This code is not in a tree with a go.mod,
1214 // so apply no changes to the path.
1218 // This import is in a tree with a go.mod.
1219 // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
1220 // if GOPATH/src/x/y/go.mod says module "x/y/v2",
1222 // If x/y/v2/z exists, use it unmodified.
1223 if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
1227 // Otherwise look for a go.mod supplying a version element.
1228 // Some version-like elements may appear in paths but not
1229 // be module versions; we skip over those to look for module
1230 // versions. For example the module m/v2 might have a
1231 // package m/v2/api/v1/foo.
1234 i, j := findVersionElement(path[:limit])
1238 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
1239 if mpath := goModPath(bp.Dir); mpath != "" {
1240 // Found a valid go.mod file, so we're stopping the search.
1241 // If the path is m/v2/p and we found m/go.mod that says
1242 // "module m/v2", then we return "m/p".
1243 if mpath == path[:j] {
1244 return path[:i] + path[j:]
1246 // Otherwise just return the original path.
1247 // We didn't find anything worth rewriting,
1248 // and the go.mod indicates that we should
1249 // not consider parent directories.
1258 // hasGoFiles reports whether dir contains any files with names ending in .go.
1259 // For a vendor check we must exclude directories that contain no .go files.
1260 // Otherwise it is not possible to vendor just a/b/c and still import the
1261 // non-vendored a/b. See golang.org/issue/13832.
1262 func hasGoFiles(dir string) bool {
1263 fis, _ := ioutil.ReadDir(dir)
1264 for _, fi := range fis {
1265 if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
1272 // reusePackage reuses package p to satisfy the import at the top
1273 // of the import stack stk. If this use causes an import loop,
1274 // reusePackage updates p's error information to record the loop.
1275 func reusePackage(p *Package, stk *ImportStack) *Package {
1276 // We use p.Internal.Imports==nil to detect a package that
1277 // is in the midst of its own loadPackage call
1278 // (all the recursion below happens before p.Internal.Imports gets set).
1279 if p.Internal.Imports == nil {
1281 p.Error = &PackageError{
1282 ImportStack: stk.Copy(),
1283 Err: errors.New("import cycle not allowed"),
1284 IsImportCycle: true,
1289 // Don't rewrite the import stack in the error if we have an import cycle.
1290 // If we do, we'll lose the path that describes the cycle.
1291 if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
1292 p.Error.ImportStack = stk.Copy()
1297 // disallowInternal checks that srcDir (containing package importerPath, if non-empty)
1298 // is allowed to import p.
1299 // If the import is allowed, disallowInternal returns the original package p.
1300 // If not, it returns a new package containing just an appropriate error.
1301 func disallowInternal(srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package {
1302 // golang.org/s/go14internal:
1303 // An import of a path containing the element “internal”
1304 // is disallowed if the importing code is outside the tree
1305 // rooted at the parent of the “internal” directory.
1307 // There was an error loading the package; stop here.
1312 // The generated 'testmain' package is allowed to access testing/internal/...,
1313 // as if it were generated into the testing directory tree
1314 // (it's actually in a temporary directory outside any Go tree).
1315 // This cleans up a former kludge in passing functionality to the testing package.
1316 if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
1320 // We can't check standard packages with gccgo.
1321 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
1325 // The sort package depends on internal/reflectlite, but during bootstrap
1326 // the path rewriting causes the normal internal checks to fail.
1327 // Instead, just ignore the internal rules during bootstrap.
1328 if p.Standard && strings.HasPrefix(importerPath, "bootstrap/") {
1332 // importerPath is empty: we started
1333 // with a name given on the command line, not an
1334 // import. Anything listed on the command line is fine.
1335 if importerPath == "" {
1339 // Check for "internal" element: three cases depending on begin of string and/or end of string.
1340 i, ok := findInternal(p.ImportPath)
1345 // Internal is present.
1346 // Map import path back to directory corresponding to parent of internal.
1348 i-- // rewind over slash in ".../internal"
1351 if p.Module == nil {
1352 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
1354 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1358 // Look for symlinks before reporting error.
1359 srcDir = expandPath(srcDir)
1360 parent = expandPath(parent)
1361 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1365 // p is in a module, so make it available based on the importer's import path instead
1366 // of the file path (https://golang.org/issue/23970).
1367 if importer.Internal.CmdlineFiles {
1368 // The importer is a list of command-line files.
1369 // Pretend that the import path is the import path of the
1370 // directory containing them.
1371 // If the directory is outside the main module, this will resolve to ".",
1372 // which is not a prefix of any valid module.
1373 importerPath = ModDirImportPath(importer.Dir)
1375 parentOfInternal := p.ImportPath[:i]
1376 if str.HasPathPrefix(importerPath, parentOfInternal) {
1381 // Internal is present, and srcDir is outside parent's tree. Not allowed.
1383 perr.Error = &PackageError{
1384 alwaysPrintStack: true,
1385 ImportStack: stk.Copy(),
1386 Err: ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
1388 perr.Incomplete = true
1392 // findInternal looks for the final "internal" path element in the given import path.
1393 // If there isn't one, findInternal returns ok=false.
1394 // Otherwise, findInternal returns ok=true and the index of the "internal".
1395 func findInternal(path string) (index int, ok bool) {
1396 // Three cases, depending on internal at start/end of string or not.
1397 // The order matters: we must return the index of the final element,
1398 // because the final one produces the most restrictive requirement
1401 case strings.HasSuffix(path, "/internal"):
1402 return len(path) - len("internal"), true
1403 case strings.Contains(path, "/internal/"):
1404 return strings.LastIndex(path, "/internal/") + 1, true
1405 case path == "internal", strings.HasPrefix(path, "internal/"):
1411 // disallowVendor checks that srcDir is allowed to import p as path.
1412 // If the import is allowed, disallowVendor returns the original package p.
1413 // If not, it returns a new package containing just an appropriate error.
1414 func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *Package {
1415 // If the importerPath is empty, we started
1416 // with a name given on the command line, not an
1417 // import. Anything listed on the command line is fine.
1418 if importerPath == "" {
1422 if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != p {
1426 // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
1427 if i, ok := FindVendor(path); ok {
1429 perr.Error = &PackageError{
1430 ImportStack: stk.Copy(),
1431 Err: ImportErrorf(path, "%s must be imported as %s", path, path[i+len("vendor/"):]),
1433 perr.Incomplete = true
1440 // disallowVendorVisibility checks that srcDir is allowed to import p.
1441 // The rules are the same as for /internal/ except that a path ending in /vendor
1442 // is not subject to the rules, only subdirectories of vendor.
1443 // This allows people to have packages and commands named vendor,
1444 // for maximal compatibility with existing source trees.
1445 func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *Package {
1446 // The stack does not include p.ImportPath.
1447 // If there's nothing on the stack, we started
1448 // with a name given on the command line, not an
1449 // import. Anything listed on the command line is fine.
1450 if importerPath == "" {
1454 // Check for "vendor" element.
1455 i, ok := FindVendor(p.ImportPath)
1460 // Vendor is present.
1461 // Map import path back to directory corresponding to parent of vendor.
1463 i-- // rewind over slash in ".../vendor"
1465 truncateTo := i + len(p.Dir) - len(p.ImportPath)
1466 if truncateTo < 0 || len(p.Dir) < truncateTo {
1469 parent := p.Dir[:truncateTo]
1470 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1474 // Look for symlinks before reporting error.
1475 srcDir = expandPath(srcDir)
1476 parent = expandPath(parent)
1477 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1481 // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1483 perr.Error = &PackageError{
1484 ImportStack: stk.Copy(),
1485 Err: errors.New("use of vendored package not allowed"),
1487 perr.Incomplete = true
1491 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1492 // If there isn't one, FindVendor returns ok=false.
1493 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1495 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1496 // not the vendored copy of an import "" (the empty import path).
1497 // This will allow people to have packages or commands named vendor.
1498 // This may help reduce breakage, or it may just be confusing. We'll see.
1499 func FindVendor(path string) (index int, ok bool) {
1500 // Two cases, depending on internal at start of string or not.
1501 // The order matters: we must return the index of the final element,
1502 // because the final one is where the effective import path starts.
1504 case strings.Contains(path, "/vendor/"):
1505 return strings.LastIndex(path, "/vendor/") + 1, true
1506 case strings.HasPrefix(path, "vendor/"):
1515 ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1516 ToBin // to bin dir inside package root (default for non-cmd/*)
1517 StalePath // an old import path; fail to build
1520 // InstallTargetDir reports the target directory for installing the command p.
1521 func InstallTargetDir(p *Package) TargetDir {
1522 if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1525 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1526 switch p.ImportPath {
1527 case "cmd/go", "cmd/gofmt":
1535 var cgoExclude = map[string]bool{
1536 "runtime/cgo": true,
1539 var cgoSyscallExclude = map[string]bool{
1540 "runtime/cgo": true,
1541 "runtime/race": true,
1542 "runtime/msan": true,
1545 var foldPath = make(map[string]string)
1547 // exeFromImportPath returns an executable name
1548 // for a package using the import path.
1550 // The executable name is the last element of the import path.
1551 // In module-aware mode, an additional rule is used on import paths
1552 // consisting of two or more path elements. If the last element is
1553 // a vN path element specifying the major version, then the
1554 // second last element of the import path is used instead.
1555 func (p *Package) exeFromImportPath() string {
1556 _, elem := pathpkg.Split(p.ImportPath)
1557 if cfg.ModulesEnabled {
1558 // If this is example.com/mycmd/v2, it's more useful to
1559 // install it as mycmd than as v2. See golang.org/issue/24667.
1560 if elem != p.ImportPath && isVersionElement(elem) {
1561 _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
1567 // exeFromFiles returns an executable name for a package
1568 // using the first element in GoFiles or CgoFiles collections without the prefix.
1570 // Returns empty string in case of empty collection.
1571 func (p *Package) exeFromFiles() string {
1573 if len(p.GoFiles) > 0 {
1575 } else if len(p.CgoFiles) > 0 {
1580 _, elem := filepath.Split(src)
1581 return elem[:len(elem)-len(".go")]
1584 // DefaultExecName returns the default executable name for a package
1585 func (p *Package) DefaultExecName() string {
1586 if p.Internal.CmdlineFiles {
1587 return p.exeFromFiles()
1589 return p.exeFromImportPath()
1592 // load populates p using information from bp, err, which should
1593 // be the result of calling build.Context.Import.
1594 // stk contains the import stack, not including path itself.
1595 func (p *Package) load(path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
1598 // The localPrefix is the path we interpret ./ imports relative to.
1599 // Synthesized main packages sometimes override this.
1600 if p.Internal.Local {
1601 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1604 // setError sets p.Error if it hasn't already been set. We may proceed
1605 // after encountering some errors so that 'go list -e' has more complete
1606 // output. If there's more than one error, we should report the first.
1607 setError := func(err error) {
1609 p.Error = &PackageError{
1610 ImportStack: stk.Copy(),
1614 // Add the importer's position information if the import position exists, and
1615 // the current package being examined is the importer.
1616 // If we have not yet accepted package p onto the import stack,
1617 // then the cause of the error is not within p itself: the error
1618 // must be either in an explicit command-line argument,
1619 // or on the importer side (indicated by a non-empty importPos).
1620 if path != stk.Top() && len(importPos) > 0 {
1621 p = setErrorPos(p, importPos)
1628 p.setLoadPackageDataError(err, path, stk, importPos)
1631 useBindir := p.Name == "main"
1633 switch cfg.BuildBuildmode {
1634 case "c-archive", "c-shared", "plugin":
1640 // Report an error when the old code.google.com/p/go.tools paths are used.
1641 if InstallTargetDir(p) == StalePath {
1642 // TODO(matloob): remove this branch, and StalePath itself. code.google.com/p/go is so
1643 // old, even this code checking for it is stale now!
1644 newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1645 e := ImportErrorf(p.ImportPath, "the %v command has moved; use %v instead.", p.ImportPath, newPath)
1649 elem := p.DefaultExecName()
1650 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1651 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1652 // Install cross-compiled binaries to subdirectories of bin.
1655 if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
1656 p.Internal.Build.BinDir = ModBinDir()
1658 if p.Internal.Build.BinDir != "" {
1659 // Install to GOBIN or bin of GOPATH entry.
1660 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1661 if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1662 // Do not create $GOBIN/goos_goarch/elem.
1664 p.Internal.GobinSubdir = true
1667 if InstallTargetDir(p) == ToTool {
1668 // This is for 'go tool'.
1669 // Override all the usual logic and force it into the tool directory.
1670 if cfg.BuildToolchainName == "gccgo" {
1671 p.Target = filepath.Join(base.ToolDir, elem)
1673 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1676 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1679 } else if p.Internal.Local {
1680 // Local import turned into absolute path.
1681 // No permanent install target.
1684 p.Target = p.Internal.Build.PkgObj
1685 if cfg.BuildLinkshared && p.Target != "" {
1686 // TODO(bcmills): The reliance on p.Target implies that -linkshared does
1687 // not work for any package that lacks a Target — such as a non-main
1688 // package in module mode. We should probably fix that.
1689 shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1690 shlib, err := ioutil.ReadFile(shlibnamefile)
1691 if err != nil && !os.IsNotExist(err) {
1692 base.Fatalf("reading shlibname: %v", err)
1695 libname := strings.TrimSpace(string(shlib))
1696 if cfg.BuildContext.Compiler == "gccgo" {
1697 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1699 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1705 // Build augmented import list to add implicit dependencies.
1706 // Be careful not to add imports twice, just to avoid confusion.
1707 importPaths := p.Imports
1708 addImport := func(path string, forCompiler bool) {
1709 for _, p := range importPaths {
1714 importPaths = append(importPaths, path)
1716 p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
1720 // Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall",
1721 // except for certain packages, to avoid circular dependencies.
1723 addImport("unsafe", true)
1725 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1726 addImport("runtime/cgo", true)
1728 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1729 addImport("syscall", true)
1732 // SWIG adds imports of some standard packages.
1734 addImport("unsafe", true)
1735 if cfg.BuildContext.Compiler != "gccgo" {
1736 addImport("runtime/cgo", true)
1738 addImport("syscall", true)
1739 addImport("sync", true)
1741 // TODO: The .swig and .swigcxx files can use
1742 // %go_import directives to import other packages.
1745 // The linker loads implicit dependencies.
1746 if p.Name == "main" && !p.Internal.ForceLibrary {
1747 for _, dep := range LinkerDeps(p) {
1748 addImport(dep, false)
1752 // Check for case-insensitive collisions of import paths.
1753 fold := str.ToFold(p.ImportPath)
1754 if other := foldPath[fold]; other == "" {
1755 foldPath[fold] = p.ImportPath
1756 } else if other != p.ImportPath {
1757 setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
1761 if !SafeArg(p.ImportPath) {
1762 setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
1769 // Check for case-insensitive collision of input files.
1770 // To avoid problems on case-insensitive files, we reject any package
1771 // where two different input files have equal names under a case-insensitive
1773 inputs := p.AllFiles()
1774 f1, f2 := str.FoldDup(inputs)
1776 setError(fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2))
1780 // If first letter of input file is ASCII, it must be alphanumeric.
1781 // This avoids files turning into flags when invoking commands,
1782 // and other problems we haven't thought of yet.
1783 // Also, _cgo_ files must be generated by us, not supplied.
1784 // They are allowed to have //go:cgo_ldflag directives.
1785 // The directory scan ignores files beginning with _,
1786 // so we shouldn't see any _cgo_ files anyway, but just be safe.
1787 for _, file := range inputs {
1788 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1789 setError(fmt.Errorf("invalid input file name %q", file))
1793 if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1794 setError(fmt.Errorf("invalid input directory name %q", name))
1798 // Build list of imported packages and full dependency list.
1799 imports := make([]*Package, 0, len(p.Imports))
1800 for i, path := range importPaths {
1804 p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1806 path = p1.ImportPath
1807 importPaths[i] = path
1808 if i < len(p.Imports) {
1812 imports = append(imports, p1)
1817 p.Internal.Imports = imports
1820 // unsafe is a fake package.
1821 if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1825 // If cgo is not enabled, ignore cgo supporting sources
1826 // just as we ignore go files containing import "C".
1827 if !cfg.BuildContext.CgoEnabled {
1832 p.SwigCXXFiles = nil
1833 // Note that SFiles are okay (they go to the Go assembler)
1834 // and HFiles are okay (they might be used by the SFiles).
1835 // Also Sysofiles are okay (they might not contain object
1836 // code; see issue #16050).
1839 // The gc toolchain only permits C source files with cgo or SWIG.
1840 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1841 setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1845 // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1846 // regardless of toolchain.
1847 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1848 setError(fmt.Errorf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1851 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1852 setError(fmt.Errorf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1855 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1856 setError(fmt.Errorf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1860 if cfg.ModulesEnabled && p.Error == nil {
1861 mainPath := p.ImportPath
1862 if p.Internal.CmdlineFiles {
1863 mainPath = "command-line-arguments"
1865 p.Module = ModPackageModuleInfo(mainPath)
1866 if p.Name == "main" && len(p.DepsErrors) == 0 {
1867 p.Internal.BuildInfo = ModPackageBuildInfo(mainPath, p.Deps)
1872 // collectDeps populates p.Deps and p.DepsErrors by iterating over
1873 // p.Internal.Imports.
1875 // TODO(jayconrod): collectDeps iterates over transitive imports for every
1876 // package. We should only need to visit direct imports.
1877 func (p *Package) collectDeps() {
1878 deps := make(map[string]*Package)
1880 q = append(q, p.Internal.Imports...)
1881 for i := 0; i < len(q); i++ {
1883 path := p1.ImportPath
1884 // The same import path could produce an error or not,
1885 // depending on what tries to import it.
1886 // Prefer to record entries with errors, so we can report them.
1888 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
1890 for _, p2 := range p1.Internal.Imports {
1891 if deps[p2.ImportPath] != p2 {
1898 p.Deps = make([]string, 0, len(deps))
1899 for dep := range deps {
1900 p.Deps = append(p.Deps, dep)
1902 sort.Strings(p.Deps)
1903 for _, dep := range p.Deps {
1906 panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
1908 if p1.Error != nil {
1909 p.DepsErrors = append(p.DepsErrors, p1.Error)
1914 // SafeArg reports whether arg is a "safe" command-line argument,
1915 // meaning that when it appears in a command-line, it probably
1916 // doesn't have some special meaning other than its own name.
1917 // Obviously args beginning with - are not safe (they look like flags).
1918 // Less obviously, args beginning with @ are not safe (they look like
1919 // GNU binutils flagfile specifiers, sometimes called "response files").
1920 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
1921 // We accept leading . _ and / as likely in file system paths.
1922 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
1923 func SafeArg(name string) bool {
1928 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1931 // LinkerDeps returns the list of linker-induced dependencies for main package p.
1932 func LinkerDeps(p *Package) []string {
1933 // Everything links runtime.
1934 deps := []string{"runtime"}
1936 // External linking mode forces an import of runtime/cgo.
1937 if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
1938 deps = append(deps, "runtime/cgo")
1940 // On ARM with GOARM=5, it forces an import of math, for soft floating point.
1941 if cfg.Goarch == "arm" {
1942 deps = append(deps, "math")
1944 // Using the race detector forces an import of runtime/race.
1946 deps = append(deps, "runtime/race")
1948 // Using memory sanitizer forces an import of runtime/msan.
1950 deps = append(deps, "runtime/msan")
1956 // externalLinkingForced reports whether external linking is being
1957 // forced even for programs that do not use cgo.
1958 func externalLinkingForced(p *Package) bool {
1959 // Some targets must use external linking even inside GOROOT.
1960 switch cfg.BuildContext.GOOS {
1962 if cfg.BuildContext.GOARCH != "arm64" {
1966 if cfg.BuildContext.GOARCH == "arm64" {
1971 if !cfg.BuildContext.CgoEnabled {
1974 // Currently build modes c-shared, pie (on systems that do not
1975 // support PIE with internal linking mode (currently all
1976 // systems: issue #18968)), plugin, and -linkshared force
1977 // external linking mode, as of course does
1978 // -ldflags=-linkmode=external. External linking mode forces
1979 // an import of runtime/cgo.
1980 pieCgo := cfg.BuildBuildmode == "pie"
1981 linkmodeExternal := false
1983 ldflags := BuildLdflags.For(p)
1984 for i, a := range ldflags {
1985 if a == "-linkmode=external" {
1986 linkmodeExternal = true
1988 if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
1989 linkmodeExternal = true
1994 return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
1997 // mkAbs rewrites list, which must be paths relative to p.Dir,
1998 // into a sorted list of absolute paths. It edits list in place but for
1999 // convenience also returns list back to its caller.
2000 func (p *Package) mkAbs(list []string) []string {
2001 for i, f := range list {
2002 list[i] = filepath.Join(p.Dir, f)
2008 // InternalGoFiles returns the list of Go files being built for the package,
2009 // using absolute paths.
2010 func (p *Package) InternalGoFiles() []string {
2011 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
2014 // InternalXGoFiles returns the list of Go files being built for the XTest package,
2015 // using absolute paths.
2016 func (p *Package) InternalXGoFiles() []string {
2017 return p.mkAbs(p.XTestGoFiles)
2020 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
2021 // using absolute paths. "Possibly relevant" means that files are not excluded
2022 // due to build tags, but files with names beginning with . or _ are still excluded.
2023 func (p *Package) InternalAllGoFiles() []string {
2024 return p.mkAbs(str.StringList(p.constraintIgnoredGoFiles(), p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
2027 // constraintIgnoredGoFiles returns the list of Go files ignored for reasons
2028 // other than having a name beginning with '.' or '_'.
2029 func (p *Package) constraintIgnoredGoFiles() []string {
2030 if len(p.IgnoredGoFiles) == 0 {
2033 files := make([]string, 0, len(p.IgnoredGoFiles))
2034 for _, f := range p.IgnoredGoFiles {
2035 if f != "" && f[0] != '.' && f[0] != '_' {
2036 files = append(files, f)
2042 // usesSwig reports whether the package needs to run SWIG.
2043 func (p *Package) UsesSwig() bool {
2044 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
2047 // usesCgo reports whether the package needs to run cgo
2048 func (p *Package) UsesCgo() bool {
2049 return len(p.CgoFiles) > 0
2052 // PackageList returns the list of packages in the dag rooted at roots
2053 // as visited in a depth-first post-order traversal.
2054 func PackageList(roots []*Package) []*Package {
2055 seen := map[*Package]bool{}
2057 var walk func(*Package)
2058 walk = func(p *Package) {
2063 for _, p1 := range p.Internal.Imports {
2066 all = append(all, p)
2068 for _, root := range roots {
2074 // TestPackageList returns the list of packages in the dag rooted at roots
2075 // as visited in a depth-first post-order traversal, including the test
2076 // imports of the roots. This ignores errors in test packages.
2077 func TestPackageList(roots []*Package) []*Package {
2078 seen := map[*Package]bool{}
2080 var walk func(*Package)
2081 walk = func(p *Package) {
2086 for _, p1 := range p.Internal.Imports {
2089 all = append(all, p)
2091 walkTest := func(root *Package, path string) {
2093 p1 := LoadImport(path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
2094 if p1.Error == nil {
2098 for _, root := range roots {
2100 for _, path := range root.TestImports {
2101 walkTest(root, path)
2103 for _, path := range root.XTestImports {
2104 walkTest(root, path)
2110 // LoadImportWithFlags loads the package with the given import path and
2111 // sets tool flags on that package. This function is useful loading implicit
2112 // dependencies (like sync/atomic for coverage).
2113 // TODO(jayconrod): delete this function and set flags automatically
2114 // in LoadImport instead.
2115 func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
2116 p := LoadImport(path, srcDir, parent, stk, importPos, mode)
2121 // Packages returns the packages named by the
2122 // command line arguments 'args'. If a named package
2123 // cannot be loaded at all (for example, if the directory does not exist),
2124 // then packages prints an error and does not include that
2125 // package in the results. However, if errors occur trying
2126 // to load dependencies of a named package, the named
2127 // package is still returned, with p.Incomplete = true
2128 // and details in p.DepsErrors.
2129 func Packages(args []string) []*Package {
2131 for _, pkg := range PackagesAndErrors(args) {
2132 if pkg.Error != nil {
2133 base.Errorf("%v", pkg.Error)
2136 pkgs = append(pkgs, pkg)
2141 // PackagesAndErrors is like 'packages' but returns a
2142 // *Package for every argument, even the ones that
2143 // cannot be loaded at all.
2144 // The packages that fail to load will have p.Error != nil.
2145 func PackagesAndErrors(patterns []string) []*Package {
2146 for _, p := range patterns {
2147 // Listing is only supported with all patterns referring to either:
2148 // - Files that are part of the same directory.
2149 // - Explicit package paths or patterns.
2150 if strings.HasSuffix(p, ".go") {
2151 // We need to test whether the path is an actual Go file and not a
2152 // package path or pattern ending in '.go' (see golang.org/issue/34653).
2153 if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
2154 return []*Package{GoFilesPackage(patterns)}
2159 matches := ImportPaths(patterns)
2163 seenPkg = make(map[*Package]bool)
2168 pre.preloadMatches(matches)
2170 for _, m := range matches {
2171 for _, pkg := range m.Pkgs {
2173 panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
2175 p := loadImport(pre, pkg, base.Cwd, nil, &stk, nil, 0)
2176 p.Match = append(p.Match, m.Pattern())
2177 p.Internal.CmdlinePkg = true
2179 // Note: do not set = m.IsLiteral unconditionally
2180 // because maybe we'll see p matching both
2181 // a literal and also a non-literal pattern.
2182 p.Internal.CmdlinePkgLiteral = true
2188 pkgs = append(pkgs, p)
2191 if len(m.Errs) > 0 {
2192 // In addition to any packages that were actually resolved from the
2193 // pattern, there was some error in resolving the pattern itself.
2194 // Report it as a synthetic package.
2196 p.ImportPath = m.Pattern()
2197 // Pass an empty ImportStack and nil importPos: the error arose from a pattern, not an import.
2199 var importPos []token.Position
2200 p.setLoadPackageDataError(m.Errs[0], m.Pattern(), &stk, importPos)
2202 p.Match = append(p.Match, m.Pattern())
2203 p.Internal.CmdlinePkg = true
2205 p.Internal.CmdlinePkgLiteral = true
2207 pkgs = append(pkgs, p)
2211 // Now that CmdlinePkg is set correctly,
2212 // compute the effective flags for all loaded packages
2213 // (not just the ones matching the patterns but also
2214 // their dependencies).
2215 setToolFlags(pkgs...)
2220 func setToolFlags(pkgs ...*Package) {
2221 for _, p := range PackageList(pkgs) {
2222 p.Internal.Asmflags = BuildAsmflags.For(p)
2223 p.Internal.Gcflags = BuildGcflags.For(p)
2224 p.Internal.Ldflags = BuildLdflags.For(p)
2225 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
2229 func ImportPaths(args []string) []*search.Match {
2230 if ModInit(); cfg.ModulesEnabled {
2231 return ModImportPaths(args)
2233 return search.ImportPaths(args)
2236 // PackagesForBuild is like Packages but exits
2237 // if any of the packages or their dependencies have errors
2238 // (cannot be built).
2239 func PackagesForBuild(args []string) []*Package {
2240 pkgs := PackagesAndErrors(args)
2241 printed := map[*PackageError]bool{}
2242 for _, pkg := range pkgs {
2243 if pkg.Error != nil {
2244 base.Errorf("%v", pkg.Error)
2245 printed[pkg.Error] = true
2247 for _, err := range pkg.DepsErrors {
2248 // Since these are errors in dependencies,
2249 // the same error might show up multiple times,
2250 // once in each package that depends on it.
2251 // Only print each once.
2254 base.Errorf("%v", err)
2260 // Check for duplicate loads of the same package.
2261 // That should be impossible, but if it does happen then
2262 // we end up trying to build the same package twice,
2263 // usually in parallel overwriting the same files,
2264 // which doesn't work very well.
2265 seen := map[string]bool{}
2266 reported := map[string]bool{}
2267 for _, pkg := range PackageList(pkgs) {
2268 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
2269 reported[pkg.ImportPath] = true
2270 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
2272 seen[pkg.ImportPath] = true
2279 // GoFilesPackage creates a package for building a collection of Go files
2280 // (typically named on the command line). The target is named p.a for
2281 // package p or named after the first Go file for package main.
2282 func GoFilesPackage(gofiles []string) *Package {
2285 for _, f := range gofiles {
2286 if !strings.HasSuffix(f, ".go") {
2288 pkg.Internal.Local = true
2289 pkg.Internal.CmdlineFiles = true
2291 pkg.Error = &PackageError{
2292 Err: fmt.Errorf("named files must be .go files: %s", pkg.Name),
2299 ctxt := cfg.BuildContext
2300 ctxt.UseAllFiles = true
2302 // Synthesize fake "directory" that only shows the named files,
2303 // to make it look like this is a standard package or
2304 // command directory. So that local imports resolve
2305 // consistently, the files must all be in the same directory.
2306 var dirent []os.FileInfo
2308 for _, file := range gofiles {
2309 fi, err := os.Stat(file)
2311 base.Fatalf("%s", err)
2314 base.Fatalf("%s is a directory, should be a Go file", file)
2316 dir1, _ := filepath.Split(file)
2322 } else if dir != dir1 {
2323 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
2325 dirent = append(dirent, fi)
2327 ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
2329 if cfg.ModulesEnabled {
2330 ModImportFromFiles(gofiles)
2337 dir, err = filepath.Abs(dir)
2339 base.Fatalf("%s", err)
2342 bp, err := ctxt.ImportDir(dir, 0)
2344 pkg.Internal.Local = true
2345 pkg.Internal.CmdlineFiles = true
2346 pkg.load("command-line-arguments", &stk, nil, bp, err)
2347 pkg.Internal.LocalPrefix = dirToImportPath(dir)
2348 pkg.ImportPath = "command-line-arguments"
2352 if pkg.Name == "main" {
2353 exe := pkg.DefaultExecName() + cfg.ExeSuffix
2355 if cfg.GOBIN != "" {
2356 pkg.Target = filepath.Join(cfg.GOBIN, exe)
2357 } else if cfg.ModulesEnabled {
2358 pkg.Target = filepath.Join(ModBinDir(), exe)