build

Imports

Imports #

"runtime"
"bufio"
"bytes"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/scanner"
"go/token"
"io"
"strconv"
"strings"
"unicode"
"unicode/utf8"
_ "unsafe"
"bytes"
"errors"
"fmt"
"go/ast"
"go/build/constraint"
"go/doc"
"go/token"
"internal/buildcfg"
"internal/godebug"
"internal/goroot"
"internal/goversion"
"internal/platform"
"internal/syslist"
"io"
"io/fs"
"os"
"os/exec"
pathpkg "path"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf8"
_ "unsafe"
"path/filepath"
"runtime"

Constants & Variables

AllowBinary const #

If AllowBinary is set, Import can be satisfied by a compiled package object without corresponding sources. Deprecated: The supported way to create a compiled-only package is to write source code containing a //go:binary-only-package comment at the top of the file. Such a package will be recognized regardless of this flag setting (because it has source code) and will have BinaryOnly set to true in the returned Package.

const AllowBinary

Default var #

Default is the default Context for builds. It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables if set, or else the compiled code's GOARCH, GOOS, and GOROOT.

var Default Context = *ast.CallExpr

FindOnly const #

If FindOnly is set, Import stops after locating the directory that should contain the sources for a package. It does not read any files in the directory.

const FindOnly ImportMode = *ast.BinaryExpr

IgnoreVendor const #

By default, Import searches vendor directories that apply in the given source directory before searching the GOROOT and GOPATH roots. If an Import finds and returns a package using a vendor directory, the resulting ImportPath is the complete path to the package, including the path elements leading up to and including "vendor". For example, if Import("y", "x/subdir", 0) finds "x/vendor/y", the returned package's ImportPath is "x/vendor/y", not plain "y". See golang.org/s/go15vendor for more information. Setting IgnoreVendor ignores vendor directories. In contrast to the package's ImportPath, the returned package's Imports, TestImports, and XTestImports are always the exact import paths from the source files: Import makes no attempt to resolve or check those paths.

const IgnoreVendor

ImportComment const #

If ImportComment is set, parse import comments on package statements. Import returns an error if it finds a comment it cannot understand or finds conflicting comments in multiple source files. See golang.org/s/go14customimport for more information.

const ImportComment

ToolDir var #

ToolDir is the directory containing build tools.

var ToolDir = *ast.CallExpr

binaryOnlyComment var #

Special comment denoting a binary-only package. See https://golang.org/design/2775-binary-only-packages for more about the design of binary-only packages.

var binaryOnlyComment = *ast.CallExpr

bom var #

var bom = []byte{...}

defaultCGO_ENABLED const #

const defaultCGO_ENABLED = ""

defaultReleaseTags var #

defaultReleaseTags should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/gopherjs/gopherjs Do not remove or change the type signature. See go.dev/issue/67401. go:linkname defaultReleaseTags

var defaultReleaseTags []string

defaultToolTags var #

defaultToolTags should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/gopherjs/gopherjs Do not remove or change the type signature. See go.dev/issue/67401. go:linkname defaultToolTags

var defaultToolTags []string

dummyPkg var #

var dummyPkg Package

errMultipleGoBuild var #

var errMultipleGoBuild = *ast.CallExpr

errNUL var #

var errNUL = *ast.CallExpr

errNoModules var #

var errNoModules = *ast.CallExpr

errSyntax var #

var errSyntax = *ast.CallExpr

goBuildComment var #

var goBuildComment = *ast.CallExpr

goEmbed var #

var goEmbed = *ast.CallExpr

installgoroot var #

var installgoroot = *ast.CallExpr

newline var #

var newline = *ast.CallExpr

plusBuild var #

var plusBuild = *ast.CallExpr

safeString const #

NOTE: $ is not safe for the shell, but it is allowed here because of linker options like -Wl,$ORIGIN. We never pass these arguments to a shell (just to programs we construct argv for), so this should be okay. See golang.org/issue/6038. The @ is for OS X. See golang.org/issue/13720. The % is for Jenkins. See golang.org/issue/16959. The ! is because module paths may use them. See golang.org/issue/26716. The ~ and ^ are for sr.ht. See golang.org/issue/32260.

const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%! ~^"

slashSlash var #

var slashSlash = *ast.CallExpr

slashStar var #

var slashStar = *ast.CallExpr

starSlash var #

var starSlash = *ast.CallExpr

Type Aliases

ImportMode type #

An ImportMode controls the behavior of the Import method.

type ImportMode uint

Structs

Context struct #

A Context specifies the supporting context for a build.

type Context struct {
GOARCH string
GOOS string
GOROOT string
GOPATH string
Dir string
CgoEnabled bool
UseAllFiles bool
Compiler string
BuildTags []string
ToolTags []string
ReleaseTags []string
InstallSuffix string
JoinPath func(elem ...string) string
SplitPathList func(list string) []string
IsAbsPath func(path string) bool
IsDir func(path string) bool
HasSubdir func(root string, dir string) (rel string, ok bool)
ReadDir func(dir string) ([]fs.FileInfo, error)
OpenFile func(path string) (io.ReadCloser, error)
}

Directive struct #

A Directive is a Go directive comment (//go:zzz...) found in a source file.

type Directive struct {
Text string
Pos token.Position
}

MultiplePackageError struct #

MultiplePackageError describes a directory containing multiple buildable Go source files for multiple packages.

type MultiplePackageError struct {
Dir string
Packages []string
Files []string
}

NoGoError struct #

NoGoError is the error used by [Import] to describe a directory containing no buildable Go source files. (It may still contain test files, files hidden by build tags, and so on.)

type NoGoError struct {
Dir string
}

Package struct #

A Package describes the Go package found in a directory.

type Package struct {
Dir string
Name string
ImportComment string
Doc string
ImportPath string
Root string
SrcRoot string
PkgRoot string
PkgTargetRoot string
BinDir string
Goroot bool
PkgObj string
AllTags []string
ConflictDir string
BinaryOnly bool
GoFiles []string
CgoFiles []string
IgnoredGoFiles []string
InvalidGoFiles []string
IgnoredOtherFiles []string
CFiles []string
CXXFiles []string
MFiles []string
HFiles []string
FFiles []string
SFiles []string
SwigFiles []string
SwigCXXFiles []string
SysoFiles []string
CgoCFLAGS []string
CgoCPPFLAGS []string
CgoCXXFLAGS []string
CgoFFLAGS []string
CgoLDFLAGS []string
CgoPkgConfig []string
TestGoFiles []string
XTestGoFiles []string
Directives []Directive
TestDirectives []Directive
XTestDirectives []Directive
Imports []string
ImportPos map[string][]token.Position
TestImports []string
TestImportPos map[string][]token.Position
XTestImports []string
XTestImportPos map[string][]token.Position
EmbedPatterns []string
EmbedPatternPos map[string][]token.Position
TestEmbedPatterns []string
TestEmbedPatternPos map[string][]token.Position
XTestEmbedPatterns []string
XTestEmbedPatternPos map[string][]token.Position
}

fileEmbed struct #

type fileEmbed struct {
pattern string
pos token.Position
}

fileImport struct #

type fileImport struct {
path string
pos token.Pos
doc *ast.CommentGroup
}

fileInfo struct #

fileInfo records information learned about a file included in a build.

type fileInfo struct {
name string
header []byte
fset *token.FileSet
parsed *ast.File
parseErr error
imports []fileImport
embeds []fileEmbed
directives []Directive
}

importReader struct #

type importReader struct {
b *bufio.Reader
buf []byte
peek byte
err error
eof bool
nerr int
pos token.Position
}

Functions

ArchChar function #

ArchChar returns "?" and an error. In earlier versions of Go, the returned string was used to derive the compiler and linker tool names, the default object file suffix, and the default linker output name. As of Go 1.5, those strings no longer vary by architecture; they are compile, link, .o, and a.out, respectively.

func ArchChar(goarch string) (string, error)

Error method #

func (e *NoGoError) Error() string

Error method #

func (e *MultiplePackageError) Error() string

Import function #

Import is shorthand for Default.Import.

func Import(path string, srcDir string, mode ImportMode) (*Package, error)

Import method #

Import returns details about the Go package named by the import path, interpreting local import paths relative to the srcDir directory. If the path is a local import path naming a package that can be imported using a standard import path, the returned package will set p.ImportPath to that path. In the directory containing the package, .go, .c, .h, and .s files are considered part of the package except for: - .go files in package documentation - files starting with _ or . (likely editor temporary files) - files with build constraints not satisfied by the context If an error occurs, Import returns a non-nil error and a non-nil *[Package] containing partial information.

func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error)

ImportDir function #

ImportDir is shorthand for Default.ImportDir.

func ImportDir(dir string, mode ImportMode) (*Package, error)

ImportDir method #

ImportDir is like [Import] but processes the Go package found in the named directory.

func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error)

IsCommand method #

IsCommand reports whether the package is considered a command to be installed (not just a library). Packages named "main" are treated as commands.

func (p *Package) IsCommand() bool

IsLocalImport function #

IsLocalImport reports whether the import path is a local import path, like ".", "..", "./foo", or "../foo".

func IsLocalImport(path string) bool

MatchFile method #

MatchFile reports whether the file with the given name in the given directory matches the context and would be included in a [Package] created by [ImportDir] of that directory. MatchFile considers the name of the file and may use ctxt.OpenFile to read some or all of the file's content.

func (ctxt *Context) MatchFile(dir string, name string) (match bool, err error)

SrcDirs method #

SrcDirs returns a list of package source root directories. It draws from the current Go root and Go path but omits directories that do not exist.

func (ctxt *Context) SrcDirs() []string

cleanDecls function #

func cleanDecls(m map[string][]token.Position) ([]string, map[string][]token.Position)

defaultContext function #

func defaultContext() Context

defaultGOPATH function #

Keep consistent with cmd/go/internal/cfg.defaultGOPATH.

func defaultGOPATH() string

envOr function #

func envOr(name string, def string) string

equal function #

func equal(x []string, y []string) bool

eval method #

func (ctxt *Context) eval(x constraint.Expr, allTags map[string]bool) bool

expandSrcDir function #

expandSrcDir expands any occurrence of ${SRCDIR}, making sure the result is safe for the shell.

func expandSrcDir(str string, srcdir string) (string, bool)

fileListForExt function #

func fileListForExt(p *Package, ext string) *[]string

findEmbed method #

findEmbed advances the input reader to the next //go:embed comment. It reports whether it found a comment. (Otherwise it found an error or EOF.)

func (r *importReader) findEmbed(first bool) bool

findImportComment function #

func findImportComment(data []byte) (s string, line int)

getToolDir function #

getToolDir returns the default value of ToolDir.

func getToolDir() string

getToolDir function #

getToolDir returns the default value of ToolDir.

func getToolDir() string

goodOSArchFile method #

goodOSArchFile returns false if the name contains a $GOOS or $GOARCH suffix which does not match the current system. The recognized name formats are: name_$(GOOS).* name_$(GOARCH).* name_$(GOOS)_$(GOARCH).* name_$(GOOS)_test.* name_$(GOARCH)_test.* name_$(GOOS)_$(GOARCH)_test.* Exceptions: if GOOS=android, then files with GOOS=linux are also matched. if GOOS=illumos, then files with GOOS=solaris are also matched. if GOOS=ios, then files with GOOS=darwin are also matched.

func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool

gopath method #

gopath returns the list of Go path directories.

func (ctxt *Context) gopath() []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(ctxt *Context, dir string) bool

hasSubdir method #

hasSubdir calls ctxt.HasSubdir (if not nil) or else uses the local file system to answer the question.

func (ctxt *Context) hasSubdir(root string, dir string) (rel string, ok bool)

hasSubdir function #

hasSubdir reports if dir is within root by performing lexical analysis only.

func hasSubdir(root string, dir string) (rel string, ok bool)

importGo method #

importGo checks whether it can use the go command to find the directory for path. If using the go command is not appropriate, importGo returns errNoModules. Otherwise, importGo tries using the go command and reports whether that succeeded. Using the go command lets build.Import and build.Context.Import find code in Go modules. In the long term we want tools to use go/packages (currently golang.org/x/tools/go/packages), which will also use the go command. Invoking the go command here is not very efficient in that it computes information about the requested package and all dependencies and then only reports about the requested package. Then we reinvoke it for every dependency. But this is still better than not working at all. See golang.org/issue/26504.

func (ctxt *Context) importGo(p *Package, path string, srcDir string, mode ImportMode) error

isAbsPath method #

isAbsPath calls ctxt.IsAbsPath (if not nil) or else filepath.IsAbs.

func (ctxt *Context) isAbsPath(path string) bool

isDir method #

isDir calls ctxt.IsDir (if not nil) or else uses os.Stat.

func (ctxt *Context) isDir(path string) bool

isFile method #

isFile determines whether path is a file by trying to open it. It reuses openFile instead of adding another function to the list in Context.

func (ctxt *Context) isFile(path string) bool

isGoBuildComment function #

func isGoBuildComment(line []byte) bool

isIdent function #

func isIdent(c byte) bool

isValidImport function #

isValidImport checks if the import is a valid import using the more strict checks allowed by the implementation restriction in https://go.dev/ref/spec#Import_declarations. It was ported from the function of the same name that was removed from the parser in CL 424855, when the parser stopped doing these checks.

func isValidImport(s string) bool

joinPath method #

joinPath calls ctxt.JoinPath (if not nil) or else filepath.Join.

func (ctxt *Context) joinPath(elem ...string) string

makePathsAbsolute method #

makePathsAbsolute looks for compiler options that take paths and makes them absolute. We do this because through the 1.8 release we ran the compiler in the package directory, so any relative -I or -L options would be relative to that directory. In 1.9 we changed to running the compiler in the build directory, to get consistent build results (issue #19964). To keep builds working, we change any relative -I or -L options to be absolute. Using filepath.IsAbs and filepath.Join here means the results will be different on different systems, but that's OK: -I and -L options are inherently system-dependent.

func (ctxt *Context) makePathsAbsolute(args []string, srcDir string)

matchAuto method #

matchAuto interprets text as either a +build or //go:build expression (whichever works), reporting whether the expression matches the build context. matchAuto is only used for testing of tag evaluation and in #cgo lines, which accept either syntax.

func (ctxt *Context) matchAuto(text string, allTags map[string]bool) bool

matchFile method #

matchFile determines whether the file with the given name in the given directory should be included in the package being constructed. If the file should be included, matchFile returns a non-nil *fileInfo (and a nil error). Non-nil errors are reserved for unexpected problems. If name denotes a Go program, matchFile reads until the end of the imports and returns that section of the file in the fileInfo's header field, even though it only considers text until the first non-comment for go:build lines. If allTags is non-nil, matchFile records any encountered build tag by setting allTags[tag] = true.

func (ctxt *Context) matchFile(dir string, name string, allTags map[string]bool, binaryOnly *bool, fset *token.FileSet) (*fileInfo, error)

matchTag method #

matchTag reports whether the name is one of: cgo (if cgo is enabled) $GOOS $GOARCH ctxt.Compiler linux (if GOOS = android) solaris (if GOOS = illumos) darwin (if GOOS = ios) unix (if this is a Unix GOOS) boringcrypto (if GOEXPERIMENT=boringcrypto is enabled) tag (if tag is listed in ctxt.BuildTags, ctxt.ToolTags, or ctxt.ReleaseTags) It records all consulted tags in allTags.

func (ctxt *Context) matchTag(name string, allTags map[string]bool) bool

nameExt function #

func nameExt(name string) string

newImportReader function #

func newImportReader(name string, r io.Reader) *importReader

nextByte method #

nextByte is like peekByte but advances beyond the returned byte.

func (r *importReader) nextByte(skipSpace bool) byte

openFile method #

openFile calls ctxt.OpenFile (if not nil) or else os.Open.

func (ctxt *Context) openFile(path string) (io.ReadCloser, error)

parseFileHeader function #

parseFileHeader should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/bazelbuild/bazel-gazelle Do not remove or change the type signature. See go.dev/issue/67401. go:linkname parseFileHeader

func parseFileHeader(content []byte) (trimmed []byte, goBuild []byte, sawBinaryOnly bool, err error)

parseGoEmbed function #

parseGoEmbed parses the text following "//go:embed" to extract the glob patterns. It accepts unquoted space-separated patterns as well as double-quoted and back-quoted Go strings. This is based on a similar function in cmd/compile/internal/gc/noder.go; this version calculates position information as well.

func parseGoEmbed(args string, pos token.Position) ([]fileEmbed, error)

parseWord function #

parseWord skips any leading spaces or comments in data and then parses the beginning of data as an identifier or keyword, returning that word and what remains after the word.

func parseWord(data []byte) (word []byte, rest []byte)

peekByte method #

peekByte returns the next byte from the input reader but does not advance beyond it. If skipSpace is set, peekByte skips leading spaces and comments.

func (r *importReader) peekByte(skipSpace bool) byte

readByte method #

readByte reads the next byte from the input, saves it in buf, and returns it. If an error occurs, readByte records the error in r.err and returns 0.

func (r *importReader) readByte() byte

readByteNoBuf method #

readByteNoBuf is like readByte but doesn't buffer the byte. It exhausts r.buf before reading from r.b.

func (r *importReader) readByteNoBuf() byte

readComments function #

readComments is like io.ReadAll, except that it only reads the leading block of comments in the file. readComments should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/bazelbuild/bazel-gazelle Do not remove or change the type signature. See go.dev/issue/67401. go:linkname readComments

func readComments(f io.Reader) ([]byte, error)

readDir method #

readDir calls ctxt.ReadDir (if not nil) or else os.ReadDir.

func (ctxt *Context) readDir(path string) ([]fs.DirEntry, error)

readGoInfo function #

readGoInfo expects a Go file as input and reads the file up to and including the import section. It records what it learned in *info. If info.fset is non-nil, readGoInfo parses the file and sets info.parsed, info.parseErr, info.imports and info.embeds. It only returns an error if there are problems reading the file, not for syntax errors in the file itself.

func readGoInfo(f io.Reader, info *fileInfo) error

readIdent method #

readIdent reads an identifier from the input. If an identifier is not present, readIdent records a syntax error.

func (r *importReader) readIdent()

readImport method #

readImport reads an import clause - optional identifier followed by quoted string - from the input.

func (r *importReader) readImport()

readKeyword method #

readKeyword reads the given keyword from the input. If the keyword is not present, readKeyword records a syntax error.

func (r *importReader) readKeyword(kw string)

readString method #

readString reads a quoted string literal from the input. If an identifier is not present, readString records a syntax error.

func (r *importReader) readString()

safeCgoName function #

func safeCgoName(s string) bool

saveCgo method #

saveCgo saves the information from the #cgo lines in the import "C" comment. These lines set CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS and pkg-config directives that affect the way cgo's C code is built.

func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error

shouldBuild method #

shouldBuild reports whether it is okay to use this file, The rule is that in the file's leading run of // comments and blank lines, which must be followed by a blank line (to avoid including a Go package clause doc comment), lines beginning with '//go:build' are taken as build directives. The file is accepted only if each such line lists something matching the file. For example: //go:build windows linux marks the file as applicable only on Windows and Linux. For each build tag it consults, shouldBuild sets allTags[tag] = true. shouldBuild reports whether the file should be built and whether a //go:binary-only-package comment was found.

func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool) (shouldBuild bool, binaryOnly bool, err error)

skipSpaceOrComment function #

skipSpaceOrComment returns data with any leading spaces or comments removed.

func skipSpaceOrComment(data []byte) []byte

splitPathList method #

splitPathList calls ctxt.SplitPathList (if not nil) or else filepath.SplitList.

func (ctxt *Context) splitPathList(s string) []string

splitQuoted function #

splitQuoted splits the string s around each instance of one or more consecutive white space characters while taking into account quotes and escaping, and returns an array of substrings of s or an empty list if s contains only white space. Single quotes and double quotes are recognized to prevent splitting within the quoted region, and are removed from the resulting substrings. If a quote in s isn't closed err will be set and r will have the unclosed argument as the last element. The backslash is used for escaping. For example, the following string: a b:"c d" 'e''f' "g\"" Would be parsed as: []string{"a", "b:c d", "ef", `g"`}

func splitQuoted(s string) (r []string, err error)

syntaxError method #

syntaxError records a syntax error, but only if an I/O error has not already been recorded.

func (r *importReader) syntaxError()

uniq function #

func uniq(list []string) []string

Generated with Arrow