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) {
221 // Include the path on the import stack unless the error includes it already.
223 if impErr, ok := err.(ImportPathError); ok && impErr.ImportPath() == path {
225 } else if matchErr, ok := err.(*search.MatchError); ok && matchErr.Match.Pattern() == path {
227 if matchErr.Match.IsLiteral() {
228 // The error has a pattern has a pattern similar to the import path.
229 // It may be slightly different (./foo matching example.com/foo),
230 // but close enough to seem redundant.
231 // Unwrap the error so we don't show the pattern.
244 // Replace (possibly wrapped) *build.NoGoError with *load.NoGoError.
245 // The latter is more specific about the cause.
246 var nogoErr *build.NoGoError
247 if errors.As(err, &nogoErr) {
248 if p.Dir == "" && nogoErr.Dir != "" {
251 err = &NoGoError{Package: p}
254 // Take only the first error from a scanner.ErrorList. PackageError only
255 // has room for one position, so we report the first error with a position
256 // instead of all of the errors without a position.
258 if scanErr, ok := err.(scanner.ErrorList); ok && len(scanErr) > 0 {
259 scanPos := scanErr[0].Pos
260 scanPos.Filename = base.ShortPath(scanPos.Filename)
261 pos = scanPos.String()
262 err = errors.New(scanErr[0].Msg)
265 p.Error = &PackageError{
272 // Resolve returns the resolved version of imports,
273 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
274 // The imports in p.TestImports and p.XTestImports are not recursively
275 // loaded during the initial load of p, so they list the imports found in
276 // the source file, but most processing should be over the vendor-resolved
277 // import paths. We do this resolution lazily both to avoid file system work
278 // and because the eventual real load of the test imports (during 'go test')
279 // can produce better error messages if it starts with the original paths.
280 // The initial load of p loads all the non-test imports and rewrites
281 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
282 func (p *Package) Resolve(imports []string) []string {
283 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
284 panic("internal error: p.Resolve(p.Imports) called")
286 seen := make(map[string]bool)
288 for _, path := range imports {
289 path = ResolveImportPath(p, path)
292 all = append(all, path)
299 // CoverVar holds the name of the generated coverage variables targeting the named file.
300 type CoverVar struct {
301 File string // local file name
302 Var string // name of count struct
305 func (p *Package) copyBuild(pp *build.Package) {
306 p.Internal.Build = pp
308 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
309 old := pp.PkgTargetRoot
310 pp.PkgRoot = cfg.BuildPkgdir
311 pp.PkgTargetRoot = cfg.BuildPkgdir
312 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
316 p.ImportPath = pp.ImportPath
317 p.ImportComment = pp.ImportComment
321 p.ConflictDir = pp.ConflictDir
322 p.BinaryOnly = pp.BinaryOnly
326 p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
327 p.GoFiles = pp.GoFiles
328 p.CgoFiles = pp.CgoFiles
329 p.IgnoredGoFiles = pp.IgnoredGoFiles
331 p.CXXFiles = pp.CXXFiles
336 p.SwigFiles = pp.SwigFiles
337 p.SwigCXXFiles = pp.SwigCXXFiles
338 p.SysoFiles = pp.SysoFiles
340 // There's no way for .syso files to be built both with and without
341 // support for memory sanitizer. Assume they are built without,
345 p.CgoCFLAGS = pp.CgoCFLAGS
346 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
347 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
348 p.CgoFFLAGS = pp.CgoFFLAGS
349 p.CgoLDFLAGS = pp.CgoLDFLAGS
350 p.CgoPkgConfig = pp.CgoPkgConfig
351 // We modify p.Imports in place, so make copy now.
352 p.Imports = make([]string, len(pp.Imports))
353 copy(p.Imports, pp.Imports)
354 p.Internal.RawImports = pp.Imports
355 p.TestGoFiles = pp.TestGoFiles
356 p.TestImports = pp.TestImports
357 p.XTestGoFiles = pp.XTestGoFiles
358 p.XTestImports = pp.XTestImports
361 p.Internal.RawImports = nil
367 // A PackageError describes an error loading information about a package.
368 type PackageError struct {
369 ImportStack []string // shortest path from package named on command line to this one
370 Pos string // position of error
371 Err error // the error itself
372 IsImportCycle bool // the error is an import cycle
373 Hard bool // whether the error is soft or hard; soft errors are ignored in some places
374 alwaysPrintStack bool // whether to always print the ImportStack
377 func (p *PackageError) Error() string {
378 if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
379 // Omit import stack. The full path to the file where the error
380 // is the most important thing.
381 return p.Pos + ": " + p.Err.Error()
384 // If the error is an ImportPathError, and the last path on the stack appears
385 // in the error message, omit that path from the stack to avoid repetition.
386 // If an ImportPathError wraps another ImportPathError that matches the
387 // last path on the stack, we don't omit the path. An error like
388 // "package A imports B: error loading C caused by B" would not be clearer
389 // if "imports B" were omitted.
390 if len(p.ImportStack) == 0 {
395 optpos = "\n\t" + p.Pos
397 return "package " + strings.Join(p.ImportStack, "\n\timports ") + optpos + ": " + p.Err.Error()
400 func (p *PackageError) Unwrap() error { return p.Err }
402 // PackageError implements MarshalJSON so that Err is marshaled as a string
403 // and non-essential fields are omitted.
404 func (p *PackageError) MarshalJSON() ([]byte, error) {
409 }{p.ImportStack, p.Pos, p.Err.Error()}
410 return json.Marshal(perr)
413 // ImportPathError is a type of error that prevents a package from being loaded
414 // for a given import path. When such a package is loaded, a *Package is
415 // returned with Err wrapping an ImportPathError: the error is attached to
416 // the imported package, not the importing package.
418 // The string returned by ImportPath must appear in the string returned by
419 // Error. Errors that wrap ImportPathError (such as PackageError) may omit
421 type ImportPathError interface {
426 type importError struct {
428 err error // created with fmt.Errorf
431 var _ ImportPathError = (*importError)(nil)
433 func ImportErrorf(path, format string, args ...interface{}) ImportPathError {
434 err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
435 if errStr := err.Error(); !strings.Contains(errStr, path) {
436 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
441 func (e *importError) Error() string {
445 func (e *importError) Unwrap() error {
446 // Don't return e.err directly, since we're only wrapping an error if %w
447 // was passed to ImportErrorf.
448 return errors.Unwrap(e.err)
451 func (e *importError) ImportPath() string {
455 // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
456 // The import path of a test package is the import path of the corresponding
457 // non-test package with the suffix "_test" added.
458 type ImportStack []string
460 func (s *ImportStack) Push(p string) {
464 func (s *ImportStack) Pop() {
465 *s = (*s)[0 : len(*s)-1]
468 func (s *ImportStack) Copy() []string {
469 return append([]string{}, *s...)
472 // shorterThan reports whether sp is shorter than t.
473 // We use this to record the shortest import sequence
474 // that leads to a particular package.
475 func (sp *ImportStack) shorterThan(t []string) bool {
477 if len(s) != len(t) {
478 return len(s) < len(t)
480 // If they are the same length, settle ties using string ordering.
486 return false // they are equal
489 // packageCache is a lookup cache for LoadImport,
490 // so that if we look up a package multiple times
491 // we return the same pointer each time.
492 var packageCache = map[string]*Package{}
494 // ClearPackageCache clears the in-memory package cache and the preload caches.
495 // It is only for use by GOPATH-based "go get".
496 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
497 func ClearPackageCache() {
498 for name := range packageCache {
499 delete(packageCache, name)
501 resolvedImportCache.Clear()
502 packageDataCache.Clear()
505 // ClearPackageCachePartial clears packages with the given import paths from the
506 // in-memory package cache and the preload caches. It is only for use by
507 // GOPATH-based "go get".
508 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
509 func ClearPackageCachePartial(args []string) {
510 shouldDelete := make(map[string]bool)
511 for _, arg := range args {
512 shouldDelete[arg] = true
513 if p := packageCache[arg]; p != nil {
514 delete(packageCache, arg)
517 resolvedImportCache.DeleteIf(func(key interface{}) bool {
518 return shouldDelete[key.(importSpec).path]
520 packageDataCache.DeleteIf(func(key interface{}) bool {
521 return shouldDelete[key.(string)]
525 // ReloadPackageNoFlags is like LoadImport but makes sure
526 // not to use the package cache.
527 // It is only for use by GOPATH-based "go get".
528 // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
529 func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
530 p := packageCache[arg]
532 delete(packageCache, arg)
533 resolvedImportCache.DeleteIf(func(key interface{}) bool {
534 return key.(importSpec).path == p.ImportPath
536 packageDataCache.Delete(p.ImportPath)
538 return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
541 // dirToImportPath returns the pseudo-import path we use for a package
542 // outside the Go path. It begins with _/ and then contains the full path
543 // to the directory. If the package lives in c:\home\gopher\my\pkg then
544 // the pseudo-import path is _/c_/home/gopher/my/pkg.
545 // Using a pseudo-import path like this makes the ./ imports no longer
546 // a special case, so that all the code to deal with ordinary imports works
548 func dirToImportPath(dir string) string {
549 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
552 func makeImportValid(r rune) rune {
553 // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
554 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
555 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
561 // Mode flags for loadImport and download (in get.go).
563 // ResolveImport means that loadImport should do import path expansion.
564 // That is, ResolveImport means that the import path came from
565 // a source file and has not been expanded yet to account for
566 // vendoring or possible module adjustment.
567 // Every import path should be loaded initially with ResolveImport,
568 // and then the expanded version (for example with the /vendor/ in it)
569 // gets recorded as the canonical import path. At that point, future loads
570 // of that package must not pass ResolveImport, because
571 // disallowVendor will reject direct use of paths containing /vendor/.
572 ResolveImport = 1 << iota
574 // ResolveModule is for download (part of "go get") and indicates
575 // that the module adjustment should be done, but not vendor adjustment.
578 // GetTestDeps is for download (part of "go get") and indicates
579 // that test dependencies should be fetched too.
583 // LoadImport scans the directory named by path, which must be an import path,
584 // but possibly a local import path (an absolute file system path or one beginning
585 // with ./ or ../). A local relative path is interpreted relative to srcDir.
586 // It returns a *Package describing the package found in that directory.
587 // LoadImport does not set tool flags and should only be used by
588 // this package, as part of a bigger load operation, and by GOPATH-based "go get".
589 // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
590 func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
591 return loadImport(nil, path, srcDir, parent, stk, importPos, mode)
594 func loadImport(pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
596 panic("LoadImport called with empty package path")
599 var parentPath, parentRoot string
602 parentPath = parent.ImportPath
603 parentRoot = parent.Root
604 parentIsStd = parent.Standard
606 bp, loaded, err := loadPackageData(path, parentPath, srcDir, parentRoot, parentIsStd, mode)
607 if loaded && pre != nil && !IgnoreImports {
608 pre.preloadImports(bp.Imports, bp)
611 if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
612 // Only add path to the error's import stack if it's not already present on the error.
617 PackagePublic: PackagePublic{
619 Error: &PackageError{
620 ImportStack: stk.Copy(),
627 importPath := bp.ImportPath
628 p := packageCache[importPath]
631 p = reusePackage(p, stk)
635 p.Internal.Local = build.IsLocalImport(path)
636 p.ImportPath = importPath
637 packageCache[importPath] = p
640 // loadPackageData may return bp != nil even if an error occurs,
641 // in order to return partial information.
642 p.load(path, stk, bp, err)
643 // Add position information unless this is a NoGoError or an ImportCycle error.
644 // Import cycles deserve special treatment.
645 var g *build.NoGoError
646 if p.Error != nil && p.Error.Pos == "" && !errors.As(err, &g) && !p.Error.IsImportCycle {
647 p = setErrorPos(p, importPos)
650 if !cfg.ModulesEnabled && path != cleanImport(path) {
651 p.Error = &PackageError{
652 ImportStack: stk.Copy(),
653 Err: ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
656 setErrorPos(p, importPos)
660 // Checked on every import because the rules depend on the code doing the importing.
661 if perr := disallowInternal(srcDir, parent, parentPath, p, stk); perr != p {
662 return setErrorPos(perr, importPos)
664 if mode&ResolveImport != 0 {
665 if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != p {
666 return setErrorPos(perr, importPos)
670 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
672 perr.Error = &PackageError{
673 ImportStack: stk.Copy(),
674 Err: ImportErrorf(path, "import %q is a program, not an importable package", path),
676 return setErrorPos(&perr, importPos)
679 if p.Internal.Local && parent != nil && !parent.Internal.Local {
683 err = ImportErrorf(path, "%s: cannot import current directory", path)
685 err = ImportErrorf(path, "local import %q in non-local package", path)
687 perr.Error = &PackageError{
688 ImportStack: stk.Copy(),
691 return setErrorPos(&perr, importPos)
697 func setErrorPos(p *Package, importPos []token.Position) *Package {
698 if len(importPos) > 0 {
700 pos.Filename = base.ShortPath(pos.Filename)
701 p.Error.Pos = pos.String()
706 // loadPackageData loads information needed to construct a *Package. The result
707 // is cached, and later calls to loadPackageData for the same package will return
710 // loadPackageData returns a non-nil package even if err is non-nil unless
711 // the package path is malformed (for example, the path contains "mod/" or "@").
713 // loadPackageData returns a boolean, loaded, which is true if this is the
714 // first time the package was loaded. Callers may preload imports in this case.
715 func loadPackageData(path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
717 panic("loadPackageData called with empty package path")
720 if strings.HasPrefix(path, "mod/") {
721 // Paths beginning with "mod/" might accidentally
722 // look in the module cache directory tree in $GOPATH/pkg/mod/.
723 // This prefix is owned by the Go core for possible use in the
724 // standard library (since it does not begin with a domain name),
725 // so it's OK to disallow entirely.
726 return nil, false, fmt.Errorf("disallowed import path %q", path)
729 if strings.Contains(path, "@") {
730 if cfg.ModulesEnabled {
731 return nil, false, errors.New("can only use path@version syntax with 'go get'")
733 return nil, false, errors.New("cannot use path@version syntax in GOPATH mode")
737 // Determine canonical package path and directory.
738 // For a local import the identifier is the pseudo-import path
739 // we create from the full directory to the package.
740 // Otherwise it is the usual import path.
741 // For vendored imports, it is the expanded form.
743 // Note that when modules are enabled, local import paths are normally
744 // canonicalized by modload.ImportPaths before now. However, if there's an
745 // error resolving a local path, it will be returned untransformed
746 // so that 'go list -e' reports something useful.
747 importKey := importSpec{
749 parentPath: parentPath,
750 parentDir: parentDir,
751 parentRoot: parentRoot,
752 parentIsStd: parentIsStd,
755 r := resolvedImportCache.Do(importKey, func() interface{} {
757 if build.IsLocalImport(path) {
758 r.dir = filepath.Join(parentDir, path)
759 r.path = dirToImportPath(r.dir)
760 } else if cfg.ModulesEnabled {
761 r.dir, r.path, r.err = ModLookup(parentPath, parentIsStd, path)
762 } else if mode&ResolveImport != 0 {
763 // We do our own path resolution, because we want to
764 // find out the key to use in packageCache without the
765 // overhead of repeated calls to buildContext.Import.
766 // The code is also needed in a few other places anyway.
767 r.path = resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
768 } else if mode&ResolveModule != 0 {
769 r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
776 // Invariant: r.path is set to the resolved import path. If the path cannot
777 // be resolved, r.path is set to path, the source import path.
778 // r.path is never empty.
780 // Load the package from its directory. If we already found the package's
781 // directory when resolving its import path, use that.
782 data := packageDataCache.Do(r.path, func() interface{} {
786 var buildMode build.ImportMode
787 if !cfg.ModulesEnabled {
788 buildMode = build.ImportComment
790 data.p, data.err = cfg.BuildContext.ImportDir(r.dir, buildMode)
791 if data.p.Root == "" && cfg.ModulesEnabled {
792 if info := ModPackageModuleInfo(path); info != nil {
793 data.p.Root = info.Dir
796 } else if r.err != nil {
797 data.p = new(build.Package)
799 } else if cfg.ModulesEnabled && path != "unsafe" {
800 data.p = new(build.Package)
801 data.err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", r.path)
803 buildMode := build.ImportComment
804 if mode&ResolveImport == 0 || r.path != path {
805 // Not vendoring, or we already found the vendored path.
806 buildMode |= build.IgnoreVendor
808 data.p, data.err = cfg.BuildContext.Import(r.path, parentDir, buildMode)
810 data.p.ImportPath = r.path
812 // Set data.p.BinDir in cases where go/build.Context.Import
813 // may give us a path we don't want.
816 data.p.BinDir = cfg.GOBIN
817 } else if cfg.ModulesEnabled {
818 data.p.BinDir = ModBinDir()
822 if !cfg.ModulesEnabled && data.err == nil &&
823 data.p.ImportComment != "" && data.p.ImportComment != path &&
824 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
825 data.err = fmt.Errorf("code in directory %s expects import %q", data.p.Dir, data.p.ImportComment)
830 return data.p, loaded, data.err
833 // importSpec describes an import declaration in source code. It is used as a
834 // cache key for resolvedImportCache.
835 type importSpec struct {
837 parentPath, parentDir, parentRoot string
842 // resolvedImport holds a canonical identifier for a package. It may also contain
843 // a path to the package's directory and an error if one occurred. resolvedImport
844 // is the value type in resolvedImportCache.
845 type resolvedImport struct {
850 // packageData holds information loaded from a package. It is the value type
851 // in packageDataCache.
852 type packageData struct {
857 // resolvedImportCache maps import strings (importSpec) to canonical package names
859 var resolvedImportCache par.Cache
861 // packageDataCache maps canonical package names (string) to package metadata
863 var packageDataCache par.Cache
865 // preloadWorkerCount is the number of concurrent goroutines that can load
866 // packages. Experimentally, there are diminishing returns with more than
867 // 4 workers. This was measured on the following machines.
869 // * MacBookPro with a 4-core Intel Core i7 CPU
870 // * Linux workstation with 6-core Intel Xeon CPU
871 // * Linux workstation with 24-core Intel Xeon CPU
873 // It is very likely (though not confirmed) that this workload is limited
874 // by memory bandwidth. We don't have a good way to determine the number of
875 // workers that would saturate the bus though, so runtime.GOMAXPROCS
876 // seems like a reasonable default.
877 var preloadWorkerCount = runtime.GOMAXPROCS(0)
879 // preload holds state for managing concurrent preloading of package data.
881 // A preload should be created with newPreload before loading a large
882 // package graph. flush must be called when package loading is complete
883 // to ensure preload goroutines are no longer active. This is necessary
884 // because of global mutable state that cannot safely be read and written
885 // concurrently. In particular, packageDataCache may be cleared by "go get"
886 // in GOPATH mode, and modload.loaded (accessed via ModLookup) may be
887 // modified by modload.ImportPaths (ModImportPaths).
888 type preload struct {
893 // newPreload creates a new preloader. flush must be called later to avoid
894 // accessing global state while it is being modified.
895 func newPreload() *preload {
897 cancel: make(chan struct{}),
898 sema: make(chan struct{}, preloadWorkerCount),
903 // preloadMatches loads data for package paths matched by patterns.
904 // When preloadMatches returns, some packages may not be loaded yet, but
905 // loadPackageData and loadImport are always safe to call.
906 func (pre *preload) preloadMatches(matches []*search.Match) {
907 for _, m := range matches {
908 for _, pkg := range m.Pkgs {
912 case pre.sema <- struct{}{}:
913 go func(pkg string) {
914 mode := 0 // don't use vendoring or module import resolution
915 bp, loaded, err := loadPackageData(pkg, "", base.Cwd, "", false, mode)
917 if bp != nil && loaded && err == nil && !IgnoreImports {
918 pre.preloadImports(bp.Imports, bp)
926 // preloadImports queues a list of imports for preloading.
927 // When preloadImports returns, some packages may not be loaded yet,
928 // but loadPackageData and loadImport are always safe to call.
929 func (pre *preload) preloadImports(imports []string, parent *build.Package) {
930 parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
931 for _, path := range imports {
932 if path == "C" || path == "unsafe" {
938 case pre.sema <- struct{}{}:
939 go func(path string) {
940 bp, loaded, err := loadPackageData(path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
942 if bp != nil && loaded && err == nil && !IgnoreImports {
943 pre.preloadImports(bp.Imports, bp)
950 // flush stops pending preload operations. flush blocks until preload calls to
951 // loadPackageData have completed. The preloader will not make any new calls
952 // to loadPackageData.
953 func (pre *preload) flush() {
955 for i := 0; i < preloadWorkerCount; i++ {
956 pre.sema <- struct{}{}
960 func cleanImport(path string) string {
962 path = pathpkg.Clean(path)
963 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
969 var isDirCache par.Cache
971 func isDir(path string) bool {
972 return isDirCache.Do(path, func() interface{} {
973 fi, err := os.Stat(path)
974 return err == nil && fi.IsDir()
978 // ResolveImportPath returns the true meaning of path when it appears in parent.
979 // There are two different resolutions applied.
980 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
981 // If vendor expansion doesn't trigger, then the path is also subject to
982 // Go 1.11 module legacy conversion (golang.org/issue/25069).
983 func ResolveImportPath(parent *Package, path string) (found string) {
984 var parentPath, parentDir, parentRoot string
987 parentPath = parent.ImportPath
988 parentDir = parent.Dir
989 parentRoot = parent.Root
990 parentIsStd = parent.Standard
992 return resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
995 func resolveImportPath(path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
996 if cfg.ModulesEnabled {
997 if _, p, e := ModLookup(parentPath, parentIsStd, path); e == nil {
1002 found = vendoredImportPath(path, parentPath, parentDir, parentRoot)
1006 return moduleImportPath(path, parentPath, parentDir, parentRoot)
1009 // dirAndRoot returns the source directory and workspace root
1010 // for the package p, guaranteeing that root is a path prefix of dir.
1011 func dirAndRoot(path string, dir, root string) (string, string) {
1012 origDir, origRoot := dir, root
1013 dir = filepath.Clean(dir)
1014 root = filepath.Join(root, "src")
1015 if !str.HasFilePathPrefix(dir, root) || path != "command-line-arguments" && filepath.Join(root, path) != dir {
1016 // Look for symlinks before reporting error.
1017 dir = expandPath(dir)
1018 root = expandPath(root)
1021 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 {
1022 base.Fatalf("unexpected directory layout:\n"+
1023 " import path: %s\n"+
1026 " expand root: %s\n"+
1027 " expand dir: %s\n"+
1030 filepath.Join(origRoot, "src"),
1031 filepath.Clean(origDir),
1034 string(filepath.Separator))
1040 // vendoredImportPath returns the vendor-expansion of path when it appears in parent.
1041 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
1042 // x/vendor/path, vendor/path, or else stay path if none of those exist.
1043 // vendoredImportPath returns the expanded path or, if no expansion is found, the original.
1044 func vendoredImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1045 if parentRoot == "" {
1049 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1051 vpath := "vendor/" + path
1052 for i := len(dir); i >= len(root); i-- {
1053 if i < len(dir) && dir[i] != filepath.Separator {
1056 // Note: checking for the vendor directory before checking
1057 // for the vendor/path directory helps us hit the
1058 // isDir cache more often. It also helps us prepare a more useful
1059 // list of places we looked, to report when an import is not found.
1060 if !isDir(filepath.Join(dir[:i], "vendor")) {
1063 targ := filepath.Join(dir[:i], vpath)
1064 if isDir(targ) && hasGoFiles(targ) {
1065 importPath := parentPath
1066 if importPath == "command-line-arguments" {
1067 // If parent.ImportPath is 'command-line-arguments'.
1068 // set to relative directory to root (also chopped root directory)
1069 importPath = dir[len(root)+1:]
1071 // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
1072 // We know the import path for parent's dir.
1073 // We chopped off some number of path elements and
1074 // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
1075 // Now we want to know the import path for that directory.
1076 // Construct it by chopping the same number of path elements
1077 // (actually the same number of bytes) from parent's import path
1078 // and then append /vendor/path.
1079 chopped := len(dir) - i
1080 if chopped == len(importPath)+1 {
1081 // We walked up from c:\gopath\src\foo\bar
1082 // and found c:\gopath\src\vendor\path.
1083 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
1084 // Use "vendor/path" without any prefix.
1087 return importPath[:len(importPath)-chopped] + "/" + vpath
1094 modulePrefix = []byte("\nmodule ")
1095 goModPathCache par.Cache
1098 // goModPath returns the module path in the go.mod in dir, if any.
1099 func goModPath(dir string) (path string) {
1100 return goModPathCache.Do(dir, func() interface{} {
1101 data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
1106 if bytes.HasPrefix(data, modulePrefix[1:]) {
1109 i = bytes.Index(data, modulePrefix)
1117 // Cut line at \n, drop trailing \r if present.
1118 if j := bytes.IndexByte(line, '\n'); j >= 0 {
1121 if line[len(line)-1] == '\r' {
1122 line = line[:len(line)-1]
1124 line = line[len("module "):]
1126 // If quoted, unquote.
1127 path = strings.TrimSpace(string(line))
1128 if path != "" && path[0] == '"' {
1129 s, err := strconv.Unquote(path)
1139 // findVersionElement returns the slice indices of the final version element /vN in path.
1140 // If there is no such element, it returns -1, -1.
1141 func findVersionElement(path string) (i, j int) {
1143 for i = len(path) - 1; i >= 0; i-- {
1145 if isVersionElement(path[i+1 : j]) {
1154 // isVersionElement reports whether s is a well-formed path version element:
1155 // v2, v3, v10, etc, but not v0, v05, v1.
1156 func isVersionElement(s string) bool {
1157 if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
1160 for i := 1; i < len(s); i++ {
1161 if s[i] < '0' || '9' < s[i] {
1168 // moduleImportPath translates import paths found in go modules
1169 // back down to paths that can be resolved in ordinary builds.
1171 // Define “new” code as code with a go.mod file in the same directory
1172 // or a parent directory. If an import in new code says x/y/v2/z but
1173 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
1174 // then go build will read the import as x/y/z instead.
1175 // See golang.org/issue/25069.
1176 func moduleImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1177 if parentRoot == "" {
1181 // If there are no vN elements in path, leave it alone.
1182 // (The code below would do the same, but only after
1183 // some other file system accesses that we can avoid
1184 // here by returning early.)
1185 if i, _ := findVersionElement(path); i < 0 {
1189 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1191 // Consider dir and parents, up to and including root.
1192 for i := len(dir); i >= len(root); i-- {
1193 if i < len(dir) && dir[i] != filepath.Separator {
1196 if goModPath(dir[:i]) != "" {
1200 // This code is not in a tree with a go.mod,
1201 // so apply no changes to the path.
1205 // This import is in a tree with a go.mod.
1206 // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
1207 // if GOPATH/src/x/y/go.mod says module "x/y/v2",
1209 // If x/y/v2/z exists, use it unmodified.
1210 if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
1214 // Otherwise look for a go.mod supplying a version element.
1215 // Some version-like elements may appear in paths but not
1216 // be module versions; we skip over those to look for module
1217 // versions. For example the module m/v2 might have a
1218 // package m/v2/api/v1/foo.
1221 i, j := findVersionElement(path[:limit])
1225 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
1226 if mpath := goModPath(bp.Dir); mpath != "" {
1227 // Found a valid go.mod file, so we're stopping the search.
1228 // If the path is m/v2/p and we found m/go.mod that says
1229 // "module m/v2", then we return "m/p".
1230 if mpath == path[:j] {
1231 return path[:i] + path[j:]
1233 // Otherwise just return the original path.
1234 // We didn't find anything worth rewriting,
1235 // and the go.mod indicates that we should
1236 // not consider parent directories.
1245 // hasGoFiles reports whether dir contains any files with names ending in .go.
1246 // For a vendor check we must exclude directories that contain no .go files.
1247 // Otherwise it is not possible to vendor just a/b/c and still import the
1248 // non-vendored a/b. See golang.org/issue/13832.
1249 func hasGoFiles(dir string) bool {
1250 fis, _ := ioutil.ReadDir(dir)
1251 for _, fi := range fis {
1252 if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
1259 // reusePackage reuses package p to satisfy the import at the top
1260 // of the import stack stk. If this use causes an import loop,
1261 // reusePackage updates p's error information to record the loop.
1262 func reusePackage(p *Package, stk *ImportStack) *Package {
1263 // We use p.Internal.Imports==nil to detect a package that
1264 // is in the midst of its own loadPackage call
1265 // (all the recursion below happens before p.Internal.Imports gets set).
1266 if p.Internal.Imports == nil {
1268 p.Error = &PackageError{
1269 ImportStack: stk.Copy(),
1270 Err: errors.New("import cycle not allowed"),
1271 IsImportCycle: true,
1276 // Don't rewrite the import stack in the error if we have an import cycle.
1277 // If we do, we'll lose the path that describes the cycle.
1278 if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
1279 p.Error.ImportStack = stk.Copy()
1284 // disallowInternal checks that srcDir (containing package importerPath, if non-empty)
1285 // is allowed to import p.
1286 // If the import is allowed, disallowInternal returns the original package p.
1287 // If not, it returns a new package containing just an appropriate error.
1288 func disallowInternal(srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package {
1289 // golang.org/s/go14internal:
1290 // An import of a path containing the element “internal”
1291 // is disallowed if the importing code is outside the tree
1292 // rooted at the parent of the “internal” directory.
1294 // There was an error loading the package; stop here.
1299 // The generated 'testmain' package is allowed to access testing/internal/...,
1300 // as if it were generated into the testing directory tree
1301 // (it's actually in a temporary directory outside any Go tree).
1302 // This cleans up a former kludge in passing functionality to the testing package.
1303 if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
1307 // We can't check standard packages with gccgo.
1308 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
1312 // The sort package depends on internal/reflectlite, but during bootstrap
1313 // the path rewriting causes the normal internal checks to fail.
1314 // Instead, just ignore the internal rules during bootstrap.
1315 if p.Standard && strings.HasPrefix(importerPath, "bootstrap/") {
1319 // importerPath is empty: we started
1320 // with a name given on the command line, not an
1321 // import. Anything listed on the command line is fine.
1322 if importerPath == "" {
1326 // Check for "internal" element: three cases depending on begin of string and/or end of string.
1327 i, ok := findInternal(p.ImportPath)
1332 // Internal is present.
1333 // Map import path back to directory corresponding to parent of internal.
1335 i-- // rewind over slash in ".../internal"
1338 if p.Module == nil {
1339 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
1341 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1345 // Look for symlinks before reporting error.
1346 srcDir = expandPath(srcDir)
1347 parent = expandPath(parent)
1348 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1352 // p is in a module, so make it available based on the importer's import path instead
1353 // of the file path (https://golang.org/issue/23970).
1354 if importer.Internal.CmdlineFiles {
1355 // The importer is a list of command-line files.
1356 // Pretend that the import path is the import path of the
1357 // directory containing them.
1358 // If the directory is outside the main module, this will resolve to ".",
1359 // which is not a prefix of any valid module.
1360 importerPath = ModDirImportPath(importer.Dir)
1362 parentOfInternal := p.ImportPath[:i]
1363 if str.HasPathPrefix(importerPath, parentOfInternal) {
1368 // Internal is present, and srcDir is outside parent's tree. Not allowed.
1370 perr.Error = &PackageError{
1371 alwaysPrintStack: true,
1372 ImportStack: stk.Copy(),
1373 Err: ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
1375 perr.Incomplete = true
1379 // findInternal looks for the final "internal" path element in the given import path.
1380 // If there isn't one, findInternal returns ok=false.
1381 // Otherwise, findInternal returns ok=true and the index of the "internal".
1382 func findInternal(path string) (index int, ok bool) {
1383 // Three cases, depending on internal at start/end of string or not.
1384 // The order matters: we must return the index of the final element,
1385 // because the final one produces the most restrictive requirement
1388 case strings.HasSuffix(path, "/internal"):
1389 return len(path) - len("internal"), true
1390 case strings.Contains(path, "/internal/"):
1391 return strings.LastIndex(path, "/internal/") + 1, true
1392 case path == "internal", strings.HasPrefix(path, "internal/"):
1398 // disallowVendor checks that srcDir is allowed to import p as path.
1399 // If the import is allowed, disallowVendor returns the original package p.
1400 // If not, it returns a new package containing just an appropriate error.
1401 func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *Package {
1402 // If the importerPath is empty, we started
1403 // with a name given on the command line, not an
1404 // import. Anything listed on the command line is fine.
1405 if importerPath == "" {
1409 if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != p {
1413 // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
1414 if i, ok := FindVendor(path); ok {
1416 perr.Error = &PackageError{
1417 ImportStack: stk.Copy(),
1418 Err: ImportErrorf(path, "%s must be imported as %s", path, path[i+len("vendor/"):]),
1420 perr.Incomplete = true
1427 // disallowVendorVisibility checks that srcDir is allowed to import p.
1428 // The rules are the same as for /internal/ except that a path ending in /vendor
1429 // is not subject to the rules, only subdirectories of vendor.
1430 // This allows people to have packages and commands named vendor,
1431 // for maximal compatibility with existing source trees.
1432 func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *Package {
1433 // The stack does not include p.ImportPath.
1434 // If there's nothing on the stack, we started
1435 // with a name given on the command line, not an
1436 // import. Anything listed on the command line is fine.
1437 if importerPath == "" {
1441 // Check for "vendor" element.
1442 i, ok := FindVendor(p.ImportPath)
1447 // Vendor is present.
1448 // Map import path back to directory corresponding to parent of vendor.
1450 i-- // rewind over slash in ".../vendor"
1452 truncateTo := i + len(p.Dir) - len(p.ImportPath)
1453 if truncateTo < 0 || len(p.Dir) < truncateTo {
1456 parent := p.Dir[:truncateTo]
1457 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1461 // Look for symlinks before reporting error.
1462 srcDir = expandPath(srcDir)
1463 parent = expandPath(parent)
1464 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1468 // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1470 perr.Error = &PackageError{
1471 ImportStack: stk.Copy(),
1472 Err: errors.New("use of vendored package not allowed"),
1474 perr.Incomplete = true
1478 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1479 // If there isn't one, FindVendor returns ok=false.
1480 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1482 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1483 // not the vendored copy of an import "" (the empty import path).
1484 // This will allow people to have packages or commands named vendor.
1485 // This may help reduce breakage, or it may just be confusing. We'll see.
1486 func FindVendor(path string) (index int, ok bool) {
1487 // Two cases, depending on internal at start of string or not.
1488 // The order matters: we must return the index of the final element,
1489 // because the final one is where the effective import path starts.
1491 case strings.Contains(path, "/vendor/"):
1492 return strings.LastIndex(path, "/vendor/") + 1, true
1493 case strings.HasPrefix(path, "vendor/"):
1502 ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1503 ToBin // to bin dir inside package root (default for non-cmd/*)
1504 StalePath // an old import path; fail to build
1507 // InstallTargetDir reports the target directory for installing the command p.
1508 func InstallTargetDir(p *Package) TargetDir {
1509 if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1512 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1513 switch p.ImportPath {
1514 case "cmd/go", "cmd/gofmt":
1522 var cgoExclude = map[string]bool{
1523 "runtime/cgo": true,
1526 var cgoSyscallExclude = map[string]bool{
1527 "runtime/cgo": true,
1528 "runtime/race": true,
1529 "runtime/msan": true,
1532 var foldPath = make(map[string]string)
1534 // exeFromImportPath returns an executable name
1535 // for a package using the import path.
1537 // The executable name is the last element of the import path.
1538 // In module-aware mode, an additional rule is used on import paths
1539 // consisting of two or more path elements. If the last element is
1540 // a vN path element specifying the major version, then the
1541 // second last element of the import path is used instead.
1542 func (p *Package) exeFromImportPath() string {
1543 _, elem := pathpkg.Split(p.ImportPath)
1544 if cfg.ModulesEnabled {
1545 // If this is example.com/mycmd/v2, it's more useful to
1546 // install it as mycmd than as v2. See golang.org/issue/24667.
1547 if elem != p.ImportPath && isVersionElement(elem) {
1548 _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
1554 // exeFromFiles returns an executable name for a package
1555 // using the first element in GoFiles or CgoFiles collections without the prefix.
1557 // Returns empty string in case of empty collection.
1558 func (p *Package) exeFromFiles() string {
1560 if len(p.GoFiles) > 0 {
1562 } else if len(p.CgoFiles) > 0 {
1567 _, elem := filepath.Split(src)
1568 return elem[:len(elem)-len(".go")]
1571 // DefaultExecName returns the default executable name for a package
1572 func (p *Package) DefaultExecName() string {
1573 if p.Internal.CmdlineFiles {
1574 return p.exeFromFiles()
1576 return p.exeFromImportPath()
1579 // load populates p using information from bp, err, which should
1580 // be the result of calling build.Context.Import.
1581 // stk contains the import stack, not including path itself.
1582 func (p *Package) load(path string, stk *ImportStack, bp *build.Package, err error) {
1585 // The localPrefix is the path we interpret ./ imports relative to.
1586 // Synthesized main packages sometimes override this.
1587 if p.Internal.Local {
1588 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1591 // setError sets p.Error if it hasn't already been set. We may proceed
1592 // after encountering some errors so that 'go list -e' has more complete
1593 // output. If there's more than one error, we should report the first.
1594 setError := func(err error) {
1596 p.Error = &PackageError{
1597 ImportStack: stk.Copy(),
1605 p.setLoadPackageDataError(err, path, stk)
1608 useBindir := p.Name == "main"
1610 switch cfg.BuildBuildmode {
1611 case "c-archive", "c-shared", "plugin":
1617 // Report an error when the old code.google.com/p/go.tools paths are used.
1618 if InstallTargetDir(p) == StalePath {
1619 newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1620 e := ImportErrorf(p.ImportPath, "the %v command has moved; use %v instead.", p.ImportPath, newPath)
1624 elem := p.DefaultExecName()
1625 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1626 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1627 // Install cross-compiled binaries to subdirectories of bin.
1630 if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
1631 p.Internal.Build.BinDir = ModBinDir()
1633 if p.Internal.Build.BinDir != "" {
1634 // Install to GOBIN or bin of GOPATH entry.
1635 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1636 if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1637 // Do not create $GOBIN/goos_goarch/elem.
1639 p.Internal.GobinSubdir = true
1642 if InstallTargetDir(p) == ToTool {
1643 // This is for 'go tool'.
1644 // Override all the usual logic and force it into the tool directory.
1645 if cfg.BuildToolchainName == "gccgo" {
1646 p.Target = filepath.Join(base.ToolDir, elem)
1648 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1651 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1654 } else if p.Internal.Local {
1655 // Local import turned into absolute path.
1656 // No permanent install target.
1659 p.Target = p.Internal.Build.PkgObj
1660 if cfg.BuildLinkshared && p.Target != "" {
1661 // TODO(bcmills): The reliance on p.Target implies that -linkshared does
1662 // not work for any package that lacks a Target — such as a non-main
1663 // package in module mode. We should probably fix that.
1664 shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1665 shlib, err := ioutil.ReadFile(shlibnamefile)
1666 if err != nil && !os.IsNotExist(err) {
1667 base.Fatalf("reading shlibname: %v", err)
1670 libname := strings.TrimSpace(string(shlib))
1671 if cfg.BuildContext.Compiler == "gccgo" {
1672 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1674 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1680 // Build augmented import list to add implicit dependencies.
1681 // Be careful not to add imports twice, just to avoid confusion.
1682 importPaths := p.Imports
1683 addImport := func(path string, forCompiler bool) {
1684 for _, p := range importPaths {
1689 importPaths = append(importPaths, path)
1691 p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
1695 // Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall",
1696 // except for certain packages, to avoid circular dependencies.
1698 addImport("unsafe", true)
1700 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1701 addImport("runtime/cgo", true)
1703 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1704 addImport("syscall", true)
1707 // SWIG adds imports of some standard packages.
1709 addImport("unsafe", true)
1710 if cfg.BuildContext.Compiler != "gccgo" {
1711 addImport("runtime/cgo", true)
1713 addImport("syscall", true)
1714 addImport("sync", true)
1716 // TODO: The .swig and .swigcxx files can use
1717 // %go_import directives to import other packages.
1720 // The linker loads implicit dependencies.
1721 if p.Name == "main" && !p.Internal.ForceLibrary {
1722 for _, dep := range LinkerDeps(p) {
1723 addImport(dep, false)
1727 // Check for case-insensitive collisions of import paths.
1728 fold := str.ToFold(p.ImportPath)
1729 if other := foldPath[fold]; other == "" {
1730 foldPath[fold] = p.ImportPath
1731 } else if other != p.ImportPath {
1732 setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
1736 if !SafeArg(p.ImportPath) {
1737 setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
1744 // Check for case-insensitive collision of input files.
1745 // To avoid problems on case-insensitive files, we reject any package
1746 // where two different input files have equal names under a case-insensitive
1748 inputs := p.AllFiles()
1749 f1, f2 := str.FoldDup(inputs)
1751 setError(fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2))
1755 // If first letter of input file is ASCII, it must be alphanumeric.
1756 // This avoids files turning into flags when invoking commands,
1757 // and other problems we haven't thought of yet.
1758 // Also, _cgo_ files must be generated by us, not supplied.
1759 // They are allowed to have //go:cgo_ldflag directives.
1760 // The directory scan ignores files beginning with _,
1761 // so we shouldn't see any _cgo_ files anyway, but just be safe.
1762 for _, file := range inputs {
1763 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1764 setError(fmt.Errorf("invalid input file name %q", file))
1768 if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1769 setError(fmt.Errorf("invalid input directory name %q", name))
1773 // Build list of imported packages and full dependency list.
1774 imports := make([]*Package, 0, len(p.Imports))
1775 for i, path := range importPaths {
1779 p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1781 path = p1.ImportPath
1782 importPaths[i] = path
1783 if i < len(p.Imports) {
1787 imports = append(imports, p1)
1792 p.Internal.Imports = imports
1795 // unsafe is a fake package.
1796 if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1800 // If cgo is not enabled, ignore cgo supporting sources
1801 // just as we ignore go files containing import "C".
1802 if !cfg.BuildContext.CgoEnabled {
1807 p.SwigCXXFiles = nil
1808 // Note that SFiles are okay (they go to the Go assembler)
1809 // and HFiles are okay (they might be used by the SFiles).
1810 // Also Sysofiles are okay (they might not contain object
1811 // code; see issue #16050).
1814 // The gc toolchain only permits C source files with cgo or SWIG.
1815 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1816 setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1820 // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1821 // regardless of toolchain.
1822 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1823 setError(fmt.Errorf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1826 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1827 setError(fmt.Errorf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1830 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1831 setError(fmt.Errorf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1835 if cfg.ModulesEnabled && p.Error == nil {
1836 mainPath := p.ImportPath
1837 if p.Internal.CmdlineFiles {
1838 mainPath = "command-line-arguments"
1840 p.Module = ModPackageModuleInfo(mainPath)
1841 if p.Name == "main" && len(p.DepsErrors) == 0 {
1842 p.Internal.BuildInfo = ModPackageBuildInfo(mainPath, p.Deps)
1847 // collectDeps populates p.Deps and p.DepsErrors by iterating over
1848 // p.Internal.Imports.
1850 // TODO(jayconrod): collectDeps iterates over transitive imports for every
1851 // package. We should only need to visit direct imports.
1852 func (p *Package) collectDeps() {
1853 deps := make(map[string]*Package)
1855 q = append(q, p.Internal.Imports...)
1856 for i := 0; i < len(q); i++ {
1858 path := p1.ImportPath
1859 // The same import path could produce an error or not,
1860 // depending on what tries to import it.
1861 // Prefer to record entries with errors, so we can report them.
1863 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
1865 for _, p2 := range p1.Internal.Imports {
1866 if deps[p2.ImportPath] != p2 {
1873 p.Deps = make([]string, 0, len(deps))
1874 for dep := range deps {
1875 p.Deps = append(p.Deps, dep)
1877 sort.Strings(p.Deps)
1878 for _, dep := range p.Deps {
1881 panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
1883 if p1.Error != nil {
1884 p.DepsErrors = append(p.DepsErrors, p1.Error)
1889 // SafeArg reports whether arg is a "safe" command-line argument,
1890 // meaning that when it appears in a command-line, it probably
1891 // doesn't have some special meaning other than its own name.
1892 // Obviously args beginning with - are not safe (they look like flags).
1893 // Less obviously, args beginning with @ are not safe (they look like
1894 // GNU binutils flagfile specifiers, sometimes called "response files").
1895 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
1896 // We accept leading . _ and / as likely in file system paths.
1897 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
1898 func SafeArg(name string) bool {
1903 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1906 // LinkerDeps returns the list of linker-induced dependencies for main package p.
1907 func LinkerDeps(p *Package) []string {
1908 // Everything links runtime.
1909 deps := []string{"runtime"}
1911 // External linking mode forces an import of runtime/cgo.
1912 if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
1913 deps = append(deps, "runtime/cgo")
1915 // On ARM with GOARM=5, it forces an import of math, for soft floating point.
1916 if cfg.Goarch == "arm" {
1917 deps = append(deps, "math")
1919 // Using the race detector forces an import of runtime/race.
1921 deps = append(deps, "runtime/race")
1923 // Using memory sanitizer forces an import of runtime/msan.
1925 deps = append(deps, "runtime/msan")
1931 // externalLinkingForced reports whether external linking is being
1932 // forced even for programs that do not use cgo.
1933 func externalLinkingForced(p *Package) bool {
1934 // Some targets must use external linking even inside GOROOT.
1935 switch cfg.BuildContext.GOOS {
1937 if cfg.BuildContext.GOARCH != "arm64" {
1941 if cfg.BuildContext.GOARCH == "arm64" {
1946 if !cfg.BuildContext.CgoEnabled {
1949 // Currently build modes c-shared, pie (on systems that do not
1950 // support PIE with internal linking mode (currently all
1951 // systems: issue #18968)), plugin, and -linkshared force
1952 // external linking mode, as of course does
1953 // -ldflags=-linkmode=external. External linking mode forces
1954 // an import of runtime/cgo.
1955 pieCgo := cfg.BuildBuildmode == "pie"
1956 linkmodeExternal := false
1958 ldflags := BuildLdflags.For(p)
1959 for i, a := range ldflags {
1960 if a == "-linkmode=external" {
1961 linkmodeExternal = true
1963 if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
1964 linkmodeExternal = true
1969 return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
1972 // mkAbs rewrites list, which must be paths relative to p.Dir,
1973 // into a sorted list of absolute paths. It edits list in place but for
1974 // convenience also returns list back to its caller.
1975 func (p *Package) mkAbs(list []string) []string {
1976 for i, f := range list {
1977 list[i] = filepath.Join(p.Dir, f)
1983 // InternalGoFiles returns the list of Go files being built for the package,
1984 // using absolute paths.
1985 func (p *Package) InternalGoFiles() []string {
1986 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
1989 // InternalXGoFiles returns the list of Go files being built for the XTest package,
1990 // using absolute paths.
1991 func (p *Package) InternalXGoFiles() []string {
1992 return p.mkAbs(p.XTestGoFiles)
1995 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
1996 // using absolute paths. "Possibly relevant" means that files are not excluded
1997 // due to build tags, but files with names beginning with . or _ are still excluded.
1998 func (p *Package) InternalAllGoFiles() []string {
1999 return p.mkAbs(str.StringList(p.constraintIgnoredGoFiles(), p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
2002 // constraintIgnoredGoFiles returns the list of Go files ignored for reasons
2003 // other than having a name beginning with '.' or '_'.
2004 func (p *Package) constraintIgnoredGoFiles() []string {
2005 if len(p.IgnoredGoFiles) == 0 {
2008 files := make([]string, 0, len(p.IgnoredGoFiles))
2009 for _, f := range p.IgnoredGoFiles {
2010 if f != "" && f[0] != '.' && f[0] != '_' {
2011 files = append(files, f)
2017 // usesSwig reports whether the package needs to run SWIG.
2018 func (p *Package) UsesSwig() bool {
2019 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
2022 // usesCgo reports whether the package needs to run cgo
2023 func (p *Package) UsesCgo() bool {
2024 return len(p.CgoFiles) > 0
2027 // PackageList returns the list of packages in the dag rooted at roots
2028 // as visited in a depth-first post-order traversal.
2029 func PackageList(roots []*Package) []*Package {
2030 seen := map[*Package]bool{}
2032 var walk func(*Package)
2033 walk = func(p *Package) {
2038 for _, p1 := range p.Internal.Imports {
2041 all = append(all, p)
2043 for _, root := range roots {
2049 // TestPackageList returns the list of packages in the dag rooted at roots
2050 // as visited in a depth-first post-order traversal, including the test
2051 // imports of the roots. This ignores errors in test packages.
2052 func TestPackageList(roots []*Package) []*Package {
2053 seen := map[*Package]bool{}
2055 var walk func(*Package)
2056 walk = func(p *Package) {
2061 for _, p1 := range p.Internal.Imports {
2064 all = append(all, p)
2066 walkTest := func(root *Package, path string) {
2068 p1 := LoadImport(path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
2069 if p1.Error == nil {
2073 for _, root := range roots {
2075 for _, path := range root.TestImports {
2076 walkTest(root, path)
2078 for _, path := range root.XTestImports {
2079 walkTest(root, path)
2085 // LoadImportWithFlags loads the package with the given import path and
2086 // sets tool flags on that package. This function is useful loading implicit
2087 // dependencies (like sync/atomic for coverage).
2088 // TODO(jayconrod): delete this function and set flags automatically
2089 // in LoadImport instead.
2090 func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
2091 p := LoadImport(path, srcDir, parent, stk, importPos, mode)
2096 // Packages returns the packages named by the
2097 // command line arguments 'args'. If a named package
2098 // cannot be loaded at all (for example, if the directory does not exist),
2099 // then packages prints an error and does not include that
2100 // package in the results. However, if errors occur trying
2101 // to load dependencies of a named package, the named
2102 // package is still returned, with p.Incomplete = true
2103 // and details in p.DepsErrors.
2104 func Packages(args []string) []*Package {
2106 for _, pkg := range PackagesAndErrors(args) {
2107 if pkg.Error != nil {
2108 base.Errorf("%v", pkg.Error)
2111 pkgs = append(pkgs, pkg)
2116 // PackagesAndErrors is like 'packages' but returns a
2117 // *Package for every argument, even the ones that
2118 // cannot be loaded at all.
2119 // The packages that fail to load will have p.Error != nil.
2120 func PackagesAndErrors(patterns []string) []*Package {
2121 for _, p := range patterns {
2122 // Listing is only supported with all patterns referring to either:
2123 // - Files that are part of the same directory.
2124 // - Explicit package paths or patterns.
2125 if strings.HasSuffix(p, ".go") {
2126 // We need to test whether the path is an actual Go file and not a
2127 // package path or pattern ending in '.go' (see golang.org/issue/34653).
2128 if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
2129 return []*Package{GoFilesPackage(patterns)}
2134 matches := ImportPaths(patterns)
2138 seenPkg = make(map[*Package]bool)
2143 pre.preloadMatches(matches)
2145 for _, m := range matches {
2146 for _, pkg := range m.Pkgs {
2148 panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
2150 p := loadImport(pre, pkg, base.Cwd, nil, &stk, nil, 0)
2151 p.Match = append(p.Match, m.Pattern())
2152 p.Internal.CmdlinePkg = true
2154 // Note: do not set = m.IsLiteral unconditionally
2155 // because maybe we'll see p matching both
2156 // a literal and also a non-literal pattern.
2157 p.Internal.CmdlinePkgLiteral = true
2163 pkgs = append(pkgs, p)
2166 if len(m.Errs) > 0 {
2167 // In addition to any packages that were actually resolved from the
2168 // pattern, there was some error in resolving the pattern itself.
2169 // Report it as a synthetic package.
2171 p.ImportPath = m.Pattern()
2172 var stk ImportStack // empty stack, since the error arose from a pattern, not an import
2173 p.setLoadPackageDataError(m.Errs[0], m.Pattern(), &stk)
2175 p.Match = append(p.Match, m.Pattern())
2176 p.Internal.CmdlinePkg = true
2178 p.Internal.CmdlinePkgLiteral = true
2180 pkgs = append(pkgs, p)
2184 // Now that CmdlinePkg is set correctly,
2185 // compute the effective flags for all loaded packages
2186 // (not just the ones matching the patterns but also
2187 // their dependencies).
2188 setToolFlags(pkgs...)
2193 func setToolFlags(pkgs ...*Package) {
2194 for _, p := range PackageList(pkgs) {
2195 p.Internal.Asmflags = BuildAsmflags.For(p)
2196 p.Internal.Gcflags = BuildGcflags.For(p)
2197 p.Internal.Ldflags = BuildLdflags.For(p)
2198 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
2202 func ImportPaths(args []string) []*search.Match {
2203 if ModInit(); cfg.ModulesEnabled {
2204 return ModImportPaths(args)
2206 return search.ImportPaths(args)
2209 // PackagesForBuild is like Packages but exits
2210 // if any of the packages or their dependencies have errors
2211 // (cannot be built).
2212 func PackagesForBuild(args []string) []*Package {
2213 pkgs := PackagesAndErrors(args)
2214 printed := map[*PackageError]bool{}
2215 for _, pkg := range pkgs {
2216 if pkg.Error != nil {
2217 base.Errorf("%v", pkg.Error)
2218 printed[pkg.Error] = true
2220 for _, err := range pkg.DepsErrors {
2221 // Since these are errors in dependencies,
2222 // the same error might show up multiple times,
2223 // once in each package that depends on it.
2224 // Only print each once.
2227 base.Errorf("%v", err)
2233 // Check for duplicate loads of the same package.
2234 // That should be impossible, but if it does happen then
2235 // we end up trying to build the same package twice,
2236 // usually in parallel overwriting the same files,
2237 // which doesn't work very well.
2238 seen := map[string]bool{}
2239 reported := map[string]bool{}
2240 for _, pkg := range PackageList(pkgs) {
2241 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
2242 reported[pkg.ImportPath] = true
2243 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
2245 seen[pkg.ImportPath] = true
2252 // GoFilesPackage creates a package for building a collection of Go files
2253 // (typically named on the command line). The target is named p.a for
2254 // package p or named after the first Go file for package main.
2255 func GoFilesPackage(gofiles []string) *Package {
2258 for _, f := range gofiles {
2259 if !strings.HasSuffix(f, ".go") {
2261 pkg.Internal.Local = true
2262 pkg.Internal.CmdlineFiles = true
2264 pkg.Error = &PackageError{
2265 Err: fmt.Errorf("named files must be .go files: %s", pkg.Name),
2272 ctxt := cfg.BuildContext
2273 ctxt.UseAllFiles = true
2275 // Synthesize fake "directory" that only shows the named files,
2276 // to make it look like this is a standard package or
2277 // command directory. So that local imports resolve
2278 // consistently, the files must all be in the same directory.
2279 var dirent []os.FileInfo
2281 for _, file := range gofiles {
2282 fi, err := os.Stat(file)
2284 base.Fatalf("%s", err)
2287 base.Fatalf("%s is a directory, should be a Go file", file)
2289 dir1, _ := filepath.Split(file)
2295 } else if dir != dir1 {
2296 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
2298 dirent = append(dirent, fi)
2300 ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
2302 if cfg.ModulesEnabled {
2303 ModImportFromFiles(gofiles)
2310 dir, err = filepath.Abs(dir)
2312 base.Fatalf("%s", err)
2315 bp, err := ctxt.ImportDir(dir, 0)
2317 pkg.Internal.Local = true
2318 pkg.Internal.CmdlineFiles = true
2319 pkg.load("command-line-arguments", &stk, bp, err)
2320 pkg.Internal.LocalPrefix = dirToImportPath(dir)
2321 pkg.ImportPath = "command-line-arguments"
2325 if pkg.Name == "main" {
2326 exe := pkg.DefaultExecName() + cfg.ExeSuffix
2328 if cfg.GOBIN != "" {
2329 pkg.Target = filepath.Join(cfg.GOBIN, exe)
2330 } else if cfg.ModulesEnabled {
2331 pkg.Target = filepath.Join(ModBinDir(), exe)