Involved Source Filesbuild.go
Package build gathers information about Go packages.
Go Path
The Go path is a list of directory trees containing Go source code.
It is consulted to resolve imports that cannot be found in the standard
Go tree. The default path is the value of the GOPATH environment
variable, interpreted as a path list appropriate to the operating system
(on Unix, the variable is a colon-separated string;
on Windows, a semicolon-separated string;
on Plan 9, a list).
Each directory listed in the Go path must have a prescribed structure:
The src/ directory holds source code. The path below 'src' determines
the import path or executable name.
The pkg/ directory holds installed package objects.
As in the Go tree, each target operating system and
architecture pair has its own subdirectory of pkg
(pkg/GOOS_GOARCH).
If DIR is a directory listed in the Go path, a package with
source in DIR/src/foo/bar can be imported as "foo/bar" and
has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a"
(or, for gccgo, "DIR/pkg/gccgo/foo/libbar.a").
The bin/ directory holds compiled commands.
Each command is named for its source directory, but only
using the final element, not the entire path. That is, the
command with source in DIR/src/foo/quux is installed into
DIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped
so that you can add DIR/bin to your PATH to get at the
installed commands.
Here's an example directory layout:
GOPATH=/home/user/gocode
/home/user/gocode/
src/
foo/
bar/ (go code in package bar)
x.go
quux/ (go code in package main)
y.go
bin/
quux (installed command)
pkg/
linux_amd64/
foo/
bar.a (installed package object)
Build Constraints
A build constraint, also known as a build tag, is a line comment that begins
//go:build
that lists the conditions under which a file should be included in the
package. Build constraints may also be part of a file's name
(for example, source_windows.go will only be included if the target
operating system is windows).
See 'go help buildconstraint'
(https://golang.org/cmd/go/#hdr-Build_constraints) for details.
Binary-Only Packages
In Go 1.12 and earlier, it was possible to distribute packages in binary
form without including the source code used for compiling the package.
The package was distributed with a source file not excluded by build
constraints and containing a "//go:binary-only-package" comment. Like a
build constraint, this comment appeared at the top of a file, preceded
only by blank lines and other line comments and with a blank line
following the comment, to separate it from the package documentation.
Unlike build constraints, this comment is only recognized in non-test
Go source files.
The minimal source code for a binary-only package was therefore:
//go:binary-only-package
package mypkg
The source code could include additional Go code. That code was never
compiled but would be processed by tools like godoc and might be useful
as end-user documentation.
"go build" and other commands no longer support binary-only-packages.
Import and ImportDir will still set the BinaryOnly flag in packages
containing these comments for use in tools and error messages.
gc.goread.gosyslist.gozcgo.go
Package-Level Type Names (total 9, in which 5 are exported)
/* sort exporteds by: | */
A Context specifies the supporting context for a build.
The build, tool, and release tags specify build constraints
that should be considered satisfied when processing +build lines.
Clients creating a new context may customize BuildTags, which
defaults to empty, but it is usually an error to customize ToolTags or ReleaseTags.
ToolTags defaults to build tags appropriate to the current Go toolchain configuration.
ReleaseTags defaults to the list of Go releases the current release is compatible with.
BuildTags is not set for the Default build Context.
In addition to the BuildTags, ToolTags, and ReleaseTags, build constraints
consider the values of GOARCH and GOOS as satisfied tags.
The last element in ReleaseTags is assumed to be the current release.
// whether cgo files are included
// compiler to assume when computing target paths
Dir is the caller's working directory, or the empty string to use
the current directory of the running process. In module mode, this is used
to locate the main module.
If Dir is non-empty, directories passed to Import and ImportDir must
be absolute.
// target architecture
// target operating system
// Go path
// Go root
HasSubdir reports whether dir is lexically a subdirectory of
root, perhaps multiple levels below. It does not try to check
whether dir exists.
If so, HasSubdir sets rel to a slash-separated path that
can be joined to root to produce a path equivalent to dir.
If HasSubdir is nil, Import uses an implementation built on
filepath.EvalSymlinks.
The install suffix specifies a suffix to use in the name of the installation
directory. By default it is empty, but custom builds that need to keep
their outputs separate can set InstallSuffix to do so. For example, when
using the race detector, the go command uses InstallSuffix = "race", so
that on a Linux/386 system, packages are written to a directory named
"linux_386_race" instead of the usual "linux_386".
IsAbsPath reports whether path is an absolute path.
If IsAbsPath is nil, Import uses filepath.IsAbs.
IsDir reports whether the path names a directory.
If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.
JoinPath joins the sequence of path fragments into a single path.
If JoinPath is nil, Import uses filepath.Join.
OpenFile opens a file (not a directory) for reading.
If OpenFile is nil, Import uses os.Open.
ReadDir returns a slice of fs.FileInfo, sorted by Name,
describing the content of the named directory.
If ReadDir is nil, Import uses ioutil.ReadDir.
ReleaseTags[]string
SplitPathList splits the path list into a slice of individual paths.
If SplitPathList is nil, Import uses filepath.SplitList.
ToolTags[]string
// use files regardless of +build lines, file names
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.
ImportDir is like Import but processes the Go package found in
the named directory.
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.
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.
(*Context) eval(x constraint.Expr, allTags map[string]bool) bool
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.
gopath returns the list of Go path directories.
hasSubdir calls ctxt.HasSubdir (if not nil) or else uses
the local file system to answer the question.
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.
isAbsPath calls ctxt.IsAbsPath (if not nil) or else filepath.IsAbs.
isDir calls ctxt.IsDir (if not nil) or else uses os.Stat.
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.
joinPath calls ctxt.JoinPath (if not nil) or else filepath.Join.
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.
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.
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 +build lines.
If allTags is non-nil, matchFile records any encountered build tag
by setting allTags[tag] = true.
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)
tag (if tag is listed in ctxt.BuildTags or ctxt.ReleaseTags)
It records all consulted tags in allTags.
openFile calls ctxt.OpenFile (if not nil) or else os.Open.
readDir calls ctxt.ReadDir (if not nil) or else ioutil.ReadDir.
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.
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 '// +build' are taken as build directives.
The file is accepted only if each such line lists something
matching the file. For example:
// +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.
splitPathList calls ctxt.SplitPathList (if not nil) or else filepath.SplitList.
func defaultContext() Context
func hasGoFiles(ctxt *Context, dir string) bool
var Default
MultiplePackageError describes a directory containing
multiple buildable Go source files for multiple packages.
// directory containing files
// corresponding files: Files[i] declares package Packages[i]
// package names found
(*MultiplePackageError) Error() string
*MultiplePackageError : error
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.)
Dirstring(*NoGoError) Error() string
*NoGoError : error
A Package describes the Go package found in a directory.
// tags that can influence file selection in this directory
// command install directory ("" if unknown)
// cannot be rebuilt from source (has //go:binary-only-package comment)
// .c source files
// .cc, .cpp and .cxx source files
Cgo directives
// Cgo CFLAGS directives
// Cgo CPPFLAGS directives
// Cgo CXXFLAGS directives
// Cgo FFLAGS directives
// .go source files that import "C"
// Cgo LDFLAGS directives
// Cgo pkg-config directives
// this directory shadows Dir in $GOPATH
// directory containing package sources
// documentation synopsis
// line information for EmbedPatterns
//go:embed patterns found in Go source files
For example, if a source file says
//go:embed a* b.c
then the list will contain those two strings as separate entries.
(See package embed for more details about //go:embed.)
// patterns from GoFiles, CgoFiles
// .f, .F, .for and .f90 Fortran source files
Source files
// .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
// package found in Go root
// .h, .hh, .hpp and .hxx source files
// .go source files ignored for this build (including ignored _test.go files)
// non-.go source files ignored for this build
// path in import comment on package statement
// import path of package ("" if unknown)
// line information for Imports
Dependency information
// import paths from GoFiles, CgoFiles
// .go source files with detected problems (parse error, wrong package name, and so on)
// .m (Objective-C) source files
// package name
// installed .a file
// package install root directory ("" if unknown)
// architecture dependent install root directory ("" if unknown)
// root of Go tree where this package lives
// .s source files
// package source root directory ("" if unknown)
// .swigcxx files
// .swig files
// .syso system object files to add to archive
// line information for TestEmbedPatterns
// patterns from TestGoFiles
Test information
// _test.go files in package
// line information for TestImports
// import paths from TestGoFiles
// line information for XTestEmbedPatternPos
// patterns from XTestGoFiles
// _test.go files outside package
// line information for XTestImports
// import paths from XTestGoFiles
IsCommand reports whether the package is considered a
command to be installed (not just a library).
Packages named "main" are treated as commands.
func Import(path, srcDir string, mode ImportMode) (*Package, error)
func ImportDir(dir string, mode ImportMode) (*Package, error)
func (*Context).Import(path string, srcDir string, mode ImportMode) (*Package, error)
func (*Context).ImportDir(dir string, mode ImportMode) (*Package, error)
func fileListForExt(p *Package, ext string) *[]string
func (*Context).importGo(p *Package, path, srcDir string, mode ImportMode) error
func (*Context).saveCgo(filename string, di *Package, cg *ast.CommentGroup) error
var dummyPkg
b*bufio.Readerbuf[]byteeofboolerrerrornerrintpeekbytepostoken.Position
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.)
nextByte is like peekByte but advances beyond the returned byte.
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.
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.
readByteNoBuf is like readByte but doesn't buffer the byte.
It exhausts r.buf before reading from r.b.
readIdent reads an identifier from the input.
If an identifier is not present, readIdent records a syntax error.
readImport reads an import clause - optional identifier followed by quoted string -
from the input.
readKeyword reads the given keyword from the input.
If the keyword is not present, readKeyword records a syntax error.
readString reads a quoted string literal from the input.
If an identifier is not present, readString records a syntax error.
syntaxError records a syntax error, but only if an I/O error has not already been recorded.
func newImportReader(name string, r io.Reader) *importReader
Package-Level Functions (total 29, in which 4 are exported)
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.
Import is shorthand for Default.Import.
ImportDir is shorthand for Default.ImportDir.
IsLocalImport reports whether the import path is
a local import path, like ".", "..", "./foo", or "../foo".
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.
hasSubdir reports if dir is within root by performing lexical analysis only.
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.
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.
readComments is like io.ReadAll, except that it only reads the leading
block of comments in the file.
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, info.embeds, and info.embedErr.
It only returns an error if there are problems reading the file,
not for syntax errors in the file itself.
skipSpaceOrComment returns data with any leading spaces or comments removed.
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"`}
Package-Level Variables (total 25, in which 2 are exported)
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.
ToolDir is the directory containing build tools.
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.
Package-Level Constants (total 8, in which 4 are exported)
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.
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.
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.
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.
constgoosList = "aix android darwin dragonfly freebsd hurd illumos ios js linux nacl ...
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.
The pages are generated with Goldsv0.4.9. (GOOS=linux GOARCH=amd64)