github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/cmd/go/internal/work/build.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package work
     6  
     7  import (
     8  	"github.com/shogo82148/std/context"
     9  
    10  	"github.com/shogo82148/std/cmd/go/internal/base"
    11  	"github.com/shogo82148/std/cmd/go/internal/load"
    12  )
    13  
    14  var CmdBuild = &base.Command{
    15  	UsageLine: "go build [-o output] [build flags] [packages]",
    16  	Short:     "compile packages and dependencies",
    17  	Long: `
    18  Build compiles the packages named by the import paths,
    19  along with their dependencies, but it does not install the results.
    20  
    21  If the arguments to build are a list of .go files from a single directory,
    22  build treats them as a list of source files specifying a single package.
    23  
    24  When compiling packages, build ignores files that end in '_test.go'.
    25  
    26  When compiling a single main package, build writes the resulting
    27  executable to an output file named after the last non-major-version
    28  component of the package import path. The '.exe' suffix is added
    29  when writing a Windows executable.
    30  So 'go build example/sam' writes 'sam' or 'sam.exe'.
    31  'go build example.com/foo/v2' writes 'foo' or 'foo.exe', not 'v2.exe'.
    32  
    33  When compiling a package from a list of .go files, the executable
    34  is named after the first source file.
    35  'go build ed.go rx.go' writes 'ed' or 'ed.exe'.
    36  
    37  When compiling multiple packages or a single non-main package,
    38  build compiles the packages but discards the resulting object,
    39  serving only as a check that the packages can be built.
    40  
    41  The -o flag forces build to write the resulting executable or object
    42  to the named output file or directory, instead of the default behavior described
    43  in the last two paragraphs. If the named output is an existing directory or
    44  ends with a slash or backslash, then any resulting executables
    45  will be written to that directory.
    46  
    47  The build flags are shared by the build, clean, get, install, list, run,
    48  and test commands:
    49  
    50  	-C dir
    51  		Change to dir before running the command.
    52  		Any files named on the command line are interpreted after
    53  		changing directories.
    54  		If used, this flag must be the first one in the command line.
    55  	-a
    56  		force rebuilding of packages that are already up-to-date.
    57  	-n
    58  		print the commands but do not run them.
    59  	-p n
    60  		the number of programs, such as build commands or
    61  		test binaries, that can be run in parallel.
    62  		The default is GOMAXPROCS, normally the number of CPUs available.
    63  	-race
    64  		enable data race detection.
    65  		Supported only on linux/amd64, freebsd/amd64, darwin/amd64, darwin/arm64, windows/amd64,
    66  		linux/ppc64le and linux/arm64 (only for 48-bit VMA).
    67  	-msan
    68  		enable interoperation with memory sanitizer.
    69  		Supported only on linux/amd64, linux/arm64, linux/loong64, freebsd/amd64
    70  		and only with Clang/LLVM as the host C compiler.
    71  		PIE build mode will be used on all platforms except linux/amd64.
    72  	-asan
    73  		enable interoperation with address sanitizer.
    74  		Supported only on linux/arm64, linux/amd64, linux/loong64.
    75  		Supported on linux/amd64 or linux/arm64 and only with GCC 7 and higher
    76  		or Clang/LLVM 9 and higher.
    77  		And supported on linux/loong64 only with Clang/LLVM 16 and higher.
    78  	-cover
    79  		enable code coverage instrumentation.
    80  	-covermode set,count,atomic
    81  		set the mode for coverage analysis.
    82  		The default is "set" unless -race is enabled,
    83  		in which case it is "atomic".
    84  		The values:
    85  		set: bool: does this statement run?
    86  		count: int: how many times does this statement run?
    87  		atomic: int: count, but correct in multithreaded tests;
    88  			significantly more expensive.
    89  		Sets -cover.
    90  	-coverpkg pattern1,pattern2,pattern3
    91  		For a build that targets package 'main' (e.g. building a Go
    92  		executable), apply coverage analysis to each package matching
    93  		the patterns. The default is to apply coverage analysis to
    94  		packages in the main Go module. See 'go help packages' for a
    95  		description of package patterns.  Sets -cover.
    96  	-v
    97  		print the names of packages as they are compiled.
    98  	-work
    99  		print the name of the temporary work directory and
   100  		do not delete it when exiting.
   101  	-x
   102  		print the commands.
   103  	-asmflags '[pattern=]arg list'
   104  		arguments to pass on each go tool asm invocation.
   105  	-buildmode mode
   106  		build mode to use. See 'go help buildmode' for more.
   107  	-buildvcs
   108  		Whether to stamp binaries with version control information
   109  		("true", "false", or "auto"). By default ("auto"), version control
   110  		information is stamped into a binary if the main package, the main module
   111  		containing it, and the current directory are all in the same repository.
   112  		Use -buildvcs=false to always omit version control information, or
   113  		-buildvcs=true to error out if version control information is available but
   114  		cannot be included due to a missing tool or ambiguous directory structure.
   115  	-compiler name
   116  		name of compiler to use, as in runtime.Compiler (gccgo or gc).
   117  	-gccgoflags '[pattern=]arg list'
   118  		arguments to pass on each gccgo compiler/linker invocation.
   119  	-gcflags '[pattern=]arg list'
   120  		arguments to pass on each go tool compile invocation.
   121  	-installsuffix suffix
   122  		a suffix to use in the name of the package installation directory,
   123  		in order to keep output separate from default builds.
   124  		If using the -race flag, the install suffix is automatically set to race
   125  		or, if set explicitly, has _race appended to it. Likewise for the -msan
   126  		and -asan flags. Using a -buildmode option that requires non-default compile
   127  		flags has a similar effect.
   128  	-ldflags '[pattern=]arg list'
   129  		arguments to pass on each go tool link invocation.
   130  	-linkshared
   131  		build code that will be linked against shared libraries previously
   132  		created with -buildmode=shared.
   133  	-mod mode
   134  		module download mode to use: readonly, vendor, or mod.
   135  		By default, if a vendor directory is present and the go version in go.mod
   136  		is 1.14 or higher, the go command acts as if -mod=vendor were set.
   137  		Otherwise, the go command acts as if -mod=readonly were set.
   138  		See https://golang.org/ref/mod#build-commands for details.
   139  	-modcacherw
   140  		leave newly-created directories in the module cache read-write
   141  		instead of making them read-only.
   142  	-modfile file
   143  		in module aware mode, read (and possibly write) an alternate go.mod
   144  		file instead of the one in the module root directory. A file named
   145  		"go.mod" must still be present in order to determine the module root
   146  		directory, but it is not accessed. When -modfile is specified, an
   147  		alternate go.sum file is also used: its path is derived from the
   148  		-modfile flag by trimming the ".mod" extension and appending ".sum".
   149  	-overlay file
   150  		read a JSON config file that provides an overlay for build operations.
   151  		The file is a JSON struct with a single field, named 'Replace', that
   152  		maps each disk file path (a string) to its backing file path, so that
   153  		a build will run as if the disk file path exists with the contents
   154  		given by the backing file paths, or as if the disk file path does not
   155  		exist if its backing file path is empty. Support for the -overlay flag
   156  		has some limitations: importantly, cgo files included from outside the
   157  		include path must be in the same directory as the Go package they are
   158  		included from, and overlays will not appear when binaries and tests are
   159  		run through go run and go test respectively.
   160  	-pgo file
   161  		specify the file path of a profile for profile-guided optimization (PGO).
   162  		When the special name "auto" is specified, for each main package in the
   163  		build, the go command selects a file named "default.pgo" in the package's
   164  		directory if that file exists, and applies it to the (transitive)
   165  		dependencies of the main package (other packages are not affected).
   166  		Special name "off" turns off PGO. The default is "auto".
   167  	-pkgdir dir
   168  		install and load all packages from dir instead of the usual locations.
   169  		For example, when building with a non-standard configuration,
   170  		use -pkgdir to keep generated packages in a separate location.
   171  	-tags tag,list
   172  		a comma-separated list of additional build tags to consider satisfied
   173  		during the build. For more information about build tags, see
   174  		'go help buildconstraint'. (Earlier versions of Go used a
   175  		space-separated list, and that form is deprecated but still recognized.)
   176  	-trimpath
   177  		remove all file system paths from the resulting executable.
   178  		Instead of absolute file system paths, the recorded file names
   179  		will begin either a module path@version (when using modules),
   180  		or a plain import path (when using the standard library, or GOPATH).
   181  	-toolexec 'cmd args'
   182  		a program to use to invoke toolchain programs like vet and asm.
   183  		For example, instead of running asm, the go command will run
   184  		'cmd args /path/to/asm <arguments for asm>'.
   185  		The TOOLEXEC_IMPORTPATH environment variable will be set,
   186  		matching 'go list -f {{.ImportPath}}' for the package being built.
   187  
   188  The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept a
   189  space-separated list of arguments to pass to an underlying tool
   190  during the build. To embed spaces in an element in the list, surround
   191  it with either single or double quotes. The argument list may be
   192  preceded by a package pattern and an equal sign, which restricts
   193  the use of that argument list to the building of packages matching
   194  that pattern (see 'go help packages' for a description of package
   195  patterns). Without a pattern, the argument list applies only to the
   196  packages named on the command line. The flags may be repeated
   197  with different patterns in order to specify different arguments for
   198  different sets of packages. If a package matches patterns given in
   199  multiple flags, the latest match on the command line wins.
   200  For example, 'go build -gcflags=-S fmt' prints the disassembly
   201  only for package fmt, while 'go build -gcflags=all=-S fmt'
   202  prints the disassembly for fmt and all its dependencies.
   203  
   204  For more about specifying packages, see 'go help packages'.
   205  For more about where packages and binaries are installed,
   206  run 'go help gopath'.
   207  For more about calling between Go and C/C++, run 'go help c'.
   208  
   209  Note: Build adheres to certain conventions such as those described
   210  by 'go help gopath'. Not all projects can follow these conventions,
   211  however. Installations that have their own conventions or that use
   212  a separate software build system may choose to use lower-level
   213  invocations such as 'go tool compile' and 'go tool link' to avoid
   214  some of the overheads and design decisions of the build tool.
   215  
   216  See also: go install, go get, go clean.
   217  	`,
   218  }
   219  
   220  var BuildToolchain toolchain = noToolchain{}
   221  
   222  type BuildFlagMask int
   223  
   224  const (
   225  	DefaultBuildFlags BuildFlagMask = 0
   226  	OmitModFlag       BuildFlagMask = 1 << iota
   227  	OmitModCommonFlags
   228  	OmitVFlag
   229  )
   230  
   231  // AddBuildFlags adds the flags common to the build, clean, get,
   232  // install, list, run, and test commands.
   233  func AddBuildFlags(cmd *base.Command, mask BuildFlagMask)
   234  
   235  // AddCoverFlags adds coverage-related flags to "cmd". If the
   236  // CoverageRedesign experiment is enabled, we add -cover{mode,pkg} to
   237  // the build command and only -coverprofile to the test command. If
   238  // the CoverageRedesign experiment is disabled, -cover* flags are
   239  // added only to the test command.
   240  func AddCoverFlags(cmd *base.Command, coverProfileFlag *string)
   241  
   242  var CmdInstall = &base.Command{
   243  	UsageLine: "go install [build flags] [packages]",
   244  	Short:     "compile and install packages and dependencies",
   245  	Long: `
   246  Install compiles and installs the packages named by the import paths.
   247  
   248  Executables are installed in the directory named by the GOBIN environment
   249  variable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH
   250  environment variable is not set. Executables in $GOROOT
   251  are installed in $GOROOT/bin or $GOTOOLDIR instead of $GOBIN.
   252  
   253  If the arguments have version suffixes (like @latest or @v1.0.0), "go install"
   254  builds packages in module-aware mode, ignoring the go.mod file in the current
   255  directory or any parent directory, if there is one. This is useful for
   256  installing executables without affecting the dependencies of the main module.
   257  To eliminate ambiguity about which module versions are used in the build, the
   258  arguments must satisfy the following constraints:
   259  
   260  - Arguments must be package paths or package patterns (with "..." wildcards).
   261  They must not be standard packages (like fmt), meta-patterns (std, cmd,
   262  all), or relative or absolute file paths.
   263  
   264  - All arguments must have the same version suffix. Different queries are not
   265  allowed, even if they refer to the same version.
   266  
   267  - All arguments must refer to packages in the same module at the same version.
   268  
   269  - Package path arguments must refer to main packages. Pattern arguments
   270  will only match main packages.
   271  
   272  - No module is considered the "main" module. If the module containing
   273  packages named on the command line has a go.mod file, it must not contain
   274  directives (replace and exclude) that would cause it to be interpreted
   275  differently than if it were the main module. The module must not require
   276  a higher version of itself.
   277  
   278  - Vendor directories are not used in any module. (Vendor directories are not
   279  included in the module zip files downloaded by 'go install'.)
   280  
   281  If the arguments don't have version suffixes, "go install" may run in
   282  module-aware mode or GOPATH mode, depending on the GO111MODULE environment
   283  variable and the presence of a go.mod file. See 'go help modules' for details.
   284  If module-aware mode is enabled, "go install" runs in the context of the main
   285  module.
   286  
   287  When module-aware mode is disabled, non-main packages are installed in the
   288  directory $GOPATH/pkg/$GOOS_$GOARCH. When module-aware mode is enabled,
   289  non-main packages are built and cached but not installed.
   290  
   291  Before Go 1.20, the standard library was installed to
   292  $GOROOT/pkg/$GOOS_$GOARCH.
   293  Starting in Go 1.20, the standard library is built and cached but not installed.
   294  Setting GODEBUG=installgoroot=all restores the use of
   295  $GOROOT/pkg/$GOOS_$GOARCH.
   296  
   297  For more about build flags, see 'go help build'.
   298  
   299  For more about specifying packages, see 'go help packages'.
   300  
   301  See also: go build, go get, go clean.
   302  	`,
   303  }
   304  
   305  func InstallPackages(ctx context.Context, patterns []string, pkgs []*load.Package)
   306  
   307  // ExecCmd is the command to use to run user binaries.
   308  // Normally it is empty, meaning run the binaries directly.
   309  // If cross-compiling and running on a remote system or
   310  // simulator, it is typically go_GOOS_GOARCH_exec, with
   311  // the target GOOS and GOARCH substituted.
   312  // The -exec flag overrides these defaults.
   313  var ExecCmd []string
   314  
   315  // FindExecCmd derives the value of ExecCmd to use.
   316  // It returns that value and leaves ExecCmd set for direct use.
   317  func FindExecCmd() []string