build
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package build gathers information about Go packages.
Build Constraints¶
A build constraint, also known as a build tag, is a condition under which afile should be included in the package. Build constraints are given by aline comment that begins
//go:build
Build constraints may also be part of a file's name(for example, source_windows.go will only be included if the targetoperating system is windows).
See 'go help buildconstraint'(https://pkg.go.dev/cmd/go#hdr-Build_constraints) for details.
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 standardGo tree. The default path is the value of the GOPATH environmentvariable, 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' determinesthe import path or executable name.
The pkg/ directory holds installed package objects.As in the Go tree, each target operating system andarchitecture pair has its own subdirectory of pkg(pkg/GOOS_GOARCH).
If DIR is a directory listed in the Go path, a package withsource in DIR/src/foo/bar can be imported as "foo/bar" andhas 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 onlyusing the final element, not the entire path. That is, thecommand with source in DIR/src/foo/quux is installed intoDIR/bin/quux, not DIR/bin/foo/quux. The foo/ is strippedso that you can add DIR/bin to your PATH to get at theinstalled 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)
Binary-Only Packages¶
In Go 1.12 and earlier, it was possible to distribute packages in binaryform without including the source code used for compiling the package.The package was distributed with a source file not excluded by buildconstraints and containing a "//go:binary-only-package" comment. Like abuild constraint, this comment appeared at the top of a file, precededonly by blank lines and other line comments and with a blank linefollowing the comment, to separate it from the package documentation.Unlike build constraints, this comment is only recognized in non-testGo source files.
The minimal source code for a binary-only package was therefore:
//go:binary-only-packagepackage mypkg
The source code could include additional Go code. That code was nevercompiled but would be processed by tools like godoc and might be usefulas end-user documentation.
"go build" and other commands no longer support binary-only-packages.Import andImportDir will still set the BinaryOnly flag in packagescontaining these comments for use in tools and error messages.
Index¶
Constants¶
This section is empty.
Variables¶
var ToolDir = getToolDir()ToolDir is the directory containing build tools.
Functions¶
funcArchChar¶
ArchChar returns "?" and an error.In earlier versions of Go, the returned string was used to derivethe compiler and linker tool names, the default object file suffix,and the default linker output name. As of Go 1.5, those stringsno longer vary by architecture; they are compile, link, .o, and a.out, respectively.
funcIsLocalImport¶
IsLocalImport reports whether the import path isa local import path, like ".", "..", "./foo", or "../foo".
Types¶
typeContext¶
type Context struct {GOARCHstring// target architectureGOOSstring// target operating systemGOROOTstring// Go rootGOPATHstring// Go 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.DirstringCgoEnabledbool// whether cgo files are includedUseAllFilesbool// use files regardless of go:build lines, file namesCompilerstring// compiler to assume when computing target paths// The build, tool, and release tags specify build constraints// that should be considered satisfied when processing go: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.BuildTags []stringToolTags []stringReleaseTags []string// 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".InstallSuffixstring// JoinPath joins the sequence of path fragments into a single path.// If JoinPath is nil, Import uses filepath.Join.JoinPath func(elem ...string)string// SplitPathList splits the path list into a slice of individual paths.// If SplitPathList is nil, Import uses filepath.SplitList.SplitPathList func(liststring) []string// IsAbsPath reports whether path is an absolute path.// If IsAbsPath is nil, Import uses filepath.IsAbs.IsAbsPath func(pathstring)bool// IsDir reports whether the path names a directory.// If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.IsDir func(pathstring)bool// 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.HasSubdir func(root, dirstring) (relstring, okbool)// ReadDir returns a slice of fs.FileInfo, sorted by Name,// describing the content of the named directory.// If ReadDir is nil, Import uses os.ReadDir.ReadDir func(dirstring) ([]fs.FileInfo,error)// OpenFile opens a file (not a directory) for reading.// If OpenFile is nil, Import uses os.Open.OpenFile func(pathstring) (io.ReadCloser,error)}A Context specifies the supporting context for a build.
var DefaultContext = defaultContext()Default is the default Context for builds.It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variablesif set, or else the compiled code's GOARCH, GOOS, and GOROOT.
func (*Context)Import¶
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 importedusing a standard import path, the returned package will set p.ImportPathto that path.
In the directory containing the package, .go, .c, .h, and .s files areconsidered 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 (*Context)ImportDir¶
func (ctxt *Context) ImportDir(dirstring, modeImportMode) (*Package,error)
ImportDir is likeImport but processes the Go package found inthe named directory.
func (*Context)MatchFile¶added ingo1.2
MatchFile reports whether the file with the given name in the given directorymatches the context and would be included in aPackage created byImportDirof that directory.
MatchFile considers the name of the file and may use ctxt.OpenFile toread some or all of the file's content.
typeDirective¶added ingo1.21.0
type Directive struct {Textstring// full line comment including leading slashesPostoken.Position// position of comment}A Directive is a Go directive comment (//go:zzz...) found in a source file.
typeImportMode¶
type ImportModeuint
An ImportMode controls the behavior of the Import method.
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.FindOnlyImportMode = 1 <<iota// 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.AllowBinary// 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.ImportComment// 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.IgnoreVendor)
typeMultiplePackageError¶added ingo1.4
type MultiplePackageError struct {Dirstring// directory containing filesPackages []string// package names foundFiles []string// corresponding files: Files[i] declares package Packages[i]}MultiplePackageError describes a directory containingmultiple buildable Go source files for multiple packages.
func (*MultiplePackageError)Error¶added ingo1.4
func (e *MultiplePackageError) Error()string
typeNoGoError¶
type NoGoError struct {Dirstring}NoGoError is the error used byImport to describe a directorycontaining no buildable Go source files. (It may still containtest files, files hidden by build tags, and so on.)
typePackage¶
type Package struct {Dirstring// directory containing package sourcesNamestring// package nameImportCommentstring// path in import comment on package statementDocstring// documentation synopsisImportPathstring// import path of package ("" if unknown)Rootstring// root of Go tree where this package livesSrcRootstring// package source root directory ("" if unknown)PkgRootstring// package install root directory ("" if unknown)PkgTargetRootstring// architecture dependent install root directory ("" if unknown)BinDirstring// command install directory ("" if unknown)Gorootbool// package found in Go rootPkgObjstring// installed .a fileAllTags []string// tags that can influence file selection in this directoryConflictDirstring// this directory shadows Dir in $GOPATHBinaryOnlybool// cannot be rebuilt from source (has //go:binary-only-package comment)// Source filesGoFiles []string// .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)CgoFiles []string// .go source files that import "C"IgnoredGoFiles []string// .go source files ignored for this build (including ignored _test.go files)InvalidGoFiles []string// .go source files with detected problems (parse error, wrong package name, and so on)IgnoredOtherFiles []string// non-.go source files ignored for this buildCFiles []string// .c source filesCXXFiles []string// .cc, .cpp and .cxx source filesMFiles []string// .m (Objective-C) source filesHFiles []string// .h, .hh, .hpp and .hxx source filesFFiles []string// .f, .F, .for and .f90 Fortran source filesSFiles []string// .s source filesSwigFiles []string// .swig filesSwigCXXFiles []string// .swigcxx filesSysoFiles []string// .syso system object files to add to archive// Cgo directivesCgoCFLAGS []string// Cgo CFLAGS directivesCgoCPPFLAGS []string// Cgo CPPFLAGS directivesCgoCXXFLAGS []string// Cgo CXXFLAGS directivesCgoFFLAGS []string// Cgo FFLAGS directivesCgoLDFLAGS []string// Cgo LDFLAGS directivesCgoPkgConfig []string// Cgo pkg-config directives// Test informationTestGoFiles []string// _test.go files in packageXTestGoFiles []string// _test.go files outside package// Go directive comments (//go:zzz...) found in source files.Directives []DirectiveTestDirectives []DirectiveXTestDirectives []Directive// Dependency informationImports []string// import paths from GoFiles, CgoFilesImportPos map[string][]token.Position// line information for ImportsTestImports []string// import paths from TestGoFilesTestImportPos map[string][]token.Position// line information for TestImportsXTestImports []string// import paths from XTestGoFilesXTestImportPos map[string][]token.Position// line information for XTestImports// //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.)EmbedPatterns []string// patterns from GoFiles, CgoFilesEmbedPatternPos map[string][]token.Position// line information for EmbedPatternsTestEmbedPatterns []string// patterns from TestGoFilesTestEmbedPatternPos map[string][]token.Position// line information for TestEmbedPatternsXTestEmbedPatterns []string// patterns from XTestGoFilesXTestEmbedPatternPos map[string][]token.Position// line information for XTestEmbedPatternPos}A Package describes the Go package found in a directory.
funcImport¶
func Import(path, srcDirstring, modeImportMode) (*Package,error)
Import is shorthand for Default.Import.
Directories¶
| Path | Synopsis |
|---|---|
Package constraint implements parsing and evaluation of build constraint lines. | Package constraint implements parsing and evaluation of build constraint lines. |