Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 22 additions & 11 deletions src/bazel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,24 +122,29 @@ impl BazelOptions {
/// (#531). `mod graph` stays as the fallback for a Bazel without `dump_repo_mapping`,
/// taking the partial answer it gives over such an extension.
pub fn is_bzlmod_enabled(&self) -> bool {
let (enabled, _root_mapping) = self.probe_bzlmod();
let (enabled, _root_mapping) = self.probe_bzlmod(None);
enabled
}

fn probe_bzlmod(&self) -> (bool, Option<Vec<u8>>) {
/// `graph` is a `bazel mod graph --output=json` answer already in hand. It stands in for the
/// fallback `bazel mod graph`, which differs from it only in how the graph is printed.
fn probe_bzlmod(&self, graph: Option<&Output>) -> (bool, Option<Vec<u8>>) {
if let Ok(output) = self.run_capture(&["mod", "dump_repo_mapping", ""]) {
if output.status.success() {
return (true, Some(output.stdout));
}
}
let enabled = self
.run_capture(&["mod", "graph"])
.map(|output| {
output.status.success()
|| extension_failure(&String::from_utf8_lossy(&output.stderr))
.is_some_and(|failure| failure.answered)
})
.unwrap_or(false);
let answered = |output: &Output| {
output.status.success()
|| extension_failure(&String::from_utf8_lossy(&output.stderr))
.is_some_and(|failure| failure.answered)
};
let enabled = match graph {
Some(output) => answered(output),
None => self
.run_capture(&["mod", "graph"])
.is_ok_and(|output| answered(&output)),
};
(enabled, None)
}

Expand All @@ -164,7 +169,7 @@ impl BazelOptions {
return (true, Some(root));
}
}
self.probe_bzlmod()
self.probe_bzlmod(survey.graph.as_ref())
}

fn prefetch_module_mappings(
Expand Down Expand Up @@ -826,6 +831,9 @@ impl BazelOptions {
configured_roots,
module_graph_json,
module_graph_complete,
// A workspace without Bzlmod has no module graph, and the probe already had
// `bazel mod graph` fail to say so.
module_graph_absent: !bzlmod_enabled,
root_mapping,
output_base: server_info.output_base,
scoped_sources: ScopedSources {
Expand Down Expand Up @@ -3906,6 +3914,9 @@ pub(crate) struct QueriedTargets {
pub(crate) configured_roots: Option<BTreeMap<String, String>>,
pub(crate) module_graph_json: Option<String>,
pub(crate) module_graph_complete: bool,
/// Discovery established that there is no module graph to ask Bazel for (Bzlmod is
/// disabled), so hashing does not run `bazel mod graph` again only to see it fail.
pub(crate) module_graph_absent: bool,
pub(crate) root_mapping: Option<Vec<u8>>,
pub(crate) scoped_sources: ScopedSources,
/// The output base `bazel info` reported before the query, when it was asked.
Expand Down
75 changes: 74 additions & 1 deletion src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,7 @@ pub fn hash_targets(options: &HashOptions, targets: Vec<Target>) -> Result<HashF
configured_roots: None,
module_graph_json: None,
module_graph_complete: false,
module_graph_absent: false,
root_mapping: None,
scoped_sources: ScopedSources::default(),
output_base: None,
Expand All @@ -427,6 +428,7 @@ fn hash_targets_with_digests(
configured_roots,
module_graph_json,
module_graph_complete,
module_graph_absent,
root_mapping,
scoped_sources,
output_base,
Expand All @@ -436,7 +438,11 @@ fn hash_targets_with_digests(
ExternalRepoResolver::new(&options.bazel, root_mapping, output_base)?;
external_resolver.scoped_sources = scoped_sources;
let module_graph_started = Instant::now();
let module_graph_json = module_graph_json.or_else(|| options.bazel.module_graph_json());
let module_graph_json = match module_graph_json {
Some(json) => Some(json),
None if module_graph_absent => None,
None => options.bazel.module_graph_json(),
};
let verification = verification.filter(|_| {
module_graph_complete
&& module_graph_json
Expand Down Expand Up @@ -4431,6 +4437,73 @@ esac
}
}

/// Without Bzlmod there is no module graph. Discovery already has Bazel say so once, so
/// generation asks `bazel mod graph` exactly once, whether or not a MODULE.bazel file makes
/// discovery ask for the JSON graph first.
#[test]
#[cfg(unix)]
fn generation_asks_once_for_a_module_graph_bzlmod_disables() {
for module_file in [false, true] {
let workspace = tempfile::tempdir().unwrap();
if module_file {
fs::write(workspace.path().join("MODULE.bazel"), "").unwrap();
}
fs::create_dir_all(workspace.path().join("app")).unwrap();
fs::write(workspace.path().join("app/input"), "input").unwrap();
let target = source_target("//app:input", &[]);
let mut encoded = Vec::new();
target.encode_length_delimited(&mut encoded);
fs::write(workspace.path().join("targets.pb"), encoded).unwrap();
let script = workspace.path().join("fake-bazel.sh");
fs::write(
&script,
r#"#!/bin/sh
case "$1 $2" in
"mod dump_repo_mapping")
printf '%s\n' mapping >> "$PWD/mod-calls"
echo 'ERROR: Bzlmod has to be enabled for mod command to work.' >&2
exit 2
;;
"mod graph")
printf '%s\n' "$*" >> "$PWD/mod-calls"
echo 'ERROR: Bzlmod has to be enabled for mod command to work.' >&2
exit 2
;;
"version ") printf '%s\n' 'Build label: 8.7.0' ;;
"info output_base") printf '%s\n' "$PWD" ;;
"query "*)
while [ "$1" != --output_file ]; do shift; done
cp "$PWD/targets.pb" "$2"
;;
*) exit 80 ;;
esac
"#,
)
.unwrap();
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
let mut options = hash_options(workspace.path());
options.bazel.bazel = script;
options.bazel.no_bazelrc = false;

let generated = generate_hashes(&options).unwrap();
assert_eq!(generated.hashes.len(), 1);
assert_eq!(generated.module_graph_json, None);
let calls = fs::read_to_string(workspace.path().join("mod-calls")).unwrap();
let graph_calls = calls.lines().filter(|call| call.contains("graph")).count();
assert_eq!(graph_calls, 1, "module_file={module_file}: {calls}");
assert_eq!(calls.lines().filter(|call| *call == "mapping").count(), 1);

// Hashing targets handed in directly still asks for the graph itself.
let direct = hash_targets(&options, vec![target.clone()]).unwrap();
assert_eq!(direct.hashes, generated.hashes);
let calls = fs::read_to_string(workspace.path().join("mod-calls")).unwrap();
assert_eq!(
calls.lines().filter(|call| call.contains("graph")).count(),
2
);
}
}

#[test]
fn canonical_rule_inputs_are_sorted_and_configuration_sensitive() {
let rule = Rule {
Expand Down
Loading