Documentation ¶
Overview ¶
Package load loads packages.
Index ¶
- Constants
- Variables
- func CheckPackageErrors(pkgs []*Package)
- func ClearPackageCache()
- func ClearPackageCachePartial(args []string)
- func FindVendor(path string) (index int, ok bool)
- func LinkerDeps(p *Package) []string
- func MatchPackage(pattern, cwd string) func(*Package) bool
- func ResolveImportPath(parent *Package, path string) (found string)
- func SafeArg(name string) bool
- type CoverVar
- type ImportPathError
- type ImportStack
- type NoGoError
- type Package
- func GoFilesPackage(ctx context.Context, gofiles []string) *Package
- func LoadImport(ctx context.Context, path, srcDir string, parent *Package, stk *ImportStack, ...) *Package
- func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, ...) *Package
- func PackageList(roots []*Package) []*Package
- func PackagesAndErrors(ctx context.Context, patterns []string) []*Package
- func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package
- func TestPackageList(ctx context.Context, roots []*Package) []*Package
- func TestPackagesAndErrors(ctx context.Context, p *Package, cover *TestCover) (pmain, ptest, pxtest *Package)
- func TestPackagesFor(ctx context.Context, p *Package, cover *TestCover) (pmain, ptest, pxtest *Package, err error)
- func (p *Package) AllFiles() []string
- func (p *Package) DefaultExecName() string
- func (p *Package) Desc() string
- func (p *Package) InternalAllGoFiles() []string
- func (p *Package) InternalGoFiles() []string
- func (p *Package) InternalXGoFiles() []string
- func (p *Package) Resolve(imports []string) []string
- func (p *Package) ResolveEmbed(patterns []string) []string
- func (p *Package) UsesCgo() bool
- func (p *Package) UsesSwig() bool
- type PackageError
- type PackageInternal
- type PackagePublic
- type PerPackageFlag
- type TargetDir
- type TestCover
Constants ¶
const ( // ResolveImport means that loadImport should do import path expansion. // That is, ResolveImport means that the import path came from // a source file and has not been expanded yet to account for // vendoring or possible module adjustment. // Every import path should be loaded initially with ResolveImport, // and then the expanded version (for example with the /vendor/ in it) // gets recorded as the canonical import path. At that point, future loads // of that package must not pass ResolveImport, because // disallowVendor will reject direct use of paths containing /vendor/. ResolveImport = 1 << iota // ResolveModule is for download (part of "go get") and indicates // that the module adjustment should be done, but not vendor adjustment. ResolveModule // GetTestDeps is for download (part of "go get") and indicates // that test dependencies should be fetched too. GetTestDeps )
Mode flags for loadImport and download (in get.go).
Variables ¶
var IgnoreImports bool // control whether we ignore imports in packages
var ModResolveTests bool
ModResolveTests indicates whether calls to the module loader should also resolve test dependencies of the requested packages.
If ModResolveTests is true, then the module loader needs to resolve test dependencies at the same time as packages; otherwise, the test dependencies of those packages could be missing, and resolving those missing dependencies could change the selected versions of modules that provide other packages.
TODO(#40775): Change this from a global variable to an explicit function argument where needed.
var TestMainDeps = []string{
"os",
"reflect",
"testing",
"testing/internal/testdeps",
}
Functions ¶
func CheckPackageErrors ¶ added in go1.16
func CheckPackageErrors(pkgs []*Package)
CheckPackageErrors prints errors encountered loading pkgs and their dependencies, then exits with a non-zero status if any errors were found.
func ClearPackageCache ¶
func ClearPackageCache()
ClearPackageCache clears the in-memory package cache and the preload caches. It is only for use by GOPATH-based "go get". TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
func ClearPackageCachePartial ¶
func ClearPackageCachePartial(args []string)
ClearPackageCachePartial clears packages with the given import paths from the in-memory package cache and the preload caches. It is only for use by GOPATH-based "go get". TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
func FindVendor ¶
FindVendor looks for the last non-terminating "vendor" path element in the given import path. If there isn't one, FindVendor returns ok=false. Otherwise, FindVendor returns ok=true and the index of the "vendor".
Note that terminating "vendor" elements don't count: "x/vendor" is its own package, not the vendored copy of an import "" (the empty import path). This will allow people to have packages or commands named vendor. This may help reduce breakage, or it may just be confusing. We'll see.
func LinkerDeps ¶ added in go1.10
LinkerDeps returns the list of linker-induced dependencies for main package p.
func MatchPackage ¶ added in go1.10
MatchPackage(pattern, cwd)(p) reports whether package p matches pattern in the working directory cwd.
func ResolveImportPath ¶ added in go1.9.7
ResolveImportPath returns the true meaning of path when it appears in parent. There are two different resolutions applied. First, there is Go 1.5 vendoring (golang.org/s/go15vendor). If vendor expansion doesn't trigger, then the path is also subject to Go 1.11 module legacy conversion (golang.org/issue/25069).
func SafeArg ¶ added in go1.9.4
SafeArg reports whether arg is a "safe" command-line argument, meaning that when it appears in a command-line, it probably doesn't have some special meaning other than its own name. Obviously args beginning with - are not safe (they look like flags). Less obviously, args beginning with @ are not safe (they look like GNU binutils flagfile specifiers, sometimes called "response files"). To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII. We accept leading . _ and / as likely in file system paths. There is a copy of this function in cmd/compile/internal/gc/noder.go.
Types ¶
type CoverVar ¶
CoverVar holds the name of the generated coverage variables targeting the named file.
type ImportPathError ¶ added in go1.14
ImportPathError is a type of error that prevents a package from being loaded for a given import path. When such a package is loaded, a *Package is returned with Err wrapping an ImportPathError: the error is attached to the imported package, not the importing package.
The string returned by ImportPath must appear in the string returned by Error. Errors that wrap ImportPathError (such as PackageError) may omit the import path.
func ImportErrorf ¶ added in go1.14
func ImportErrorf(path, format string, args ...interface{}) ImportPathError
type ImportStack ¶
type ImportStack []string
An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended. The import path of a test package is the import path of the corresponding non-test package with the suffix "_test" added.
func (*ImportStack) Copy ¶
func (s *ImportStack) Copy() []string
func (*ImportStack) Pop ¶
func (s *ImportStack) Pop()
func (*ImportStack) Push ¶
func (s *ImportStack) Push(p string)
func (*ImportStack) Top ¶ added in go1.15
func (s *ImportStack) Top() string
type NoGoError ¶
type NoGoError struct {
Package *Package
}
A NoGoError indicates that no Go files for the package were applicable to the build for that package.
That may be because there were no files whatsoever, or because all files were excluded, or because all non-excluded files were test sources.
type Package ¶
type Package struct { PackagePublic // visible in 'go list' Internal PackageInternal // for use inside go command only }
A Package describes a single package found in a directory.
func GoFilesPackage ¶
GoFilesPackage creates a package for building a collection of Go files (typically named on the command line). The target is named p.a for package p or named after the first Go file for package main.
func LoadImport ¶
func LoadImport(ctx context.Context, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package
LoadImport scans the directory named by path, which must be an import path, but possibly a local import path (an absolute file system path or one beginning with ./ or ../). A local relative path is interpreted relative to srcDir. It returns a *Package describing the package found in that directory. LoadImport does not set tool flags and should only be used by this package, as part of a bigger load operation, and by GOPATH-based "go get". TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
func LoadImportWithFlags ¶ added in go1.13
func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package
LoadImportWithFlags loads the package with the given import path and sets tool flags on that package. This function is useful loading implicit dependencies (like sync/atomic for coverage). TODO(jayconrod): delete this function and set flags automatically in LoadImport instead.
func PackageList ¶
PackageList returns the list of packages in the dag rooted at roots as visited in a depth-first post-order traversal.
func PackagesAndErrors ¶
PackagesAndErrors returns the packages named by the command line arguments 'patterns'. If a named package cannot be loaded, PackagesAndErrors returns a *Package with the Error field describing the failure. If errors are found loading imported packages, the DepsErrors field is set. The Incomplete field may be set as well.
To obtain a flat list of packages, use PackageList. To report errors loading packages, use ReportPackageErrors.
func ReloadPackageNoFlags ¶ added in go1.11
func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package
ReloadPackageNoFlags is like LoadImport but makes sure not to use the package cache. It is only for use by GOPATH-based "go get". TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
func TestPackageList ¶ added in go1.11
TestPackageList returns the list of packages in the dag rooted at roots as visited in a depth-first post-order traversal, including the test imports of the roots. This ignores errors in test packages.
func TestPackagesAndErrors ¶ added in go1.13
func TestPackagesAndErrors(ctx context.Context, p *Package, cover *TestCover) (pmain, ptest, pxtest *Package)
TestPackagesAndErrors returns three packages:
- pmain, the package main corresponding to the test binary (running tests in ptest and pxtest).
- ptest, the package p compiled with added "package p" test files.
- pxtest, the result of compiling any "package p_test" (external) test files.
If the package has no "package p_test" test files, pxtest will be nil. If the non-test compilation of package p can be reused (for example, if there are no "package p" test files and package p need not be instrumented for coverage or any other reason), then the returned ptest == p.
An error is returned if the testmain source cannot be completely generated (for example, due to a syntax error in a test file). No error will be returned for errors loading packages, but the Error or DepsError fields of the returned packages may be set.
The caller is expected to have checked that len(p.TestGoFiles)+len(p.XTestGoFiles) > 0, or else there's no point in any of this.
func TestPackagesFor ¶ added in go1.10
func TestPackagesFor(ctx context.Context, p *Package, cover *TestCover) (pmain, ptest, pxtest *Package, err error)
TestPackagesFor is like TestPackagesAndErrors but it returns an error if the test packages or their dependencies have errors. Only test packages without errors are returned.
func (*Package) AllFiles ¶ added in go1.9.4
AllFiles returns the names of all the files considered for the package. This is used for sanity and security checks, so we include all files, even IgnoredGoFiles, because some subcommands consider them. The go/build package filtered others out (like foo_wrongGOARCH.s) and that's OK.
func (*Package) DefaultExecName ¶ added in go1.14
DefaultExecName returns the default executable name for a package
func (*Package) Desc ¶ added in go1.11
Desc returns the package "description", for use in b.showOutput.
func (*Package) InternalAllGoFiles ¶ added in go1.10
InternalGoFiles returns the list of all Go files possibly relevant for the package, using absolute paths. "Possibly relevant" means that files are not excluded due to build tags, but files with names beginning with . or _ are still excluded.
func (*Package) InternalGoFiles ¶ added in go1.10
InternalGoFiles returns the list of Go files being built for the package, using absolute paths.
func (*Package) InternalXGoFiles ¶ added in go1.11
InternalXGoFiles returns the list of Go files being built for the XTest package, using absolute paths.
func (*Package) Resolve ¶ added in go1.9.7
Resolve returns the resolved version of imports, which should be p.TestImports or p.XTestImports, NOT p.Imports. The imports in p.TestImports and p.XTestImports are not recursively loaded during the initial load of p, so they list the imports found in the source file, but most processing should be over the vendor-resolved import paths. We do this resolution lazily both to avoid file system work and because the eventual real load of the test imports (during 'go test') can produce better error messages if it starts with the original paths. The initial load of p loads all the non-test imports and rewrites the vendored paths, so nothing should ever call p.vendored(p.Imports).
func (*Package) ResolveEmbed ¶
ResolveEmbed resolves //go:embed patterns and returns only the file list. For use by go list to compute p.TestEmbedFiles and p.XTestEmbedFiles.
type PackageError ¶
type PackageError struct { ImportStack []string // shortest path from package named on command line to this one Pos string // position of error Err error // the error itself IsImportCycle bool // the error is an import cycle Hard bool // whether the error is soft or hard; soft errors are ignored in some places // contains filtered or unexported fields }
A PackageError describes an error loading information about a package.
func (*PackageError) Error ¶
func (p *PackageError) Error() string
func (*PackageError) MarshalJSON ¶ added in go1.14
func (p *PackageError) MarshalJSON() ([]byte, error)
PackageError implements MarshalJSON so that Err is marshaled as a string and non-essential fields are omitted.
func (*PackageError) Unwrap ¶ added in go1.15
func (p *PackageError) Unwrap() error
type PackageInternal ¶
type PackageInternal struct { // Unexported fields are not part of the public API. Build *build.Package Imports []*Package // this package's direct imports CompiledImports []string // additional Imports necessary when using CompiledGoFiles (all from standard library) RawImports []string // this package's original imports as they appear in the text of the program ForceLibrary bool // this package is a library (even if named "main") CmdlineFiles bool // package built from files listed on command line CmdlinePkg bool // package listed on command line CmdlinePkgLiteral bool // package listed as literal on command line (not via wildcard) Local bool // imported via local path (./ or ../) LocalPrefix string // interpret ./ and ../ imports relative to this prefix ExeName string // desired name for temporary executable CoverMode string // preprocess Go source files with the coverage tool in this mode CoverVars map[string]*CoverVar // variables created by coverage analysis OmitDebug bool // tell linker not to write debug information GobinSubdir bool // install target would be subdir of GOBIN BuildInfo string // add this info to package main TestmainGo *[]byte // content for _testmain.go Embed map[string][]string // //go:embed comment mapping Asmflags []string // -asmflags for this package Gcflags []string // -gcflags for this package Ldflags []string // -ldflags for this package Gccgoflags []string // -gccgoflags for this package }
type PackagePublic ¶
type PackagePublic struct { // Note: These fields are part of the go command's public API. // See list.go. It is okay to add fields, but not to change or // remove existing ones. Keep in sync with list.go Dir string `json:",omitempty"` // directory containing package sources ImportPath string `json:",omitempty"` // import path of package in dir ImportComment string `json:",omitempty"` // path in import comment on package statement Name string `json:",omitempty"` // package name Doc string `json:",omitempty"` // package documentation string Target string `json:",omitempty"` // installed target for this package (may be executable) Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared) Root string `json:",omitempty"` // Go root, Go path dir, or module root dir containing this package ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory ForTest string `json:",omitempty"` // package is only for use in named test Export string `json:",omitempty"` // file containing export data (set by go list -export) BuildID string `json:",omitempty"` // build ID of the compiled package (set by go list -export) Module *modinfo.ModulePublic `json:",omitempty"` // info about package's module, if any Match []string `json:",omitempty"` // command-line patterns matching this package Goroot bool `json:",omitempty"` // is this package found in the Go root? Standard bool `json:",omitempty"` // is this package part of the standard Go library? DepOnly bool `json:",omitempty"` // package is only as a dependency, not explicitly listed BinaryOnly bool `json:",omitempty"` // package cannot be recompiled Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies? // Stale and StaleReason remain here *only* for the list command. // They are only initialized in preparation for list execution. // The regular build determines staleness on the fly during action execution. Stale bool `json:",omitempty"` // would 'go install' do anything for this package? StaleReason string `json:",omitempty"` // why is Stale true? // Source files // If you add to this list you MUST add to p.AllFiles (below) too. // Otherwise file name security lists will not apply to any new additions. GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) CgoFiles []string `json:",omitempty"` // .go source files that import "C" CompiledGoFiles []string `json:",omitempty"` // .go output from running cgo on CgoFiles IgnoredGoFiles []string `json:",omitempty"` // .go source files ignored due to build constraints IgnoredOtherFiles []string `json:",omitempty"` // non-.go source files ignored due to build constraints CFiles []string `json:",omitempty"` // .c source files CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files MFiles []string `json:",omitempty"` // .m source files HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files SFiles []string `json:",omitempty"` // .s source files SwigFiles []string `json:",omitempty"` // .swig files SwigCXXFiles []string `json:",omitempty"` // .swigcxx files SysoFiles []string `json:",omitempty"` // .syso system object files added to package // Embedded files EmbedPatterns []string `json:",omitempty"` // //go:embed patterns EmbedFiles []string `json:",omitempty"` // files and directories matched by EmbedPatterns // Cgo directives CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names // Dependency information Imports []string `json:",omitempty"` // import paths used by this package ImportMap map[string]string `json:",omitempty"` // map from source import to ImportPath (identity entries omitted) Deps []string `json:",omitempty"` // all (recursively) imported dependencies // Error information // Incomplete is above, packed into the other bools Error *PackageError `json:",omitempty"` // error loading this package (not dependencies) DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies // Test information // If you add to this list you MUST add to p.AllFiles (below) too. // Otherwise file name security lists will not apply to any new additions. TestGoFiles []string `json:",omitempty"` // _test.go files in package TestImports []string `json:",omitempty"` // imports from TestGoFiles TestEmbedPatterns []string `json:",omitempty"` // //go:embed patterns TestEmbedFiles []string `json:",omitempty"` // //files matched by EmbedPatterns XTestGoFiles []string `json:",omitempty"` // _test.go files outside package XTestImports []string `json:",omitempty"` // imports from XTestGoFiles XTestEmbedPatterns []string `json:",omitempty"` // //go:embed patterns XTestEmbedFiles []string `json:",omitempty"` // //files matched by EmbedPatterns }
type PerPackageFlag ¶ added in go1.10
type PerPackageFlag struct {
// contains filtered or unexported fields
}
A PerPackageFlag is a command-line flag implementation (a flag.Value) that allows specifying different effective flags for different packages. See 'go help build' for more details about per-package flags.
var ( BuildAsmflags PerPackageFlag // -asmflags BuildGcflags PerPackageFlag // -gcflags BuildLdflags PerPackageFlag // -ldflags BuildGccgoflags PerPackageFlag // -gccgoflags )
func (*PerPackageFlag) For ¶ added in go1.10
func (f *PerPackageFlag) For(p *Package) []string
For returns the flags to use for the given package.
func (*PerPackageFlag) Present ¶ added in go1.10
func (f *PerPackageFlag) Present() bool
Present reports whether the flag appeared on the command line.
func (*PerPackageFlag) Set ¶ added in go1.10
func (f *PerPackageFlag) Set(v string) error
Set is called each time the flag is encountered on the command line.
func (*PerPackageFlag) String ¶ added in go1.10
func (f *PerPackageFlag) String() string
String is required to implement flag.Value. It is not used, because cmd/go never calls flag.PrintDefaults.
type TargetDir ¶ added in go1.10
type TargetDir int
func InstallTargetDir ¶ added in go1.10
InstallTargetDir reports the target directory for installing the command p.