load

Imports

Imports #

"errors"
"fmt"
"go/build"
"internal/godebugs"
"maps"
"sort"
"strconv"
"strings"
"cmd/go/internal/fips140"
"cmd/go/internal/gover"
"cmd/go/internal/modload"
"path/filepath"
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"go/build"
"go/scanner"
"go/token"
"internal/platform"
"io/fs"
"os"
pathpkg "path"
"path/filepath"
"runtime"
"runtime/debug"
"slices"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/fips140"
"cmd/go/internal/fsys"
"cmd/go/internal/gover"
"cmd/go/internal/imports"
"cmd/go/internal/modfetch"
"cmd/go/internal/modindex"
"cmd/go/internal/modinfo"
"cmd/go/internal/modload"
"cmd/go/internal/search"
"cmd/go/internal/str"
"cmd/go/internal/trace"
"cmd/go/internal/vcs"
"cmd/internal/par"
"cmd/internal/pathcache"
"cmd/internal/pkgpattern"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"sync"
"path/filepath"
"strings"
"cmd/go/internal/search"
"cmd/internal/pkgpattern"
"bytes"
"context"
"errors"
"fmt"
"go/ast"
"go/build"
"go/doc"
"go/parser"
"go/token"
"internal/lazytemplate"
"maps"
"path/filepath"
"slices"
"sort"
"strings"
"unicode"
"unicode/utf8"
"cmd/go/internal/cfg"
"cmd/go/internal/fsys"
"cmd/go/internal/str"
"cmd/go/internal/trace"
"cmd/go/internal/base"
"cmd/internal/quoted"
"fmt"
"strings"

Constants & Variables

BuildAsmflags var #

var BuildAsmflags PerPackageFlag

BuildGccgoflags var #

var BuildGccgoflags PerPackageFlag

BuildGcflags var #

var BuildGcflags PerPackageFlag

BuildLdflags var #

var BuildLdflags PerPackageFlag

ErrNotGoDebug var #

var ErrNotGoDebug = *ast.CallExpr

GetTestDeps const #

GetTestDeps is for download (part of "go get") and indicates that test dependencies should be fetched too.

const GetTestDeps

ResolveImport 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/.

const ResolveImport = *ast.BinaryExpr

ResolveModule const #

ResolveModule is for download (part of "go get") and indicates that the module adjustment should be done, but not vendor adjustment.

const ResolveModule

StalePath const #

const StalePath

TestMainDeps var #

var TestMainDeps = []string{...}

ToBin const #

const ToBin

ToTool const #

const ToTool TargetDir = iota

_ var #

var _ ImportPathError = *ast.CallExpr

_ var #

var _ ImportPathError = *ast.CallExpr

_ var #

var _ ImportPathError = *ast.CallExpr

_ var #

var _ ImportPathError = *ast.CallExpr

_ var #

var _ ImportPathError = *ast.CallExpr

cgoExclude var #

var cgoExclude = map[string]bool{...}

cgoSyscallExclude var #

var cgoSyscallExclude = map[string]bool{...}

cmdlinePkg const #

cmdlinePkg is for a package mentioned on the command line.

const cmdlinePkg

cmdlinePkgLiteral const #

cmdlinePkgLiteral is for a package mentioned on the command line without using any wildcards or meta-patterns.

const cmdlinePkgLiteral

defaultPrinter var #

var defaultPrinter = *ast.CallExpr

foldPath var #

var foldPath = *ast.CallExpr

goModPathCache var #

var goModPathCache *ast.IndexListExpr

isDirCache var #

var isDirCache *ast.IndexListExpr

modulePrefix var #

var modulePrefix = *ast.CallExpr

packageCache var #

packageCache is a lookup cache for LoadImport, so that if we look up a package multiple times we return the same pointer each time.

var packageCache = map[string]*Package{...}

packageDataCache var #

packageDataCache maps canonical package names (string) to package metadata.

var packageDataCache *ast.IndexListExpr

preloadWorkerCount var #

preloadWorkerCount is the number of concurrent goroutines that can load packages. Experimentally, there are diminishing returns with more than 4 workers. This was measured on the following machines. * MacBookPro with a 4-core Intel Core i7 CPU * Linux workstation with 6-core Intel Xeon CPU * Linux workstation with 24-core Intel Xeon CPU It is very likely (though not confirmed) that this workload is limited by memory bandwidth. We don't have a good way to determine the number of workers that would saturate the bus though, so runtime.GOMAXPROCS seems like a reasonable default.

var preloadWorkerCount = *ast.CallExpr

resolvedImportCache var #

resolvedImportCache maps import strings to canonical package names.

var resolvedImportCache *ast.IndexListExpr

testFileSet var #

var testFileSet = *ast.CallExpr

testmainTmpl var #

var testmainTmpl = *ast.CallExpr

testmainTmplNewCoverage var #

var testmainTmplNewCoverage = *ast.CallExpr

vcsStatusCache var #

vcsStatusCache maps repository directories (string) to their VCS information.

var vcsStatusCache *ast.IndexListExpr

Type Aliases

ImportStack type #

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.

type ImportStack []ImportInfo

TargetDir type #

type TargetDir int

Interfaces

ImportPathError interface #

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.

type ImportPathError interface {
error
ImportPath() string
}

Printer interface #

A Printer reports output about a Package.

type Printer interface {
Printf(pkg *Package, format string, args ...any)
Errorf(pkg *Package, format string, args ...any)
}

Structs

CoverSetup struct #

CoverSetup holds parameters related to coverage setup for a given package (covermode, etc).

type CoverSetup struct {
Mode string
Cfg string
GenMeta bool
}

CoverVar struct #

CoverVar holds the name of the generated coverage variables targeting the named file.

type CoverVar struct {
File string
Var string
}

EmbedError struct #

An EmbedError indicates a problem with a go:embed directive.

type EmbedError struct {
Pattern string
Err error
}

ImportInfo struct #

type ImportInfo struct {
Pkg string
Pos *token.Position
}

JSONPrinter struct #

A JSONPrinter emits output about a build in JSON format.

type JSONPrinter struct {
enc *json.Encoder
}

NoGoError struct #

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 NoGoError struct {
Package *Package
}

Package struct #

A Package describes a single package found in a directory.

type Package struct {
PackagePublic
Internal PackageInternal
}

PackageError struct #

A PackageError describes an error loading information about a package.

type PackageError struct {
ImportStack ImportStack
Pos string
Err error
IsImportCycle bool
alwaysPrintStack bool
}

PackageInternal struct #

type PackageInternal struct {
Build *build.Package
Imports []*Package
CompiledImports []string
RawImports []string
ForceLibrary bool
CmdlineFiles bool
CmdlinePkg bool
CmdlinePkgLiteral bool
Local bool
LocalPrefix string
ExeName string
FuzzInstrument bool
Cover CoverSetup
CoverVars map[string]*CoverVar
OmitDebug bool
GobinSubdir bool
BuildInfo *debug.BuildInfo
TestmainGo *[]byte
Embed map[string][]string
OrigImportPath string
PGOProfile string
ForMain string
Asmflags []string
Gcflags []string
Ldflags []string
Gccgoflags []string
}

PackageOpts struct #

PackageOpts control the behavior of PackagesAndErrors and other package loading functions.

type PackageOpts struct {
IgnoreImports bool
ModResolveTests bool
MainOnly bool
AutoVCS bool
SuppressBuildInfo bool
SuppressEmbedFiles bool
}

PackagePublic struct #

type PackagePublic struct {
Dir string `json:",omitempty"`
ImportPath string `json:",omitempty"`
ImportComment string `json:",omitempty"`
Name string `json:",omitempty"`
Doc string `json:",omitempty"`
Target string `json:",omitempty"`
Shlib string `json:",omitempty"`
Root string `json:",omitempty"`
ConflictDir string `json:",omitempty"`
ForTest string `json:",omitempty"`
Export string `json:",omitempty"`
BuildID string `json:",omitempty"`
Module *modinfo.ModulePublic `json:",omitempty"`
Match []string `json:",omitempty"`
Goroot bool `json:",omitempty"`
Standard bool `json:",omitempty"`
DepOnly bool `json:",omitempty"`
BinaryOnly bool `json:",omitempty"`
Incomplete bool `json:",omitempty"`
DefaultGODEBUG string `json:",omitempty"`
Stale bool `json:",omitempty"`
StaleReason string `json:",omitempty"`
GoFiles []string `json:",omitempty"`
CgoFiles []string `json:",omitempty"`
CompiledGoFiles []string `json:",omitempty"`
IgnoredGoFiles []string `json:",omitempty"`
InvalidGoFiles []string `json:",omitempty"`
IgnoredOtherFiles []string `json:",omitempty"`
CFiles []string `json:",omitempty"`
CXXFiles []string `json:",omitempty"`
MFiles []string `json:",omitempty"`
HFiles []string `json:",omitempty"`
FFiles []string `json:",omitempty"`
SFiles []string `json:",omitempty"`
SwigFiles []string `json:",omitempty"`
SwigCXXFiles []string `json:",omitempty"`
SysoFiles []string `json:",omitempty"`
EmbedPatterns []string `json:",omitempty"`
EmbedFiles []string `json:",omitempty"`
CgoCFLAGS []string `json:",omitempty"`
CgoCPPFLAGS []string `json:",omitempty"`
CgoCXXFLAGS []string `json:",omitempty"`
CgoFFLAGS []string `json:",omitempty"`
CgoLDFLAGS []string `json:",omitempty"`
CgoPkgConfig []string `json:",omitempty"`
Imports []string `json:",omitempty"`
ImportMap map[string]string `json:",omitempty"`
Deps []string `json:",omitempty"`
Error *PackageError `json:",omitempty"`
DepsErrors []*PackageError `json:",omitempty"`
TestGoFiles []string `json:",omitempty"`
TestImports []string `json:",omitempty"`
TestEmbedPatterns []string `json:",omitempty"`
TestEmbedFiles []string `json:",omitempty"`
XTestGoFiles []string `json:",omitempty"`
XTestImports []string `json:",omitempty"`
XTestEmbedPatterns []string `json:",omitempty"`
XTestEmbedFiles []string `json:",omitempty"`
}

PerPackageFlag struct #

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.

type PerPackageFlag struct {
raw string
present bool
values []ppfValue
}

TestCover struct #

type TestCover struct {
Mode string
Local bool
Pkgs []*Package
Paths []string
Vars []coverInfo
}

TextPrinter struct #

A TextPrinter emits text format output to Writer.

type TextPrinter struct {
Writer io.Writer
}

coverInfo struct #

type coverInfo struct {
Package *Package
Vars map[string]*CoverVar
}

importError struct #

type importError struct {
importPath string
err error
}

importSpec struct #

importSpec describes an import declaration in source code. It is used as a cache key for resolvedImportCache.

type importSpec struct {
path string
parentPath string
parentDir string
parentRoot string
parentIsStd bool
mode int
}

jsonBuildEvent struct #

type jsonBuildEvent struct {
ImportPath string
Action string
Output string `json:",omitempty"`
}

mainPackageError struct #

type mainPackageError struct {
importPath string
}

ppfValue struct #

A ppfValue is a single = per-package flag value.

type ppfValue struct {
match func(*Package) bool
flags []string
}

preload struct #

preload holds state for managing concurrent preloading of package data. A preload should be created with newPreload before loading a large package graph. flush must be called when package loading is complete to ensure preload goroutines are no longer active. This is necessary because of global mutable state that cannot safely be read and written concurrently. In particular, packageDataCache may be cleared by "go get" in GOPATH mode, and modload.loaded (accessed via modload.Lookup) may be modified by modload.LoadPackages.

type preload struct {
cancel chan struct{...}
sema chan struct{...}
}

resolvedImport struct #

resolvedImport holds a canonical identifier for a package. It may also contain a path to the package's directory and an error if one occurred. resolvedImport is the value type in resolvedImportCache.

type resolvedImport struct {
path string
dir string
err error
}

testFunc struct #

type testFunc struct {
Package string
Name string
Output string
Unordered bool
}

testFuncs struct #

type testFuncs struct {
Tests []testFunc
Benchmarks []testFunc
FuzzTargets []testFunc
Examples []testFunc
TestMain *testFunc
Package *Package
ImportTest bool
NeedTest bool
ImportXtest bool
NeedXtest bool
Cover *TestCover
}

Functions

AllFiles method #

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 (p *Package) AllFiles() []string

CheckPackageErrors function #

CheckPackageErrors prints errors encountered loading pkgs and their dependencies, then exits with a non-zero status if any errors were found.

func CheckPackageErrors(pkgs []*Package)

Copy method #

func (s *ImportStack) Copy() ImportStack

CoverSelectedPackages method #

func (t *testFuncs) CoverSelectedPackages() string

Covered method #

Covered returns a string describing which packages are being tested for coverage. If the covered package is the same as the tested package, it returns the empty string. Otherwise it is a comma-separated human-readable list of packages beginning with " in", ready for use in the coverage message.

func (t *testFuncs) Covered() string

DeclareCoverVars function #

DeclareCoverVars attaches the required cover variables names to the files, to be used when annotating the files. This function only called when using legacy coverage test/build (e.g. GOEXPERIMENT=coverageredesign is off).

func DeclareCoverVars(p *Package, files ...string) map[string]*CoverVar

DefaultExecName method #

DefaultExecName returns the default executable name for a package

func (p *Package) DefaultExecName() string

DefaultPrinter function #

DefaultPrinter returns the default Printer.

func DefaultPrinter() Printer

Desc method #

Desc returns the package "description", for use in b.showOutput.

func (p *Package) Desc() string

EnsureImport function #

EnsureImport ensures that package p imports the named package.

func EnsureImport(p *Package, pkg string)

Error method #

func (e *EmbedError) Error() string

Error method #

func (p *PackageError) Error() string

Error method #

func (e *mainPackageError) Error() string

Error method #

func (e *NoGoError) Error() string

Error method #

func (e *importError) Error() string

Errorf method #

func (p *JSONPrinter) Errorf(pkg *Package, format string, args ...any)

Errorf method #

func (p *TextPrinter) Errorf(_ *Package, format string, args ...any)

FindVendor function #

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 FindVendor(path string) (index int, ok bool)

For method #

For returns the flags to use for the given package.

func (f *PerPackageFlag) For(p *Package) []string

GoFilesPackage function #

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 GoFilesPackage(ctx context.Context, opts PackageOpts, gofiles []string) *Package

ImportErrorf function #

func ImportErrorf(path string, format string, args ...any) ImportPathError

ImportPath method #

ImportPath returns the import path of the package being tested, if it is within GOPATH. This is printed by the testing package when running benchmarks.

func (t *testFuncs) ImportPath() string

ImportPath method #

func (e *importError) ImportPath() string

ImportPath method #

func (e *mainPackageError) ImportPath() string

InstallTargetDir function #

InstallTargetDir reports the target directory for installing the command p.

func InstallTargetDir(p *Package) TargetDir

InternalAllGoFiles method #

InternalAllGoFiles 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 (p *Package) InternalAllGoFiles() []string

InternalGoFiles method #

InternalGoFiles returns the list of Go files being built for the package, using absolute paths.

func (p *Package) InternalGoFiles() []string

InternalXGoFiles method #

InternalXGoFiles returns the list of Go files being built for the XTest package, using absolute paths.

func (p *Package) InternalXGoFiles() []string

IsTestOnly method #

IsTestOnly reports whether p is a test-only package. A “test-only” package is one that: - is a test-only variant of an ordinary package, or - is a synthesized "main" package for a test binary, or - contains only _test.go files.

func (p *Package) IsTestOnly() bool

LinkerDeps function #

LinkerDeps returns the list of linker-induced dependencies for main package p.

func LinkerDeps(p *Package) ([]string, error)

LoadImportWithFlags function #

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 LoadImportWithFlags(path string, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError)

LoadPackage function #

LoadPackage does Load import, but without a parent package load context

func LoadPackage(ctx context.Context, opts PackageOpts, path string, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package

LoadPackageWithFlags function #

LoadPackageWithFlags is the same as LoadImportWithFlags but without a parent. It's then guaranteed to not return an error

func LoadPackageWithFlags(path string, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package

MarshalJSON method #

PackageError implements MarshalJSON so that Err is marshaled as a string and non-essential fields are omitted.

func (p *PackageError) MarshalJSON() ([]byte, error)

MatchPackage function #

MatchPackage(pattern, cwd)(p) reports whether package p matches pattern in the working directory cwd.

func MatchPackage(pattern string, cwd string) (func(*Package) bool)

NewImportInfo function #

func NewImportInfo(pkg string, pos *token.Position) ImportInfo

NewJSONPrinter function #

func NewJSONPrinter(w io.Writer) *JSONPrinter

PackageErrors function #

PackageErrors calls report for errors encountered loading pkgs and their dependencies.

func PackageErrors(pkgs []*Package, report func(*Package))

PackageList function #

PackageList returns the list of packages in the dag rooted at roots as visited in a depth-first post-order traversal.

func PackageList(roots []*Package) []*Package

PackagesAndErrors function #

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 PackagesAndErrors(ctx context.Context, opts PackageOpts, patterns []string) []*Package

PackagesAndErrorsOutsideModule function #

PackagesAndErrorsOutsideModule is like PackagesAndErrors but runs in module-aware mode and ignores the go.mod file in the current directory or any parent directory, if there is one. This is used in the implementation of 'go install pkg@version' and other commands that support similar forms. modload.ForceUseModules must be true, and modload.RootMode must be NoRoot before calling this function. PackagesAndErrorsOutsideModule imposes several constraints to avoid ambiguity. All arguments must have the same version suffix (not just a suffix that resolves to the same version). They must refer to packages in the same module, which must not be std or cmd. That module is not considered the main module, but its go.mod file (if it has one) must not contain directives that would cause it to be interpreted differently if it were the main module (replace, exclude).

func PackagesAndErrorsOutsideModule(ctx context.Context, opts PackageOpts, args []string) ([]*Package, error)

ParseGoDebug function #

func ParseGoDebug(text string) (key string, value string, err error)

Pkgs method #

func (s *ImportStack) Pkgs() []string

PkgsWithPos method #

func (s *ImportStack) PkgsWithPos() []string

Pop method #

func (s *ImportStack) Pop()

PrepareForCoverageBuild function #

PrepareForCoverageBuild is a helper invoked for "go install -cover", "go run -cover", and "go build -cover" (but not used by "go test -cover"). It walks through the packages being built (and dependencies) and marks them for coverage instrumentation when appropriate, and possibly adding additional deps where needed.

func PrepareForCoverageBuild(pkgs []*Package)

Present method #

Present reports whether the flag appeared on the command line.

func (f *PerPackageFlag) Present() bool

Printf method #

func (p *TextPrinter) Printf(_ *Package, format string, args ...any)

Printf method #

func (p *JSONPrinter) Printf(pkg *Package, format string, args ...any)

Push method #

func (s *ImportStack) Push(p ImportInfo)

Resolve method #

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 (p *Package) Resolve(imports []string) []string

ResolveEmbed function #

ResolveEmbed resolves //go:embed patterns and returns only the file list. For use by go mod vendor to find embedded files it should copy into the vendor directory. TODO(#42504): Once go mod vendor uses load.PackagesAndErrors, just call (*Package).ResolveEmbed

func ResolveEmbed(dir string, patterns []string) ([]string, error)

ResolveImportPath function #

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 ResolveImportPath(parent *Package, path string) (found string)

SafeArg function #

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.

func SafeArg(name string) bool

SelectCoverPackages function #

func SelectCoverPackages(roots []*Package, match []func(*Package) bool, op string) []*Package

Set method #

Set is called each time the flag is encountered on the command line.

func (f *PerPackageFlag) Set(v string) error

String method #

func (f *PerPackageFlag) String() string

Top method #

func (s *ImportStack) Top() (ImportInfo, bool)

Unwrap method #

func (e *importError) Unwrap() error

Unwrap method #

func (e *EmbedError) Unwrap() error

Unwrap method #

func (p *PackageError) Unwrap() error

UsesCgo method #

UsesCgo reports whether the package needs to run cgo

func (p *Package) UsesCgo() bool

UsesSwig method #

UsesSwig reports whether the package needs to run SWIG.

func (p *Package) UsesSwig() bool

appendBuildSetting function #

func appendBuildSetting(info *debug.BuildInfo, key string, value string)

checkTestFunc function #

func checkTestFunc(fn *ast.FuncDecl, arg string) error

cleanImport function #

func cleanImport(path string) string

copyBuild method #

func (p *Package) copyBuild(opts PackageOpts, pp *build.Package)

defaultGODEBUG function #

defaultGODEBUG returns the default GODEBUG setting for the main package p. When building a test binary, directives, testDirectives, and xtestDirectives list additional directives from the package under test.

func defaultGODEBUG(p *Package, directives []build.Directive, testDirectives []build.Directive, xtestDirectives []build.Directive) string

dirAndRoot function #

dirAndRoot returns the source directory and workspace root for the package p, guaranteeing that root is a path prefix of dir.

func dirAndRoot(path string, dir string, root string) (string, string)

dirToImportPath function #

dirToImportPath returns the pseudo-import path we use for a package outside the Go path. It begins with _/ and then contains the full path to the directory. If the package lives in c:\home\gopher\my\pkg then the pseudo-import path is _/c_/home/gopher/my/pkg. Using a pseudo-import path like this makes the ./ imports no longer a special case, so that all the code to deal with ordinary imports works automatically.

func dirToImportPath(dir string) string

disallowInternal function #

disallowInternal checks that srcDir (containing package importerPath, if non-empty) is allowed to import p. If the import is allowed, disallowInternal returns the original package p. If not, it returns a new package containing just an appropriate error.

func disallowInternal(ctx context.Context, srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *PackageError

disallowVendor function #

disallowVendor checks that srcDir is allowed to import p as path. If the import is allowed, disallowVendor returns the original package p. If not, it returns a PackageError.

func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *PackageError

disallowVendorVisibility function #

disallowVendorVisibility checks that srcDir is allowed to import p. The rules are the same as for /internal/ except that a path ending in /vendor is not subject to the rules, only subdirectories of vendor. This allows people to have packages and commands named vendor, for maximal compatibility with existing source trees.

func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *PackageError

ensureNewline function #

func ensureNewline(s string) string

exeFromFiles method #

exeFromFiles returns an executable name for a package using the first element in GoFiles or CgoFiles collections without the prefix. Returns empty string in case of empty collection.

func (p *Package) exeFromFiles() string

exeFromImportPath method #

exeFromImportPath returns an executable name for a package using the import path. The executable name is the last element of the import path. In module-aware mode, an additional rule is used on import paths consisting of two or more path elements. If the last element is a vN path element specifying the major version, then the second last element of the import path is used instead.

func (p *Package) exeFromImportPath() string

expandPath function #

expandPath returns the symlink-expanded form of path.

func expandPath(p string) string

externalLinkingReason function #

externalLinkingReason reports the reason external linking is required even for programs that do not use cgo, or the empty string if external linking is not required.

func externalLinkingReason(p *Package) (what string)

extractFirstImport function #

func extractFirstImport(importPos []token.Position) *token.Position

findInternal function #

findInternal looks for the final "internal" path element in the given import path. If there isn't one, findInternal returns ok=false. Otherwise, findInternal returns ok=true and the index of the "internal".

func findInternal(path string) (index int, ok bool)

findVersionElement function #

findVersionElement returns the slice indices of the final version element /vN in path. If there is no such element, it returns -1, -1.

func findVersionElement(path string) (i int, j int)

flush method #

flush stops pending preload operations. flush blocks until preload calls to loadPackageData have completed. The preloader will not make any new calls to loadPackageData.

func (pre *preload) flush()

formatTestmain function #

formatTestmain returns the content of the _testmain.go file for t.

func formatTestmain(t *testFuncs) ([]byte, error)

goModPath function #

goModPath returns the module path in the go.mod in dir, if any.

func goModPath(dir string) (path string)

godebugForGoVersion function #

func godebugForGoVersion(v string) map[string]string

hasGoFiles function #

hasGoFiles reports whether dir contains any files with names ending in .go. For a vendor check we must exclude directories that contain no .go files. Otherwise it is not possible to vendor just a/b/c and still import the non-vendored a/b. See golang.org/issue/13832.

func hasGoFiles(dir string) bool

isBadEmbedName function #

isBadEmbedName reports whether name is the base name of a file that can't or won't be included in modules and therefore shouldn't be treated as existing for embedding.

func isBadEmbedName(name string) bool

isDir function #

func isDir(path string) bool

isTest function #

isTest tells whether name looks like a test (or benchmark, according to prefix). It is a Test (say) if there is a character after Test that is not a lower-case letter. We don't want TesticularCancer.

func isTest(name string, prefix string) bool

isTestFunc function #

isTestFunc tells whether fn has the type of a testing function. arg specifies the parameter type we look for: B, F, M or T.

func isTestFunc(fn *ast.FuncDecl, arg string) bool

isVersionElement function #

isVersionElement reports whether s is a well-formed path version element: v2, v3, v10, etc, but not v0, v05, v1.

func isVersionElement(s string) bool

load method #

func (t *testFuncs) load(filename string, pkg string, doImport *bool, seen *bool) error

load method #

load populates p using information from bp, err, which should be the result of calling build.Context.Import. stk contains the import stack, not including path itself.

func (p *Package) load(ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error)

loadImport function #

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. The returned PackageError, if any, describes why parent is not allowed to import the named package, with the error referring to importPos. The PackageError can only be non-nil when parent is not nil.

func loadImport(ctx context.Context, opts PackageOpts, pre *preload, path string, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError)

loadPackageData function #

loadPackageData loads information needed to construct a *Package. The result is cached, and later calls to loadPackageData for the same package will return the same data. loadPackageData returns a non-nil package even if err is non-nil unless the package path is malformed (for example, the path contains "mod/" or "@"). loadPackageData returns a boolean, loaded, which is true if this is the first time the package was loaded. Callers may preload imports in this case.

func loadPackageData(ctx context.Context, path string, parentPath string, parentDir string, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error)

loadTestFuncs function #

loadTestFuncs returns the testFuncs describing the tests that will be run. The returned testFuncs is always non-nil, even if an error occurred while processing test files.

func loadTestFuncs(ptest *Package) (*testFuncs, error)

mainPackagesOnly function #

mainPackagesOnly filters out non-main packages matched only by arguments containing "..." and returns the remaining main packages. Packages with missing, invalid, or ambiguous names may be treated as possibly-main packages. mainPackagesOnly sets a non-main package's Error field and returns it if it is named by a literal argument. mainPackagesOnly prints warnings for non-literal arguments that only match non-main packages.

func mainPackagesOnly(pkgs []*Package, matches []*search.Match) []*Package

makeImportValid function #

func makeImportValid(r rune) rune

mkAbs method #

mkAbs rewrites list, which must be paths relative to p.Dir, into a sorted list of absolute paths. It edits list in place but for convenience also returns list back to its caller.

func (p *Package) mkAbs(list []string) []string

moduleImportPath function #

moduleImportPath translates import paths found in go modules back down to paths that can be resolved in ordinary builds. Define “new” code as code with a go.mod file in the same directory or a parent directory. If an import in new code says x/y/v2/z but x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”, then go build will read the import as x/y/z instead. See golang.org/issue/25069.

func moduleImportPath(path string, parentPath string, parentDir string, parentRoot string) (found string)

newPreload function #

newPreload creates a new preloader. flush must be called later to avoid accessing global state while it is being modified.

func newPreload() *preload

preloadImports method #

preloadImports queues a list of imports for preloading. When preloadImports returns, some packages may not be loaded yet, but loadPackageData and loadImport are always safe to call.

func (pre *preload) preloadImports(ctx context.Context, opts PackageOpts, imports []string, parent *build.Package)

preloadMatches method #

preloadMatches loads data for package paths matched by patterns. When preloadMatches returns, some packages may not be loaded yet, but loadPackageData and loadImport are always safe to call.

func (pre *preload) preloadMatches(ctx context.Context, opts PackageOpts, matches []*search.Match)

recompileForTest function #

recompileForTest copies and replaces certain packages in pmain's dependency graph. This is necessary for two reasons. First, if ptest is different than preal, packages that import the package under test should get ptest instead of preal. This is particularly important if pxtest depends on functionality exposed in test sources in ptest. Second, if there is a main package (other than pmain) anywhere, we need to set p.Internal.ForceLibrary and clear p.Internal.BuildInfo in the test copy to prevent link conflicts. This may happen if both -coverpkg and the command line patterns include multiple main packages.

func recompileForTest(pmain *Package, preal *Package, ptest *Package, pxtest *Package) *PackageError

resolveEmbed function #

resolveEmbed resolves //go:embed patterns to precise file lists. It sets files to the list of unique files matched (for go list), and it sets pmap to the more precise mapping from patterns to files.

func resolveEmbed(pkgdir string, patterns []string) (files []string, pmap map[string][]string, err error)

resolveImportPath function #

func resolveImportPath(path string, parentPath string, parentDir string, parentRoot string, parentIsStd bool) (found string)

reusePackage function #

reusePackage reuses package p to satisfy the import at the top of the import stack stk. If this use causes an import loop, reusePackage updates p's error information to record the loop.

func reusePackage(p *Package, stk *ImportStack) *Package

set method #

set is the implementation of Set, taking a cwd (current working directory) for easier testing.

func (f *PerPackageFlag) set(v string, cwd string) error

setBuildInfo method #

setBuildInfo gathers build information and sets it into p.Internal.BuildInfo, which will later be formatted as a string and embedded in the binary. setBuildInfo should only be called on a main package with no errors. This information can be retrieved using debug.ReadBuildInfo. Note that the GoVersion field is not set here to avoid encoding it twice. It is stored separately in the binary, mostly for historical reasons.

func (p *Package) setBuildInfo(ctx context.Context, autoVCS bool)

setLoadPackageDataError method #

setLoadPackageDataError presents an error found when loading package data as a *PackageError. It has special cases for some common errors to improve messages shown to users and reduce redundancy. setLoadPackageDataError returns true if it's safe to load information about imported packages, for example, if there was a parse error loading imports in one file, but other files are okay.

func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportStack, importPos []token.Position)

setPGOProfilePath function #

setPGOProfilePath sets the PGO profile path for pkgs. In -pgo=auto mode, it finds the default PGO profile.

func setPGOProfilePath(pkgs []*Package)

setPos method #

func (p *PackageError) setPos(posList []token.Position)

setToolFlags function #

func setToolFlags(pkgs ...*Package)

shorterThan method #

shorterThan reports whether sp is shorter than t. We use this to record the shortest import sequence that leads to a particular package.

func (sp *ImportStack) shorterThan(t []string) bool

validEmbedPattern function #

func validEmbedPattern(pattern string) bool

vendoredImportPath function #

vendoredImportPath returns the vendor-expansion of path when it appears in parent. If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path, x/vendor/path, vendor/path, or else stay path if none of those exist. vendoredImportPath returns the expanded path or, if no expansion is found, the original.

func vendoredImportPath(path string, parentPath string, parentDir string, parentRoot string) (found string)

Generated with Arrow