pkg

package
v0.33.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: Apache-2.0 Imports: 34 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AbsolutePath

func AbsolutePath(target *build.Target) string

AbsolutePath returns the absolute path to the source file Target. It assumes the passed Target is of type Source File.

func BazelOutputBase

func BazelOutputBase(workingDirectory string, BazelCmd BazelCmd) (string, error)

func BazelRelease added in v0.3.0

func BazelRelease(workingDirectory string, BazelCmd BazelCmd) (string, error)

func CompareLabels

func CompareLabels(a, b label.Label) bool

func ComputeCacheKey added in v0.33.0

func ComputeCacheKey(context *Context, gitSHA string, targetPattern string) (string, error)

ComputeCacheKey generates a unique cache key based on the binary hash, git SHA, and CLI options

func ConfigurationLess added in v0.18.0

func ConfigurationLess(l, r Configuration) bool

func DiffSingleLabel

func DiffSingleLabel(beforeMetadata, afterMetadata *QueryResults, includeDifferences bool, label label.Label, callback WalkCallback) error

func EnsureGitRepositoryClean

func EnsureGitRepositoryClean(workingDirectory string, ignoredFiles []common.RelPath) (bool, error)

func FullyProcess

func FullyProcess(context *Context, revBefore LabelledGitRev, revAfter LabelledGitRev, targets TargetsList) (*QueryResults, *QueryResults, error)

FullyProcess returns the before and after metadata maps, with fully filled caches.

func GitRevParse

func GitRevParse(workingDirectory string, rev string, isAbbrevRef bool) (string, error)

func GitTreeSHA added in v0.33.0

func GitTreeSHA(context *Context, gitRev string) (string, error)

GitTreeSHA returns the git tree SHA for the given commit-ish (e.g. a commit SHA or "HEAD").

func IsBzlmodEnabled added in v0.32.0

func IsBzlmodEnabled(workspacePath string, bazelCmd BazelCmd, releaseString string) (bool, error)

func NormalizeConfiguredTarget added in v0.31.0

func NormalizeConfiguredTarget(target *analysis.ConfiguredTarget, n *Normalizer)

func SaveToCache added in v0.33.0

func SaveToCache(context *Context, gitSHA string, targetPattern string, queryResults *QueryResults) error

SaveToCache saves QueryResults to cache

func WalkAffectedTargets

func WalkAffectedTargets(context *Context, revBefore LabelledGitRev, targets TargetsList, includeDifferences bool, callback WalkCallback) error

WalkAffectedTargets computes which targets have changed between two commits, and calls callback once for each target which has changed. Explanation of the differences may be expensive in both time and memory to compute, so if includeDifferences is set to false, the []Difference parameter to the callback will always be nil.

Types

type BazelCmd added in v0.5.0

type BazelCmd interface {
	HashableKey

	Execute(config BazelCmdConfig, startupArgs []string, command string, args ...string) (int, error)
	Cquery(bazelRelease string, config BazelCmdConfig, startupArgs []string, args ...string) (int, error)
}

type BazelCmdConfig added in v0.5.0

type BazelCmdConfig struct {
	// Dir represents the working directory to use for the command.
	// If Dir is the empty string, use the calling process's current directory.
	Dir string

	// Stdout and Stderr specify the process's standard output and error.
	// A nil value redirects the output to /dev/null.
	// The behavior is the same as the exec.Command struct.
	Stdout io.Writer
	Stderr io.Writer
}

type CacheKey added in v0.33.0

type CacheKey struct {
	TDBinaryHash  string
	BazelVersion  string
	GitTreeSHA    string
	TargetPattern string
	// Context holds the Context fields that affect the cache key (i.e. those not tagged
	// results_cache_key_ignore:"true"), plus the opaque hash returned by BazelCmd.HashKey().
	// encoding/json marshals map keys alphabetically, ensuring a deterministic serialization.
	Context map[string]interface{}
}

CacheKey represents the inputs used to generate a cache filename.

Known limitations (not included in the key, callers should be aware):

  • User and system .bazelrc files (~/.bazelrc, /etc/bazel.bazelrc, files imported from those) can affect the build configuration without changing the git tree. Target-determinator does not read these files; if they change between invocations, use --nocache_results.

  • The current machine's hardware and OS are not included. Cache entries produced on one machine are not guaranteed to be valid on another (e.g. different CPU architecture may change platform-constrained target sets). Do not share the cache directory across machines.

  • Environment variables forwarded to Bazel (CC, CXX, JAVA_HOME, BAZELRC, etc.) are not included. Changing these between invocations can affect cquery results without invalidating the cache. This is usually the expected behavior but has implications. See README.md.

type Configuration

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

func NormalizeConfiguration added in v0.18.0

func NormalizeConfiguration(c string) Configuration

func (*Configuration) ForHashing added in v0.18.0

func (c *Configuration) ForHashing() []byte

func (*Configuration) String added in v0.18.0

func (c *Configuration) String() string

type Context

type Context struct {
	// WorkspacePath is the absolute path to the root of the project's Bazel Workspace directory (which is
	// assumed to be in a git repository, but is not assumed to be the root of a git repository).
	WorkspacePath string `results_cache_key_ignore:"true"`
	// OriginalRevision is the git revision the repo was in when initializing the context.
	OriginalRevision LabelledGitRev `results_cache_key_ignore:"true"`
	// BazelCmd is used to execute when necessary Bazel.
	BazelCmd BazelCmd
	// BazelOutputBase is the path of the Bazel output base directory of the original workspace.
	BazelOutputBase string `results_cache_key_ignore:"true"`
	// DeleteCachedWorktree represents whether we should keep worktrees around for reuse in future invocations.
	DeleteCachedWorktree bool `results_cache_key_ignore:"true"`
	// IgnoredFiles represents files that should be ignored for git operations.
	IgnoredFiles []common.RelPath
	// BeforeQueryErrorBehavior describes how to handle errors when querying the "before" revision.
	// Accepted values are:
	// - "fatal" - treat an error querying as fatal.
	// - "ignore-and-build-all" - ignore the error, and build all targets at the "after" revision.
	BeforeQueryErrorBehavior string `results_cache_key_ignore:"true"`
	// AnalysisCacheClearStrategy is the strategy used for clearing the Bazel analysis cache before cquery runs.
	// Accepted values are: skip, shutdown, discard.
	// We currently don't believe clearing this cache is necessary.
	//
	// skip will not clear the analysis cache between cquery runs.
	//
	// shutdown will shut down the bazel server before queries.
	// discard will run a build with --discard_analysis_cache before queries.
	//
	// discard avoids a potentially costly JVM tear-down and start-up,
	/// but seems to over-invalidate things (e.g. it seems to force re-fetching every rules_python whl_library which can be very expensive).
	AnalysisCacheClearStrategy string `results_cache_key_ignore:"true"`
	// CompareQueriesAroundAnalysisCacheClear controls whether we validate whether clearing the analysis cache had any meaningful effect.
	// We suspect that clearing the analysis cache is now unnecessary, as cquery behaves more reasonably around not returning stale results.
	// This flag allows validating whether that is the case.
	CompareQueriesAroundAnalysisCacheClear bool `results_cache_key_ignore:"true"`
	// FilterIncompatibleTargets controls whether we filter out incompatible targets from the candidate set of affected targets.
	FilterIncompatibleTargets bool
	// EnforceCleanRepo controls whether we should fail if the repository is unclean.
	EnforceCleanRepo bool `results_cache_key_ignore:"true"`
	// CacheDirectory is the directory to store cached query results. If empty, caching is disabled.
	CacheDirectory string `results_cache_key_ignore:"true"`
	// IncludeDifferences controls whether difference explanations are computed for affected targets.
	// When true, TransitiveConfiguredTargets is required and results must not be loaded from cache.
	IncludeDifferences bool `results_cache_key_ignore:"true"`
	// NoCacheResults disables both loading results from and saving results to the cache.
	NoCacheResults bool `results_cache_key_ignore:"true"`
}

type DefaultBazelCmd added in v0.5.0

type DefaultBazelCmd struct {
	BazelPath        string
	BazelStartupOpts []string
	BazelOpts        []string
}

func (DefaultBazelCmd) Cquery added in v0.33.0

func (c DefaultBazelCmd) Cquery(bazelRelease string, config BazelCmdConfig, startupArgs []string, args ...string) (int, error)

Cquery calls bazel cquery with the provided arguments, using an output file if supported. It returns the exit status code or -1 if it errored before the process could start.

func (DefaultBazelCmd) Execute added in v0.5.0

func (c DefaultBazelCmd) Execute(config BazelCmdConfig, startupArgs []string, command string, args ...string) (int, error)

Execute calls bazel with the provided arguments. It returns the exit status code or -1 if it errored before the process could start.

func (DefaultBazelCmd) HashKey added in v0.33.0

func (c DefaultBazelCmd) HashKey() string

HashKey returns a SHA-256 digest of the cache-affecting fields: BazelStartupOpts and BazelOpts. Both slices are included in order, as their ordering affects Bazel behaviour.

The Bazel version from BazelPath is already available in the context so, to avoid running another bazel subprocess, it is not taken as input to the resulting hash.

type Difference

type Difference struct {
	// Category is the kind of change, e.g. that the target is new, that a file changed, etc.
	Category string
	// Key is the thing which changed, e.g. the name of an attribute, or the name of the input file.
	Key string
	// Before is the value of Key before the change.
	Before string
	// After is the value of Key after the change.
	After string
}

Difference represents a difference of a target between two commits. All fields except Category are optional.

func WalkDiffs

func WalkDiffs(before *TargetHashCache, after *TargetHashCache, labelAndConfiguration LabelAndConfiguration) ([]Difference, error)

WalkDiffs accumulates the differences of a LabelAndConfiguration before and after a change.

func (Difference) String

func (d Difference) String() string

type GitFileStatus

type GitFileStatus struct {
	// Status contains the shorthand notation of the status of the file. See `man git-status` for a mapping.
	Status string
	// FilePath represents the path of the file relative to the git repository.
	FilePath common.RelPath
}

func GitStatusFiltered added in v0.4.0

func GitStatusFiltered(workingDirectory string, ignoredFiles []common.RelPath) ([]GitFileStatus, error)

func (GitFileStatus) String

func (s GitFileStatus) String() string

type GitRev added in v0.4.0

type GitRev struct {
	// Revision represents the git sha or ref. These values must be absolute.
	// A value such as "HEAD^" first needs to be resolved to the relevant commit.
	Revision string
	// Sha is the resolved sha256 of the Revision.
	Sha string
}
var CurrentWorkingCopyState GitRev

CurrentWorkingCopyState represents the (potentially dirty) state of the current working copy.

func (GitRev) String added in v0.4.0

func (l GitRev) String() string

type HashableKey added in v0.33.0

type HashableKey interface {
	// HashKey returns a deterministic string that captures all the struct's
	// fields that can affect target-determinator results. It is included in
	// the results cache key for each invocation.
	HashKey() string
}

type LabelAndConfiguration

type LabelAndConfiguration struct {
	Label         label.Label
	Configuration Configuration
}

type LabelAndConfigurations

type LabelAndConfigurations struct {
	Label          label.Label
	Configurations []Configuration
}

type LabelledGitRev

type LabelledGitRev struct {
	// Label is a description of what the git sha represents which may be useful to humans.
	Label string
	// GitRev is the actual revision.
	GitRevision GitRev
}
var NoLabelledGitRev LabelledGitRev

NoLabelledGitRev represents a null value for LabelledGitRev.

func NewLabelledGitRev

func NewLabelledGitRev(workspacePath string, revision string, label string) (LabelledGitRev, error)

NewLabelledGitRev ensures that the git sha is resolved as soon as the object is created, otherwise we might encounter undesirable behaviors when switching to other revisions e.g. if using "HEAD". If the revision argument is empty, the returned object will return the current workspace's (potentially dirty) state.

func (LabelledGitRev) String

func (l LabelledGitRev) String() string

type MatchingTargets

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

MatchingTargets stores the top-level targets within a repository, i.e. those matching the Bazel pattern `...`.

func (*MatchingTargets) ConfigurationsFor

func (mt *MatchingTargets) ConfigurationsFor(label label.Label) []Configuration

func (*MatchingTargets) ContainsLabelAndConfiguration

func (mt *MatchingTargets) ContainsLabelAndConfiguration(label label.Label, configuration Configuration) bool

func (*MatchingTargets) Labels

func (mt *MatchingTargets) Labels() []label.Label

type Normalizer added in v0.31.0

type Normalizer struct {
	Mapping map[string]string
}

Normalizer is a struct that contains a mapping of non-canonical repository names to canonical repository names.

func (*Normalizer) NormalizeAttribute added in v0.31.0

func (n *Normalizer) NormalizeAttribute(attr *build.Attribute) *build.Attribute

func (*Normalizer) ParseCanonicalLabel added in v0.31.0

func (n *Normalizer) ParseCanonicalLabel(s string) (label.Label, error)

ParseCanonicalLabel parses a label from a string, and removes sources of inconsequential difference which would make comparing two labels fail. In particular, it treats @// the same as // If the label is not canonical, it will attempt to map the repository to its canonical form coming from `bazel mod dump_repo_mapping ""`.

type QueryResults

type QueryResults struct {
	MatchingTargets             *MatchingTargets
	TransitiveConfiguredTargets map[label.Label]map[Configuration]*analysis.ConfiguredTarget
	TargetHashCache             *TargetHashCache
	BazelRelease                string
	// QueryError is whatever error was returned when running the cquery to get these results.
	QueryError error
	// contains filtered or unexported fields
}

func LoadFromCache added in v0.33.0

func LoadFromCache(context *Context, treeSHA string, targetPattern string) (*QueryResults, error)

LoadFromCache attempts to load QueryResults from cache. The treeSHA argument should represent the hash of a Git Tree object (which doesn't change if only the commit metadata, such as the git commit message, changes). Returns (results, error). If error is non-nil, the cache was not hit.

func LoadIncompleteMetadata

func LoadIncompleteMetadata(context *Context, rev LabelledGitRev, targets TargetsList) (*QueryResults, func(), error)

LoadIncompleteMetadata loads the metadata about, but not hashes of, targets into a QueryResults. The (transitive) dependencies of the passed targets will be loaded. For all targets, use `//...`.

It may change the git revision of the workspace to rev, in which case it is the caller's responsibility to check out the original commit.

It returns a non-nil callback to clean up the worktree if it was created.

Note that a non-nil QueryResults may be returned even in the error case, which will have an empty target-set, but may contain other useful information (e.g. the bazel release version). Checking for nil-ness of the error is the true arbiter for whether the entire load was successful.

func (*QueryResults) PrefillCache

func (queryInfo *QueryResults) PrefillCache() error

type SerializedQueryResults added in v0.33.0

type SerializedQueryResults struct {
	// Serialized protobuf of ConfiguredTargets
	MatchingTargetsData []byte
	BazelRelease        string
	NormalizerMapping   map[string]string
	// Key: "<label>\x00<config>", value: raw SHA256 bytes.
	PrecomputedHashes map[string][]byte
}

SerializedQueryResults is the structure that gets saved to disk

type TargetHashCache

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

TargetHashCache caches hash computations for targets and files, so that transitive hashes can be cheaply computed via dynamic programming. Note that a TargetHashCache doesn't eagerly read files, it lazily reads them when they're needed for hash computation, so if you're going to mutate filesystem state after creating a TargetHashCache (e.g. because you're going to check out a different commit), you should pre-compute any hashes you're interested in before mutating the filesystem. In the future we may pre-cache file hashes to avoid this hazard (and to allow more efficient use of threadpools when hashing files).

func NewTargetHashCache

func NewTargetHashCache(
	context map[gazelle_label.Label]map[Configuration]*analysis.ConfiguredTarget,
	normalizer *Normalizer,
	bazelRelease string,
) *TargetHashCache

NewTargetHashCache creates a TargetHashCache which uses context for metadata lookups.

func (*TargetHashCache) AttributeForSerialization added in v0.31.0

func (thc *TargetHashCache) AttributeForSerialization(rawAttr *build.Attribute) *build.Attribute

AttributeForSerialization redacts details about an attribute which don't affect the output of building them, and returns equivalent canonical attribute metadata. In particular it redacts:

  • Whether an attribute was explicitly specified (because the effective value is all that matters).
  • Any attribute named `generator_location`, because these point to absolute paths for built-in `cc_toolchain_suite` targets such as `@local_config_cc//:toolchain`.

func (*TargetHashCache) ExtractHashes added in v0.33.0

func (thc *TargetHashCache) ExtractHashes() map[string][]byte

ExtractHashes collects all pre-computed hashes from the cache. Keys are formatted as "<label>\x00<configuration>". Only entries with a computed hash are included.

func (*TargetHashCache) Freeze

func (thc *TargetHashCache) Freeze()

Freeze should be called before the filesystem is mutated to signify to the TargetHashCache that any future Hash calls which need to read files should fail, because the files may no longer be accurate from when the TargetHashCache was created.

func (*TargetHashCache) Hash

func (thc *TargetHashCache) Hash(labelAndConfiguration LabelAndConfiguration) ([]byte, error)

Hash hashes a given LabelAndConfiguration, returning a sha256 which will change if any of the following change:

  • Values of attributes of the label (if it's a rule)
  • Contents or mode of source files which are direct inputs to the rule (if it's a rule).
  • The name of the rule class (e.g. `java_binary`) of the rule (if it's a rule).
  • The rule definition, if it's a rule which was implemented in starlark. Note that this is known to over-estimate - it currently factors in the whole contents of any .bzl files loaded to define the rule, where some of this contents may not be relevant.
  • The configuration the label is configured in. Note that this is known to over-estimate - per-language fragments are not filtered from this configuration, which means C++-affecting options are considered to affect Java.
  • The above recursively for all rules and files which are depended on by the given LabelAndConfiguration. Note that this is known to over-estimate - the configuration of dependencies isn't easily surfaced by Bazel, so if a dependency exists in multiple configurations, all of them will be mixed into the hash, even if only one of the configurations is actually relevant. See https://github.com/bazelbuild/bazel/issues/14610

func (*TargetHashCache) KnownConfigurations

func (thc *TargetHashCache) KnownConfigurations(label gazelle_label.Label) *ss.SortedSet[Configuration]

KnownConfigurations returns the configurations in which a Label is known to be configured.

func (*TargetHashCache) ParseCanonicalLabel added in v0.31.0

func (thc *TargetHashCache) ParseCanonicalLabel(label string) (gazelle_label.Label, error)

func (*TargetHashCache) RestoreHashes added in v0.33.0

func (thc *TargetHashCache) RestoreHashes(hashes map[string][]byte) error

RestoreHashes populates the cache with pre-computed hashes and freezes the cache. Keys must be formatted as "<label>\x00<configuration>".

type TargetsList added in v0.4.0

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

func ParseTargetsList added in v0.4.0

func ParseTargetsList(targets string) (TargetsList, error)

func (*TargetsList) String added in v0.4.0

func (tl *TargetsList) String() string

type WalkCallback

type WalkCallback func(label.Label, []Difference, *analysis.ConfiguredTarget)

WalkCallback is called once per affected (label, configuration) pair. differences explains why the target was affected; it is nil when includeDifferences is false. configuredTarget is the "after" ConfiguredTarget proto; it may be nil when results are served from cache (i.e. when the -cache-dir flag is used without -verbose).

Jump to

Keyboard shortcuts

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