build - The Go Programming Language

Golang

Package build

import "go/build"
Overview
Index

Overview ?

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:

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 is a line comment beginning with the directive +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 be appear near the top of the file, preceded only by blank lines and other line comments.

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:

// +build linux,386 darwin,!cgo

corresponds to the boolean formula:

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

During a particular build, the following words are satisfied:

- the target operating system, as spelled by runtime.GOOS
- the target architecture, as spelled by runtime.GOARCH
- "cgo", if ctxt.CgoEnabled is true
- any additional words listed in ctxt.BuildTags

If a file's name, after stripping the extension and a possible _test suffix, matches *_GOOS, *_GOARCH, or *_GOOS_GOARCH for any known operating system and architecture values, then the file is considered to have an implicit build constraint requiring those terms.

To keep a file from being considered for the build:

// +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:

// +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:

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

Index

Variables
func ArchChar(goarch string) (string, error)
func IsLocalImport(path string) bool
type Context
    func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error)
    func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error)
    func (ctxt *Context) SrcDirs() []string
type ImportMode
type NoGoError
    func (e *NoGoError) Error() string
type Package
    func Import(path, srcDir string, mode ImportMode) (*Package, error)
    func ImportDir(dir string, mode ImportMode) (*Package, error)
    func (p *Package) IsCommand() bool

Package files

build.go doc.go syslist.go

Variables

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

ToolDir is the directory containing build tools.

func ArchChar

func ArchChar(goarch string) (string, error)

ArchChar returns the architecture character for the given goarch. For example, ArchChar("amd64") returns "6".

func IsLocalImport

func IsLocalImport(path string) bool

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

type Context

type Context struct {
    GOARCH      string   // target architecture
    GOOS        string   // target operating system
    GOROOT      string   // Go root
    GOPATH      string   // Go path
    CgoEnabled  bool     // whether cgo can be used
    BuildTags   []string // additional tags to recognize in +build lines
    UseAllFiles bool     // use files regardless of +build lines, file names
    Compiler    string

    // 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(list string) []string

    // IsAbsPath reports whether path is an absolute path.
    // If IsAbsPath is nil, Import uses filepath.IsAbs.
    IsAbsPath func(path string) 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(path string) bool

    // HasSubdir reports whether dir is a subdirectory of
    // (perhaps multiple levels below) root.
    // 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, dir string) (rel string, ok bool)

    // ReadDir returns a slice of os.FileInfo, sorted by Name,
    // describing the content of the named directory.
    // If ReadDir is nil, Import uses io.ReadDir.
    ReadDir func(dir string) (fi []os.FileInfo, err error)

    // OpenFile opens a file (not a directory) for reading.
    // If OpenFile is nil, Import uses os.Open.
    OpenFile func(path string) (r io.ReadCloser, err error)
}

A Context specifies the supporting context for a build.

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

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:

- .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 also returns a non-nil *Package containing partial information.

func (*Context) ImportDir

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

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

type ImportMode uint

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.
    FindOnly ImportMode = 1 << iota

    // If AllowBinary is set, Import can be satisfied by a compiled
    // package object without corresponding sources.
    AllowBinary
)

type NoGoError

type NoGoError struct {
    Dir string
}

NoGoError is the error used by Import to describe a directory containing no Go source files.

func (*NoGoError) Error

func (e *NoGoError) Error() string

type Package

type Package struct {
    Dir        string // directory containing package sources
    Name       string // package name
    Doc        string // documentation synopsis
    ImportPath string // import path of package ("" if unknown)
    Root       string // root of Go tree where this package lives
    SrcRoot    string // package source root directory ("" if unknown)
    PkgRoot    string // package install root directory ("" if unknown)
    BinDir     string // command install directory ("" if unknown)
    Goroot     bool   // package found in Go root
    PkgObj     string

    // Source files
    GoFiles   []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
    CgoFiles  []string // .go source files that import "C"
    CFiles    []string // .c source files
    HFiles    []string // .h source files
    SFiles    []string // .s source files
    SysoFiles []string

    // Cgo directives
    CgoPkgConfig []string // Cgo pkg-config directives
    CgoCFLAGS    []string // Cgo CFLAGS directives
    CgoLDFLAGS   []string

    // Dependency information
    Imports   []string // imports from GoFiles, CgoFiles
    ImportPos map[string][]token.Position

    // Test information
    TestGoFiles    []string                    // _test.go files in package
    TestImports    []string                    // imports from TestGoFiles
    TestImportPos  map[string][]token.Position // line information for TestImports
    XTestGoFiles   []string                    // _test.go files outside package
    XTestImports   []string                    // imports from XTestGoFiles
    XTestImportPos map[string][]token.Position // line information for XTestImports
}

A Package describes the Go package found in a directory.

func Import

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

Import is shorthand for Default.Import.

func ImportDir

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

ImportDir is shorthand for Default.ImportDir.

func (*Package) IsCommand

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.