core

package
v7.4.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2017 License: Apache-2.0 Imports: 27 Imported by: 174

Documentation

Index

Constants

View Source
const (
	Kill            TaskType = 0x0000 | 0
	SubincludeBuild          = 0x1000 | 1
	SubincludeParse          = 0x2000 | 2
	Build                    = 0x4000 | 3
	Parse                    = 0x4000 | 4
	Test                     = 0x4000 | 5
	Stop                     = 0x8000 | 6
)

The values here are fiddled to make Compare work easily. Essentially we prioritise on the higher bits only and use the lower ones to make the values unique. Subinclude tasks order first, but we're happy for all build / parse / test tasks to be treated equivalently.

View Source
const BinDir string = "plz-out/bin"
View Source
const ConfigFileName string = ".plzconfig"

File name for the typical repo config - this is normally checked in

View Source
const DefaultBuildingDescription = "Building..."

Default when this isn't otherwise specified.

View Source
const DirPermissions = os.ModeDir | 0775

DirPermissions are the default permission bits we apply to directories.

View Source
const GenDir string = "plz-out/gen"
View Source
const LocalConfigFileName string = ".plzconfig.local"

File name for the local repo config - this is not normally checked in and used to override settings on the local machine.

View Source
const MachineConfigFileName = "/etc/plzconfig"

File name for the machine-level config - can use this to override things for a particular machine (eg. build machine with different caching behaviour).

View Source
const OutDir string = "plz-out"

OutDir is the output directory for everything.

View Source
const TestContainerDocker = "docker"
View Source
const TestContainerNone = "none"
View Source
const TmpDir string = "plz-out/tmp"

Variables

View Source
var ArchConfigFileName string = fmt.Sprintf(".plzconfig_%s_%s", runtime.GOOS, runtime.GOARCH)

Architecture-specific config file which overrides the repo one. Also normally checked in if needed.

View Source
var BuildLabelStdin = BuildLabel{PackageName: "", Name: "_STDIN"}

Used to indicate that we're going to consume build labels from stdin.

View Source
var OriginalTarget = BuildLabel{PackageName: "", Name: "_ORIGINAL"}

Used to indicate one of the originally requested targets on the command line.

View Source
var PleaseVersion = *semver.New("1.0.9999")
View Source
var RepoRoot string

RepoRoot is the root of the Please repository

View Source
var WholeGraph = []BuildLabel{{PackageName: "", Name: "..."}}

Build label that represents parsing the entire graph. We use this specially in one or two places.

Functions

func AcquireRepoLock

func AcquireRepoLock()

AcquireRepoLock opens the lock file and acquires the lock. Dies if the lock cannot be successfully acquired.

func BuildEnvironment

func BuildEnvironment(state *BuildState, target *BuildTarget, test bool) []string

BuildEnvironment creates the shell env vars to be passed into the exec.Command calls made by plz. Use test=true for plz test targets.

func CollapseHash

func CollapseHash(key []byte) []byte

CollapseHash combines our usual four-part hash into one by XOR'ing them together. This helps keep things short in places where sometimes we get complaints about filenames being too long (this is most noticeable on e.g. Ubuntu with an encrypted home directory, but not an entire encrypted disk) and where we don't especially care about breaking out the individual parts of hashes, which is important for many parts of the system.

func CopyFile

func CopyFile(from string, to string, mode os.FileMode) error

CopyFile copies a file from 'from' to 'to', with an attempt to perform a copy & rename to avoid chaos if anything goes wrong partway.

func ExecWithTimeout

func ExecWithTimeout(dir string, env []string, timeout time.Duration, defaultTimeout cli.Duration, showOutput bool, argv []string) ([]byte, []byte, error)

ExecWithTimeout runs an external command with a timeout. If the command times out the returned error will be a context.DeadlineExceeded error. If showOutput is true then output will be printed to stderr as well as returned. It returns the stdout only, combined stdout and stderr and any error that occurred.

func ExecWithTimeoutShell

func ExecWithTimeoutShell(dir string, env []string, timeout time.Duration, defaultTimeout cli.Duration, showOutput bool, cmd string) ([]byte, []byte, error)

ExecWithTimeoutShell runs an external command within a Bash shell. Other arguments are as ExecWithTimeout. Note that the command is deliberately a single string.

func ExecWithTimeoutSimple

func ExecWithTimeoutSimple(timeout cli.Duration, cmd ...string) ([]byte, error)

ExecWithTimeoutSimple runs an external command with a timeout. It's a simpler version of ExecWithTimeout that gives less control.

func ExpandHomePath

func ExpandHomePath(path string) string

ExpandHomePath expands all prefixes of ~ without a user specifier TO $HOME.

func FileExists

func FileExists(filename string) bool

func FindRepoRoot

func FindRepoRoot() bool

FindRepoRoot returns the root directory of the current repo and sets the initial working dir. It returns true if the repo root was found.

func Glob

func Glob(rootPath string, includes, prefixedExcludes, excludes []string, includeHidden bool) []string

Glob implements matching using Go's built-in filepath.Glob, but extends it to support Ant-style patterns using **.

func IsGlob

func IsGlob(pattern string) bool

IsGlob returns true if the given pattern requires globbing (i.e. contains characters that would be expanded by it)

func IsPackage

func IsPackage(name string) bool

IsPackage returns true if the given directory name is a package (i.e. contains a build file)

func IsSameFile

func IsSameFile(a, b string) bool

IsSameFile returns true if two filenames describe the same underlying file (i.e. inode)

func IterInputPaths

func IterInputPaths(graph *BuildGraph, target *BuildTarget) <-chan string

Yields all the transitive input files for a rule (sources & data files), similar to above (again).

func IterRuntimeFiles

func IterRuntimeFiles(graph *BuildGraph, target *BuildTarget, absoluteOuts bool) <-chan sourcePair

Yields all the runtime files for a rule (outputs & data files), similar to above.

func IterSources

func IterSources(graph *BuildGraph, target *BuildTarget) <-chan sourcePair

IterSources returns all the sources for a function, allowing for sources that are other rules and rules that require transitive dependencies. Yielded values are pairs of the original source location and its temporary location for this rule.

func LookPath

func LookPath(filename string, paths []string) (string, error)

LookPath does roughly the same as exec.LookPath, i.e. looks for the named file on the path. The main difference is that it looks based on our config which isn't necessarily the same as the external environment variable.

func LooksLikeABuildLabel

func LooksLikeABuildLabel(str string) bool

LooksLikeABuildLabel returns true if the string appears to be a build label, false if not. Useful for cases like rule sources where sources can be a filename or a label.

func MustFindRepoRoot

func MustFindRepoRoot() string

MustFindRepoRoot returns the root directory of the current repo and sets the initial working dir. It dies on failure, although will fall back to looking for a Bazel WORKSPACE file first.

func PathExists

func PathExists(filename string) bool

func PrepareSource

func PrepareSource(sourcePath string, tmpPath string) error

Symlinks a single source file for a build rule.

func PrepareSourcePair

func PrepareSourcePair(pair sourcePair) error

func ReadLastOperationOrDie

func ReadLastOperationOrDie() []string

ReadLastOperationOrDie reads the last operation performed from the lock file. Dies if unsuccessful.

func RecursiveCopyFile

func RecursiveCopyFile(from string, to string, mode os.FileMode, link, fallback bool) error

Copies either a single file or a directory. If 'link' is true then we'll hardlink files instead of copying them. If 'fallback' is true then we'll fall back to a copy if linking fails.

func ReleaseRepoLock

func ReleaseRepoLock()

ReleaseRepoLock releases the lock and closes the file handle. Does not die on errors, at this point it wouldn't really do any good.

func ReplaceEnvironment

func ReplaceEnvironment(env []string) func(string) string

ReplaceEnvironment returns a function suitable for passing to os.Expand to replace environment variables from an earlier call to BuildEnvironment.

func StampedBuildEnvironment

func StampedBuildEnvironment(state *BuildState, target *BuildTarget, test bool, stamp []byte) []string

StampedBuildEnvironment returns the shell env vars to be passed into exec.Command. Optionally includes a stamp if the target is marked as such.

func StartedAtRepoRoot

func StartedAtRepoRoot() bool

Returns true if the build was initiated from the repo root. Used to provide slightly nicer output in some places.

func TestCoverageString

func TestCoverageString(lines []LineCoverage) string

Produce a string representation of coverage for serialising to file so we don't expose the internal enum values (ordering is important so we may want to insert new ones later. This format happens to be the same as the one Phabricator uses, which is mildly useful to us since we want to integrate with it anyway. See https://secure.phabricator.com/book/phabricator/article/arcanist_coverage/ for more detail of how it works.

func WriteFile

func WriteFile(fromFile io.Reader, to string, mode os.FileMode) error

WriteFile writes data from a reader to the file named 'to', with an attempt to perform a copy & rename to avoid chaos if anything goes wrong partway.

Types

type BuildGraph

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

func NewGraph

func NewGraph() *BuildGraph

func (*BuildGraph) AddDependency

func (graph *BuildGraph) AddDependency(from BuildLabel, to BuildLabel)

func (*BuildGraph) AddPackage

func (graph *BuildGraph) AddPackage(pkg *Package)

Adds a new package to the graph with given name.

func (*BuildGraph) AddTarget

func (graph *BuildGraph) AddTarget(target *BuildTarget) *BuildTarget

Adds a new target to the graph.

func (*BuildGraph) AllDependenciesResolved

func (graph *BuildGraph) AllDependenciesResolved(target *BuildTarget) bool

AllDependenciesResolved returns true once all the dependencies of a target have been parsed and resolved to real targets.

func (*BuildGraph) AllDepsBuilt

func (graph *BuildGraph) AllDepsBuilt(target *BuildTarget) bool

AllDepsBuilt returns true if all the dependencies of a target are built.

func (*BuildGraph) AllTargets

func (graph *BuildGraph) AllTargets() BuildTargets

Returns a sorted slice of all the targets in the graph.

func (*BuildGraph) DependentTargets

func (graph *BuildGraph) DependentTargets(from, to BuildLabel) []BuildLabel

DependentTargets returns the labels that 'from' should actually depend on when it declared a dependency on 'to'. This is normally just 'to' but could be otherwise given require/provide shenanigans.

func (*BuildGraph) Len

func (graph *BuildGraph) Len() int

func (*BuildGraph) Package

func (graph *BuildGraph) Package(name string) *Package

Package retrieves a package from the graph by name

func (*BuildGraph) PackageMap

func (graph *BuildGraph) PackageMap() map[string]*Package

Used for getting a local copy of the package map without having to expose it publicly.

func (*BuildGraph) PackageOrDie

func (graph *BuildGraph) PackageOrDie(name string) *Package

PackageOrDie retrieves a package by name, and dies if it can't be found.

func (*BuildGraph) ReverseDependencies

func (graph *BuildGraph) ReverseDependencies(target *BuildTarget) []*BuildTarget

ReverseDependencies returns the set of revdeps on the given target.

func (*BuildGraph) Target

func (graph *BuildGraph) Target(label BuildLabel) *BuildTarget

Target retrieves a target from the graph by label

func (*BuildGraph) TargetOrDie

func (graph *BuildGraph) TargetOrDie(label BuildLabel) *BuildTarget

TargetOrDie retrieves a target from the graph by label. Dies if the target doesn't exist.

type BuildInput

type BuildInput interface {
	// Returns a slice of paths to the files of this input.
	Paths(graph *BuildGraph) []string
	// As above, but includes the leading plz-out/gen directory.
	FullPaths(graph *BuildGraph) []string
	// Paths within the local package
	LocalPaths(graph *BuildGraph) []string
	// Returns the build label associated with this input, or nil if it doesn't have one (eg. it's just a file).
	Label() *BuildLabel
	// Returns a string representation of this input
	String() string
}

Inputs to a build can be either a file in the local package or another build rule. All users care about is where they find them.

type BuildLabel

type BuildLabel struct {
	PackageName string
	Name        string
}

Representation of an identifier of a build target, eg. //spam/eggs:ham corresponds to BuildLabel{PackageName: spam/eggs name: ham} BuildLabels are always absolute, so relative identifiers like :ham are always parsed into an absolute form. There is also implicit expansion of the final element of a target (ala Blaze) so //spam/eggs is equivalent to //spam/eggs:eggs

func FindOwningPackage

func FindOwningPackage(file string) BuildLabel

FindOwningPackage returns a build label identifying the package that owns a given file.

func FindOwningPackages

func FindOwningPackages(files []string) []BuildLabel

FindOwningPackages returns build labels corresponding to the packages that own each of the given files.

func InitialPackage

func InitialPackage() []BuildLabel

InitialPackage returns a label corresponding to the initial package we started in.

func NewBuildLabel

func NewBuildLabel(pkgName string, name string) BuildLabel

NewBuildLabel constructs a new build label from the given components. Panics on failure.

func ParseBuildLabel

func ParseBuildLabel(target string, currentPath string) BuildLabel

ParseBuildLabel parses a single build label from a string. Panics on failure.

func ParseBuildLabels

func ParseBuildLabels(targets []string) []BuildLabel

Parse a bunch of build labels. Relative labels are allowed since this is generally used at initialisation.

func TryNewBuildLabel

func TryNewBuildLabel(pkgName string, name string) (BuildLabel, error)

TryNewBuildLabel constructs a new build label from the given components.

func TryParseBuildLabel

func TryParseBuildLabel(target string, currentPath string) (BuildLabel, error)

TryParseBuildLabel attempts to parse a single build label from a string. Returns an error if unsuccessful.

func (BuildLabel) FullPaths

func (label BuildLabel) FullPaths(graph *BuildGraph) []string

func (BuildLabel) HasParent

func (label BuildLabel) HasParent() bool

HasParent returns true if the build label has a parent that's not itself.

func (BuildLabel) IsAllSubpackages

func (label BuildLabel) IsAllSubpackages() bool

Returns true if the label ends in ..., ie. it includes all subpackages.

func (BuildLabel) IsAllTargets

func (label BuildLabel) IsAllTargets() bool

Returns true if the label is the pseudo-label referring to all targets in this package.

func (BuildLabel) IsEmpty

func (label BuildLabel) IsEmpty() bool

IsEmpty returns true if this is an empty build label, i.e. nothing's populated it yet.

func (BuildLabel) Label

func (label BuildLabel) Label() *BuildLabel

func (BuildLabel) Less

func (this BuildLabel) Less(that BuildLabel) bool

func (BuildLabel) LocalPaths

func (label BuildLabel) LocalPaths(graph *BuildGraph) []string

func (BuildLabel) Parent

func (label BuildLabel) Parent() BuildLabel

Parent returns what would be the parent of a build label, or the label itself if it's parentless. Note that there is not a concrete guarantee that the returned label exists in the build graph, and that the label returned is the ultimate ancestor (ie. not necessarily immediate parent).

func (BuildLabel) Paths

func (label BuildLabel) Paths(graph *BuildGraph) []string

Implementation of BuildInput interface

func (BuildLabel) String

func (label BuildLabel) String() string

func (*BuildLabel) UnmarshalFlag

func (label *BuildLabel) UnmarshalFlag(value string) error

UnmarshalFlag unmarshals a build label from a command line flag. Implementation of flags.Unmarshaler interface.

func (*BuildLabel) UnmarshalText

func (label *BuildLabel) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. This is used by gcfg to unmarshal the config files.

type BuildLabels

type BuildLabels []BuildLabel

Make slices of these guys sortable.

func (BuildLabels) Len

func (slice BuildLabels) Len() int

func (BuildLabels) Less

func (slice BuildLabels) Less(i, j int) bool

func (BuildLabels) Swap

func (slice BuildLabels) Swap(i, j int)

type BuildResult

type BuildResult struct {
	// Thread id (or goroutine id, really) that generated this result.
	ThreadId int
	// Timestamp of this event
	Time time.Time
	// Target which has just changed
	Label BuildLabel
	// Its current status
	Status BuildResultStatus
	// Error, only populated for failure statuses
	Err error
	// Description of what's going on right now.
	Description string
	// Test results
	Tests TestResults
}

func NewBuildError

func NewBuildError(tid int, label BuildLabel, status BuildResultStatus, err error, description string) BuildResult

type BuildResultStatus

type BuildResultStatus int
const (
	PackageParsing BuildResultStatus = iota
	PackageParsed
	ParseFailed
	TargetBuilding
	TargetBuildStopped
	TargetBuilt
	TargetCached
	TargetBuildFailed
	TargetTesting
	TargetTested
	TargetTestFailed
)

func (BuildResultStatus) Category

func (s BuildResultStatus) Category() string

type BuildState

type BuildState struct {
	Graph *BuildGraph

	// Stream of results from the build
	Results chan *BuildResult
	// Configuration options
	Config *Configuration
	// Hashes of variouts bits of the configuration, used for incrementality.
	Hashes struct {
		// Hash of the general config, not including specialised bits.
		Config []byte
		// Hash of the config relating to containerisation for tests.
		Containerisation []byte
	}
	// Level of verbosity during the build
	Verbosity int
	// Cache to store / retrieve old build results.
	Cache Cache
	// Targets that we were originally requested to build
	OriginalTargets []BuildLabel
	// Arguments to tests.
	TestArgs []string
	// Labels of targets that we will include / exclude
	Include, Exclude []string
	// Actual targets to exclude from discovery
	ExcludeTargets []BuildLabel
	// True if we require rule hashes to be correctly verified (usually the case).
	VerifyHashes bool
	// Aggregated coverage for this run
	Coverage TestCoverage
	// True if tests should calculate coverage metrics
	NeedCoverage bool
	// True if we intend to build targets. False if we're just parsing
	// (although some may be built if they're needed for parse).
	NeedBuild bool
	// True if we're running tests. False if we're only building or parsing.
	NeedTests bool
	// True if we want to calculate target hashes (ie. 'plz hash').
	NeedHashesOnly bool
	// True if we only want to prepare build directories (ie. 'plz build --prepare')
	PrepareOnly bool
	// Number of times to run each test target. 0 == once each, plus flakes if necessary.
	NumTestRuns int
	// True to clean working directories after successful builds.
	CleanWorkdirs bool
	// True if we're forcing a rebuild of the original targets.
	ForceRebuild bool
	// True to always show test output, even on success.
	ShowTestOutput bool
	// True to print all output of all tasks to stderr.
	ShowAllOutput bool
	// contains filtered or unexported fields
}

Passed about to track the current state of the build.

var State *BuildState

Singleton instance of one of these. Tried to avoid introducing it but it ended up being inevitable to make some of the parsing code work.

func NewBuildState

func NewBuildState(numThreads int, cache Cache, verbosity int, config *Configuration) *BuildState

func (*BuildState) AddActiveTarget

func (state *BuildState) AddActiveTarget()

func (*BuildState) AddOriginalTarget

func (state *BuildState) AddOriginalTarget(label BuildLabel)

AddOriginalTarget adds one of the original targets and enqueues it for parsing / building.

func (*BuildState) AddPendingBuild

func (state *BuildState) AddPendingBuild(label BuildLabel, forSubinclude bool)

func (*BuildState) AddPendingParse

func (state *BuildState) AddPendingParse(label, dependor BuildLabel, forSubinclude bool)

func (*BuildState) AddPendingTest

func (state *BuildState) AddPendingTest(label BuildLabel)

func (*BuildState) ExpandOriginalTargets

func (state *BuildState) ExpandOriginalTargets() BuildLabels

ExpandOriginalTargets expands any pseudo-targets (ie. :all, ... has already been resolved to a bunch :all targets) from the set of original targets.

func (*BuildState) ExpandVisibleOriginalTargets

func (state *BuildState) ExpandVisibleOriginalTargets() BuildLabels

ExpandVisibleOriginalTargets expands any pseudo-targets (ie. :all, ... has already been resolved to a bunch :all targets) from the set of original targets. Hidden targets are not included.

func (*BuildState) IsOriginalTarget

func (state *BuildState) IsOriginalTarget(label BuildLabel) bool

IsOriginalTarget returns true if a target is an original target, ie. one specified on the command line.

func (*BuildState) Kill

func (state *BuildState) Kill(n int)

Kill adds n kill tasks to the list of pending tasks, which stops n workers before they do anything else.

func (*BuildState) KillAll

func (state *BuildState) KillAll()

KillAll kills all the workers.

func (*BuildState) LogBuildError

func (state *BuildState) LogBuildError(tid int, label BuildLabel, status BuildResultStatus, err error, format string, args ...interface{})

func (*BuildState) LogBuildResult

func (state *BuildState) LogBuildResult(tid int, label BuildLabel, status BuildResultStatus, description string)

func (*BuildState) LogTestResult

func (state *BuildState) LogTestResult(tid int, label BuildLabel, status BuildResultStatus, results TestResults, coverage TestCoverage, err error, format string, args ...interface{})

func (*BuildState) NextTask

func (state *BuildState) NextTask() (BuildLabel, BuildLabel, TaskType)

NextTask receives the next task that should be processed according to the priority queues.

func (*BuildState) NumActive

func (state *BuildState) NumActive() int

func (*BuildState) NumDone

func (state *BuildState) NumDone() int

func (*BuildState) SetIncludeAndExclude

func (state *BuildState) SetIncludeAndExclude(include, exclude []string)

SetIncludeAndExclude sets the include / exclude labels. Handles build labels on Exclude so should be preferred over setting them directly.

func (*BuildState) Stop

func (state *BuildState) Stop(n int)

Stop adds n stop tasks to the list of pending tasks, which stops n workers after all their other tasks are done.

func (*BuildState) TaskDone

func (state *BuildState) TaskDone()

TaskDone indicates that a single task is finished. Should be called after one is finished with a task returned from NextTask().

type BuildTarget

type BuildTarget struct {
	// Identifier of this build target
	Label BuildLabel

	// List of build target patterns that can use this build target.
	Visibility []BuildLabel
	// Source files of this rule. Can refer to build rules themselves.
	Sources []BuildInput
	// Named source files of this rule; as above but identified by name.
	NamedSources map[string][]BuildInput
	// Data files of this rule. Similar to sources but used at runtime, typically by tests.
	Data []BuildInput

	// Optional output files of this rule. Same as outs but aren't required to be produced always.
	// Can be glob patterns.
	OptionalOutputs []string
	// Optional labels applied to this rule. Used for including/excluding rules.
	Labels []string
	// Shell command to run.
	Command string
	// Per-configuration shell commands to run.
	Commands map[string]string
	// Shell command to run for test targets.
	TestCommand string
	// Per-configuration test commands to run.
	TestCommands map[string]string

	// True if this target is a binary (ie. runnable, will appear in plz-out/bin)
	IsBinary bool
	// True if this target is a test
	IsTest bool
	// Indicates that the target can only be depended on by tests or other rules with this set.
	// Used to restrict non-deployable code and also affects coverage detection.
	TestOnly bool
	// True if we're going to containerise the test.
	Containerise bool
	// True if the target is a test and has no output file.
	// Default is false, meaning all tests must produce test.results as output.
	NoTestOutput bool
	// True if this target needs access to its transitive dependencies to build.
	// This would be false for most 'normal' genrules but true for eg. compiler steps
	// that need to build in everything.
	NeedsTransitiveDependencies bool
	// True if this target blocks recursive exploring for transitive dependencies.
	// This is typically false for _library rules which aren't complete, and true
	// for _binary rules which normally are, and genrules where you don't care about
	// the inputs, only whatever they were turned into.
	OutputIsComplete bool
	// If true, the rule is given an env var at build time that contains the hash of its
	// transitive dependencies, which can be used to identify the output in a predictable way.
	Stamp bool
	// Marks the target as a filegroup.
	IsFilegroup bool
	// Containerisation settings that override the defaults.
	ContainerSettings *TargetContainerSettings
	// Results of test, if it is one
	Results TestResults
	// Description displayed while the command is building.
	// Default is just "Building" but it can be customised.
	BuildingDescription string
	// Acceptable hashes of the outputs of this rule. If the output doesn't match any of these
	// it's an error at build time. Can be used to validate third-party deps.
	Hashes []string
	// Licences that this target is subject to.
	Licences []string
	// Python functions to call before / after target is built. Allows deferred manipulation of the
	// build graph.
	PreBuildFunction, PostBuildFunction uintptr
	// Hash of the function's bytecode. Used for incrementality.
	// TODO(pebers): unify with RuleHash maybe? seems wasteful to store these separately.
	PreBuildHash, PostBuildHash []byte
	// Languages this rule requires. These are an arbitrary set and the only meaning is that they
	// correspond to entries in Provides; if rules match up then it allows choosing a specific
	// dependency (consider eg. code generated from protobufs; this mechanism allows us to expose
	// one rule but only compile the appropriate code for each library that consumes it).
	Requires []string
	// Dependent rules this rule provides for each language. Matches up to Requires as described above.
	Provides map[string]BuildLabel
	// Stores the hash of this build rule before any post-build function is run.
	RuleHash []byte
	// Tools that this rule will use, ie. other rules that it may use at build time which are not
	// copied into its source directory.
	Tools []BuildInput
	// Flakiness of test, ie. number of times we will rerun it before giving up. 0 is the default and
	// is interpreted the same way as 1 would be (ie. one run only).
	Flakiness int
	// Timeouts for build/test actions
	BuildTimeout time.Duration
	TestTimeout  time.Duration
	// Extra output files from the test.
	// These are in addition to the usual test.results output file.
	TestOutputs []string
	// contains filtered or unexported fields
}

func NewBuildTarget

func NewBuildTarget(label BuildLabel) *BuildTarget

func (*BuildTarget) AddCommand

func (target *BuildTarget) AddCommand(config, command string)

AddCommand adds a new config-specific command to this build target. Adding a general command is still done by simply setting the Command member.

func (*BuildTarget) AddDependency

func (target *BuildTarget) AddDependency(dep BuildLabel)

AddDependency adds a dependency to this target. It deduplicates against any existing deps.

func (*BuildTarget) AddLabel

func (target *BuildTarget) AddLabel(label string)

AddLabel adds the given label to this target if it doesn't already have it.

func (*BuildTarget) AddLicence

func (target *BuildTarget) AddLicence(licence string)

AddLicence adds a licence to the target if it's not already there.

func (*BuildTarget) AddMaybeExportedDependency

func (target *BuildTarget) AddMaybeExportedDependency(dep BuildLabel, exported bool)

AddMaybeExportedDependency adds a dependency to this target which may be exported. It deduplicates against any existing deps.

func (*BuildTarget) AddNamedSource

func (target *BuildTarget) AddNamedSource(name string, source BuildInput)

AddNamedSource adds a source to the target which is tagged with a particular name. For example, C++ rules add sources tagged as "sources" and "headers" to distinguish two conceptually different kinds of input.

func (*BuildTarget) AddOutput

func (target *BuildTarget) AddOutput(output string)

AddOutput adds a new output to the target if it's not already there.

func (*BuildTarget) AddProvide

func (target *BuildTarget) AddProvide(language string, label BuildLabel)

AddProvide adds a new provide entry to this target.

func (*BuildTarget) AddSource

func (target *BuildTarget) AddSource(source BuildInput)

AddSource adds a source to the build target, deduplicating against existing entries.

func (*BuildTarget) AddTestCommand

func (target *BuildTarget) AddTestCommand(config, command string)

AddTestCommand adds a new config-specific test command to this build target. Adding a general command is still done by simply setting the TestCommand member.

func (*BuildTarget) AllLocalSources

func (target *BuildTarget) AllLocalSources() []string

AllLocalSources returns all the "local" sources of this rule, i.e. all sources that are actually sources in the repo, not other rules or system srcs etc.

func (*BuildTarget) AllSourcePaths

func (target *BuildTarget) AllSourcePaths(graph *BuildGraph) []string

AllSourcePaths returns all the source paths for this target

func (*BuildTarget) AllSources

func (target *BuildTarget) AllSources() []BuildInput

AllSources returns all the sources of this rule.

func (*BuildTarget) CanSee

func (target *BuildTarget) CanSee(dep *BuildTarget) bool

CanSee returns true if target can see the given dependency, or false if not.

func (*BuildTarget) CheckDependencyVisibility

func (target *BuildTarget) CheckDependencyVisibility(graph *BuildGraph) error

CheckDependencyVisibility checks that all declared dependencies of this target are visible to it. Returns an error if not, or nil if all's well.

func (*BuildTarget) CheckDuplicateOutputs

func (target *BuildTarget) CheckDuplicateOutputs() error

CheckDuplicateOutputs checks if any of the outputs of this target duplicate one another. Returns an error if so, or nil if all's well.

func (*BuildTarget) DeclaredDependencies

func (target *BuildTarget) DeclaredDependencies() []BuildLabel

DeclaredDependencies returns the original declaration of this target's dependencies.

func (*BuildTarget) DeclaredOutputs

func (target *BuildTarget) DeclaredOutputs() []string

DeclaredOutputs returns the outputs from this target's original declaration. Hence it's similar to Outputs() but without the resolving of other rule names.

func (*BuildTarget) Dependencies

func (target *BuildTarget) Dependencies() []*BuildTarget

Dependencies returns the resolved dependencies of this target.

func (*BuildTarget) DependenciesFor

func (target *BuildTarget) DependenciesFor(label BuildLabel) []*BuildTarget

DependenciesFor returns the dependencies that relate to a given label.

func (*BuildTarget) ExportedDependencies

func (target *BuildTarget) ExportedDependencies() []BuildLabel

ExportedDependencies returns any exported dependencies of this target.

func (*BuildTarget) GetCommand

func (target *BuildTarget) GetCommand() string

GetCommand returns the command we should use to build this target for the current config.

func (*BuildTarget) GetTestCommand

func (target *BuildTarget) GetTestCommand() string

GetTestCommand returns the command we should use to test this target for the current config.

func (*BuildTarget) HasAnyLabel

func (target *BuildTarget) HasAnyLabel(labels []string) bool

HasAnyLabel returns true if target has any of these labels.

func (*BuildTarget) HasDependency

func (target *BuildTarget) HasDependency(label BuildLabel) bool

HasDependency checks if a target already depends on this label.

func (*BuildTarget) HasLabel

func (target *BuildTarget) HasLabel(label string) bool

HasLabel returns true if target has the given label.

func (*BuildTarget) HasParent

func (target *BuildTarget) HasParent() bool

HasParent returns true if the target has a parent rule that's not itself.

func (*BuildTarget) HasSource

func (target *BuildTarget) HasSource(source string) bool

HasSource returns true if this target has the given file as a source (named or not).

func (*BuildTarget) IsTool

func (target *BuildTarget) IsTool(tool BuildLabel) bool

IsTool returns true if the given build label is a tool used by this target.

func (*BuildTarget) OutDir

func (target *BuildTarget) OutDir() string

Returns the output directory for this target, eg. //mickey/donald:goofy -> plz-out/gen/mickey/donald (or plz-out/bin if it's a binary)

func (*BuildTarget) OutMode

func (target *BuildTarget) OutMode() os.FileMode

OutMode returns the mode to set outputs of a target to.

func (*BuildTarget) Outputs

func (target *BuildTarget) Outputs() []string

Outputs returns a slice of all the outputs of this rule.

func (*BuildTarget) Parent

func (target *BuildTarget) Parent(graph *BuildGraph) *BuildTarget

Parent finds the parent of a build target, or nil if the target is parentless. Note that this is a fairly informal relationship; we identify it by labels with the convention of a leading _ and trailing hashtag on child rules, rather than storing pointers between them in the graph. The parent returned, if any, will be the ultimate ancestor of the target.

func (*BuildTarget) PostBuildOutputFileName

func (target *BuildTarget) PostBuildOutputFileName() string

PostBuildOutputFileName returns the post-build output file for this target.

func (*BuildTarget) ProvideFor

func (target *BuildTarget) ProvideFor(other *BuildTarget) []BuildLabel

ProvideFor returns the build label that we'd provide for the given target.

func (*BuildTarget) SetContainerSetting

func (target *BuildTarget) SetContainerSetting(name, value string) error

SetContainerSetting sets one of the fields on the container settings by name.

func (*BuildTarget) SetState

func (target *BuildTarget) SetState(state BuildTargetState)

SetState sets a target's current state.

func (*BuildTarget) ShouldInclude

func (target *BuildTarget) ShouldInclude(include, exclude []string) bool

ShouldInclude handles the typical include/exclude logic for a target's labels; returns true if target has any include label and not an exclude one.

func (*BuildTarget) SourcePaths

func (target *BuildTarget) SourcePaths(graph *BuildGraph, sources []BuildInput) []string

Returns the source paths for a given set of sources.

func (*BuildTarget) State

func (target *BuildTarget) State() BuildTargetState

State returns the target's current state.

func (*BuildTarget) SyncUpdateState

func (target *BuildTarget) SyncUpdateState(before, after BuildTargetState) bool

SyncUpdateState oves the target's state from before to after via a lock. Returns true if successful, false if not (which implies something else changed the state first). The nature of our build graph ensures that most transitions are only attempted by one thread simultaneously, but this one can be attempted by several at once (eg. if a depends on b and c, which finish building simultaneously, they race to queue a).

func (*BuildTarget) TestDir

func (target *BuildTarget) TestDir() string

Returns the test directory for this target, eg. //mickey/donald:goofy -> plz-out/tmp/mickey/donald/goofy._test This is different to TmpDir so we run tests in a clean environment and to facilitate containerising tests.

func (*BuildTarget) TmpDir

func (target *BuildTarget) TmpDir() string

TmpDir returns the temporary working directory for this target, eg. //mickey/donald:goofy -> plz-out/tmp/mickey/donald/goofy._build Note the extra subdirectory to keep rules separate from one another, and the .build suffix to attempt to keep rules from duplicating the names of sub-packages; obviously that is not 100% reliable but we don't have a better solution right now.

type BuildTargetState

type BuildTargetState int32
const (
	Inactive   BuildTargetState = iota // Target isn't used in current build
	Semiactive                         // Target would be active if we needed a build
	Active                             // Target is going to be used in current build
	Pending                            // Target is ready to be built but not yet started.
	Building                           // Target is currently being built
	Stopped                            // We stopped building the target because we'd gone as far as needed.
	Built                              // Target has been successfully built
	Cached                             // Target has been retrieved from the cache
	Unchanged                          // Target has been built but hasn't changed since last build
	Reused                             // Outputs of previous build have been reused.
	Failed                             // Target failed for some reason
)

type BuildTargets

type BuildTargets []*BuildTarget

Make slices of these guys sortable.

func (BuildTargets) Len

func (slice BuildTargets) Len() int

func (BuildTargets) Less

func (slice BuildTargets) Less(i, j int) bool

func (BuildTargets) Swap

func (slice BuildTargets) Swap(i, j int)

type Cache

type Cache interface {
	// Stores the results of a single build target.
	// Optionally can store extra files against it at the same time.
	Store(target *BuildTarget, key []byte, files ...string)
	// Stores an extra file against a build target.
	// The file name is relative to the target's out directory.
	StoreExtra(target *BuildTarget, key []byte, file string)
	// Retrieves the results of a single build target.
	// If successful, the outputs will be placed into the output file tree.
	Retrieve(target *BuildTarget, key []byte) bool
	// Retrieves an extra file previously stored by StoreExtra.
	// If successful, the file will be placed into the output file tree.
	RetrieveExtra(target *BuildTarget, key []byte, file string) bool
	// Cleans any artifacts associated with this target from the cache, for any possible key.
	Clean(target *BuildTarget)
	// Shuts down the cache, blocking until any potentially pending requests are done.
	Shutdown()
}

Cache is our general interface to caches for built targets. The implementations are in //src/cache, but the interface is in this package because it's passed around on the BuildState object.

type Configuration

type Configuration struct {
	Please struct {
		Version          semver.Version
		Location         string
		SelfUpdate       bool
		DownloadLocation string
		BuildFileName    []string
		BlacklistDirs    []string
		Lang             string
		PyPyLocation     []string
		ParserEngine     string
		Nonce            string
		NumThreads       int
		ExperimentalDir  string
	}
	Build struct {
		Timeout        cli.Duration
		Path           []string
		Config         string
		FallbackConfig string
	}
	BuildConfig map[string]string
	Cache       struct {
		Workers               int
		Dir                   string
		DirCacheCleaner       string
		DirCacheHighWaterMark string
		DirCacheLowWaterMark  string
		HttpUrl               string
		HttpWriteable         bool
		HttpTimeout           cli.Duration
		RpcUrl                string
		RpcWriteable          bool
		RpcTimeout            cli.Duration
		RpcPublicKey          string
		RpcPrivateKey         string
		RpcCACert             string
		RpcSecure             bool
		RpcMaxMsgSize         cli.ByteSize
	}
	Metrics struct {
		PushGatewayURL string
		PushFrequency  cli.Duration
		PushTimeout    cli.Duration
	}
	CustomMetricLabels map[string]string
	Test               struct {
		Timeout          cli.Duration
		DefaultContainer ContainerImplementation
	}
	Cover struct {
		FileExtension    []string
		ExcludeExtension []string
	}
	Docker struct {
		DefaultImage       string
		AllowLocalFallback bool
		Timeout            cli.Duration
		ResultsTimeout     cli.Duration
		RemoveTimeout      cli.Duration
		RunArgs            []string
	}
	Gc struct {
		Keep      []BuildLabel
		KeepLabel []string
	}
	Go struct {
		GoVersion string
		GoRoot    string
		TestTool  string
		GoPath    string
		CgoCCTool string
	}
	Python struct {
		PipTool            string
		PipFlags           string
		PexTool            string
		DefaultInterpreter string
		ModuleDir          string
		DefaultPipRepo     string
		UsePyPI            bool
	}
	Java struct {
		JavacTool          string
		JavacWorker        string
		JarTool            string
		JarCatTool         string
		PleaseMavenTool    string
		JUnitRunner        string
		DefaultTestPackage string
		SourceLevel        string
		TargetLevel        string
		JavacFlags         string
		JavacTestFlags     string
		DefaultMavenRepo   string
	}
	Cpp struct {
		CCTool             string
		CppTool            string
		LdTool             string
		ArTool             string
		AsmTool            string
		LinkWithLdTool     bool
		DefaultOptCflags   string
		DefaultDbgCflags   string
		DefaultOptCppflags string
		DefaultDbgCppflags string
		DefaultLdflags     string
		DefaultNamespace   string
		Coverage           bool
	}
	Proto struct {
		ProtocTool       string
		ProtocGoPlugin   string
		GrpcPythonPlugin string
		GrpcJavaPlugin   string
		GrpcCCPlugin     string
		Language         []string
		PythonDep        string
		JavaDep          string
		GoDep            string
		PythonGrpcDep    string
		JavaGrpcDep      string
		GoGrpcDep        string
		PythonPackage    string
	}
	Licences struct {
		Accept []string
		Reject []string
	}
	Aliases map[string]string
	Bazel   struct {
		Compatibility bool
	}
}

func DefaultConfiguration

func DefaultConfiguration() *Configuration

func ReadConfigFiles

func ReadConfigFiles(filenames []string) (*Configuration, error)

Reads a config file from the given locations, in order. Values are filled in by defaults initially and then overridden by each file in turn.

func (*Configuration) ApplyOverrides

func (config *Configuration) ApplyOverrides(overrides map[string]string) error

ApplyOverrides applies a set of overrides to the config. The keys of the given map are dot notation for the config setting.

func (*Configuration) ContainerisationHash

func (config *Configuration) ContainerisationHash() []byte

ContainerisationHash returns the hash of the containerisation part of the config.

func (*Configuration) Hash

func (config *Configuration) Hash() []byte

type ContainerImplementation

type ContainerImplementation string

ContainerImplementation is an enumerated type for the container engine we'd use.

const (
	ContainerImplementationNone   ContainerImplementation = "none"
	ContainerImplementationDocker ContainerImplementation = "docker"
)

func (*ContainerImplementation) UnmarshalText

func (ci *ContainerImplementation) UnmarshalText(text []byte) error

type FileLabel

type FileLabel struct {
	// Name of the file
	File string
	// Name of the package
	Package string
}

FileLabel represents a file in the current package which is directly used by a target.

func (FileLabel) FullPaths

func (label FileLabel) FullPaths(graph *BuildGraph) []string

func (FileLabel) Label

func (label FileLabel) Label() *BuildLabel

func (FileLabel) LocalPaths

func (label FileLabel) LocalPaths(graph *BuildGraph) []string

func (FileLabel) Paths

func (label FileLabel) Paths(graph *BuildGraph) []string

func (FileLabel) String

func (label FileLabel) String() string

type LineCoverage

type LineCoverage uint8
const (
	NotExecutable LineCoverage = iota // Line isn't executable (eg. comment, blank)
	Unreachable   LineCoverage = iota // Line is executable but we've determined it can't be reached. So far not used.
	Uncovered     LineCoverage = iota // Line is executable but isn't covered.
	Covered       LineCoverage = iota // Line is executable and covered.
)

func MergeCoverageLines

func MergeCoverageLines(existing, coverage []LineCoverage) []LineCoverage

type Package

type Package struct {
	// Name of the package, ie. //spam/eggs
	Name string
	// Filename of the build file that defined this package
	Filename string
	// Subincluded build defs files that this package imported
	Subincludes []BuildLabel
	// Targets contained within the package
	Targets map[string]*BuildTarget
	// Set of output files from rules.
	Outputs map[string]*BuildTarget

	// Used to arbitrate a single post-build function running at a time.
	// It would be sort of conceptually nice if they ran simultaneously but it'd
	// be far too hard to ensure consistency in any case where they can interact with one another.
	BuildCallbackMutex sync.Mutex
	// contains filtered or unexported fields
}

Package is a representation of a package, ie. the part of the system (one or more directories) covered by a single build file.

func NewPackage

func NewPackage(name string) *Package

NewPackage constructs a new package with the given name.

func (*Package) AllChildren

func (pkg *Package) AllChildren(target *BuildTarget) []*BuildTarget

AllChildren returns all child targets of the given one. The given target is included as well.

func (*Package) HasSubinclude

func (pkg *Package) HasSubinclude(label BuildLabel) bool

HasSubinclude returns true if the package has subincluded the given label.

func (*Package) IsIncludedIn

func (pkg *Package) IsIncludedIn(label BuildLabel) bool

IsIncludedIn returns true if the given build label would include this package. e.g. //src/... includes the packages src and src/core but not src2.

func (*Package) MustRegisterOutput

func (pkg *Package) MustRegisterOutput(fileName string, target *BuildTarget)

MustRegisterOutput registers a new output file and panics if it's already been registered.

func (*Package) RegisterOutput

func (pkg *Package) RegisterOutput(fileName string, target *BuildTarget) error

RegisterOutput registers a new output file in the map. Returns an error if the file has already been registered.

func (*Package) RegisterSubinclude

func (pkg *Package) RegisterSubinclude(label BuildLabel)

RegisterSubinclude adds a new subinclude to this package, guaranteeing uniqueness.

type SystemFileLabel

type SystemFileLabel struct {
	Path string
}

SystemFileLabel represents an absolute system dependency, which is not managed by the build system.

func (SystemFileLabel) FullPaths

func (label SystemFileLabel) FullPaths(graph *BuildGraph) []string

func (SystemFileLabel) Label

func (label SystemFileLabel) Label() *BuildLabel

func (SystemFileLabel) LocalPaths

func (label SystemFileLabel) LocalPaths(graph *BuildGraph) []string

func (SystemFileLabel) Paths

func (label SystemFileLabel) Paths(graph *BuildGraph) []string

func (SystemFileLabel) String

func (label SystemFileLabel) String() string

type TargetContainerSettings

type TargetContainerSettings struct {
	// Image to use for this test
	DockerImage string
	// Username / Uid to run as
	DockerUser string
	// Extra arguments to pass to 'docker run'
	DockerRunArgs string
}

Settings controlling containerisation for a particular target.

type TaskType

type TaskType int

A TaskType identifies the kind of task returned from NextTask()

type TestCoverage

type TestCoverage struct {
	Tests map[BuildLabel]map[string][]LineCoverage
	Files map[string][]LineCoverage
}

This is a pretty simple coverage format; we record one int for each line stating what its coverage is.

func NewTestCoverage

func NewTestCoverage() TestCoverage

func (*TestCoverage) Aggregate

func (this *TestCoverage) Aggregate(that TestCoverage)

Aggregates results from that coverage object into this one.

func (TestCoverage) OrderedFiles

func (this TestCoverage) OrderedFiles() []string

Returns an ordered slice of all the files we have coverage information for.

type TestFailure

type TestFailure struct {
	Name      string // Name of failed test
	Type      string // Type of failure, eg. type of exception raised
	Traceback string // Traceback
	Stdout    string // Standard output during test
	Stderr    string // Standard error during test
}

type TestResults

type TestResults struct {
	NumTests         int // Total number of test cases in the test target.
	Passed           int // Number of tests that passed outright.
	Failed           int // Number of tests that failed.
	ExpectedFailures int // Number of tests that were expected to fail (counts as a pass, but displayed differently)
	Skipped          int // Number of tests skipped (also count as passes)
	Flakes           int // Number of failed attempts to run the test
	Failures         []TestFailure
	Passes           []string
	Output           string  // Stdout / stderr from the test.
	Cached           bool    // True if the test results were retrieved from cache
	TimedOut         bool    // True if the test failed because we timed it out.
	Duration         float64 // Length of time this test took, in seconds.
}

func (*TestResults) Aggregate

func (this *TestResults) Aggregate(that TestResults)

Aggregates the given results into this one.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL