Skip to content
Closed
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
344 changes: 169 additions & 175 deletions src/bazel.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/cancel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ fn cancelled_error() -> io::Error {
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.unwrap_or_else(std::sync::PoisonError::into_inner)
}

#[cfg(test)]
Expand Down
135 changes: 72 additions & 63 deletions src/explain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use crate::model::{impacted_types, ImpactType, TargetHash};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::fmt;
use std::fmt::{self, Write as _};

/// Why a root cause's own hash moved, independent of anything upstream of it.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
Expand Down Expand Up @@ -273,7 +273,7 @@ fn walk_upstream(

while let Some(current) = queue.pop_front() {
let depth = distances[&current];
let deps = dep_edges.get(&current).map(Vec::as_slice).unwrap_or(&[]);
let deps = dep_edges.get(&current).map_or(&[][..], Vec::as_slice);
if max_depth.is_some_and(|max| depth >= max) {
if deps
.iter()
Expand Down Expand Up @@ -355,8 +355,7 @@ fn build_subgraph(
.flat_map(|consumer| {
dep_edges
.get(consumer)
.map(Vec::as_slice)
.unwrap_or(&[])
.map_or(&[][..], Vec::as_slice)
.iter()
.filter(|dep| included.contains(*dep))
.map(|dep| ExplainEdge {
Expand Down Expand Up @@ -457,7 +456,7 @@ fn type_suffix(target_type: &str) -> String {

fn render_text(e: &ImpactExplanation) -> String {
let mut out = String::new();
out.push_str(&format!("{}{}\n", e.target, type_suffix(&e.target_type)));
let _ = writeln!(out, "{}{}", e.target, type_suffix(&e.target_type));
if !e.impacted {
out.push_str(if e.removed {
"NOT IMPACTED -- this target exists in the starting revision but not the final \
Expand Down Expand Up @@ -488,13 +487,14 @@ fn render_text(e: &ImpactExplanation) -> String {
}

if e.truncated {
out.push_str(&format!(
"Root causes: {} (showing the {} nearest)\n",
let _ = writeln!(
out,
"Root causes: {} (showing the {} nearest)",
e.total_root_causes,
e.root_causes.len()
));
);
} else {
out.push_str(&format!("Root causes: {}\n", e.total_root_causes));
let _ = writeln!(out, "Root causes: {}", e.total_root_causes);
}
out.push('\n');

Expand All @@ -504,29 +504,32 @@ fn render_text(e: &ImpactExplanation) -> String {
RootCauseKind::NewTarget => "new target in the final revision",
RootCauseKind::SelfChanged => self_changed_reason(&cause.target_type),
};
out.push_str(&format!(
" {}. {}{}\n",
let _ = writeln!(
out,
" {}. {}{}",
index + 1,
cause.label,
type_suffix(&cause.target_type)
));
out.push_str(&format!(" {reason}\n"));
out.push_str(&format!(
" {}\n",
);
let _ = writeln!(out, " {reason}");
let _ = writeln!(
out,
" {}",
hops(cause.target_distance, cause.package_hops)
));
out.push_str(&format!(" {}\n", cause.path.join(" -> ")));
);
let _ = writeln!(out, " {}", cause.path.join(" -> "));
if index != last {
out.push('\n');
}
}

if e.truncated {
out.push('\n');
out.push_str(&format!(
" ... and {} more. Pass --maxRootCauses=0 to list every root cause.\n",
let _ = writeln!(
out,
" ... and {} more. Pass --maxRootCauses=0 to list every root cause.",
e.total_root_causes - e.root_causes.len()
));
);
}
out
}
Expand Down Expand Up @@ -563,39 +566,44 @@ fn node_ids(e: &ImpactExplanation) -> HashMap<&str, String> {

fn render_dot(e: &ImpactExplanation) -> String {
let mut out = String::new();
out.push_str(&format!(
"// bazel-diff explain -- why {} was impacted\n",
let _ = writeln!(
out,
"// bazel-diff explain -- why {} was impacted",
dot_escape(&e.target)
));
);
out.push_str(
"// Edges point in impact-propagation direction: root cause -> ... -> queried target.\n",
);
out.push_str("digraph bazel_diff_impact {\n");
out.push_str(" rankdir=TB;\n");
out.push_str(&format!(" bgcolor=\"{SURFACE}\";\n"));
out.push_str(&format!(
let _ = writeln!(out, " bgcolor=\"{SURFACE}\";");
let _ = writeln!(
out,
" node [shape=box, style=\"rounded,filled\", fillcolor=\"{SURFACE}\", \
fontname=\"Helvetica\", fontsize=10, fontcolor=\"{INK}\", \
color=\"{HUE_INTERMEDIATE}\", penwidth=1];\n"
));
out.push_str(&format!(
" edge [color=\"{INK_MUTED}\", penwidth=1, arrowsize=0.7];\n"
));
color=\"{HUE_INTERMEDIATE}\", penwidth=1];"
);
let _ = writeln!(
out,
" edge [color=\"{INK_MUTED}\", penwidth=1, arrowsize=0.7];"
);
out.push('\n');

let ids = node_ids(e);
for node in &e.nodes {
out.push_str(&format!(
let _ = write!(
out,
" {} [label=\"{}\"",
ids[node.label.as_str()],
dot_escape(&node_label(node))
));
);
if node.is_queried_target {
out.push_str(&format!(", color=\"{HUE_QUERIED}\", penwidth=2"));
let _ = write!(out, ", color=\"{HUE_QUERIED}\", penwidth=2");
} else if node.is_root_cause {
out.push_str(&format!(
let _ = write!(
out,
", color=\"{HUE_ROOT_CAUSE}\", penwidth=2, peripheries=2"
));
);
}
out.push_str("];\n");
}
Expand All @@ -605,25 +613,24 @@ fn render_dot(e: &ImpactExplanation) -> String {
}
for edge in &e.edges {
if let (Some(from), Some(to)) = (ids.get(edge.from.as_str()), ids.get(edge.to.as_str())) {
out.push_str(&format!(" {from} -> {to};\n"));
let _ = writeln!(out, " {from} -> {to};");
}
}

out.push('\n');
out.push_str(" subgraph cluster_legend {\n");
out.push_str(&format!(
" label=\"Legend\"; fontname=\"Helvetica\"; fontsize=9; fontcolor=\"{INK_MUTED}\";\n"
));
out.push_str(&format!(
" color=\"{INK_MUTED}\"; penwidth=1; style=dashed;\n"
));
out.push_str(&format!(
" lg_root [label=\"root cause\", color=\"{HUE_ROOT_CAUSE}\", penwidth=2, peripheries=2];\n"
));
let _ = writeln!(
out,
" label=\"Legend\"; fontname=\"Helvetica\"; fontsize=9; fontcolor=\"{INK_MUTED}\";"
);
let _ = writeln!(out, " color=\"{INK_MUTED}\"; penwidth=1; style=dashed;");
let _ = writeln!(out, " lg_root [label=\"root cause\", color=\"{HUE_ROOT_CAUSE}\", penwidth=2, peripheries=2];"
);
out.push_str(" lg_mid [label=\"carries the change\"];\n");
out.push_str(&format!(
" lg_target [label=\"queried target\", color=\"{HUE_QUERIED}\", penwidth=2];\n"
));
let _ = writeln!(
out,
" lg_target [label=\"queried target\", color=\"{HUE_QUERIED}\", penwidth=2];"
);
out.push_str(" lg_root -> lg_mid -> lg_target [style=invis];\n");
out.push_str(" }\n");
out.push_str("}\n");
Expand All @@ -632,10 +639,11 @@ fn render_dot(e: &ImpactExplanation) -> String {

fn render_mermaid(e: &ImpactExplanation) -> String {
let mut out = String::new();
out.push_str(&format!(
"%% bazel-diff explain -- why {} was impacted\n",
let _ = writeln!(
out,
"%% bazel-diff explain -- why {} was impacted",
e.target
));
);
out.push_str(
"%% Edges point in impact-propagation direction: root cause -> ... -> queried target.\n",
);
Expand All @@ -653,24 +661,25 @@ fn render_mermaid(e: &ImpactExplanation) -> String {
} else {
format!("{id}[\"{text}\"]")
};
out.push_str(&format!(" {shaped}\n"));
let _ = writeln!(out, " {shaped}");
}

for edge in &e.edges {
if let (Some(from), Some(to)) = (ids.get(edge.from.as_str()), ids.get(edge.to.as_str())) {
out.push_str(&format!(" {from} --> {to}\n"));
let _ = writeln!(out, " {from} --> {to}");
}
}

out.push_str(&format!(
" classDef rootCause fill:{SURFACE},stroke:{HUE_ROOT_CAUSE},stroke-width:2px,color:{INK}\n"
));
out.push_str(&format!(
" classDef intermediate fill:{SURFACE},stroke:{HUE_INTERMEDIATE},stroke-width:1px,color:{INK}\n"
));
out.push_str(&format!(
" classDef queried fill:{SURFACE},stroke:{HUE_QUERIED},stroke-width:2px,color:{INK}\n"
));
let _ = writeln!(
out,
" classDef rootCause fill:{SURFACE},stroke:{HUE_ROOT_CAUSE},stroke-width:2px,color:{INK}"
);
let _ = writeln!(out, " classDef intermediate fill:{SURFACE},stroke:{HUE_INTERMEDIATE},stroke-width:1px,color:{INK}"
);
let _ = writeln!(
out,
" classDef queried fill:{SURFACE},stroke:{HUE_QUERIED},stroke-width:2px,color:{INK}"
);

let mut assign = |class_name: &str, predicate: fn(&ExplainNode) -> bool| {
let matching = e
Expand All @@ -680,7 +689,7 @@ fn render_mermaid(e: &ImpactExplanation) -> String {
.map(|node| ids[node.label.as_str()].as_str())
.collect::<Vec<_>>();
if !matching.is_empty() {
out.push_str(&format!(" class {} {class_name}\n", matching.join(",")));
let _ = writeln!(out, " class {} {class_name}", matching.join(","));
}
};
assign("queried", |node| node.is_queried_target);
Expand Down
2 changes: 1 addition & 1 deletion src/fingerprint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ pub fn write_json(
let json = serde_json::to_string_pretty(&value)? + "\n";
match path {
Some(path) if path != Path::new("-") => {
fs::write(path, json).with_context(|| format!("failed to write {}", path.display()))?
fs::write(path, json).with_context(|| format!("failed to write {}", path.display()))?;
}
_ => print!("{json}"),
}
Expand Down
1 change: 1 addition & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ impl Git {
}
}

#[must_use]
pub fn with_cancellation(mut self, cancellation: Option<Arc<Cancellation>>) -> Self {
self.cancellation = cancellation;
self
Expand Down
17 changes: 12 additions & 5 deletions src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ pub(crate) fn hash_pool() -> &'static rayon::ThreadPool {
.filter(|threads| *threads > 0)
.unwrap_or_else(|| {
std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1)
.map_or(1, usize::from)
.min(DEFAULT_HASH_THREADS)
});
rayon::ThreadPoolBuilder::new()
Expand Down Expand Up @@ -189,8 +188,10 @@ pub struct GenerationTimings {
pub target_hash_millis: u64,
}

fn elapsed_millis(started: Instant) -> u64 {
started.elapsed().as_millis() as u64
/// Milliseconds since `started`, saturating rather than truncating past `u64::MAX` (about 584
/// million years).
pub(crate) fn elapsed_millis(started: Instant) -> u64 {
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
}

pub fn generate_hashes(options: &HashOptions) -> Result<HashFileData> {
Expand Down Expand Up @@ -1372,6 +1373,10 @@ fn hash_seed_files(workspace: &Path, paths: &BTreeSet<PathBuf>) -> Result<Digest

fn hash_file_into(hasher: &mut Sha256, path: &Path) -> Result<()> {
let mut file = File::open(path)?;
// One 64 KiB read buffer per call. It stays on the stack because this runs once per
// tracked file on the hash pool's threads, where a heap allocation per file would cost more
// than the stack space.
#[allow(clippy::large_stack_arrays)]
let mut buffer = [0; FILE_HASH_BUFFER_SIZE];
loop {
let read = file.read(&mut buffer)?;
Expand All @@ -1389,6 +1394,8 @@ pub(crate) fn hash_directory_into(hasher: &mut Sha256, root: &Path) -> Result<()
hash_directory_tree(hasher, root, false)
}

// Only the non-Unix branch can fail; the Unix one hashes the raw bytes.
#[allow(clippy::unnecessary_wraps)]
fn hash_directory_entry_path(hasher: &mut Sha256, path: &Path, strict: bool) -> Result<()> {
for (index, component) in path.components().enumerate() {
if index != 0 {
Expand Down Expand Up @@ -2298,7 +2305,7 @@ impl ExternalRepoResolver {
}
}
}
Ok(external.join(canonical.map(String::as_str).unwrap_or(repo)))
Ok(external.join(canonical.map_or(repo, String::as_str)))
}

/// Returns the main repository's apparent -> canonical repository mapping,
Expand Down
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,31 @@
//! library target exists so Bazel and Cargo can share implementation code and
//! tests; its module-level API is not a stability commitment.

#![warn(clippy::pedantic)]
// Pedantic lints this crate does not adopt:
// - The doc lints: this is a CLI crate whose module API is not a stability
// commitment (see lib.rs), so `# Errors`/`# Panics` sections and `#[must_use]`
// on every accessor would be noise rather than a contract.
// - too_many_lines: the long functions are linear CLI and pipeline glue;
// splitting them to satisfy a line count would not make them clearer.
// - similar_names / struct_excessive_bools: the names mirror Bazel's own
// vocabulary and the bool-heavy structs are clap argument groups.
// - case_sensitive_file_extension_comparisons: Bazel labels and workspace
// paths are case-sensitive, so the case-insensitive comparison the lint
// proposes would change which files a rule is seen to own.
// - implicit_hasher: the target-type filters are only ever std `HashSet`s;
// a `BuildHasher` parameter would be generality nobody uses.
#![allow(
clippy::missing_errors_doc,
clippy::missing_panics_doc,
clippy::must_use_candidate,
clippy::too_many_lines,
clippy::similar_names,
clippy::struct_excessive_bools,
clippy::case_sensitive_file_extension_comparisons,
clippy::implicit_hasher
)]

pub mod bazel;
pub mod cache;
pub mod cancel;
Expand All @@ -16,6 +41,8 @@ pub mod module_graph;
pub mod partial;

pub mod proto {
// Generated by buffa-build; not held to this crate's lint policy.
#![allow(clippy::pedantic)]
include!(concat!(env!("OUT_DIR"), "/proto.rs"));
}
pub mod server;
Loading