Black Lives Matter. Support the Equal Justice Initiative.

Package build

import "go/build"
Overview
Index

Overview ▾

软件包构建收集有关Go软件包的信息.

Go Path

Go路径是包含Go源代码的目录树的列表. 咨询它来解决在标准Go树中找不到的导入. 缺省路径是GOPATH环境变量的值,它被解释为适合于操作系统的路径列表(在Unix上,该变量是用冒号分隔的字符串;在Windows上,是用分号分隔的字符串;在Plan 9上,是列表).

Go路径中列出的每个目录必须具有规定的结构:

src /目录包含源代码. " src"下面的路径确定导入路径或可执行文件名称.

pkg /目录包含已安装的软件包对象. 就像在Go树中一样,每个目标操作系统和体系结构对都有其自己的pkg子目录(pkg / GOOS_GOARCH).

如果DIR是Go路径中列出的目录,则可以将源代码位于DIR / src / foo / bar中的软件包作为" foo / bar"导入,并将其编译形式安装到" DIR / pkg / GOOS_GOARCH / foo / bar". a"(对于gccgo,则为" DIR / pkg / gccgo / foo / libbar.a").

bin /目录包含已编译的命令. 每个命令都以其源目录命名,但仅使用最后一个元素,而不使用整个路径. 也就是说,将源代码在DIR / src / foo / quux中的命令安装到DIR / bin / quux中,而不是DIR / bin / foo / quux中. 去除了foo /,以便您可以将DIR / bin添加到PATH中以获取安装的命令.

这是示例目录布局:

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

构建约束,也称为构建标记,是开始的行注释

// +build

列出了将文件包含在软件包中的条件. 约束可能会出现在任何类型的源文件中(不仅是Go),但它们必须出现在文件顶部附近,并且只能出现空白行和其他行注释. 这些规则意味着在Go文件中,构建约束必须出现在package子句之前.

为了将构建约束与程序包文档区分开,必须在一系列构建约束后跟一个空行.

将构建约束评估为以空格分隔的选项的OR. 每个选项的值均以其逗号分隔项的AND表示. 每个术语由字母,数字,下划线和点组成. 术语可以与前面的!取反. 例如,构建约束:

// +build linux,386 darwin,!cgo

对应于布尔公式:

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

一个文件可能有多个构建约束. 总体约束是各个约束的与. 也就是说,构建约束:

// +build linux darwin
// +build 386

对应于布尔公式:

(linux OR darwin) AND 386

在特定的构建过程中,满足以下条件:

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

没有针对Beta或次要版本的构建标记.

如果去除扩展名和可能的_test后缀的文件名与以下任何一种模式匹配:

*_GOOS
*_GOARCH
*_GOOS_GOARCH

(例如:source_windows_amd64.go),其中GOOS和GOARCH分别表示任何已知的操作系统和体系结构值,然后该文件被视为具有需要这些术语的隐式构建约束(除了文件中的任何显式约束).

要避免考虑将文件用于构建:

// +build ignore

(其他任何不满意的词也可以,但是"忽略"是常规的.)

要仅在使用cgo且仅在Linux和OS X上构建文件:

// +build linux,cgo darwin,cgo

这样的文件通常与另一个文件配对,该文件实现了其他系统的默认功能,在这种情况下,它将带有约束:

// +build !linux,!darwin !cgo

命名文件dns_windows.go将导致仅在构建Windows软件包时将其包含在内; 同样,仅当为32位x86构建软件包时,才会包括math_386.s.

使用GOOS = android除了匹配android标签和文件外,还像GOOS = linux一样匹配构建标签和文件.

除了illumos标签和文件外,使用GOOS = illumos还可以像GOOS = solaris一样匹配构建标签和文件.

Binary-Only Packages

在Go 1.12和更早版本中,可以以二进制形式分发软件包,而无需包括用于编译软件包的源代码. 该软件包分发时包含一个源文件,该源文件没有被构建约束排除,并且包含" // go:binary-only-package"注释. 就像构建约束一样,此注释出现在文件的顶部,仅在空白行和其他行注释的前面,并在注释之后带有空白行,以将其与软件包文档分开. 与构建约束不同,此注释仅在非测试Go源文件中被识别.

因此,仅二进制包的最小源代码是:

//go:binary-only-package

package mypkg

源代码可以包括其他Go代码. 该代码从未被编译过,但是会被godoc之类的工具处理,并且可能对最终用户文档很有用.

" go build"和其他命令不再支持仅二进制软件包. Import和ImportDir仍将在包含这些注释的程序包中设置BinaryOnly标志,以在工具和错误消息中使用.

Variables

ToolDir是包含构建工具的目录.

var ToolDir = getToolDir()

func ArchChar

func ArchChar(goarch string) (string, error)

ArchChar返回"?" 和一个错误. 在Go的早期版本中,返回的字符串用于派生编译器和链接器工具名称,默认目标文件后缀以及默认链接器输出名称. 从Go 1.5开始,这些字符串不再因体系结构而有所不同. 它们分别是compile,link,.o和a.out.

func IsLocalImport

func IsLocalImport(path string) bool

IsLocalImport报告导入路径是本地导入路径,例如"."," .."," ./ foo"还是" ../foo".

type Context

上下文指定了构建的支持上下文.

type Context struct {
    GOARCH string // target architecture
    GOOS   string // target operating system
    GOROOT string // Go root
    GOPATH string // Go path

    // 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.
    Dir string // Go 1.14

    CgoEnabled  bool   // whether cgo files are included
    UseAllFiles bool   // use files regardless of +build lines, file names
    Compiler    string // compiler to assume when computing target paths

    // The build 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 ReleaseTags,
    // which 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 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   []string
    ReleaseTags []string // Go 1.1

    // 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".
    InstallSuffix string // Go 1.1

    // 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 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, 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 ioutil.ReadDir.
    ReadDir func(dir string) ([]os.FileInfo, error)

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

默认是构建的默认上下文. 它使用GOARCH,GOOS,GOROOT和GOPATH环境变量(如果已设置),否则使用编译后的代码的GOARCH,GOOS和GOROOT.

var Default Context = defaultContext()

func (*Context) Import

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

导入返回有关由导入路径命名的Go软件包的详细信息,解释相对于srcDir目录的本地导入路径. 如果该路径是本地导入路径,命名了可以使用标准导入路径导入的软件包,则返回的软件包会将p.ImportPath设置为该路径.

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

如果发生错误,导入将返回非零错误和非零*包含部分信息的包.

func (*Context) ImportDir

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

ImportDir类似于Import,但是处理在命名目录中找到的Go包.

func (*Context) MatchFile 1.2

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

MatchFile报告给定目录中具有给定名称的文件是否与上下文匹配,并将包含在该目录的ImportDir创建的Package中.

MatchFile考虑文件的名称,可以使用ctxt.OpenFile读取文件的部分或全部内容.

func (*Context) SrcDirs

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

SrcDirs返回软件包源根目录的列表. 它从当前的Go根目录和Go路径中提取,但是省略了不存在的目录.

type ImportMode

ImportMode控制Import方法的行为.

type ImportMode uint
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.
    //
    // 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
)

type MultiplePackageError 1.4

MultiplePackageError描述了一个目录,其中包含用于多个软件包的多个可构建Go源文件.

type MultiplePackageError struct {
    Dir      string   // directory containing files
    Packages []string // package names found
    Files    []string // corresponding files: Files[i] declares package Packages[i]
}

func (*MultiplePackageError) Error 1.4

func (e *MultiplePackageError) Error() string

type NoGoError

NoGoError是Import用来描述不包含可构建Go源文件的目录的错误. (它可能仍然包含测试文件,由构建标记隐藏的文件,等等.)

type NoGoError struct {
    Dir string
}

func (*NoGoError) Error

func (e *NoGoError) Error() string

type Package

软件包描述了在目录中找到的Go软件包.

type Package struct {
    Dir           string   // directory containing package sources
    Name          string   // package name
    ImportComment string   // path in import comment on package statement; added in Go 1.4
    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)
    PkgTargetRoot string   // architecture dependent install root directory ("" if unknown); added in Go 1.5
    BinDir        string   // command install directory ("" if unknown)
    Goroot        bool     // package found in Go root
    PkgObj        string   // installed .a file
    AllTags       []string // tags that can influence file selection in this directory; added in Go 1.2
    ConflictDir   string   // this directory shadows Dir in $GOPATH; added in Go 1.2
    BinaryOnly    bool     // cannot be rebuilt from source (has //go:binary-only-package comment); added in Go 1.7

    // Source files
    GoFiles        []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; added in Go 1.1
    InvalidGoFiles []string // .go source files with detected problems (parse error, wrong package name, and so on); added in Go 1.6
    CFiles         []string // .c source files
    CXXFiles       []string // .cc, .cpp and .cxx source files; added in Go 1.2
    MFiles         []string // .m (Objective-C) source files; added in Go 1.3
    HFiles         []string // .h, .hh, .hpp and .hxx source files
    FFiles         []string // .f, .F, .for and .f90 Fortran source files; added in Go 1.7
    SFiles         []string // .s source files
    SwigFiles      []string // .swig files; added in Go 1.1
    SwigCXXFiles   []string // .swigcxx files; added in Go 1.1
    SysoFiles      []string // .syso system object files to add to archive

    // Cgo directives
    CgoCFLAGS    []string // Cgo CFLAGS directives
    CgoCPPFLAGS  []string // Cgo CPPFLAGS directives; added in Go 1.2
    CgoCXXFLAGS  []string // Cgo CXXFLAGS directives; added in Go 1.2
    CgoFFLAGS    []string // Cgo FFLAGS directives; added in Go 1.7
    CgoLDFLAGS   []string // Cgo LDFLAGS directives
    CgoPkgConfig []string // Cgo pkg-config directives

    // Dependency information
    Imports   []string                    // import paths from GoFiles, CgoFiles
    ImportPos map[string][]token.Position // line information for Imports

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

func Import

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

导入是Default.Import的简写.

func ImportDir

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

ImportDir是Default.ImportDir的简写.

func (*Package) IsCommand

func (p *Package) IsCommand() bool

IsCommand报告该软件包是否被视为要安装的命令(不仅仅是库). 名为" main"的软件包被视为命令.

by  ICOPY.SITE