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.
23 "cmd/go/internal/base"
28 var IgnoreImports bool // control whether we ignore imports in packages
30 // A Package describes a single package found in a directory.
32 PackagePublic // visible in 'go list'
33 Internal PackageInternal // for use inside go command only
36 type PackagePublic struct {
37 // Note: These fields are part of the go command's public API.
38 // See list.go. It is okay to add fields, but not to change or
39 // remove existing ones. Keep in sync with list.go
40 Dir string `json:",omitempty"` // directory containing package sources
41 ImportPath string `json:",omitempty"` // import path of package in dir
42 ImportComment string `json:",omitempty"` // path in import comment on package statement
43 Name string `json:",omitempty"` // package name
44 Doc string `json:",omitempty"` // package documentation string
45 Target string `json:",omitempty"` // installed target for this package (may be executable)
46 Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
47 Goroot bool `json:",omitempty"` // is this package found in the Go root?
48 Standard bool `json:",omitempty"` // is this package part of the standard Go library?
49 Root string `json:",omitempty"` // Go root or Go path dir containing this package
50 ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory
51 BinaryOnly bool `json:",omitempty"` // package cannot be recompiled
52 ForTest string `json:",omitempty"` // package is only for use in named test
53 DepOnly bool `json:",omitempty"` // package is only as a dependency, not explicitly listed
54 Export string `json:",omitempty"` // file containing export data (set by go list -export)
56 // Stale and StaleReason remain here *only* for the list command.
57 // They are only initialized in preparation for list execution.
58 // The regular build determines staleness on the fly during action execution.
59 Stale bool `json:",omitempty"` // would 'go install' do anything for this package?
60 StaleReason string `json:",omitempty"` // why is Stale true?
63 // If you add to this list you MUST add to p.AllFiles (below) too.
64 // Otherwise file name security lists will not apply to any new additions.
65 GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
66 CgoFiles []string `json:",omitempty"` // .go sources files that import "C"
67 IgnoredGoFiles []string `json:",omitempty"` // .go sources ignored due to build constraints
68 CFiles []string `json:",omitempty"` // .c source files
69 CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files
70 MFiles []string `json:",omitempty"` // .m source files
71 HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
72 FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
73 SFiles []string `json:",omitempty"` // .s source files
74 SwigFiles []string `json:",omitempty"` // .swig files
75 SwigCXXFiles []string `json:",omitempty"` // .swigcxx files
76 SysoFiles []string `json:",omitempty"` // .syso system object files added to package
79 CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler
80 CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor
81 CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler
82 CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler
83 CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker
84 CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
86 // Dependency information
87 Imports []string `json:",omitempty"` // import paths used by this package
88 Deps []string `json:",omitempty"` // all (recursively) imported dependencies
91 Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies?
92 Error *PackageError `json:",omitempty"` // error loading this package (not dependencies)
93 DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
96 // If you add to this list you MUST add to p.AllFiles (below) too.
97 // Otherwise file name security lists will not apply to any new additions.
98 TestGoFiles []string `json:",omitempty"` // _test.go files in package
99 TestImports []string `json:",omitempty"` // imports from TestGoFiles
100 XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
101 XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
104 // AllFiles returns the names of all the files considered for the package.
105 // This is used for sanity and security checks, so we include all files,
106 // even IgnoredGoFiles, because some subcommands consider them.
107 // The go/build package filtered others out (like foo_wrongGOARCH.s)
109 func (p *Package) AllFiles() []string {
110 return str.StringList(
128 // Desc returns the package "description", for use in b.showOutput.
129 func (p *Package) Desc() string {
131 return p.ImportPath + " [" + p.ForTest + ".test]"
136 type PackageInternal struct {
137 // Unexported fields are not part of the public API.
139 Imports []*Package // this package's direct imports
140 RawImports []string // this package's original imports as they appear in the text of the program
141 ForceLibrary bool // this package is a library (even if named "main")
142 CmdlineFiles bool // package built from files listed on command line
143 CmdlinePkg bool // package listed on command line
144 Local bool // imported via local path (./ or ../)
145 LocalPrefix string // interpret ./ and ../ imports relative to this prefix
146 ExeName string // desired name for temporary executable
147 CoverMode string // preprocess Go source files with the coverage tool in this mode
148 CoverVars map[string]*CoverVar // variables created by coverage analysis
149 OmitDebug bool // tell linker not to write debug information
150 GobinSubdir bool // install target would be subdir of GOBIN
151 TestmainGo *[]byte // content for _testmain.go
153 Asmflags []string // -asmflags for this package
154 Gcflags []string // -gcflags for this package
155 Ldflags []string // -ldflags for this package
156 Gccgoflags []string // -gccgoflags for this package
159 type NoGoError struct {
163 func (e *NoGoError) Error() string {
164 // Count files beginning with _ and ., which we will pretend don't exist at all.
166 for _, name := range e.Package.IgnoredGoFiles {
167 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
172 if len(e.Package.IgnoredGoFiles) > dummy {
173 // Go files exist, but they were ignored due to build constraints.
174 return "build constraints exclude all Go files in " + e.Package.Dir
176 if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
177 // Test Go files exist, but we're not interested in them.
178 // The double-negative is unfortunate but we want e.Package.Dir
179 // to appear at the end of error message.
180 return "no non-test Go files in " + e.Package.Dir
182 return "no Go files in " + e.Package.Dir
185 // Resolve returns the resolved version of imports,
186 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
187 // The imports in p.TestImports and p.XTestImports are not recursively
188 // loaded during the initial load of p, so they list the imports found in
189 // the source file, but most processing should be over the vendor-resolved
190 // import paths. We do this resolution lazily both to avoid file system work
191 // and because the eventual real load of the test imports (during 'go test')
192 // can produce better error messages if it starts with the original paths.
193 // The initial load of p loads all the non-test imports and rewrites
194 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
195 func (p *Package) Resolve(imports []string) []string {
196 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
197 panic("internal error: p.Resolve(p.Imports) called")
199 seen := make(map[string]bool)
201 for _, path := range imports {
202 path = ResolveImportPath(p, path)
205 all = append(all, path)
212 // CoverVar holds the name of the generated coverage variables targeting the named file.
213 type CoverVar struct {
214 File string // local file name
215 Var string // name of count struct
218 func (p *Package) copyBuild(pp *build.Package) {
219 p.Internal.Build = pp
221 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
222 old := pp.PkgTargetRoot
223 pp.PkgRoot = cfg.BuildPkgdir
224 pp.PkgTargetRoot = cfg.BuildPkgdir
225 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
229 p.ImportPath = pp.ImportPath
230 p.ImportComment = pp.ImportComment
234 p.ConflictDir = pp.ConflictDir
235 p.BinaryOnly = pp.BinaryOnly
239 p.Standard = p.Goroot && p.ImportPath != "" && isStandardImportPath(p.ImportPath)
240 p.GoFiles = pp.GoFiles
241 p.CgoFiles = pp.CgoFiles
242 p.IgnoredGoFiles = pp.IgnoredGoFiles
244 p.CXXFiles = pp.CXXFiles
249 p.SwigFiles = pp.SwigFiles
250 p.SwigCXXFiles = pp.SwigCXXFiles
251 p.SysoFiles = pp.SysoFiles
253 // There's no way for .syso files to be built both with and without
254 // support for memory sanitizer. Assume they are built without,
258 p.CgoCFLAGS = pp.CgoCFLAGS
259 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
260 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
261 p.CgoFFLAGS = pp.CgoFFLAGS
262 p.CgoLDFLAGS = pp.CgoLDFLAGS
263 p.CgoPkgConfig = pp.CgoPkgConfig
264 // We modify p.Imports in place, so make copy now.
265 p.Imports = make([]string, len(pp.Imports))
266 copy(p.Imports, pp.Imports)
267 p.Internal.RawImports = pp.Imports
268 p.TestGoFiles = pp.TestGoFiles
269 p.TestImports = pp.TestImports
270 p.XTestGoFiles = pp.XTestGoFiles
271 p.XTestImports = pp.XTestImports
279 // isStandardImportPath reports whether $GOROOT/src/path should be considered
280 // part of the standard distribution. For historical reasons we allow people to add
281 // their own code to $GOROOT instead of using $GOPATH, but we assume that
282 // code will start with a domain name (dot in the first element).
283 func isStandardImportPath(path string) bool {
284 i := strings.Index(path, "/")
289 return !strings.Contains(elem, ".")
292 // A PackageError describes an error loading information about a package.
293 type PackageError struct {
294 ImportStack []string // shortest path from package named on command line to this one
295 Pos string // position of error
296 Err string // the error itself
297 IsImportCycle bool `json:"-"` // the error is an import cycle
298 Hard bool `json:"-"` // whether the error is soft or hard; soft errors are ignored in some places
301 func (p *PackageError) Error() string {
302 // Import cycles deserve special treatment.
304 return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports "))
307 // Omit import stack. The full path to the file where the error
308 // is the most important thing.
309 return p.Pos + ": " + p.Err
311 if len(p.ImportStack) == 0 {
314 return "package " + strings.Join(p.ImportStack, "\n\timports ") + ": " + p.Err
317 // An ImportStack is a stack of import paths.
318 type ImportStack []string
320 func (s *ImportStack) Push(p string) {
324 func (s *ImportStack) Pop() {
325 *s = (*s)[0 : len(*s)-1]
328 func (s *ImportStack) Copy() []string {
329 return append([]string{}, *s...)
332 // shorterThan reports whether sp is shorter than t.
333 // We use this to record the shortest import sequence
334 // that leads to a particular package.
335 func (sp *ImportStack) shorterThan(t []string) bool {
337 if len(s) != len(t) {
338 return len(s) < len(t)
340 // If they are the same length, settle ties using string ordering.
346 return false // they are equal
349 // packageCache is a lookup cache for loadPackage,
350 // so that if we look up a package multiple times
351 // we return the same pointer each time.
352 var packageCache = map[string]*Package{}
354 func ClearPackageCache() {
355 for name := range packageCache {
356 delete(packageCache, name)
360 func ClearPackageCachePartial(args []string) {
361 for _, arg := range args {
362 p := packageCache[arg]
364 delete(packageCache, p.Dir)
365 delete(packageCache, p.ImportPath)
370 // reloadPackage is like loadPackage but makes sure
371 // not to use the package cache.
372 func ReloadPackage(arg string, stk *ImportStack) *Package {
373 p := packageCache[arg]
375 delete(packageCache, p.Dir)
376 delete(packageCache, p.ImportPath)
378 return LoadPackage(arg, stk)
381 // dirToImportPath returns the pseudo-import path we use for a package
382 // outside the Go path. It begins with _/ and then contains the full path
383 // to the directory. If the package lives in c:\home\gopher\my\pkg then
384 // the pseudo-import path is _/c_/home/gopher/my/pkg.
385 // Using a pseudo-import path like this makes the ./ imports no longer
386 // a special case, so that all the code to deal with ordinary imports works
388 func dirToImportPath(dir string) string {
389 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
392 func makeImportValid(r rune) rune {
393 // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
394 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
395 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
401 // Mode flags for loadImport and download (in get.go).
403 // ResolveImport means that loadImport should do import path expansion.
404 // That is, ResolveImport means that the import path came from
405 // a source file and has not been expanded yet to account for
406 // vendoring or possible module adjustment.
407 // Every import path should be loaded initially with ResolveImport,
408 // and then the expanded version (for example with the /vendor/ in it)
409 // gets recorded as the canonical import path. At that point, future loads
410 // of that package must not pass ResolveImport, because
411 // disallowVendor will reject direct use of paths containing /vendor/.
412 ResolveImport = 1 << iota
414 // ResolveModule is for download (part of "go get") and indicates
415 // that the module adjustment should be done, but not vendor adjustment.
418 // GetTestDeps is for download (part of "go get") and indicates
419 // that test dependencies should be fetched too.
423 // LoadImport scans the directory named by path, which must be an import path,
424 // but possibly a local import path (an absolute file system path or one beginning
425 // with ./ or ../). A local relative path is interpreted relative to srcDir.
426 // It returns a *Package describing the package found in that directory.
427 func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
431 // Determine canonical identifier for this package.
432 // For a local import the identifier is the pseudo-import path
433 // we create from the full directory to the package.
434 // Otherwise it is the usual import path.
435 // For vendored imports, it is the expanded form.
438 isLocal := build.IsLocalImport(path)
440 importPath = dirToImportPath(filepath.Join(srcDir, path))
441 } else if mode&ResolveImport != 0 {
442 // We do our own path resolution, because we want to
443 // find out the key to use in packageCache without the
444 // overhead of repeated calls to buildContext.Import.
445 // The code is also needed in a few other places anyway.
446 path = ResolveImportPath(parent, path)
448 } else if mode&ResolveModule != 0 {
449 path = ModuleImportPath(parent, path)
453 p := packageCache[importPath]
455 p = reusePackage(p, stk)
458 p.Internal.Local = isLocal
459 p.ImportPath = importPath
460 packageCache[importPath] = p
463 // Import always returns bp != nil, even if an error occurs,
464 // in order to return partial information.
465 buildMode := build.ImportComment
466 if mode&ResolveImport == 0 || path != origPath {
467 // Not vendoring, or we already found the vendored path.
468 buildMode |= build.IgnoreVendor
470 bp, err := cfg.BuildContext.Import(path, srcDir, buildMode)
471 bp.ImportPath = importPath
473 bp.BinDir = cfg.GOBIN
475 if err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path &&
476 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
477 err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment)
480 if p.Error != nil && p.Error.Pos == "" {
481 p = setErrorPos(p, importPos)
484 if origPath != cleanImport(origPath) {
485 p.Error = &PackageError{
486 ImportStack: stk.Copy(),
487 Err: fmt.Sprintf("non-canonical import path: %q should be %q", origPath, pathpkg.Clean(origPath)),
493 // Checked on every import because the rules depend on the code doing the importing.
494 if perr := disallowInternal(srcDir, p, stk); perr != p {
495 return setErrorPos(perr, importPos)
497 if mode&ResolveImport != 0 {
498 if perr := disallowVendor(srcDir, origPath, p, stk); perr != p {
499 return setErrorPos(perr, importPos)
503 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
505 perr.Error = &PackageError{
506 ImportStack: stk.Copy(),
507 Err: fmt.Sprintf("import %q is a program, not an importable package", path),
509 return setErrorPos(&perr, importPos)
512 if p.Internal.Local && parent != nil && !parent.Internal.Local {
514 perr.Error = &PackageError{
515 ImportStack: stk.Copy(),
516 Err: fmt.Sprintf("local import %q in non-local package", path),
518 return setErrorPos(&perr, importPos)
524 func setErrorPos(p *Package, importPos []token.Position) *Package {
525 if len(importPos) > 0 {
527 pos.Filename = base.ShortPath(pos.Filename)
528 p.Error.Pos = pos.String()
533 func cleanImport(path string) string {
535 path = pathpkg.Clean(path)
536 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
542 var isDirCache = map[string]bool{}
544 func isDir(path string) bool {
545 result, ok := isDirCache[path]
550 fi, err := os.Stat(path)
551 result = err == nil && fi.IsDir()
552 isDirCache[path] = result
556 // ResolveImportPath returns the true meaning of path when it appears in parent.
557 // There are two different resolutions applied.
558 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
559 // If vendor expansion doesn't trigger, then the path is also subject to
560 // Go 1.11 vgo legacy conversion (golang.org/issue/25069).
561 func ResolveImportPath(parent *Package, path string) (found string) {
562 found = VendoredImportPath(parent, path)
566 return ModuleImportPath(parent, path)
569 // dirAndRoot returns the source directory and workspace root
570 // for the package p, guaranteeing that root is a path prefix of dir.
571 func dirAndRoot(p *Package) (dir, root string) {
572 dir = filepath.Clean(p.Dir)
573 root = filepath.Join(p.Root, "src")
574 if !str.HasFilePathPrefix(dir, root) || p.ImportPath != "command-line-arguments" && filepath.Join(root, p.ImportPath) != dir {
575 // Look for symlinks before reporting error.
576 dir = expandPath(dir)
577 root = expandPath(root)
580 if !str.HasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || p.ImportPath != "command-line-arguments" && !p.Internal.Local && filepath.Join(root, p.ImportPath) != dir {
581 base.Fatalf("unexpected directory layout:\n"+
582 " import path: %s\n"+
585 " expand root: %s\n"+
589 filepath.Join(p.Root, "src"),
590 filepath.Clean(p.Dir),
593 string(filepath.Separator))
599 // VendoredImportPath returns the vendor-expansion of path when it appears in parent.
600 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
601 // x/vendor/path, vendor/path, or else stay path if none of those exist.
602 // VendoredImportPath returns the expanded path or, if no expansion is found, the original.
603 func VendoredImportPath(parent *Package, path string) (found string) {
604 if parent == nil || parent.Root == "" {
608 dir, root := dirAndRoot(parent)
610 vpath := "vendor/" + path
611 for i := len(dir); i >= len(root); i-- {
612 if i < len(dir) && dir[i] != filepath.Separator {
615 // Note: checking for the vendor directory before checking
616 // for the vendor/path directory helps us hit the
617 // isDir cache more often. It also helps us prepare a more useful
618 // list of places we looked, to report when an import is not found.
619 if !isDir(filepath.Join(dir[:i], "vendor")) {
622 targ := filepath.Join(dir[:i], vpath)
623 if isDir(targ) && hasGoFiles(targ) {
624 importPath := parent.ImportPath
625 if importPath == "command-line-arguments" {
626 // If parent.ImportPath is 'command-line-arguments'.
627 // set to relative directory to root (also chopped root directory)
628 importPath = dir[len(root)+1:]
630 // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
631 // We know the import path for parent's dir.
632 // We chopped off some number of path elements and
633 // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
634 // Now we want to know the import path for that directory.
635 // Construct it by chopping the same number of path elements
636 // (actually the same number of bytes) from parent's import path
637 // and then append /vendor/path.
638 chopped := len(dir) - i
639 if chopped == len(importPath)+1 {
640 // We walked up from c:\gopath\src\foo\bar
641 // and found c:\gopath\src\vendor\path.
642 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
643 // Use "vendor/path" without any prefix.
646 return importPath[:len(importPath)-chopped] + "/" + vpath
653 modulePrefix = []byte("\nmodule ")
654 goModPathCache = make(map[string]string)
657 // goModPath returns the module path in the go.mod in dir, if any.
658 func goModPath(dir string) (path string) {
659 path, ok := goModPathCache[dir]
664 goModPathCache[dir] = path
667 data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
672 if bytes.HasPrefix(data, modulePrefix[1:]) {
675 i = bytes.Index(data, modulePrefix)
683 // Cut line at \n, drop trailing \r if present.
684 if j := bytes.IndexByte(line, '\n'); j >= 0 {
687 if line[len(line)-1] == '\r' {
688 line = line[:len(line)-1]
690 line = line[len("module "):]
692 // If quoted, unquote.
693 path = strings.TrimSpace(string(line))
694 if path != "" && path[0] == '"' {
695 s, err := strconv.Unquote(path)
704 // findVersionElement returns the slice indices of the final version element /vN in path.
705 // If there is no such element, it returns -1, -1.
706 func findVersionElement(path string) (i, j int) {
708 for i = len(path) - 1; i >= 0; i-- {
710 if isVersionElement(path[i:j]) {
719 // isVersionElement reports whether s is a well-formed path version element:
720 // v2, v3, v10, etc, but not v0, v05, v1.
721 func isVersionElement(s string) bool {
722 if len(s) < 3 || s[0] != '/' || s[1] != 'v' || s[2] == '0' || s[2] == '1' && len(s) == 3 {
725 for i := 2; i < len(s); i++ {
726 if s[i] < '0' || '9' < s[i] {
733 // ModuleImportPath translates import paths found in go modules
734 // back down to paths that can be resolved in ordinary builds.
736 // Define “new” code as code with a go.mod file in the same directory
737 // or a parent directory. If an import in new code says x/y/v2/z but
738 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
739 // then go build will read the import as x/y/z instead.
740 // See golang.org/issue/25069.
741 func ModuleImportPath(parent *Package, path string) (found string) {
742 if parent == nil || parent.Root == "" {
746 // If there are no vN elements in path, leave it alone.
747 // (The code below would do the same, but only after
748 // some other file system accesses that we can avoid
749 // here by returning early.)
750 if i, _ := findVersionElement(path); i < 0 {
754 dir, root := dirAndRoot(parent)
756 // Consider dir and parents, up to and including root.
757 for i := len(dir); i >= len(root); i-- {
758 if i < len(dir) && dir[i] != filepath.Separator {
761 if goModPath(dir[:i]) != "" {
765 // This code is not in a tree with a go.mod,
766 // so apply no changes to the path.
770 // This import is in a tree with a go.mod.
771 // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
772 // if GOPATH/src/x/y/go.mod says module "x/y/v2",
774 // If x/y/v2/z exists, use it unmodified.
775 if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
779 // Otherwise look for a go.mod supplying a version element.
780 // Some version-like elements may appear in paths but not
781 // be module versions; we skip over those to look for module
782 // versions. For example the module m/v2 might have a
783 // package m/v2/api/v1/foo.
786 i, j := findVersionElement(path[:limit])
790 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
791 if mpath := goModPath(bp.Dir); mpath != "" {
792 // Found a valid go.mod file, so we're stopping the search.
793 // If the path is m/v2/p and we found m/go.mod that says
794 // "module m/v2", then we return "m/p".
795 if mpath == path[:j] {
796 return path[:i] + path[j:]
798 // Otherwise just return the original path.
799 // We didn't find anything worth rewriting,
800 // and the go.mod indicates that we should
801 // not consider parent directories.
810 // hasGoFiles reports whether dir contains any files with names ending in .go.
811 // For a vendor check we must exclude directories that contain no .go files.
812 // Otherwise it is not possible to vendor just a/b/c and still import the
813 // non-vendored a/b. See golang.org/issue/13832.
814 func hasGoFiles(dir string) bool {
815 fis, _ := ioutil.ReadDir(dir)
816 for _, fi := range fis {
817 if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
824 // reusePackage reuses package p to satisfy the import at the top
825 // of the import stack stk. If this use causes an import loop,
826 // reusePackage updates p's error information to record the loop.
827 func reusePackage(p *Package, stk *ImportStack) *Package {
828 // We use p.Internal.Imports==nil to detect a package that
829 // is in the midst of its own loadPackage call
830 // (all the recursion below happens before p.Internal.Imports gets set).
831 if p.Internal.Imports == nil {
833 p.Error = &PackageError{
834 ImportStack: stk.Copy(),
835 Err: "import cycle not allowed",
841 // Don't rewrite the import stack in the error if we have an import cycle.
842 // If we do, we'll lose the path that describes the cycle.
843 if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
844 p.Error.ImportStack = stk.Copy()
849 // disallowInternal checks that srcDir is allowed to import p.
850 // If the import is allowed, disallowInternal returns the original package p.
851 // If not, it returns a new package containing just an appropriate error.
852 func disallowInternal(srcDir string, p *Package, stk *ImportStack) *Package {
853 // golang.org/s/go14internal:
854 // An import of a path containing the element “internal”
855 // is disallowed if the importing code is outside the tree
856 // rooted at the parent of the “internal” directory.
858 // There was an error loading the package; stop here.
863 // The generated 'testmain' package is allowed to access testing/internal/...,
864 // as if it were generated into the testing directory tree
865 // (it's actually in a temporary directory outside any Go tree).
866 // This cleans up a former kludge in passing functionality to the testing package.
867 if strings.HasPrefix(p.ImportPath, "testing/internal") && len(*stk) >= 2 && (*stk)[len(*stk)-2] == "testmain" {
871 // We can't check standard packages with gccgo.
872 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
876 // The stack includes p.ImportPath.
877 // If that's the only thing on the stack, we started
878 // with a name given on the command line, not an
879 // import. Anything listed on the command line is fine.
884 // Check for "internal" element: three cases depending on begin of string and/or end of string.
885 i, ok := findInternal(p.ImportPath)
890 // Internal is present.
891 // Map import path back to directory corresponding to parent of internal.
893 i-- // rewind over slash in ".../internal"
895 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
896 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
900 // Look for symlinks before reporting error.
901 srcDir = expandPath(srcDir)
902 parent = expandPath(parent)
903 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
907 // Internal is present, and srcDir is outside parent's tree. Not allowed.
909 perr.Error = &PackageError{
910 ImportStack: stk.Copy(),
911 Err: "use of internal package not allowed",
913 perr.Incomplete = true
917 // findInternal looks for the final "internal" path element in the given import path.
918 // If there isn't one, findInternal returns ok=false.
919 // Otherwise, findInternal returns ok=true and the index of the "internal".
920 func findInternal(path string) (index int, ok bool) {
921 // Three cases, depending on internal at start/end of string or not.
922 // The order matters: we must return the index of the final element,
923 // because the final one produces the most restrictive requirement
926 case strings.HasSuffix(path, "/internal"):
927 return len(path) - len("internal"), true
928 case strings.Contains(path, "/internal/"):
929 return strings.LastIndex(path, "/internal/") + 1, true
930 case path == "internal", strings.HasPrefix(path, "internal/"):
936 // disallowVendor checks that srcDir is allowed to import p as path.
937 // If the import is allowed, disallowVendor returns the original package p.
938 // If not, it returns a new package containing just an appropriate error.
939 func disallowVendor(srcDir, path string, p *Package, stk *ImportStack) *Package {
940 // The stack includes p.ImportPath.
941 // If that's the only thing on the stack, we started
942 // with a name given on the command line, not an
943 // import. Anything listed on the command line is fine.
948 if perr := disallowVendorVisibility(srcDir, p, stk); perr != p {
952 // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
953 if i, ok := FindVendor(path); ok {
955 perr.Error = &PackageError{
956 ImportStack: stk.Copy(),
957 Err: "must be imported as " + path[i+len("vendor/"):],
959 perr.Incomplete = true
966 // disallowVendorVisibility checks that srcDir is allowed to import p.
967 // The rules are the same as for /internal/ except that a path ending in /vendor
968 // is not subject to the rules, only subdirectories of vendor.
969 // This allows people to have packages and commands named vendor,
970 // for maximal compatibility with existing source trees.
971 func disallowVendorVisibility(srcDir string, p *Package, stk *ImportStack) *Package {
972 // The stack includes p.ImportPath.
973 // If that's the only thing on the stack, we started
974 // with a name given on the command line, not an
975 // import. Anything listed on the command line is fine.
980 // Check for "vendor" element.
981 i, ok := FindVendor(p.ImportPath)
986 // Vendor is present.
987 // Map import path back to directory corresponding to parent of vendor.
989 i-- // rewind over slash in ".../vendor"
991 truncateTo := i + len(p.Dir) - len(p.ImportPath)
992 if truncateTo < 0 || len(p.Dir) < truncateTo {
995 parent := p.Dir[:truncateTo]
996 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1000 // Look for symlinks before reporting error.
1001 srcDir = expandPath(srcDir)
1002 parent = expandPath(parent)
1003 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1007 // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1009 perr.Error = &PackageError{
1010 ImportStack: stk.Copy(),
1011 Err: "use of vendored package not allowed",
1013 perr.Incomplete = true
1017 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1018 // If there isn't one, FindVendor returns ok=false.
1019 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1021 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1022 // not the vendored copy of an import "" (the empty import path).
1023 // This will allow people to have packages or commands named vendor.
1024 // This may help reduce breakage, or it may just be confusing. We'll see.
1025 func FindVendor(path string) (index int, ok bool) {
1026 // Two cases, depending on internal at start of string or not.
1027 // The order matters: we must return the index of the final element,
1028 // because the final one is where the effective import path starts.
1030 case strings.Contains(path, "/vendor/"):
1031 return strings.LastIndex(path, "/vendor/") + 1, true
1032 case strings.HasPrefix(path, "vendor/"):
1041 ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1042 ToBin // to bin dir inside package root (default for non-cmd/*)
1043 StalePath // an old import path; fail to build
1046 // InstallTargetDir reports the target directory for installing the command p.
1047 func InstallTargetDir(p *Package) TargetDir {
1048 if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1051 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1052 switch p.ImportPath {
1053 case "cmd/go", "cmd/gofmt":
1061 var cgoExclude = map[string]bool{
1062 "runtime/cgo": true,
1065 var cgoSyscallExclude = map[string]bool{
1066 "runtime/cgo": true,
1067 "runtime/race": true,
1068 "runtime/msan": true,
1071 var foldPath = make(map[string]string)
1073 // load populates p using information from bp, err, which should
1074 // be the result of calling build.Context.Import.
1075 func (p *Package) load(stk *ImportStack, bp *build.Package, err error) {
1078 // Decide whether p was listed on the command line.
1079 // Given that load is called while processing the command line,
1080 // you might think we could simply pass a flag down into load
1081 // saying whether we are loading something named on the command
1082 // line or something to satisfy an import. But the first load of a
1083 // package named on the command line may be as a dependency
1084 // of an earlier package named on the command line, not when we
1085 // get to that package during command line processing.
1086 // For example "go test fmt reflect" will load reflect as a dependency
1087 // of fmt before it attempts to load as a command-line argument.
1088 // Because loads are cached, the later load will be a no-op,
1089 // so it is important that the first load can fill in CmdlinePkg correctly.
1090 // Hence the call to an explicit matching check here.
1091 p.Internal.CmdlinePkg = isCmdlinePkg(p)
1093 p.Internal.Asmflags = BuildAsmflags.For(p)
1094 p.Internal.Gcflags = BuildGcflags.For(p)
1095 p.Internal.Ldflags = BuildLdflags.For(p)
1096 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
1098 // The localPrefix is the path we interpret ./ imports relative to.
1099 // Synthesized main packages sometimes override this.
1100 if p.Internal.Local {
1101 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1105 if _, ok := err.(*build.NoGoError); ok {
1106 err = &NoGoError{Package: p}
1109 err = base.ExpandScanner(err)
1110 p.Error = &PackageError{
1111 ImportStack: stk.Copy(),
1117 useBindir := p.Name == "main"
1119 switch cfg.BuildBuildmode {
1120 case "c-archive", "c-shared", "plugin":
1126 // Report an error when the old code.google.com/p/go.tools paths are used.
1127 if InstallTargetDir(p) == StalePath {
1128 newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1129 e := fmt.Sprintf("the %v command has moved; use %v instead.", p.ImportPath, newPath)
1130 p.Error = &PackageError{Err: e}
1133 _, elem := filepath.Split(p.Dir)
1134 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1135 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1136 // Install cross-compiled binaries to subdirectories of bin.
1139 if p.Internal.Build.BinDir != "" {
1140 // Install to GOBIN or bin of GOPATH entry.
1141 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1142 if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1143 // Do not create $GOBIN/goos_goarch/elem.
1145 p.Internal.GobinSubdir = true
1148 if InstallTargetDir(p) == ToTool {
1149 // This is for 'go tool'.
1150 // Override all the usual logic and force it into the tool directory.
1151 if cfg.BuildToolchainName == "gccgo" {
1152 p.Target = filepath.Join(base.ToolDir, elem)
1154 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1157 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1160 } else if p.Internal.Local {
1161 // Local import turned into absolute path.
1162 // No permanent install target.
1165 p.Target = p.Internal.Build.PkgObj
1166 if cfg.BuildLinkshared {
1167 shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1168 shlib, err := ioutil.ReadFile(shlibnamefile)
1169 if err != nil && !os.IsNotExist(err) {
1170 base.Fatalf("reading shlibname: %v", err)
1173 libname := strings.TrimSpace(string(shlib))
1174 if cfg.BuildContext.Compiler == "gccgo" {
1175 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1177 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1183 // Build augmented import list to add implicit dependencies.
1184 // Be careful not to add imports twice, just to avoid confusion.
1185 importPaths := p.Imports
1186 addImport := func(path string) {
1187 for _, p := range importPaths {
1192 importPaths = append(importPaths, path)
1195 // Cgo translation adds imports of "runtime/cgo" and "syscall",
1196 // except for certain packages, to avoid circular dependencies.
1197 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1198 addImport("runtime/cgo")
1200 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1201 addImport("syscall")
1204 // SWIG adds imports of some standard packages.
1206 if cfg.BuildContext.Compiler != "gccgo" {
1207 addImport("runtime/cgo")
1209 addImport("syscall")
1212 // TODO: The .swig and .swigcxx files can use
1213 // %go_import directives to import other packages.
1216 // The linker loads implicit dependencies.
1217 if p.Name == "main" && !p.Internal.ForceLibrary {
1218 for _, dep := range LinkerDeps(p) {
1223 // Check for case-insensitive collision of input files.
1224 // To avoid problems on case-insensitive files, we reject any package
1225 // where two different input files have equal names under a case-insensitive
1227 inputs := p.AllFiles()
1228 f1, f2 := str.FoldDup(inputs)
1230 p.Error = &PackageError{
1231 ImportStack: stk.Copy(),
1232 Err: fmt.Sprintf("case-insensitive file name collision: %q and %q", f1, f2),
1237 // If first letter of input file is ASCII, it must be alphanumeric.
1238 // This avoids files turning into flags when invoking commands,
1239 // and other problems we haven't thought of yet.
1240 // Also, _cgo_ files must be generated by us, not supplied.
1241 // They are allowed to have //go:cgo_ldflag directives.
1242 // The directory scan ignores files beginning with _,
1243 // so we shouldn't see any _cgo_ files anyway, but just be safe.
1244 for _, file := range inputs {
1245 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1246 p.Error = &PackageError{
1247 ImportStack: stk.Copy(),
1248 Err: fmt.Sprintf("invalid input file name %q", file),
1253 if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1254 p.Error = &PackageError{
1255 ImportStack: stk.Copy(),
1256 Err: fmt.Sprintf("invalid input directory name %q", name),
1260 if !SafeArg(p.ImportPath) {
1261 p.Error = &PackageError{
1262 ImportStack: stk.Copy(),
1263 Err: fmt.Sprintf("invalid import path %q", p.ImportPath),
1268 // Build list of imported packages and full dependency list.
1269 imports := make([]*Package, 0, len(p.Imports))
1270 for i, path := range importPaths {
1274 p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1275 if p.Standard && p.Error == nil && !p1.Standard && p1.Error == nil {
1276 p.Error = &PackageError{
1277 ImportStack: stk.Copy(),
1278 Err: fmt.Sprintf("non-standard import %q in standard package %q", path, p.ImportPath),
1280 pos := p.Internal.Build.ImportPos[path]
1282 p.Error.Pos = pos[0].String()
1286 path = p1.ImportPath
1287 importPaths[i] = path
1288 if i < len(p.Imports) {
1292 imports = append(imports, p1)
1297 p.Internal.Imports = imports
1299 deps := make(map[string]*Package)
1301 q = append(q, imports...)
1302 for i := 0; i < len(q); i++ {
1304 path := p1.ImportPath
1305 // The same import path could produce an error or not,
1306 // depending on what tries to import it.
1307 // Prefer to record entries with errors, so we can report them.
1309 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
1311 for _, p2 := range p1.Internal.Imports {
1312 if deps[p2.ImportPath] != p2 {
1319 p.Deps = make([]string, 0, len(deps))
1320 for dep := range deps {
1321 p.Deps = append(p.Deps, dep)
1323 sort.Strings(p.Deps)
1324 for _, dep := range p.Deps {
1327 panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
1329 if p1.Error != nil {
1330 p.DepsErrors = append(p.DepsErrors, p1.Error)
1334 // unsafe is a fake package.
1335 if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1339 // If cgo is not enabled, ignore cgo supporting sources
1340 // just as we ignore go files containing import "C".
1341 if !cfg.BuildContext.CgoEnabled {
1346 p.SwigCXXFiles = nil
1347 // Note that SFiles are okay (they go to the Go assembler)
1348 // and HFiles are okay (they might be used by the SFiles).
1349 // Also Sysofiles are okay (they might not contain object
1350 // code; see issue #16050).
1353 setError := func(msg string) {
1354 p.Error = &PackageError{
1355 ImportStack: stk.Copy(),
1360 // The gc toolchain only permits C source files with cgo or SWIG.
1361 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1362 setError(fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1366 // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1367 // regardless of toolchain.
1368 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1369 setError(fmt.Sprintf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1372 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1373 setError(fmt.Sprintf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1376 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1377 setError(fmt.Sprintf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1381 // Check for case-insensitive collisions of import paths.
1382 fold := str.ToFold(p.ImportPath)
1383 if other := foldPath[fold]; other == "" {
1384 foldPath[fold] = p.ImportPath
1385 } else if other != p.ImportPath {
1386 setError(fmt.Sprintf("case-insensitive import collision: %q and %q", p.ImportPath, other))
1391 // SafeArg reports whether arg is a "safe" command-line argument,
1392 // meaning that when it appears in a command-line, it probably
1393 // doesn't have some special meaning other than its own name.
1394 // Obviously args beginning with - are not safe (they look like flags).
1395 // Less obviously, args beginning with @ are not safe (they look like
1396 // GNU binutils flagfile specifiers, sometimes called "response files").
1397 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
1398 // We accept leading . _ and / as likely in file system paths.
1399 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
1400 func SafeArg(name string) bool {
1405 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1408 // LinkerDeps returns the list of linker-induced dependencies for main package p.
1409 func LinkerDeps(p *Package) []string {
1410 // Everything links runtime.
1411 deps := []string{"runtime"}
1413 // External linking mode forces an import of runtime/cgo.
1414 if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
1415 deps = append(deps, "runtime/cgo")
1417 // On ARM with GOARM=5, it forces an import of math, for soft floating point.
1418 if cfg.Goarch == "arm" {
1419 deps = append(deps, "math")
1421 // Using the race detector forces an import of runtime/race.
1423 deps = append(deps, "runtime/race")
1425 // Using memory sanitizer forces an import of runtime/msan.
1427 deps = append(deps, "runtime/msan")
1433 // externalLinkingForced reports whether external linking is being
1434 // forced even for programs that do not use cgo.
1435 func externalLinkingForced(p *Package) bool {
1436 // Some targets must use external linking even inside GOROOT.
1437 switch cfg.BuildContext.GOOS {
1441 switch cfg.BuildContext.GOARCH {
1442 case "arm", "arm64":
1447 if !cfg.BuildContext.CgoEnabled {
1450 // Currently build modes c-shared, pie (on systems that do not
1451 // support PIE with internal linking mode (currently all
1452 // systems: issue #18968)), plugin, and -linkshared force
1453 // external linking mode, as of course does
1454 // -ldflags=-linkmode=external. External linking mode forces
1455 // an import of runtime/cgo.
1456 pieCgo := cfg.BuildBuildmode == "pie"
1457 linkmodeExternal := false
1459 ldflags := BuildLdflags.For(p)
1460 for i, a := range ldflags {
1461 if a == "-linkmode=external" {
1462 linkmodeExternal = true
1464 if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
1465 linkmodeExternal = true
1470 return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
1473 // mkAbs rewrites list, which must be paths relative to p.Dir,
1474 // into a sorted list of absolute paths. It edits list in place but for
1475 // convenience also returns list back to its caller.
1476 func (p *Package) mkAbs(list []string) []string {
1477 for i, f := range list {
1478 list[i] = filepath.Join(p.Dir, f)
1484 // InternalGoFiles returns the list of Go files being built for the package,
1485 // using absolute paths.
1486 func (p *Package) InternalGoFiles() []string {
1487 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
1490 // InternalXGoFiles returns the list of Go files being built for the XTest package,
1491 // using absolute paths.
1492 func (p *Package) InternalXGoFiles() []string {
1493 return p.mkAbs(p.XTestGoFiles)
1496 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
1497 // using absolute paths. "Possibly relevant" means that files are not excluded
1498 // due to build tags, but files with names beginning with . or _ are still excluded.
1499 func (p *Package) InternalAllGoFiles() []string {
1501 for _, f := range p.IgnoredGoFiles {
1502 if f != "" && f[0] != '.' || f[0] != '_' {
1503 extra = append(extra, f)
1506 return p.mkAbs(str.StringList(extra, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
1509 // usesSwig reports whether the package needs to run SWIG.
1510 func (p *Package) UsesSwig() bool {
1511 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
1514 // usesCgo reports whether the package needs to run cgo
1515 func (p *Package) UsesCgo() bool {
1516 return len(p.CgoFiles) > 0
1519 // packageList returns the list of packages in the dag rooted at roots
1520 // as visited in a depth-first post-order traversal.
1521 func PackageList(roots []*Package) []*Package {
1522 seen := map[*Package]bool{}
1524 var walk func(*Package)
1525 walk = func(p *Package) {
1530 for _, p1 := range p.Internal.Imports {
1533 all = append(all, p)
1535 for _, root := range roots {
1541 var cmdCache = map[string]*Package{}
1543 func ClearCmdCache() {
1544 for name := range cmdCache {
1545 delete(cmdCache, name)
1549 // loadPackage is like loadImport but is used for command-line arguments,
1550 // not for paths found in import statements. In addition to ordinary import paths,
1551 // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands
1552 // in the Go command directory, as well as paths to those directories.
1553 func LoadPackage(arg string, stk *ImportStack) *Package {
1554 if build.IsLocalImport(arg) {
1556 if !filepath.IsAbs(dir) {
1557 if abs, err := filepath.Abs(dir); err == nil {
1558 // interpret relative to current directory
1562 if sub, ok := hasSubdir(cfg.GOROOTsrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") {
1566 if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") {
1567 if p := cmdCache[arg]; p != nil {
1573 bp, err := cfg.BuildContext.ImportDir(filepath.Join(cfg.GOROOTsrc, arg), 0)
1576 bp.BinDir = cfg.GOROOTbin
1577 if cfg.GOROOTbin != "" {
1578 bp.BinDir = cfg.GOROOTbin
1580 bp.Root = cfg.GOROOT
1581 bp.SrcRoot = cfg.GOROOTsrc
1584 p.load(stk, bp, err)
1585 if p.Error == nil && p.Name != "main" {
1586 p.Error = &PackageError{
1587 ImportStack: stk.Copy(),
1588 Err: fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir),
1594 // Wasn't a command; must be a package.
1595 // If it is a local import path but names a standard package,
1596 // we treat it as if the user specified the standard package.
1597 // This lets you run go test ./ioutil in package io and be
1598 // referring to io/ioutil rather than a hypothetical import of
1600 if build.IsLocalImport(arg) {
1601 bp, _ := cfg.BuildContext.ImportDir(filepath.Join(base.Cwd, arg), build.FindOnly)
1602 if bp.ImportPath != "" && bp.ImportPath != "." {
1607 return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
1610 // packages returns the packages named by the
1611 // command line arguments 'args'. If a named package
1612 // cannot be loaded at all (for example, if the directory does not exist),
1613 // then packages prints an error and does not include that
1614 // package in the results. However, if errors occur trying
1615 // to load dependencies of a named package, the named
1616 // package is still returned, with p.Incomplete = true
1617 // and details in p.DepsErrors.
1618 func Packages(args []string) []*Package {
1620 for _, pkg := range PackagesAndErrors(args) {
1621 if pkg.Error != nil {
1622 base.Errorf("can't load package: %s", pkg.Error)
1625 pkgs = append(pkgs, pkg)
1630 // packagesAndErrors is like 'packages' but returns a
1631 // *Package for every argument, even the ones that
1632 // cannot be loaded at all.
1633 // The packages that fail to load will have p.Error != nil.
1634 func PackagesAndErrors(args []string) []*Package {
1635 if len(args) > 0 && strings.HasSuffix(args[0], ".go") {
1636 return []*Package{GoFilesPackage(args)}
1639 args = ImportPaths(args)
1643 seenArg = make(map[string]bool)
1644 seenPkg = make(map[*Package]bool)
1647 for _, arg := range args {
1652 pkg := LoadPackage(arg, &stk)
1657 pkgs = append(pkgs, pkg)
1663 // packagesForBuild is like 'packages' but fails if any of
1664 // the packages or their dependencies have errors
1665 // (cannot be built).
1666 func PackagesForBuild(args []string) []*Package {
1667 pkgs := PackagesAndErrors(args)
1668 printed := map[*PackageError]bool{}
1669 for _, pkg := range pkgs {
1670 if pkg.Error != nil {
1671 base.Errorf("can't load package: %s", pkg.Error)
1672 printed[pkg.Error] = true
1674 for _, err := range pkg.DepsErrors {
1675 // Since these are errors in dependencies,
1676 // the same error might show up multiple times,
1677 // once in each package that depends on it.
1678 // Only print each once.
1681 base.Errorf("%s", err)
1687 // Check for duplicate loads of the same package.
1688 // That should be impossible, but if it does happen then
1689 // we end up trying to build the same package twice,
1690 // usually in parallel overwriting the same files,
1691 // which doesn't work very well.
1692 seen := map[string]bool{}
1693 reported := map[string]bool{}
1694 for _, pkg := range PackageList(pkgs) {
1695 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
1696 reported[pkg.ImportPath] = true
1697 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
1699 seen[pkg.ImportPath] = true
1706 // GoFilesPackage creates a package for building a collection of Go files
1707 // (typically named on the command line). The target is named p.a for
1708 // package p or named after the first Go file for package main.
1709 func GoFilesPackage(gofiles []string) *Package {
1710 // TODO: Remove this restriction.
1711 for _, f := range gofiles {
1712 if !strings.HasSuffix(f, ".go") {
1713 base.Fatalf("named files must be .go files")
1718 ctxt := cfg.BuildContext
1719 ctxt.UseAllFiles = true
1721 // Synthesize fake "directory" that only shows the named files,
1722 // to make it look like this is a standard package or
1723 // command directory. So that local imports resolve
1724 // consistently, the files must all be in the same directory.
1725 var dirent []os.FileInfo
1727 for _, file := range gofiles {
1728 fi, err := os.Stat(file)
1730 base.Fatalf("%s", err)
1733 base.Fatalf("%s is a directory, should be a Go file", file)
1735 dir1, _ := filepath.Split(file)
1741 } else if dir != dir1 {
1742 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
1744 dirent = append(dirent, fi)
1746 ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
1752 dir, err = filepath.Abs(dir)
1754 base.Fatalf("%s", err)
1757 bp, err := ctxt.ImportDir(dir, 0)
1759 pkg.Internal.Local = true
1760 pkg.Internal.CmdlineFiles = true
1762 pkg.load(&stk, bp, err)
1764 pkg.Internal.LocalPrefix = dirToImportPath(dir)
1765 pkg.ImportPath = "command-line-arguments"
1768 if pkg.Name == "main" {
1769 _, elem := filepath.Split(gofiles[0])
1770 exe := elem[:len(elem)-len(".go")] + cfg.ExeSuffix
1771 if cfg.BuildO == "" {
1774 if cfg.GOBIN != "" {
1775 pkg.Target = filepath.Join(cfg.GOBIN, exe)