package work

import "cmd/go/internal/work"

Index

Constants

const DefaultCFlags = "-O2 -g"

Variables

var AllowInstall = func(*Action) error { return nil }

AllowInstall returns a non-nil error if this invocation of the go command is allowed to install a.Target.

The build of cmd/go running under its own test is forbidden from installing to its original GOROOT. The var is exported so it can be set by TestMain.

var BuildToolchain toolchain = noToolchain{}
var CmdBuild = &base.Command{
	UsageLine: "go build [-o output] [build flags] [packages]",
	Short:     "compile packages and dependencies",
	Long:      "" /* 9993 byte string literal not displayed */,
}
var CmdInstall = &base.Command{
	UsageLine: "go install [build flags] [packages]",
	Short:     "compile and install packages and dependencies",
	Long:      "" /* 2644 byte string literal not displayed */,
}
var ExecCmd []string

ExecCmd is the command to use to run user binaries. Normally it is empty, meaning run the binaries directly. If cross-compiling and running on a remote system or simulator, it is typically go_GOOS_GOARCH_exec, with the target GOOS and GOARCH substituted. The -exec flag overrides these defaults.

var GccgoName, GccgoBin string
var ToolchainVersion = runtime.Version()

Tests can override this by setting $TESTGO_TOOLCHAIN_VERSION.

var VetExplicit bool

VetExplicit records whether the vet flags were set explicitly on the command line.

var VetFlags []string

VetFlags are the default flags to pass to vet. The caller is expected to set them before executing any vet actions.

var VetTool string

VetTool is the path to an alternate vet tool binary. The caller is expected to set it (if needed) before executing any vet actions.

Functions

func AddBuildFlags

func AddBuildFlags(cmd *base.Command, mask BuildFlagMask)

AddBuildFlags adds the flags common to the build, clean, get, install, list, run, and test commands.

func AddCoverFlags

func AddCoverFlags(cmd *base.Command, coverProfileFlag *string)

AddCoverFlags adds coverage-related flags to "cmd". If the CoverageRedesign experiment is enabled, we add -cover{mode,pkg} to the build command and only -coverprofile to the test command. If the CoverageRedesign experiment is disabled, -cover* flags are added only to the test command.

func BuildActionCoverMetaFile

func BuildActionCoverMetaFile(runAct *Action) (string, error)

BuildActionCoverMetaFile locates and returns the path of the meta-data file written by the "go tool cover" step as part of the build action for the "go test -cover" run action 'runAct'. Note that if the package has no functions the meta-data file will exist but will be empty; in this case the return is an empty string.

func BuildInit

func BuildInit()

func BuildInstallFunc

func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error)

BuildInstallFunc is the action for installing a single package or executable.

func CheckGOOSARCHPair

func CheckGOOSARCHPair(goos, goarch string) error

func FindExecCmd

func FindExecCmd() []string

FindExecCmd derives the value of ExecCmd to use. It returns that value and leaves ExecCmd set for direct use.

func InstallPackages

func InstallPackages(ctx context.Context, patterns []string, pkgs []*load.Package)

func WriteCoverMetaFilesFile

func WriteCoverMetaFilesFile(b *Builder, ctx context.Context, a *Action) error

WriteCoverMetaFilesFile writes out a summary file ("meta-files file") as part of the action function for the "writeCoverMeta" pseudo action employed during "go test -coverpkg" runs where there are multiple tests and multiple packages covered. It builds up a table mapping package import path to meta-data file fragment and writes it out to a file where it can be read by the various test run actions. Note that this function has to be called A) after the build actions are complete for all packages being tested, and B) before any of the "run test" actions for those packages happen. This requirement is enforced by adding making this action ("a") dependent on all test package build actions, and making all test run actions dependent on this action.

func WriteCoveragePercent

func WriteCoveragePercent(b *Builder, runAct *Action, mf string, w io.Writer) error

WriteCoveragePercent writes out to the writer 'w' a "percent statements covered" for the package whose test-run action is 'runAct', based on the meta-data file 'mf'. This helper is used in cases where a user runs "go test -cover" on a package that has functions but no tests; in the normal case (package has tests) the percentage is written by the test binary when it runs.

func WriteCoverageProfile

func WriteCoverageProfile(b *Builder, runAct *Action, mf, outf string, w io.Writer) error

WriteCoverageProfile writes out a coverage profile fragment for the package whose test-run action is 'runAct'; content is written to the file 'outf' based on the coverage meta-data info found in 'mf'. This helper is used in cases where a user runs "go test -cover" on a package that has functions but no tests.

Types

type Action

type Action struct {
	Mode       string        // description of action operation
	Package    *load.Package // the package this action works on
	Deps       []*Action     // actions that must happen before this one
	Actor      Actor         // the action itself (nil = no-op)
	IgnoreFail bool          // whether to run f even if dependencies fail
	TestOutput *bytes.Buffer // test output buffer
	Args       []string      // additional args for runProgram

	TryCache func(*Builder, *Action) bool // callback for cache bypass

	CacheExecutable bool // Whether to cache executables produced by link steps

	// Generated files, directories.
	Objdir string // directory for intermediate objects
	Target string // goal of the action: the created package or executable

	VetxOnly bool // Mode=="vet": only being called to supply info about dependencies

	Failed *Action // set to root cause if the action failed
	// contains filtered or unexported fields
}

An Action represents a single action in the action graph.

func (*Action) BuildActionID

func (a *Action) BuildActionID() string

BuildActionID returns the action ID section of a's build ID.

func (*Action) BuildContentID

func (a *Action) BuildContentID() string

BuildContentID returns the content ID section of a's build ID.

func (*Action) BuildID

func (a *Action) BuildID() string

BuildID returns a's build ID.

func (*Action) BuiltTarget

func (a *Action) BuiltTarget() string

BuiltTarget returns the actual file that was built. This differs from Target when the result was cached.

type Actor

type Actor interface {
	Act(*Builder, context.Context, *Action) error
}

An Actor runs an action.

type ActorFunc

type ActorFunc func(*Builder, context.Context, *Action) error

An ActorFunc is an Actor that calls the function.

func (ActorFunc) Act

func (f ActorFunc) Act(b *Builder, ctx context.Context, a *Action) error

type BuildFlagMask

type BuildFlagMask int
const (
	DefaultBuildFlags BuildFlagMask = 0
	OmitModFlag       BuildFlagMask = 1 << iota
	OmitModCommonFlags
	OmitVFlag
	OmitBuildOnlyFlags // Omit flags that only affect building packages
	OmitJSONFlag
)

type BuildMode

type BuildMode int

BuildMode specifies the build mode: are we just building things or also installing the results?

const (
	ModeBuild BuildMode = iota
	ModeInstall
	ModeBuggyInstall

	ModeVetOnly = 1 << 8
)

type Builder

type Builder struct {
	WorkDir string // the temporary work directory (ends in filepath.Separator)

	IsCmdList           bool // running as part of go list; set p.Stale and additional fields below
	NeedError           bool // list needs p.Error
	NeedExport          bool // list needs p.Export
	NeedCompiledGoFiles bool // list needs p.CompiledGoFiles
	AllowErrors         bool // errors don't immediately exit the program
	// contains filtered or unexported fields
}

A Builder holds global state about a build. It does not hold per-package state, because we build packages in parallel, and the builder is shared.

func NewBuilder

func NewBuilder(workDir string) *Builder

NewBuilder returns a new Builder ready for use.

If workDir is the empty string, NewBuilder creates a WorkDir if needed and arranges for it to be removed in case of an unclean exit. The caller must Close the builder explicitly to clean up the WorkDir before a clean exit.

func (*Builder) AutoAction

func (b *Builder) AutoAction(mode, depMode BuildMode, p *load.Package) *Action

AutoAction returns the "right" action for go build or go install of p.

func (*Builder) BackgroundShell

func (b *Builder) BackgroundShell() *Shell

BackgroundShell returns a Builder-wide Shell that's not bound to any Action. Try not to use this unless there's really no sensible Action available.

func (*Builder) CFlags

func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error)

CFlags returns the flags to use when invoking the C, C++ or Fortran compilers, or cgo.

func (*Builder) Close

func (b *Builder) Close() error

func (*Builder) CompileAction

func (b *Builder) CompileAction(mode, depMode BuildMode, p *load.Package) *Action

CompileAction returns the action for compiling and possibly installing (according to mode) the given package. The resulting action is only for building packages (archives), never for linking executables. depMode is the action (build or install) to use when building dependencies. To turn package main into an executable, call b.Link instead.

func (*Builder) CovData

func (b *Builder) CovData(a *Action, cmdargs ...any) ([]byte, error)

CovData invokes "go tool covdata" with the specified arguments as part of the execution of action 'a'.

func (*Builder) Do

func (b *Builder) Do(ctx context.Context, root *Action)

Do runs the action graph rooted at root.

func (*Builder) GccCmd

func (b *Builder) GccCmd(incdir, workdir string) []string

GccCmd returns a gcc command line prefix defaultCC is defined in zdefaultcc.go, written by cmd/dist.

func (*Builder) GxxCmd

func (b *Builder) GxxCmd(incdir, workdir string) []string

GxxCmd returns a g++ command line prefix defaultCXX is defined in zdefaultcc.go, written by cmd/dist.

func (*Builder) LinkAction

func (b *Builder) LinkAction(mode, depMode BuildMode, p *load.Package) *Action

LinkAction returns the action for linking p into an executable and possibly installing the result (according to mode). depMode is the action (build or install) to use when compiling dependencies.

func (*Builder) NewObjdir

func (b *Builder) NewObjdir() string

NewObjdir returns the name of a fresh object directory under b.WorkDir. It is up to the caller to call b.Mkdir on the result at an appropriate time. The result ends in a slash, so that file names in that directory can be constructed with direct string addition.

NewObjdir must be called only from a single goroutine at a time, so it is safe to call during action graph construction, but it must not be called during action graph execution.

func (*Builder) PkgconfigCmd

func (b *Builder) PkgconfigCmd() string

PkgconfigCmd returns a pkg-config binary name defaultPkgConfig is defined in zdefaultcc.go, written by cmd/dist.

func (*Builder) Shell

func (b *Builder) Shell(a *Action) *Shell

Shell returns a shell for running commands on behalf of Action a.

func (*Builder) VetAction

func (b *Builder) VetAction(mode, depMode BuildMode, p *load.Package) *Action

VetAction returns the action for running go vet on package p. It depends on the action for compiling p. If the caller may be causing p to be installed, it is up to the caller to make sure that the install depends on (runs after) vet.

type Shell

type Shell struct {
	// contains filtered or unexported fields
}

A Shell runs shell commands and performs shell-like file system operations.

Shell tracks context related to running commands, and form a tree much like context.Context.

func NewShell

func NewShell(workDir string, printer load.Printer) *Shell

NewShell returns a new Shell.

Shell will internally serialize calls to the printer. If printer is nil, it uses load.DefaultPrinter.

func (*Shell) CopyFile

func (sh *Shell) CopyFile(dst, src string, perm fs.FileMode, force bool) error

copyFile is like 'cp src dst'.

func (*Shell) Errorf

func (sh *Shell) Errorf(format string, a ...any)

Errorf reports an error on sh's package and sets the process exit status to 1.

func (*Shell) Mkdir

func (sh *Shell) Mkdir(dir string) error

Mkdir makes the named directory.

func (*Shell) Printf

func (sh *Shell) Printf(format string, a ...any)

Printf emits a to this Shell's output stream, formatting it like fmt.Printf. It is safe to call concurrently.

func (*Shell) RemoveAll

func (sh *Shell) RemoveAll(paths ...string) error

RemoveAll is like 'rm -rf'. It attempts to remove all paths even if there's an error, and returns the first error.

func (*Shell) ShowCmd

func (sh *Shell) ShowCmd(dir string, format string, args ...any)

ShowCmd prints the given command to standard output for the implementation of -n or -x.

ShowCmd also replaces the name of the current script directory with dot (.) but only when it is at the beginning of a space-separated token.

If dir is not "" or "/" and not the current script directory, ShowCmd first prints a "cd" command to switch to dir and updates the script directory.

func (sh *Shell) Symlink(oldname, newname string) error

Symlink creates a symlink newname -> oldname.

func (*Shell) WithAction

func (sh *Shell) WithAction(a *Action) *Shell

WithAction returns a Shell identical to sh, but bound to Action a.

Source Files

action.go build.go buildid.go cover.go exec.go gc.go gccgo.go init.go security.go shell.go

Version
v1.24.0 (latest)
Published
Feb 10, 2025
Platform
linux/amd64
Imports
52 packages
Last checked
22 minutes ago

Tools for package owners.