bazel

package
v0.0.0-...-5f133c6 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: BSD-3-Clause, BSD-3-Clause Imports: 23 Imported by: 0

Documentation

Overview

Package bazel provides functions and types for interacting with a bazel workspace.

Index

Constants

This section is empty.

Variables

View Source
var NewCommand = func(cmd *exec.Cmd, env ...string) (Command, error) {
	stdout, err := ioutil.TempFile("", "bazel_stdout_*")
	if err != nil {
		return nil, fmt.Errorf("failed to create stdout file: %w", err)
	}
	stdout.Close()
	stderr, err := ioutil.TempFile("", "bazel_stderr_*")
	if err != nil {
		return nil, fmt.Errorf("failed to create stderr file: %w", err)
	}
	stderr.Close()

	return &fileCommand{
		cmd:        cmd,
		env:        env,
		stdoutPath: stdout.Name(),
		stderrPath: stderr.Name(),
	}, nil
}

NewCommand returns a fileCommand wrapping the provided exec.Cmd. It is defined as a var so it can be stubbed in unit tests.

Functions

func CommandString

func CommandString(cmd *exec.Cmd, cmdenv []string) string

CommandString returns a string describing a command.

Differently from cmd.String(), the command description includes environment variables that were explicitly set on the binary.

func FindRoot

func FindRoot(dir string) (string, error)

FindRoot returns the path to the bazel workspace root in which `dir` resides, or an error if `dir` is not inside a bazel workspace.

func GetAffectedTargets

func GetAffectedTargets(config *ppb.PresubmitConfig, mode GetMode, opts GetModeOptions, log logger.Logger) ([]*Target, []*Target, error)

Types

type BaseOption

type BaseOption func(*baseOptions)

Option modifies Bazel startup options.

func WithExtraEnv

func WithExtraEnv(extra ...string) BaseOption

WithExtraEnv adds extra environment variables for this bazel invocation.

func WithExtraStartupFlags

func WithExtraStartupFlags(extra ...string) BaseOption

WithExtraStartupFlags adds extra startup flags for this bazel invocation.

func WithLogging

func WithLogging(log logger.Logger) BaseOption

func WithOutputBase

func WithOutputBase(outputBase string) BaseOption

WithOutputBase sets --output_base for this bazel invocation.

type BaseOptions

type BaseOptions []BaseOption

type Command

type Command interface {
	// Run runs the underlying exec.Cmd.
	Run() error

	// Close releases resources associated with this command. It should be called
	// once the output is no longer needed/has already been consumed.
	Close() error

	// Stdout provides access to the command's stdout. Run() must be called first.
	// The caller should close the returned io.ReadCloser.
	Stdout() (io.ReadCloser, error)

	// Stderr provides access to the command's stderr. Run() must be called first.
	// The caller should close the returned io.ReadCloser.
	Stderr() (io.ReadCloser, error)

	// StdoutContents reads all of stdout into a raw byte slice.
	StdoutContents() ([]byte, error)

	// Returns a string representation of the command itself, for debug purposes.
	String() string

	// StderrContents reads stderr into a string. This method cannot fail, as it
	// is intended to be used only in logging/errors; if reading fails, a sentinel
	// error string will be returned instead.
	StderrContents() string
}

Command wraps an exec.Cmd, providing a common way to access stdout and stderr from the underlying command across production code and tests.

type ExactPattern

type ExactPattern string

ExactPattern represents a pattern that is actually an exact label like `//foo/bar:baz`, and only matches `//foo/bar:baz`.

func (ExactPattern) Contains

func (p ExactPattern) Contains(target string) bool

Contains matches target if target is the same as this pattern.

type GetMode

type GetMode func(options GetModeOptions, log logger.Logger) (*GetResult, error)

GetMode is a function to run bazel queries.

As paramters, it takes a temporary directory to use for the work, and a GetModeOptions object.

There are currently two implementations of GetMode: ParallelQuery, and SerialQuery.

type GetModeOptions

type GetModeOptions struct {
	// The starting point to compute the diff.
	Start SourceOptions
	// The end point to compute the diff.
	End SourceOptions

	// Bazel query to use to find all the targets. Must be set.
	// A good default is "deps(//...)"
	Query string

	// Extra startup flags to pass to bazel.
	// Those flags are appended after other common flags (but before
	// subcommand flags), so should override any global flag.
	ExtraStartup []string
}

type GetResult

type GetResult struct {
	StartQueryResult *QueryResult
	StartQueryError  error
	EndQueryResult   *QueryResult
	EndQueryError    error
}

The result of running a GetMode function below.

func ParallelQuery

func ParallelQuery(opt GetModeOptions, log logger.Logger) (*GetResult, error)

func SerialQuery

func SerialQuery(opt GetModeOptions, log logger.Logger) (*GetResult, error)

type InfoOption

type InfoOption func(*infoOptions)

Option modifies Bazel startup options.

func ForElement

func ForElement(elem string) InfoOption

type InfoOptions

type InfoOptions []InfoOption

type Label

type Label struct {
	Workspace string
	Package   string
	Rule      string
}

func (*Label) String

func (l *Label) String() string

type Pattern

type Pattern interface {
	Contains(string) bool
}

type PatternSet

type PatternSet []Pattern

PatternSet represents a collection of patterns.

func NewPatternSet

func NewPatternSet(patternStrs []string) (PatternSet, error)

NewPatternSet parses and returns a set of patterns for the supplied pattern strings.

func (PatternSet) Contains

func (p PatternSet) Contains(target string) bool

Contains returns true if any of the patterns in the set match the given target.

type QueryOption

type QueryOption func(*queryOptions)

QueryOption modifies bazel query subcommand flags.

func WithKeepGoing

func WithKeepGoing() QueryOption

WithKeepGoing sets `--keep_going` for this `bazel query` invocation.

func WithTempWorkspaceRulesLog

func WithTempWorkspaceRulesLog() (QueryOption, error)

func WithUnorderedOutput

func WithUnorderedOutput() QueryOption

WithUnorderedOutput sets `--order_output=no` for this `bazel query` invocation.

type QueryOptions

type QueryOptions []QueryOption

type QueryResult

type QueryResult struct {
	Targets         map[string]*Target
	WorkspaceEvents map[string][]*bpb.WorkspaceEvent
	// contains filtered or unexported fields
}

func (*QueryResult) TargetHashes

func (r *QueryResult) TargetHashes() (TargetHashes, error)

type RecursivePattern

type RecursivePattern string

RecursivePattern represents a pattern like `//foo/bar/...`, and matches all targets under `//foo/bar`.

func (RecursivePattern) Contains

func (p RecursivePattern) Contains(target string) bool

Contains matches target if target is under this RecursivePattern.

type SourceOptions

type SourceOptions struct {
	// Path of the git repository containing the start/end code.
	RepoPath string
	// Path of the --output_base to use with bazel.
	// If empty, a default path will be used depending on the GetMode used.
	OutputBase string
}

type Target

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

Target wraps a build.proto Target message with some lazily computed properties.

func NewExternalPseudoTarget

func NewExternalPseudoTarget(t *bpb.Target, eventMap map[string][]*bpb.WorkspaceEvent) (*Target, error)

Creates a Target object from the supplied proto message that represents an external target. This target only has attributes based on the hashes used during download of the external repository, to save time on hashing third-party files that are unlikely to change often. These hashes are fetched from the supplied set of workspace events.

func NewTarget

func NewTarget(w *Workspace, t *bpb.Target) (*Target, error)

Creates a Target object that holds computations based on the supplied target proto message.

func (*Target) Name

func (t *Target) Name() string

func (*Target) ResolveDeps

func (t *Target) ResolveDeps(others map[string]*Target) error

ResolveDeps resolves each target name to the actual target object using the supplied mapping.

func (*Target) RuleType

func (t *Target) RuleType() string

type TargetHashes

type TargetHashes map[string]uint32

func (TargetHashes) Diff

func (h TargetHashes) Diff(baseline TargetHashes) []string

Diff returns the changed targets between this set and a baseline set. Ordering of the two sets is important, as targets only present in baseline are omitted, whereas targets only present in this set are included.

type Workspace

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

Workspace corresponds to a bazel workspace on the filesystem, as defined by the presence of a WORKSPACE file.

func OpenWorkspace

func OpenWorkspace(rootPath string, options ...BaseOption) (*Workspace, error)

OpenWorkspace returns the bazel workspace at the specified path. If outputBase is provided, --output_base will be provided to all commands, which can allow for caching of bazel data when temp workspaces are used.

func (*Workspace) GeneratedFilesDir

func (w *Workspace) GeneratedFilesDir() (string, error)

func (*Workspace) Info

func (w *Workspace) Info(options ...InfoOption) (string, error)

func (*Workspace) OpenSource

func (w *Workspace) OpenSource(path string) (fs.File, error)

func (*Workspace) OutputBaseDir

func (w *Workspace) OutputBaseDir() (string, error)

func (*Workspace) OutputExternal

func (w *Workspace) OutputExternal() (string, error)

func (*Workspace) Query

func (w *Workspace) Query(query string, options ...QueryOption) (*QueryResult, error)

Query performs a `bazel query` using the provided query string. If `keep_going` is set, then `--keep_going` is set on the bazel commandline, and errors from the bazel process are ignored.

func (*Workspace) SourceDir

func (w *Workspace) SourceDir() (string, error)

Notes

Bugs

  • - By default, cargo will download packages to a well-known directory under $HOME; this will mean that parallel bazel invocations could race on this directory if they both fetch Cargo packages. Cargo respects the $CARGO_HOME environment variable, so set it to something unique for this invocation.

Directories

Path Synopsis
Package proto is empty here because this package is generated solely from protobuf; having a source file here helps `go get -u ./...` to not error.
Package proto is empty here because this package is generated solely from protobuf; having a source file here helps `go get -u ./...` to not error.

Jump to

Keyboard shortcuts

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