version: 1.10

package build

import "go/build"

Overview

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:

  1. GOPATH=/home/user/gocode
  2. /home/user/gocode/
  3. src/
  4. foo/
  5. bar/ (go code in package bar)
  6. x.go
  7. quux/ (go code in package main)
  8. y.go
  9. bin/
  10. quux (installed command)
  11. pkg/
  12. linux_amd64/
  13. foo/
  14. bar.a (installed package object)

Build Constraints

A build constraint, also known as a build tag, is a line comment that begins

  1. // +build

that lists the conditions under which a file should be included in the package.
Constraints may appear in any kind of source file (not just Go), but they must
appear near the top of the file, preceded only by blank lines and other line
comments. These rules mean that in Go files a build constraint must appear
before the package clause.

To distinguish build constraints from package documentation, a series of build
constraints must be followed by a blank line.

A build constraint is evaluated as the OR of space-separated options; each
option evaluates as the AND of its comma-separated terms; and each term is an
alphanumeric word or, preceded by !, its negation. That is, the build
constraint:

  1. // +build linux,386 darwin,!cgo

corresponds to the boolean formula:

  1. (linux AND 386) OR (darwin AND (NOT cgo))

A file may have multiple build constraints. The overall constraint is the AND of
the individual constraints. That is, the build constraints:

  1. // +build linux darwin
  2. // +build 386

corresponds to the boolean formula:

  1. (linux OR darwin) AND 386

During a particular build, the following words are satisfied:

  1. - the target operating system, as spelled by runtime.GOOS
  2. - the target architecture, as spelled by runtime.GOARCH
  3. - the compiler being used, either "gc" or "gccgo"
  4. - "cgo", if ctxt.CgoEnabled is true
  5. - "go1.1", from Go version 1.1 onward
  6. - "go1.2", from Go version 1.2 onward
  7. - "go1.3", from Go version 1.3 onward
  8. - "go1.4", from Go version 1.4 onward
  9. - "go1.5", from Go version 1.5 onward
  10. - "go1.6", from Go version 1.6 onward
  11. - "go1.7", from Go version 1.7 onward
  12. - "go1.8", from Go version 1.8 onward
  13. - "go1.9", from Go version 1.9 onward
  14. - "go1.10", from Go version 1.10 onward
  15. - any additional words listed in ctxt.BuildTags

If a file’s name, after stripping the extension and a possible _test suffix,
matches any of the following patterns:

  1. *_GOOS
  2. *_GOARCH
  3. *_GOOS_GOARCH

(example: source_windows_amd64.go) where GOOS and GOARCH represent any known
operating system and architecture values respectively, then the file is
considered to have an implicit build constraint requiring those terms (in
addition to any explicit constraints in the file).

To keep a file from being considered for the build:

  1. // +build ignore

(any other unsatisfied word will work as well, but ``ignore’’ is conventional.)

To build a file only when using cgo, and only on Linux and OS X:

  1. // +build linux,cgo darwin,cgo

Such a file is usually paired with another file implementing the default
functionality for other systems, which in this case would carry the constraint:

  1. // +build !linux,!darwin !cgo

Naming a file dns_windows.go will cause it to be included only when building the
package for Windows; similarly, math_386.s will be included only when building
the package for 32-bit x86.

Using GOOS=android matches build tags and files as for GOOS=linux in addition to
android tags and files.

Binary-Only Packages

It is possible to distribute packages in binary form without including the
source code used for compiling the package. To do this, the package must be
distributed with a source file not excluded by build constraints and containing
a “//go:binary-only-package” comment. Like a build constraint, this comment must
appear near the top of the 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 is therefore:

  1. //go:binary-only-package
  2. package mypkg

The source code may include additional Go code. That code is never compiled but
will be processed by tools like godoc and might be useful as end-user
documentation.

Index

Package files

build.go doc.go read.go syslist.go zcgo.go

Variables

  1. var ToolDir = filepath.Join(runtime.GOROOT(), "pkg/tool/"+runtime.GOOS+"_"+runtime.GOARCH)

ToolDir is the directory containing build tools.

func ArchChar

  1. func ArchChar(goarch string) (string, error)

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 IsLocalImport

  1. func IsLocalImport(path string) bool

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

type Context

  1. type Context struct {
  2. GOARCH string // target architecture
  3. GOOS string // target operating system
  4. GOROOT string // Go root
  5. GOPATH string // Go path
  6. CgoEnabled bool // whether cgo can be used
  7. UseAllFiles bool // use files regardless of +build lines, file names
  8. Compiler string // compiler to assume when computing target paths
  9.  
  10. // The build and release tags specify build constraints
  11. // that should be considered satisfied when processing +build lines.
  12. // Clients creating a new context may customize BuildTags, which
  13. // defaults to empty, but it is usually an error to customize ReleaseTags,
  14. // which defaults to the list of Go releases the current release is compatible with.
  15. // In addition to the BuildTags and ReleaseTags, build constraints
  16. // consider the values of GOARCH and GOOS as satisfied tags.
  17. BuildTags []string
  18. ReleaseTags []string
  19.  
  20. // The install suffix specifies a suffix to use in the name of the installation
  21. // directory. By default it is empty, but custom builds that need to keep
  22. // their outputs separate can set InstallSuffix to do so. For example, when
  23. // using the race detector, the go command uses InstallSuffix = "race", so
  24. // that on a Linux/386 system, packages are written to a directory named
  25. // "linux_386_race" instead of the usual "linux_386".
  26. InstallSuffix string
  27.  
  28. // JoinPath joins the sequence of path fragments into a single path.
  29. // If JoinPath is nil, Import uses filepath.Join.
  30. JoinPath func(elem ...string) string
  31.  
  32. // SplitPathList splits the path list into a slice of individual paths.
  33. // If SplitPathList is nil, Import uses filepath.SplitList.
  34. SplitPathList func(list string) []string
  35.  
  36. // IsAbsPath reports whether path is an absolute path.
  37. // If IsAbsPath is nil, Import uses filepath.IsAbs.
  38. IsAbsPath func(path string) bool
  39.  
  40. // IsDir reports whether the path names a directory.
  41. // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.
  42. IsDir func(path string) bool
  43.  
  44. // HasSubdir reports whether dir is lexically a subdirectory of
  45. // root, perhaps multiple levels below. It does not try to check
  46. // whether dir exists.
  47. // If so, HasSubdir sets rel to a slash-separated path that
  48. // can be joined to root to produce a path equivalent to dir.
  49. // If HasSubdir is nil, Import uses an implementation built on
  50. // filepath.EvalSymlinks.
  51. HasSubdir func(root, dir string) (rel string, ok bool)
  52.  
  53. // ReadDir returns a slice of os.FileInfo, sorted by Name,
  54. // describing the content of the named directory.
  55. // If ReadDir is nil, Import uses ioutil.ReadDir.
  56. ReadDir func(dir string) ([]os.FileInfo, error)
  57.  
  58. // OpenFile opens a file (not a directory) for reading.
  59. // If OpenFile is nil, Import uses os.Open.
  60. OpenFile func(path string) (io.ReadCloser, error)
  61. }

A Context specifies the supporting context for a build.

  1. var Default Context = defaultContext()

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.

func (*Context) Import

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

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:

  1. - .go files in package documentation
  2. - files starting with _ or . (likely editor temporary files)
  3. - 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

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

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

func (*Context) MatchFile

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

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 (*Context) SrcDirs

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

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.

type ImportMode

  1. type ImportMode uint

An ImportMode controls the behavior of the Import method.

  1. const (
  2. // If FindOnly is set, Import stops after locating the directory
  3. // that should contain the sources for a package. It does not
  4. // read any files in the directory.
  5. FindOnly ImportMode = 1 << iota
  6.  
  7. // If AllowBinary is set, Import can be satisfied by a compiled
  8. // package object without corresponding sources.
  9. //
  10. // Deprecated:
  11. // The supported way to create a compiled-only package is to
  12. // write source code containing a //go:binary-only-package comment at
  13. // the top of the file. Such a package will be recognized
  14. // regardless of this flag setting (because it has source code)
  15. // and will have BinaryOnly set to true in the returned Package.
  16. AllowBinary
  17.  
  18. // If ImportComment is set, parse import comments on package statements.
  19. // Import returns an error if it finds a comment it cannot understand
  20. // or finds conflicting comments in multiple source files.
  21. // See golang.org/s/go14customimport for more information.
  22. ImportComment
  23.  
  24. // By default, Import searches vendor directories
  25. // that apply in the given source directory before searching
  26. // the GOROOT and GOPATH roots.
  27. // If an Import finds and returns a package using a vendor
  28. // directory, the resulting ImportPath is the complete path
  29. // to the package, including the path elements leading up
  30. // to and including "vendor".
  31. // For example, if Import("y", "x/subdir", 0) finds
  32. // "x/vendor/y", the returned package's ImportPath is "x/vendor/y",
  33. // not plain "y".
  34. // See golang.org/s/go15vendor for more information.
  35. //
  36. // Setting IgnoreVendor ignores vendor directories.
  37. //
  38. // In contrast to the package's ImportPath,
  39. // the returned package's Imports, TestImports, and XTestImports
  40. // are always the exact import paths from the source files:
  41. // Import makes no attempt to resolve or check those paths.
  42. IgnoreVendor
  43. )

type MultiplePackageError

  1. type MultiplePackageError struct {
  2. Dir string // directory containing files
  3. Packages []string // package names found
  4. Files []string // corresponding files: Files[i] declares package Packages[i]
  5. }

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

func (*MultiplePackageError) Error

  1. func (e *MultiplePackageError) Error() string

type NoGoError

  1. type NoGoError struct {
  2. Dir string
  3. }

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.)

func (*NoGoError) Error

  1. func (e *NoGoError) Error() string

type Package

  1. type Package struct {
  2. Dir string // directory containing package sources
  3. Name string // package name
  4. ImportComment string // path in import comment on package statement
  5. Doc string // documentation synopsis
  6. ImportPath string // import path of package ("" if unknown)
  7. Root string // root of Go tree where this package lives
  8. SrcRoot string // package source root directory ("" if unknown)
  9. PkgRoot string // package install root directory ("" if unknown)
  10. PkgTargetRoot string // architecture dependent install root directory ("" if unknown)
  11. BinDir string // command install directory ("" if unknown)
  12. Goroot bool // package found in Go root
  13. PkgObj string // installed .a file
  14. AllTags []string // tags that can influence file selection in this directory
  15. ConflictDir string // this directory shadows Dir in $GOPATH
  16. BinaryOnly bool // cannot be rebuilt from source (has //go:binary-only-package comment)
  17.  
  18. // Source files
  19. GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
  20. CgoFiles []string // .go source files that import "C"
  21. IgnoredGoFiles []string // .go source files ignored for this build
  22. InvalidGoFiles []string // .go source files with detected problems (parse error, wrong package name, and so on)
  23. CFiles []string // .c source files
  24. CXXFiles []string // .cc, .cpp and .cxx source files
  25. MFiles []string // .m (Objective-C) source files
  26. HFiles []string // .h, .hh, .hpp and .hxx source files
  27. FFiles []string // .f, .F, .for and .f90 Fortran source files
  28. SFiles []string // .s source files
  29. SwigFiles []string // .swig files
  30. SwigCXXFiles []string // .swigcxx files
  31. SysoFiles []string // .syso system object files to add to archive
  32.  
  33. // Cgo directives
  34. CgoCFLAGS []string // Cgo CFLAGS directives
  35. CgoCPPFLAGS []string // Cgo CPPFLAGS directives
  36. CgoCXXFLAGS []string // Cgo CXXFLAGS directives
  37. CgoFFLAGS []string // Cgo FFLAGS directives
  38. CgoLDFLAGS []string // Cgo LDFLAGS directives
  39. CgoPkgConfig []string // Cgo pkg-config directives
  40.  
  41. // Dependency information
  42. Imports []string // import paths from GoFiles, CgoFiles
  43. ImportPos map[string][]token.Position // line information for Imports
  44.  
  45. // Test information
  46. TestGoFiles []string // _test.go files in package
  47. TestImports []string // import paths from TestGoFiles
  48. TestImportPos map[string][]token.Position // line information for TestImports
  49. XTestGoFiles []string // _test.go files outside package
  50. XTestImports []string // import paths from XTestGoFiles
  51. XTestImportPos map[string][]token.Position // line information for XTestImports
  52. }

A Package describes the Go package found in a directory.

func Import

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

Import is shorthand for Default.Import.

func ImportDir

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

ImportDir is shorthand for Default.ImportDir.

func (*Package) IsCommand

  1. func (p *Package) IsCommand() bool

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