From b66df989c3aa3afe2b1c3c7b54346f997d32bf08 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:20:40 +0000 Subject: [PATCH 1/2] Adopt clippy::pedantic across the Rust crates Every first-party crate (the bazel-diff lib and binary, the e2e suite and tools/coverage) now opts into clippy::pedantic at the crate root, with a short, commented allow list for the lints that do not fit a CLI crate (the doc-section and must_use lints, too_many_lines, similar_names, struct_excessive_bools, case-sensitive extension checks on Bazel labels, implicit_hasher). The generated protobuf module is exempt. The rest of the warnings are fixed, and most of the fixes simplify the code they touch: match-for-destructuring becomes if-let/let-else, format!-then-push_str becomes write!/writeln!, Result wrappers that could not fail are gone (deduplicate_targets, prune_cache), arguments that were cloned to be passed by value are borrowed instead (break_module_cycles, compute_query, normalize_path, probe_options), with_exclude_filter consumes its query instead of cloning it, the extension-failure bookkeeping moves onto FailedExtensions as methods instead of taking an unused &self on BazelOptions, and one elapsed_millis helper (now saturating instead of truncating) replaces two copies. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01KJs3XwoUGNh7WtEZHGSPVn --- src/bazel.rs | 344 +++++++++++++++++----------------- src/cancel.rs | 2 +- src/explain.rs | 135 ++++++------- src/fingerprint.rs | 2 +- src/git.rs | 1 + src/hash.rs | 17 +- src/lib.rs | 27 +++ src/main.rs | 42 ++++- src/model.rs | 14 +- src/module_graph.rs | 2 +- src/partial.rs | 76 ++++---- src/server.rs | 129 ++++++------- tests/e2e.rs | 14 ++ tests/e2e/external.rs | 2 +- tests/e2e/regressions.rs | 12 +- tools/coverage/src/args.rs | 2 +- tools/coverage/src/enforce.rs | 17 +- tools/coverage/src/lcov.rs | 18 +- tools/coverage/src/lib.rs | 23 ++- tools/coverage/src/main.rs | 10 + tools/coverage/src/pattern.rs | 2 +- 21 files changed, 492 insertions(+), 399 deletions(-) diff --git a/src/bazel.rs b/src/bazel.rs index 07635325..b303a300 100644 --- a/src/bazel.rs +++ b/src/bazel.rs @@ -113,14 +113,11 @@ impl BazelOptions { 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 enabled = self.run_capture(&["mod", "graph"]).is_ok_and(|output| { + output.status.success() + || extension_failure(&String::from_utf8_lossy(&output.stderr)) + .is_some_and(|failure| failure.answered) + }); (enabled, None) } @@ -208,7 +205,7 @@ impl BazelOptions { None => self.run_capture(&["mod", "graph", "--output=json"])?, }; let complete = output.status.success(); - let stdout = self.accept_mod_output(output, "graph --output=json", failed)?; + let stdout = failed.accept_mod_output(output, "graph --output=json")?; let json = if self.isolated_dependency_root.is_some() { String::from_utf8(stdout).context("module graph is not valid UTF-8")? } else { @@ -276,12 +273,14 @@ impl BazelOptions { } fn with_exclude_filter(&self, query: String) -> String { - self.exclude_targets_query - .as_ref() - .filter(|query| !query.trim().is_empty()) - .map_or(query.clone(), |exclude| { - format!("({query}) except ({exclude})") - }) + match self + .exclude_targets_query + .as_deref() + .filter(|exclude| !exclude.trim().is_empty()) + { + Some(exclude) => format!("({query}) except ({exclude})"), + None => query, + } } pub fn query_all_targets(&self) -> Result> { @@ -390,7 +389,7 @@ impl BazelOptions { ) } else { self.query_with(expression, use_cquery, version, &mut |batch| { - transform(batch, None) + transform(batch, None); }) } })?; @@ -487,7 +486,7 @@ impl BazelOptions { } } targets.extend(bzlmod_repos); - deduplicate_targets(targets) + Ok(deduplicate_targets(targets)) } else { queries.push("'//...:all-targets'".to_owned()); queries.extend( @@ -499,7 +498,7 @@ impl BazelOptions { match query(&full, false) { Ok(mut targets) => { targets.extend(bzlmod_repos); - deduplicate_targets(targets) + Ok(deduplicate_targets(targets)) } Err(error) if !self.exclude_external_targets @@ -517,7 +516,7 @@ impl BazelOptions { ); let mut targets = query(&without_external, false)?; targets.extend(bzlmod_repos); - deduplicate_targets(targets) + Ok(deduplicate_targets(targets)) } Err(error) => Err(error), } @@ -532,12 +531,11 @@ impl BazelOptions { let mut failed = FailedExtensions::default(); // The initial probe returns stdout only on success. The fallback may be partial. let retain_root_mapping = root_mapping.is_some(); - let root_mapping = match root_mapping { - Some(mapping) => mapping, - None => { - let output = self.run_capture(&["mod", "dump_repo_mapping", ""])?; - self.accept_mod_output(output, "dump_repo_mapping", &mut failed)? - } + let root_mapping = if let Some(mapping) = root_mapping { + mapping + } else { + let output = self.run_capture(&["mod", "dump_repo_mapping", ""])?; + failed.accept_mod_output(output, "dump_repo_mapping")? }; let canonical_to_apparent = parse_repo_mapping(&String::from_utf8_lossy(&root_mapping)); let (module_graph, complete_graph) = @@ -578,7 +576,7 @@ impl BazelOptions { // so nothing above names them. Enumerate them from the extensions' own mappings (#522). let extension_repos = match self.extension_repositories( &canonical_to_apparent, - hidden_modules.values().cloned().collect(), + &hidden_modules.values().cloned().collect::>(), survey.mappings, retain_root_mapping && complete_graph, &mut failed, @@ -694,15 +692,14 @@ impl BazelOptions { ); continue; }; - let canonical = match repo.strip_prefix("@@") { - Some(canonical) => Some(canonical.to_owned()), - None => { - let apparent = repo.trim_start_matches('@'); - canonical_to_apparent - .iter() - .find(|(_, names)| names.iter().any(|name| name == apparent)) - .map(|(canonical, _)| canonical.clone()) - } + let canonical = if let Some(canonical) = repo.strip_prefix("@@") { + Some(canonical.to_owned()) + } else { + let apparent = repo.trim_start_matches('@'); + canonical_to_apparent + .iter() + .find(|(_, names)| names.iter().any(|name| name == apparent)) + .map(|(canonical, _)| canonical.clone()) }; let Some(prefix) = canonical .map(|canonical| format!("{canonical}+{name}")) @@ -859,21 +856,18 @@ impl BazelOptions { true } else { let stderr = String::from_utf8_lossy(&output.stderr); - match extension_failure(&stderr) { - Some(failure) => { - self.note_failed_extensions(failed, failure.extensions); - failure.answered - } - None => { - if self.verbose { - eprintln!( - "[Info] bazel mod show_repo --all_repos failed with {}, asking by name instead: {}", - output.status, - stderr.trim() - ); - } - false + if let Some(failure) = extension_failure(&stderr) { + failed.note(failure.extensions); + failure.answered + } else { + if self.verbose { + eprintln!( + "[Info] bazel mod show_repo --all_repos failed with {}, asking by name instead: {}", + output.status, + stderr.trim() + ); } + false } }; if !answered { @@ -912,7 +906,7 @@ impl BazelOptions { fn extension_repositories( &self, canonical_to_apparent: &BTreeMap>, - hidden_module_repos: Vec, + hidden_module_repos: &[String], prefetched: BTreeMap, complete_inputs: bool, failed: &mut FailedExtensions, @@ -973,36 +967,36 @@ impl BazelOptions { let mut complete_spoke_mappings = true; if !representatives.is_empty() { let names = representatives.values().cloned().collect::>(); - let mappings = - match self.dump_repo_mappings(&names, failed, &mut complete_spoke_mappings) { - Ok(mappings) => mappings, - Err(_) => { - complete_spoke_mappings = false; - // One extension that fails to evaluate should not hide the rest; retry - // one at a time and report the ones Bazel cannot describe. - let mut mappings = Vec::new(); - for name in &names { - match self.dump_repo_mappings( - std::slice::from_ref(name), - failed, - &mut complete_mappings, - ) { - Ok(mapping) => mappings.extend(mapping), - Err(error) if self.keep_going => { - eprintln!( - "[Warn] skipping the module extension behind {name}: {error:#}" - ); - } - Err(error) => return Err(error), - } + let mappings = if let Ok(mappings) = + self.dump_repo_mappings(&names, failed, &mut complete_spoke_mappings) + { + mappings + } else { + complete_spoke_mappings = false; + // One extension that fails to evaluate should not hide the rest; retry + // one at a time and report the ones Bazel cannot describe. + let mut mappings = Vec::new(); + for name in &names { + match self.dump_repo_mappings( + std::slice::from_ref(name), + failed, + &mut complete_mappings, + ) { + Ok(mapping) => mappings.extend(mapping), + Err(error) if self.keep_going => { + eprintln!( + "[Warn] skipping the module extension behind {name}: {error:#}" + ); } - mappings + Err(error) => return Err(error), } - }; + } + mappings + }; generated.extend( mappings .into_iter() - .flat_map(|mapping| mapping.into_values()) + .flat_map(std::collections::BTreeMap::into_values) .filter(|canonical| { canonical .rsplit_once('+') @@ -1126,7 +1120,7 @@ impl BazelOptions { stderr.trim() ); }; - self.note_failed_extensions(failed, failure.extensions); + failed.note(failure.extensions); if failure.answered { return Ok(Some(value)); } @@ -1177,7 +1171,7 @@ impl BazelOptions { ); }; if let [repo] = repos { - self.note_failed_extensions(failed, failure.extensions); + failed.note(failure.extensions); failed.unavailable.insert(repo.clone()); } else { let (left, right) = repos.split_at(repos.len() / 2); @@ -1188,42 +1182,6 @@ impl BazelOptions { Ok(()) } - /// The stdout of a `bazel mod` invocation that takes no repository names, kept when the - /// invocation only failed because a module extension in the graph cannot be evaluated. - fn accept_mod_output( - &self, - output: Output, - subcommand: &str, - failed: &mut FailedExtensions, - ) -> Result> { - if output.status.success() { - return Ok(output.stdout); - } - let stderr = String::from_utf8_lossy(&output.stderr); - match extension_failure(&stderr) { - Some(failure) if failure.answered => { - self.note_failed_extensions(failed, failure.extensions); - Ok(output.stdout) - } - _ => bail!( - "bazel mod {subcommand} failed with {}: {}", - output.status, - stderr.trim() - ), - } - } - - fn note_failed_extensions(&self, failed: &mut FailedExtensions, extensions: BTreeSet) { - failed.observed = true; - for extension in extensions { - if failed.extensions.insert(extension.clone()) { - eprintln!( - "[Warn] Bazel reported that module extension {extension} cannot be evaluated" - ); - } - } - } - /// `bazel query //...:all-targets` lists repository inputs without loading their /// dependencies, so it does not report their failed mappings (#531). Checks those inputs /// after an extension failure. Returns an error, or warns under `--keep_going`. @@ -1481,11 +1439,8 @@ impl BazelOptions { fn canonical_bzlmod_repo_names(&self) -> Result> { let mapping_output = self.run_capture(&["mod", "dump_repo_mapping", ""])?; - let mapping = self.accept_mod_output( - mapping_output, - "dump_repo_mapping", - &mut FailedExtensions::default(), - )?; + let mapping = + FailedExtensions::default().accept_mod_output(mapping_output, "dump_repo_mapping")?; Ok(parse_repo_mapping(&String::from_utf8_lossy(&mapping)) .keys() .filter(|name| name.contains('+') || name.contains('~')) @@ -2183,6 +2138,40 @@ struct FailedExtensions { unavailable: BTreeSet, } +impl FailedExtensions { + /// Records the extensions Bazel could not evaluate, warning once per extension. + fn note(&mut self, extensions: BTreeSet) { + self.observed = true; + for extension in extensions { + if self.extensions.insert(extension.clone()) { + eprintln!( + "[Warn] Bazel reported that module extension {extension} cannot be evaluated" + ); + } + } + } + + /// The stdout of a `bazel mod` invocation that takes no repository names, kept when the + /// invocation only failed because a module extension in the graph cannot be evaluated. + fn accept_mod_output(&mut self, output: Output, subcommand: &str) -> Result> { + if output.status.success() { + return Ok(output.stdout); + } + let stderr = String::from_utf8_lossy(&output.stderr); + match extension_failure(&stderr) { + Some(failure) if failure.answered => { + self.note(failure.extensions); + Ok(output.stdout) + } + _ => bail!( + "bazel mod {subcommand} failed with {}: {}", + output.status, + stderr.trim() + ), + } + } +} + impl FailedExtensions { fn is_empty(&self) -> bool { !self.observed && self.extensions.is_empty() && self.unavailable.is_empty() @@ -2264,7 +2253,12 @@ fn materialize_repository_inputs_for_batch(batch: &mut [Target], inputs: Option< fn materialize_repository_inputs(target: &mut Target, shared: Option) { if let Some(inputs) = shared { - target.rule.as_option_mut().unwrap().rule_input = inputs.labels.clone(); + target + .rule + .as_option_mut() + .unwrap() + .rule_input + .clone_from(&inputs.labels); } } @@ -2483,7 +2477,7 @@ fn is_external_package_error(message: &str) -> bool { || message.contains("//external package is not available") } -fn deduplicate_targets(mut targets: Vec) -> Result> { +fn deduplicate_targets(mut targets: Vec) -> Vec { // Decide which targets to keep while their names can still be borrowed. let mut keep = { let mut seen = HashSet::new(); @@ -2494,7 +2488,7 @@ fn deduplicate_targets(mut targets: Vec) -> Result> { .into_iter() }; targets.retain(|_| keep.next().expect("one decision per target")); - Ok(targets) + targets } pub fn decode_delimited(path: &Path) -> Result> { @@ -2861,14 +2855,13 @@ fn package_group_rule(group: &PackageGroup) -> Rule { string_list_value: group.contained_package.clone(), ..Default::default() }; - let mut rule = Rule { + Rule { name: group.name.clone(), rule_class: "package_group".to_owned(), + attribute: vec![packages], + rule_input: group.included_package_group.clone(), ..Default::default() - }; - rule.attribute.push(packages); - rule.rule_input = group.included_package_group.clone(); - rule + } } struct RepositoryFiles { @@ -2903,11 +2896,12 @@ fn repository_rule( ..Default::default() }; let mut push_attribute = |name: &str, value: String| { - let mut attribute = Attribute::default(); - attribute.name = name.to_owned(); - attribute.r#type = crate::proto::blaze_query::attribute::Discriminator::String; - attribute.string_value = Some(value); - rule.attribute.push(attribute); + rule.attribute.push(Attribute { + name: name.to_owned(), + r#type: crate::proto::blaze_query::attribute::Discriminator::String, + string_value: Some(value), + ..Default::default() + }); }; if let Some(content_hash) = files.tree_hash { push_attribute("_bazel_diff_content_hash", content_hash); @@ -2961,7 +2955,7 @@ pub(crate) fn attribute_main_repo_labels(attributes: &[Attribute]) -> impl Itera } /// The slots that can name targets after the caller checks the attribute discriminator. -/// LABEL_DICT_UNARY is string -> label and LABEL_KEYED_STRING_DICT is label -> string. +/// `LABEL_DICT_UNARY` is string -> label and `LABEL_KEYED_STRING_DICT` is label -> string. fn attribute_label_values(attribute: &Attribute) -> impl Iterator { attribute .string_value @@ -3233,7 +3227,7 @@ fn parse_module_dependency_edges(json: &str) -> BTreeMap>, + edges: &BTreeMap>, ) -> BTreeMap> { fn visit( node: &str, @@ -3424,13 +3418,7 @@ fn break_module_cycles( let mut result = BTreeMap::new(); let mut visited = BTreeSet::new(); for node in edges.keys() { - visit( - node, - &edges, - &mut visited, - &mut BTreeSet::new(), - &mut result, - ); + visit(node, edges, &mut visited, &mut BTreeSet::new(), &mut result); } result } @@ -3450,6 +3438,7 @@ mod tests { use crate::proto::analysis::{Configuration, ConfiguredTarget, CqueryResult}; use crate::proto::blaze_query::{ attribute, EnvironmentGroup, GeneratedFile, LabelDictUnaryEntry, SourceFile, + StringListDictEntry, }; fn rule_target(name: &str) -> Target { let mut target = Target::default(); @@ -3674,7 +3663,7 @@ mod tests { duplicate.rule.as_option_mut().unwrap().rule_class = "other".into(); let last = rule_target("//b:b"); let targets = vec![first.clone(), Target::default(), last.clone(), duplicate]; - assert_eq!(deduplicate_targets(targets).unwrap(), [first, last]); + assert_eq!(deduplicate_targets(targets), [first, last]); assert!(is_external_package_error("no such package 'external'")); assert!(is_external_package_error( "//external package is not available" @@ -4738,7 +4727,7 @@ exit 1 let workspace = tempfile::tempdir().unwrap(); let script = workspace.path().join("bazel"); fs::write(&script, "#!/bin/sh\ncat reply\n").unwrap(); - let options = probe_options(workspace.path(), script); + let options = probe_options(workspace.path(), &script); let names = ["first+", "second+"].map(str::to_owned); for (reply, rows, expected_complete) in [ ("{}\n{}\n", 2, true), @@ -4783,7 +4772,7 @@ exit 1 "#!/bin/sh\nshift 2\necho \"$*\" >> calls\nfor name do cat \"$name\" || exit 1; done\n", ) .unwrap(); - let options = probe_options(workspace.path(), script); + let options = probe_options(workspace.path(), &script); let root = BTreeMap::from([ ("dep+".into(), vec!["dep".into()]), (first.into(), vec!["hub".into()]), @@ -4791,7 +4780,7 @@ exit 1 let result = options .extension_repositories( &root, - Vec::new(), + &[], BTreeMap::new(), true, &mut FailedExtensions::default(), @@ -5004,7 +4993,7 @@ exit 1 use std::os::unix::process::ExitStatusExt; let workspace = tempfile::tempdir().unwrap(); - let mut options = probe_options(workspace.path(), PathBuf::from("unused")); + let mut options = probe_options(workspace.path(), Path::new("unused")); let output = || Output { status: ExitStatus::from_raw(0), stdout: b"{\"key\":\"\",\"name\":\"\xff\",\"dependencies\":[]}".to_vec(), @@ -5164,7 +5153,7 @@ exit 1 ] .map(str::to_owned) .into(); - let mut options = probe_options(Path::new("."), PathBuf::from("unused")); + let mut options = probe_options(Path::new("."), Path::new("unused")); options.label_only_module_extensions = [ "@rules_rs//rs:extensions.bzl%crate", "@rs//rs:extensions.bzl%crate", @@ -5255,7 +5244,7 @@ exit 1 r#type: target::Discriminator::SourceFile, source_file: buffa::MessageField::some(SourceFile { name: name.to_owned(), - subinclude: loads.iter().map(|s| s.to_string()).collect(), + subinclude: loads.iter().map(std::string::ToString::to_string).collect(), ..Default::default() }), ..Default::default() @@ -5302,7 +5291,8 @@ exit 1 r#type: Kind::LabelDictUnary, ..Default::default() }; - attr.label_dict_unary_value.push(Default::default()); + attr.label_dict_unary_value + .push(LabelDictUnaryEntry::default()); let entry = &mut attr.label_dict_unary_value[0]; entry.key = "//:string".into(); entry.value = "//:label".into(); @@ -5422,7 +5412,8 @@ exit 1 r#type: attribute::Discriminator::StringListDict, ..Default::default() }; - dict.string_list_dict_value.push(Default::default()); + dict.string_list_dict_value + .push(StringListDictEntry::default()); dict.string_list_dict_value[0].key = "//:text".into(); dict.string_list_dict_value[0].value = vec![format!("@@{config}//:dl")]; outside[4].attribute = vec![dict]; @@ -5852,7 +5843,7 @@ exit 1 repo_rule_name: Some("http_archive".into()), ..Default::default() }; - let options = probe_options(path, extension_flow_script(path, &[repo], None)); + let options = probe_options(path, &extension_flow_script(path, &[repo], None)); let original = options .query_all_targets_with(materialize_repository_inputs_for_batch) .unwrap(); @@ -5988,13 +5979,13 @@ exit 1 // global owner on that survey, even if the visible module read succeeded. let visible = BTreeMap::from([("rules_python+".into(), vec!["rules_python".into()])]); let mut failed = FailedExtensions::default(); - let resolved = |hidden, failed: &mut FailedExtensions| { + let resolved = |hidden: &[String], failed: &mut FailedExtensions| { options .extension_repositories(&visible, hidden, BTreeMap::new(), true, failed) .unwrap() }; - assert!(resolved(Vec::new(), &mut failed).complete_mappings); - let recovered = resolved(vec!["unknown_hidden+".into()], &mut failed); + assert!(resolved(&[], &mut failed).complete_mappings); + let recovered = resolved(&["unknown_hidden+".into()], &mut failed); assert!(!recovered.complete_mappings); assert!(failed.is_empty()); } @@ -6169,7 +6160,7 @@ exit 1 } #[cfg(unix)] - fn probe_options(workspace: &Path, script: PathBuf) -> BazelOptions { + fn probe_options(workspace: &Path, script: &Path) -> BazelOptions { BazelOptions { workspace: workspace.to_path_buf(), bazel: PathBuf::from("/bin/sh"), @@ -6215,18 +6206,19 @@ exit 1 "echo '{\"\":\"\",\"dep\":\"dep+\"}'; exit 0", marker, ); - assert!(probe_options(workspace.path(), mapping_answers_graph_fails).is_bzlmod_enabled()); + assert!(probe_options(workspace.path(), &mapping_answers_graph_fails).is_bzlmod_enabled()); let no_dump_repo_mapping = script( "probe-b.sh", "echo \"ERROR: Unknown command 'dump_repo_mapping'\" >&2; exit 2", "echo ''; exit 0", ); - assert!(probe_options(workspace.path(), no_dump_repo_mapping).is_bzlmod_enabled()); + assert!(probe_options(workspace.path(), &no_dump_repo_mapping).is_bzlmod_enabled()); let no_dump_repo_mapping_graph_partial = script("probe-c.sh", "exit 2", marker); assert!( - probe_options(workspace.path(), no_dump_repo_mapping_graph_partial).is_bzlmod_enabled() + probe_options(workspace.path(), &no_dump_repo_mapping_graph_partial) + .is_bzlmod_enabled() ); let bzlmod_disabled = script( @@ -6234,7 +6226,7 @@ exit 1 "echo 'ERROR: Bzlmod has to be enabled for mod command to work.' >&2; exit 2", "echo 'ERROR: Bzlmod has to be enabled for mod command to work.' >&2; exit 2", ); - assert!(!probe_options(workspace.path(), bzlmod_disabled).is_bzlmod_enabled()); + assert!(!probe_options(workspace.path(), &bzlmod_disabled).is_bzlmod_enabled()); } /// Fake Bazel for a workspace whose transitive module `transitive_dep` imports @@ -6340,7 +6332,7 @@ exit 1 fn query_bzlmod_repos_skips_a_failed_extension() { let workspace = tempfile::tempdir().unwrap(); let script = failed_extension_script(workspace.path(), &[rule_target("//app:lib")]); - let options = probe_options(workspace.path(), script); + let options = probe_options(workspace.path(), &script); let targets = options.query_all_targets().unwrap(); let names = targets @@ -6376,9 +6368,8 @@ exit 1 let refuses = |options: &BazelOptions, expected: &str| { let mut transformed = false; let result = options.query_all_targets_with(|_, _| transformed = true); - let error = match result { - Ok(_) => panic!("isolated root unexpectedly accepted"), - Err(error) => error, + let Err(error) = result else { + panic!("isolated root unexpectedly accepted") }; let error = format!("{error:#}"); assert!(error.contains(expected), "{error}"); @@ -6396,7 +6387,7 @@ exit 1 }; let workspace = tempfile::tempdir().unwrap(); let script = failed_extension_script(workspace.path(), &[rule_target("//app:lib")]); - let mut options = probe_options(workspace.path(), script.clone()); + let mut options = probe_options(workspace.path(), &script); options.isolated_dependency_root = Some("@missing_repo".into()); refuses( &options, @@ -6430,7 +6421,7 @@ exit 1 let disabled = tempfile::tempdir().unwrap(); let script = query_script(disabled.path(), "8.7.0", &[], 0); - let mut options = probe_options(disabled.path(), script); + let mut options = probe_options(disabled.path(), &script); options.isolated_dependency_root = Some("@hub".into()); refuses(&options, "Bzlmod repository discovery is unavailable"); } @@ -6452,7 +6443,7 @@ exit 1 ), ], ); - let mut options = probe_options(workspace.path(), script); + let mut options = probe_options(workspace.path(), &script); let error = options.query_all_targets().unwrap_err().to_string(); assert!( @@ -6550,7 +6541,7 @@ exit 1 write_delimited(&streamed, &messages); let mut seen = Vec::new(); let targets = decode_cquery_stream(&streamed, true, &mut |target| { - seen.push(target_name(target).unwrap().to_owned()) + seen.push(target_name(target).unwrap().to_owned()); }) .unwrap(); let names = targets.iter().filter_map(target_name).collect::>(); @@ -6572,7 +6563,7 @@ exit 1 .generating_rule, "//a:a|abc123" ); - assert_eq!(deduplicate_targets(targets).unwrap().len(), 4); + assert_eq!(deduplicate_targets(targets).len(), 4); let non_streamed = directory.path().join("cquery.pb"); let mut combined = results(vec![configured(rule_target("//a:a"), None, 2)]); @@ -6664,8 +6655,11 @@ exit 1 calls = workspace.join("calls.log").display(), compatible = compatible .iter() - .map(|label| format!("{label}\n")) - .collect::() + .fold(String::new(), |mut acc, label| { + acc.push_str(label); + acc.push('\n'); + acc + }) .replacen('\n', "\n\n", 1), streamed = streamed_proto.display(), proto = proto.display(), @@ -6699,7 +6693,7 @@ exit 1 ] { let workspace = tempfile::tempdir().unwrap(); let script = query_script(workspace.path(), version, &["//app:lib", "//app:tool"], 0); - let mut options = probe_options(workspace.path(), script); + let mut options = probe_options(workspace.path(), &script); options.use_cquery = true; options.cquery_options = vec!["--define=flavor=test".into()]; options.command_options = vec!["--query-only".into()]; @@ -6751,7 +6745,7 @@ exit 1 fn query_surfaces_bazel_failures_and_tolerates_partial_answers_with_keep_going() { let workspace = tempfile::tempdir().unwrap(); let script = query_script(workspace.path(), "8.7.0", &[], 1); - let mut options = probe_options(workspace.path(), script); + let mut options = probe_options(workspace.path(), &script); options.command_options = vec!["--noimplicit_deps".into()]; let error = options.query("//app:all", false).unwrap_err().to_string(); @@ -6781,7 +6775,7 @@ exit 1 let partial = tempfile::tempdir().unwrap(); let script = query_script(partial.path(), "8.7.0", &[], 3); - let mut options = probe_options(partial.path(), script); + let mut options = probe_options(partial.path(), &script); let error = options.query("//app:all", false).unwrap_err().to_string(); assert!(error.contains("Bazel query failed, exit code 3"), "{error}"); options.keep_going = true; @@ -6799,7 +6793,7 @@ exit 1 "#!/bin/sh\necho \"$*\" >> calls.log\nif [ \"$1\" = version ]; then echo 'Build label: 8.7.0'; exit 0; fi\necho 'ERROR: no such target' >&2\nexit 1\n", ) .unwrap(); - let mut options = probe_options(incompatible.path(), script); + let mut options = probe_options(incompatible.path(), &script); options.use_cquery = true; let error = options .query("deps(//app:all)", true) diff --git a/src/cancel.rs b/src/cancel.rs index b5b2ce0a..98a5e863 100644 --- a/src/cancel.rs +++ b/src/cancel.rs @@ -200,7 +200,7 @@ fn cancelled_error() -> io::Error { fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { mutex .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) + .unwrap_or_else(std::sync::PoisonError::into_inner) } #[cfg(test)] diff --git a/src/explain.rs b/src/explain.rs index b27267a2..b1d88934 100644 --- a/src/explain.rs +++ b/src/explain.rs @@ -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)] @@ -273,7 +273,7 @@ fn walk_upstream( while let Some(current) = queue.pop_front() { let depth = distances[¤t]; - let deps = dep_edges.get(¤t).map(Vec::as_slice).unwrap_or(&[]); + let deps = dep_edges.get(¤t).map_or(&[][..], Vec::as_slice); if max_depth.is_some_and(|max| depth >= max) { if deps .iter() @@ -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 { @@ -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 \ @@ -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'); @@ -504,18 +504,20 @@ 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'); } @@ -523,10 +525,11 @@ fn render_text(e: &ImpactExplanation) -> String { 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 } @@ -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"); } @@ -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"); @@ -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", ); @@ -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 @@ -680,7 +689,7 @@ fn render_mermaid(e: &ImpactExplanation) -> String { .map(|node| ids[node.label.as_str()].as_str()) .collect::>(); 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); diff --git a/src/fingerprint.rs b/src/fingerprint.rs index 144395be..b719c4dd 100644 --- a/src/fingerprint.rs +++ b/src/fingerprint.rs @@ -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}"), } diff --git a/src/git.rs b/src/git.rs index 1150083c..290050c9 100644 --- a/src/git.rs +++ b/src/git.rs @@ -37,6 +37,7 @@ impl Git { } } + #[must_use] pub fn with_cancellation(mut self, cancellation: Option>) -> Self { self.cancellation = cancellation; self diff --git a/src/hash.rs b/src/hash.rs index 9a4e40cd..055932f3 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -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() @@ -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 { @@ -1372,6 +1373,10 @@ fn hash_seed_files(workspace: &Path, paths: &BTreeSet) -> Result 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)?; @@ -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 { @@ -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, diff --git a/src/lib.rs b/src/lib.rs index 81dd1219..e32b8803 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; @@ -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; diff --git a/src/main.rs b/src/main.rs index da20531d..6b5d1d1f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,28 @@ +#![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 +)] + use anyhow::{bail, Context, Result}; use bazel_diff::bazel::BazelOptions; use bazel_diff::explain::{self, ExplainFormat, ExplainLimits}; @@ -494,7 +519,7 @@ struct ServeArgs { #[arg(long = "nexusPrefix", default_value = "")] nexus_prefix: String, - /// Basic-auth user; the password is read from the BAZEL_DIFF_NEXUS_PASSWORD environment variable + /// Basic-auth user; the password is read from the `BAZEL_DIFF_NEXUS_PASSWORD` environment variable #[arg(long = "nexusUsername", env = "BAZEL_DIFF_NEXUS_USERNAME")] nexus_username: Option, @@ -518,7 +543,7 @@ fn flatten_options(values: &[String]) -> Vec { /// Folds `.` and `..` away lexically. Only meaningful on an absolute path: /// applied to a relative one, `.` and a leading `..` have nothing to resolve /// against and simply vanish, so callers go through [`parse_normalized_path`]. -fn normalize_path(path: PathBuf) -> PathBuf { +fn normalize_path(path: &Path) -> PathBuf { path.components() .fold(PathBuf::new(), |mut normalized, component| { match component { @@ -546,7 +571,7 @@ fn normalize_path(path: PathBuf) -> PathBuf { fn parse_normalized_path(value: &str) -> Result { let absolute = std::path::absolute(value) .map_err(|error| format!("failed to resolve path {value:?}: {error}"))?; - Ok(normalize_path(absolute)) + Ok(normalize_path(&absolute)) } fn read_lines(path: Option<&Path>) -> Result> { @@ -954,8 +979,11 @@ fn run_get_impacted(args: &GetImpactedTargetsArgs, verbose: bool) -> Result<()> exclude_external, )? .into_iter() - .map(|label| format!("{label}\n")) - .collect() + .fold(String::new(), |mut acc, label| { + acc.push_str(&label); + acc.push('\n'); + acc + }) }; match &args.output { Some(path) => fs::write(path, output)?, @@ -1306,7 +1334,7 @@ mod tests { ["a", "b", "c", "d"] ); assert_eq!( - normalize_path(PathBuf::from("/home/../some-dir")), + normalize_path(Path::new("/home/../some-dir")), PathBuf::from("/some-dir") ); } @@ -1799,7 +1827,7 @@ mod tests { config .partial_graph_rebuild_patterns .iter() - .map(|glob| glob.pattern()) + .map(bazel_diff::partial::Glob::pattern) .collect::>(), ["*.lock", "tools/**", "requirements.txt"] ); diff --git a/src/model.rs b/src/model.rs index de0d9529..b6d8a607 100644 --- a/src/model.rs +++ b/src/model.rs @@ -37,14 +37,14 @@ fn decode_lowercase_hex(value: &str) -> Option<[u8; 32]> { const INVALID: u8 = 0xff; const TABLE: [u8; 256] = { let mut table = [INVALID; 256]; - let mut digit = 0; + let mut digit: u8 = 0; while digit < 10 { - table[b'0' as usize + digit] = digit as u8; + table[b'0' as usize + digit as usize] = digit; digit += 1; } - let mut letter = 0; + let mut letter: u8 = 0; while letter < 6 { - table[b'a' as usize + letter] = 10 + letter as u8; + table[b'a' as usize + letter as usize] = 10 + letter; letter += 1; } table @@ -594,10 +594,10 @@ pub fn impacted_types( None => Some((label.clone(), ImpactType::Direct)), Some(starting_hash) if !starting_hash.same_as(final_hash) => Some(( label.clone(), - if starting_hash.direct_hash != final_hash.direct_hash { - ImpactType::Direct - } else { + if starting_hash.direct_hash == final_hash.direct_hash { ImpactType::Indirect + } else { + ImpactType::Direct }, )), _ => None, diff --git a/src/module_graph.rs b/src/module_graph.rs index fc151b26..7621e49a 100644 --- a/src/module_graph.rs +++ b/src/module_graph.rs @@ -520,7 +520,7 @@ mod tests { }; let reformatted = graph("0.50.1") .replace("noise before JSON", "INFO: Invocation ID: 1234") - .replace("\n", "") + .replace('\n', "") .replace(" ", " "); assert_ne!(reformatted, graph("0.50.1")); let to = HashFileData { diff --git a/src/partial.rs b/src/partial.rs index d3798fcb..642944d2 100644 --- a/src/partial.rs +++ b/src/partial.rs @@ -93,7 +93,7 @@ impl TreeIndex { let object_type = fields.next()?; let object = fields.next()?.to_owned(); let kind = match (mode, object_type) { - ("100644", "blob") | ("100664", "blob") => TreeKind::File { executable: false }, + ("100644" | "100664", "blob") => TreeKind::File { executable: false }, ("100755", "blob") => TreeKind::File { executable: true }, ("120000", "blob") => TreeKind::Symlink, ("160000", "commit") => TreeKind::Submodule, @@ -107,6 +107,7 @@ impl TreeIndex { } /// Tags the index with the id of the tree it was listed from. + #[must_use] pub fn with_id(mut self, id: impl Into) -> Self { self.id = Some(id.into()); self @@ -184,24 +185,23 @@ pub fn source_digest(tree: &TreeIndex, label: &str, seed: &[u8]) -> DigestBytes }; let path = path.to_string_lossy().into_owned(); let mut hasher = Sha256::new(); - match tree.get(&path) { - Some(entry) => update_entry(&mut hasher, entry), - None => { - let mut directory = Sha256::new(); - let mut populated = false; - for (relative, entry) in tree.under(&path) { - populated = true; - directory.update(relative.as_bytes()); - directory.update([0]); - update_entry(&mut directory, entry); - directory.update([0]); - } - if populated { - hasher.update(directory.finalize()); - hasher.update([2]); - } else { - hasher.update([0]); - } + if let Some(entry) = tree.get(&path) { + update_entry(&mut hasher, entry); + } else { + let mut directory = Sha256::new(); + let mut populated = false; + for (relative, entry) in tree.under(&path) { + populated = true; + directory.update(relative.as_bytes()); + directory.update([0]); + update_entry(&mut directory, entry); + directory.update([0]); + } + if populated { + hasher.update(directory.finalize()); + hasher.update([2]); + } else { + hasher.update([0]); } } hasher.update(seed); @@ -452,12 +452,11 @@ pub fn normalize_workspace_path(workspace: &Path, value: &str) -> Option .unwrap_or(value); let path = Path::new(value); let relative = if path.is_absolute() { - match path.strip_prefix(workspace) { - Ok(stripped) => stripped.to_path_buf(), - Err(_) => { - let canonical = fs::canonicalize(workspace).ok()?; - path.strip_prefix(&canonical).ok()?.to_path_buf() - } + if let Ok(stripped) = path.strip_prefix(workspace) { + stripped.to_path_buf() + } else { + let canonical = fs::canonicalize(workspace).ok()?; + path.strip_prefix(&canonical).ok()?.to_path_buf() } } else { path.to_path_buf() @@ -638,19 +637,18 @@ impl Evaluator<'_> { let mut direct = Sha256::new(); direct.update(static_digest); for source in recipe.sources() { - let digest = match self.source_digests.get(source) { - Some(digest) => *digest, - None => { - let soft = *self - .soft_digests - .entry(source.clone()) - .or_insert_with(|| soft_digest(self.tree, source)); - match soft { - Some(digest) => digest, - None => bail!( - "source input {source} of {key} is neither a target nor a tracked file" - ), - } + let digest = if let Some(digest) = self.source_digests.get(source) { + *digest + } else { + let soft = *self + .soft_digests + .entry(source.clone()) + .or_insert_with(|| soft_digest(self.tree, source)); + match soft { + Some(digest) => digest, + None => bail!( + "source input {source} of {key} is neither a target nor a tracked file" + ), } }; direct.update(digest); @@ -1652,7 +1650,7 @@ mod tests { diff, tree, base, ) { Classification::Rebuild { reason } => reason, - other => panic!("expected a rebuild, got {other:?}"), + other @ Classification::Derivable { .. } => panic!("expected a rebuild, got {other:?}"), }; assert!(reason( &[entry("pkg/new.txt", 'A', "000000", "100644")], diff --git a/src/server.rs b/src/server.rs index 0816a15b..6633f7b3 100644 --- a/src/server.rs +++ b/src/server.rs @@ -2,7 +2,7 @@ use crate::bazel::BazelOptions; use crate::cache; use crate::cancel::{Cancellation, CANCELLED}; use crate::git::{self, DerivationPolicy, Git}; -use crate::hash::{generate_hashes_timed, HashOptions}; +use crate::hash::{elapsed_millis, generate_hashes_timed, GenerationTimings, HashOptions}; use crate::model::{ filter_and_sort_labels, impacted_targets, impacted_targets_with_distances, HashFileData, }; @@ -177,7 +177,7 @@ fn memory_cache(state: &State) -> std::sync::MutexGuard<'_, MemoryCache> { state .memory .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) + .unwrap_or_else(std::sync::PoisonError::into_inner) } impl State { @@ -249,10 +249,7 @@ impl Workspace { } fn is_busy(&self) -> bool { - self.holder - .lock() - .map(|holder| holder.is_some()) - .unwrap_or(true) + self.holder.lock().map_or(true, |holder| holder.is_some()) } /// Fails once the operation holding the workspace has been cancelled: the caller is about to @@ -936,7 +933,7 @@ pub fn serve(config: ServerConfig) -> Result<()> { fs::create_dir_all(&config.cache_dir)?; let remote = RemoteCache::new(&config)?; let state = Arc::new(State::new(config, remote)); - prune_cache(&state)?; + prune_cache(&state); start_cache_pruner(&state)?; perform_initial_fetch(&state); let server = Server::http(("0.0.0.0", state.config.port)) @@ -947,7 +944,7 @@ pub fn serve(config: ServerConfig) -> Result<()> { ); for request in server.incoming_requests() { let state = Arc::clone(&state); - std::thread::spawn(move || handle_request(request, state)); + std::thread::spawn(move || handle_request(request, &state)); } Ok(()) } @@ -994,16 +991,14 @@ fn start_cache_pruner(state: &Arc) -> Result<()> { .name("bazel-diff-cache-pruner".to_owned()) .spawn(move || loop { std::thread::sleep(interval); - if let Err(error) = prune_cache(&state) { - eprintln!("[Warn] cache prune pass failed; retrying next interval: {error:#}"); - } + prune_cache(&state); }) .context("failed to start cache pruner")?; Ok(()) } -fn handle_request(request: Request, state: Arc) { - if let Err(error) = route(request, &state) { +fn handle_request(request: Request, state: &Arc) { + if let Err(error) = route(request, state) { eprintln!("[Error] failed to handle HTTP request: {error:#}"); } } @@ -1072,7 +1067,7 @@ fn route(mut request: Request, state: &Arc) -> Result<()> { let worker_token = Arc::clone(&token); let (sender, receiver) = mpsc::sync_channel(1); std::thread::spawn(move || { - let result = compute_query(&state_for_compute, inputs, kind, &worker_token); + let result = compute_query(&state_for_compute, &inputs, kind, &worker_token); // Decrement before answering so a client that polls /metrics right after its // response never sees its own finished query still counted. drop(active); @@ -1213,7 +1208,7 @@ fn normalized_types(types: Option>) -> Option> { fn compute_query( state: &Arc, - inputs: QueryInputs, + inputs: &QueryInputs, kind: QueryKind, token: &Arc, ) -> Result { @@ -1221,13 +1216,13 @@ fn compute_query( let _guard = state.workspace.acquire(token)?; let resolve_started = Instant::now(); let (from_sha, to_sha) = resolve_both(state, &inputs.from, &inputs.to)?; - let resolve_millis = resolve_started.elapsed().as_millis() as u64; + let resolve_millis = elapsed_millis(resolve_started); if matches!(kind, QueryKind::DepEdges) { // Same graph generate-hashes writes to --depEdgesFile: the end revision's // full (unscoped) dependency map. modifiedFilepaths must not shrink it — // PRI/CRI BFS-walk this file from the app target and need every edge. let to = get_hashes_locked(state, &to_sha, &BTreeSet::new(), None)?.data; - prune_cache(state)?; + prune_cache(state); return Ok(serde_json::to_value(&to.dep_edges)?); } let from_started = Instant::now(); @@ -1273,7 +1268,7 @@ fn compute_query( exclude_external, )?)? }; - let diff_millis = diff_started.elapsed().as_millis() as u64; + let diff_millis = elapsed_millis(diff_started); let mut result = serde_json::Map::from_iter([ ("from".to_owned(), Value::String(from_sha.clone())), ("to".to_owned(), Value::String(to_sha.clone())), @@ -1283,7 +1278,7 @@ fn compute_query( result.insert( "profile".to_owned(), json!({ - "totalDurationMillis": started.elapsed().as_millis() as u64, + "totalDurationMillis": elapsed_millis(started), "resolveRevisionsDurationMillis": resolve_millis, "hashRetrievals": [from_profile, to_profile], "diffDurationMillis": diff_millis, @@ -1303,7 +1298,7 @@ fn compute_query( }), ); } - prune_cache(state)?; + prune_cache(state); Ok(Value::Object(result)) } @@ -1317,7 +1312,7 @@ fn warm_revision(state: &Arc, revision: &str) -> Result<()> { /// Wall-clock breakdown of one cache-miss hash generation, in pipeline order: the `git /// checkout`, then the phases of [`generate_hashes_timed`], then serialising the result and /// writing it to the cache tiers. `targetCount` sizes the graph the phases operated on. Field -/// names match the profile the Kotlin service emitted, which tools/serve_harness.py asserts on. +/// names match the profile the Kotlin service emitted, which `tools/serve_harness.py` asserts on. /// /// In partial-graph mode the `partial` fields say how the entry was produced: `mode` is /// `derived` (no checkout, no query: the base's recipes were re-evaluated) or `full`, with @@ -1376,10 +1371,6 @@ impl Retrieval { } } -fn elapsed_millis(started: Instant) -> u64 { - started.elapsed().as_millis() as u64 -} - /// One `profile.hashRetrievals[]` entry. Optional phases are omitted rather than nulled so a hit /// never shows a `generation` key and a miss never shows `cacheReadMillis`. fn retrieval_profile(sha: &str, retrieval: &Retrieval, started: Instant) -> Value { @@ -1478,7 +1469,7 @@ fn get_hashes_locked( } let mut options = state.config.hash_options.clone(); options.bazel.cancellation = state.workspace.holder(); - options.modified_filepaths = modified.clone(); + options.modified_filepaths.clone_from(modified); options.track_deps = state.config.track_deps; let mut tree = None; if modified.is_empty() && options.content_hashes.is_none() { @@ -1572,22 +1563,21 @@ fn get_hashes_locked( state.partial_derived.fetch_add(1, Ordering::SeqCst); } } - let (mut data, timings, checkout_millis) = match derived { - Some(data) => (data, Default::default(), 0), - None => { - let checkout_started = Instant::now(); - checkout(state, sha)?; - let checkout_millis = elapsed_millis(checkout_started); - if state.config.partial_graph { - options.partial_tree = tree.clone(); - } - let (data, timings) = generate_hashes_timed(&options)?; - // The scoped `modifiedFilepaths` path has no tree index and keeps its disk semantics. - if let Some(tree) = &tree { - check_tracked_packages(state, sha, &data, tree)?; - } - (data, timings, checkout_millis) + let (mut data, timings, checkout_millis) = if let Some(data) = derived { + (data, GenerationTimings::default(), 0) + } else { + let checkout_started = Instant::now(); + checkout(state, sha)?; + let checkout_millis = elapsed_millis(checkout_started); + if state.config.partial_graph { + options.partial_tree.clone_from(&tree); + } + let (data, timings) = generate_hashes_timed(&options)?; + // The scoped `modifiedFilepaths` path has no tree index and keeps its disk semantics. + if let Some(tree) = &tree { + check_tracked_packages(state, sha, &data, tree)?; } + (data, timings, checkout_millis) }; // A generation the client stopped waiting for is not cached: the subprocess kill above may // have left the working tree mid-checkout, and the caller may already be reusing it. @@ -1708,24 +1698,20 @@ fn cache_entry_matches_dependency_fingerprint( } }; } - Ok(match current_dependency_fingerprint.as_deref() { - Some(current) => { - let matched = current == cached_fingerprint; - eprintln!( - "[BD-DBG][cache-guard-check] scope={scope} sha={sha} cachedFp={} currentFp={} matched={matched}", - short_fingerprint(cached_fingerprint), - short_fingerprint(current) - ); - matched - } - None => { - eprintln!( - "[BD-DBG][cache-guard-check] scope={scope} sha={sha} cachedFp={} currentFp=NONE matched=false", - short_fingerprint(cached_fingerprint) - ); - false - } - }) + let Some(current) = current_dependency_fingerprint.as_deref() else { + eprintln!( + "[BD-DBG][cache-guard-check] scope={scope} sha={sha} cachedFp={} currentFp=NONE matched=false", + short_fingerprint(cached_fingerprint) + ); + return Ok(false); + }; + let matched = current == cached_fingerprint; + eprintln!( + "[BD-DBG][cache-guard-check] scope={scope} sha={sha} cachedFp={} currentFp={} matched={matched}", + short_fingerprint(cached_fingerprint), + short_fingerprint(current) + ); + Ok(matched) } fn short_fingerprint(value: &str) -> &str { @@ -2014,7 +2000,7 @@ fn cache_entries(directory: &Path) -> Vec { .collect() } -fn prune_cache(state: &State) -> Result<()> { +fn prune_cache(state: &State) { let mut entries = cache_entries(&state.config.cache_dir); entries.sort_by_key(|entry| entry.modified); let now = SystemTime::now(); @@ -2041,7 +2027,6 @@ fn prune_cache(state: &State) -> Result<()> { let _ = fs::remove_file(entry.path); } } - Ok(()) } fn touch(path: &Path) { @@ -2057,6 +2042,8 @@ fn human_bytes(bytes: u64) -> String { return format!("{bytes} B"); } let units = ["KB", "MB", "GB", "TB"]; + // Rounded to one decimal below, so the f64 mantissa is more than enough. + #[allow(clippy::cast_precision_loss)] let mut value = bytes as f64 / 1024.0; let mut unit = 0; while value >= 1024.0 && unit < units.len() - 1 { @@ -2760,11 +2747,13 @@ esac .into_iter() .collect() ); - assert!( - to.data.hashes["//pkg:lib"].direct_hash != from.data.hashes["//pkg:lib"].direct_hash + assert_ne!( + to.data.hashes["//pkg:lib"].direct_hash, + from.data.hashes["//pkg:lib"].direct_hash ); - assert!( - to.data.hashes["//pkg:bin"].direct_hash == from.data.hashes["//pkg:bin"].direct_hash + assert_eq!( + to.data.hashes["//pkg:bin"].direct_hash, + from.data.hashes["//pkg:bin"].direct_hash ); // A full generation of the same revision, in a fresh cache, writes the identical entry. @@ -3423,7 +3412,7 @@ nQBeQ4AIl47nDOrFeVnvse8R9IHJ assert_eq!( normalized_types(Some(vec![ " Rule ".into(), - "".into(), + String::new(), "SourceFile".into(), "Rule".into(), ])), @@ -3796,7 +3785,7 @@ nQBeQ4AIl47nDOrFeVnvse8R9IHJ }; let result = compute_query( &state, - inputs, + &inputs, QueryKind::Distances, &Arc::new(Cancellation::new()), ) @@ -3827,11 +3816,11 @@ nQBeQ4AIl47nDOrFeVnvse8R9IHJ let mut state = state_for_repo(repo.path(), cache.path(), false); Arc::get_mut(&mut state).unwrap().config.cache_max_entries = Some(2); - prune_cache(&state).unwrap(); + prune_cache(&state); assert_eq!(cache_entries(cache.path()).len(), 2); Arc::get_mut(&mut state).unwrap().config.cache_max_size = Some(7); - prune_cache(&state).unwrap(); + prune_cache(&state); assert!( cache_entries(cache.path()) .iter() @@ -3842,7 +3831,7 @@ nQBeQ4AIl47nDOrFeVnvse8R9IHJ Arc::get_mut(&mut state).unwrap().config.cache_max_age = Some(Duration::ZERO); thread::sleep(Duration::from_millis(2)); - prune_cache(&state).unwrap(); + prune_cache(&state); assert!(cache_entries(cache.path()).is_empty()); assert!(cache.path().join("ignored.tmp").exists()); } diff --git a/tests/e2e.rs b/tests/e2e.rs index f89742a7..96e5db47 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -1,3 +1,17 @@ +//! End-to-end suite: drives the real `bazel-diff` binary against fixture workspaces. + +#![warn(clippy::pedantic)] +// The fixtures are case-sensitive Bazel paths, and the suite is test code with +// long, linear scenarios; see src/lib.rs for the reasoning behind each allow. +#![allow( + clippy::missing_errors_doc, + clippy::missing_panics_doc, + clippy::must_use_candidate, + clippy::too_many_lines, + clippy::similar_names, + clippy::case_sensitive_file_extension_comparisons +)] + #[path = "e2e/core.rs"] mod core; #[path = "e2e/example.rs"] diff --git a/tests/e2e/external.rs b/tests/e2e/external.rs index 7bbc1231..965e346a 100644 --- a/tests/e2e/external.rs +++ b/tests/e2e/external.rs @@ -209,7 +209,7 @@ fn transitive_external_repo_change_reaches_consumer() { /// (`@inner//:data`). The synthetic `//external:inner` node is named by the apparent name, so /// until the canonical name was translated the edge from `@@outer+//:lib` to the node was dropped /// and a change inside `inner` never reached `//:consume` under `--useCquery`. hashbench -/// (2026-10-18) hit the same gap on a rules_multitool lockfile bump. +/// (2026-10-18) hit the same gap on a `rules_multitool` lockfile bump. #[test] fn transitive_external_repo_change_reaches_consumer_cquery() { if !supports_mod_show_repo() { diff --git a/tests/e2e/regressions.rs b/tests/e2e/regressions.rs index 6da59472..278ed0bf 100644 --- a/tests/e2e/regressions.rs +++ b/tests/e2e/regressions.rs @@ -214,7 +214,7 @@ fn wrapped_external_repo_change_reaches_main_consumer() { ); } -/// Regression for https://github.com/Tinder/bazel-diff/issues/510: like the +/// Regression for : like the /// #197 case above, but the wrapper module (`middle`) is only declared by /// `facade`, under a private apparent name, so it is not visible from the root. #[test] @@ -314,7 +314,7 @@ fn hidden_wrapper_external_repo_change_propagates_with_explicit_chain() { assert!(!impacted.contains("//:control"), "{impacted:?}"); } -/// Regression for https://github.com/Tinder/bazel-diff/issues/522: a module patched through +/// Regression for : a module patched through /// `single_version_override(patches = [...])`, where the patch rewrites a plain data file and no /// `.bzl`. The patch is hashed into the module's `//external:dep` node /// (`_bazel_diff_local_inputs_hash`), and `//:consumer` reaches that node through its input @@ -414,7 +414,7 @@ fn repository_outside_the_workspace_keeps_its_path() { ); } -/// Regression for https://github.com/Tinder/bazel-diff/issues/544: the local registry lives inside +/// Regression for : the local registry lives inside /// the workspace (`write_local_registry` registers it by its absolute path, which is what /// `%workspace%` expands to), so the `file://` URLs of `dep`'s registry patch and `MODULE.bazel` /// name each checkout's absolute path. Two identical checkouts at different paths must impact @@ -656,7 +656,7 @@ fn cquery_keeps_dependencies_of_every_configured_instance() { ); } -/// Regression for https://github.com/Tinder/bazel-diff/issues/522 and hashbench's +/// Regression for and hashbench's /// `toolchain_patch_edit` scenario: a repository created by a module extension that no /// module imports (`go_sdk.download(patches = ...)`) is reached by toolchain resolution /// only. Editing its patch changes what every user of the toolchain builds, so the users @@ -716,7 +716,7 @@ fn extension_repo_nodes_are_stable_without_a_change() { assert!(impacted.is_empty(), "{impacted:?}"); } -/// Reproducer for https://github.com/Tinder/bazel-diff/issues/531: a transitive module's +/// Reproducer for : a transitive module's /// `use_extension` is broken (it imports a repository the extension no longer generates), /// but nothing in `//...` reaches that extension, so Bazel's lazy evaluation keeps /// `bazel build //...` green. `bazel mod graph` and `bazel mod show_repo` evaluate every @@ -906,7 +906,7 @@ fn same_symbol_extension_failure_keeps_healthy_repo_hashed() { } } -/// Reproducer for https://github.com/Tinder/bazel-diff/issues/535: the root maps the apparent +/// Reproducer for : the root maps the apparent /// name `dep` to a repository rule (`+_repo_rules+dep`) and, under the apparent name /// `module_dep`, also depends on a *module* named `dep`, whose directory is `external/dep+`. /// `//:consumer` reads `@dep` only. Fine-grained hashing guessed the repository's directory diff --git a/tools/coverage/src/args.rs b/tools/coverage/src/args.rs index c37556f5..efbe401d 100644 --- a/tools/coverage/src/args.rs +++ b/tools/coverage/src/args.rs @@ -62,7 +62,7 @@ mod tests { use super::*; fn to_vec(argv: &[&str]) -> Vec { - argv.iter().map(|s| s.to_string()).collect() + argv.iter().map(ToString::to_string).collect() } #[test] diff --git a/tools/coverage/src/enforce.rs b/tools/coverage/src/enforce.rs index a5f1c87f..77fdc04b 100644 --- a/tools/coverage/src/enforce.rs +++ b/tools/coverage/src/enforce.rs @@ -99,7 +99,7 @@ pub fn check(report: &Report, config: &Config) -> Outcome { let hit = cov.lines_hit(); total_found += found; total_hit += hit; - rows.push((hit as f64 / found as f64 * 100.0, hit, found, path)); + rows.push((percent(hit, found), hit, found, path)); } let mut text = String::new(); @@ -127,7 +127,7 @@ pub fn check(report: &Report, config: &Config) -> Outcome { }; } - let overall = total_hit as f64 / total_found as f64 * 100.0; + let overall = percent(total_hit, total_found); let _ = writeln!( text, "\nTarget line coverage: {overall:.2}% ({total_hit} / {total_found} lines)" @@ -158,6 +158,13 @@ pub fn check(report: &Report, config: &Config) -> Outcome { } } +/// `hit` as a percentage of `found`. Line counts never approach 2^53, so the +/// `u64 -> f64` conversion is exact for every report this tool will see. +#[allow(clippy::cast_precision_loss)] +fn percent(hit: u64, found: u64) -> f64 { + hit as f64 / found as f64 * 100.0 +} + #[cfg(test)] mod tests { use super::*; @@ -189,7 +196,7 @@ mod tests { ])) .unwrap() .unwrap(); - assert_eq!(cfg.min_line_coverage, 87.5); + assert!((cfg.min_line_coverage - 87.5).abs() < f64::EPSILON); assert_eq!(cfg.include, vec!["src/", "lib/"]); assert_eq!(cfg.exclude, vec!["src/generated/"]); } @@ -214,8 +221,8 @@ mod tests { fn cfg(min: f64, include: &[&str], exclude: &[&str]) -> Config { Config { min_line_coverage: min, - include: include.iter().map(|s| s.to_string()).collect(), - exclude: exclude.iter().map(|s| s.to_string()).collect(), + include: include.iter().map(ToString::to_string).collect(), + exclude: exclude.iter().map(ToString::to_string).collect(), } } diff --git a/tools/coverage/src/lcov.rs b/tools/coverage/src/lcov.rs index 0c3c31b5..ddb7065b 100644 --- a/tools/coverage/src/lcov.rs +++ b/tools/coverage/src/lcov.rs @@ -1,7 +1,7 @@ //! LCOV tracefile parsing, merging, and emission. //! //! Bazel's per-test coverage post-processor receives a directory of raw -//! per-runner LCOV tracefiles (Jacoco for JVM targets, rules_go's native LCOV +//! per-runner LCOV tracefiles (Jacoco for JVM targets, `rules_go`'s native LCOV //! conversion for Go, llvm-cov's LCOV export for Rust) and must merge them //! into the single tracefile Bazel publishes as the test's `coverage.dat`. //! @@ -81,14 +81,14 @@ pub fn parse(text: &str) -> (Report, Vec) { if let Some(path) = line.strip_prefix("SF:") { if let Some((prev_path, prev)) = current.take() { // Tolerate a missing end_of_record before the next SF. - merge_into(&mut report, prev_path, prev); + merge_into(&mut report, prev_path, &prev); } current = Some((path.to_string(), FileCoverage::default())); continue; } if line == "end_of_record" { if let Some((path, cov)) = current.take() { - merge_into(&mut report, path, cov); + merge_into(&mut report, path, &cov); } continue; } @@ -112,7 +112,7 @@ pub fn parse(text: &str) -> (Report, Vec) { cov.function_lines.entry(name.to_string()).or_insert(n); } Err(_) => { - warnings.push(format!("line {}: unparseable FN record '{line}'", idx + 1)) + warnings.push(format!("line {}: unparseable FN record '{line}'", idx + 1)); } }, None => warnings.push(format!("line {}: unparseable FN record '{line}'", idx + 1)), @@ -150,13 +150,13 @@ pub fn parse(text: &str) -> (Report, Vec) { // else (e.g. lcov 2.x extensions) is intentionally ignored. } if let Some((path, cov)) = current.take() { - merge_into(&mut report, path, cov); + merge_into(&mut report, path, &cov); } (report, warnings) } -fn merge_into(report: &mut Report, path: String, cov: FileCoverage) { - report.entry(path).or_default().merge(&cov); +fn merge_into(report: &mut Report, path: String, cov: &FileCoverage) { + report.entry(path).or_default().merge(cov); } /// `DA:,[,]` @@ -183,12 +183,12 @@ fn parse_brda(rest: &str) -> Option<((u64, String, String), BranchTaken)> { /// Merge `incoming` into `merged`. pub fn merge_reports(merged: &mut Report, incoming: Report) { for (path, cov) in incoming { - merge_into(merged, path, cov); + merge_into(merged, path, &cov); } } /// Serialise a report back to LCOV text, mirroring the record order of -/// Bazel's built-in CoverageOutputGenerator (SF, FN, FNDA, FNF, FNH, BRDA, +/// Bazel's built-in `CoverageOutputGenerator` (SF, FN, FNDA, FNF, FNH, BRDA, /// BRF, BRH, DA, LH, LF) so downstream consumers see no format change. pub fn emit(report: &Report) -> String { let mut out = String::new(); diff --git a/tools/coverage/src/lib.rs b/tools/coverage/src/lib.rs index d8ed570f..de81c1eb 100644 --- a/tools/coverage/src/lib.rs +++ b/tools/coverage/src/lib.rs @@ -8,6 +8,16 @@ //! `bazel test` runs never see it — so enforcement engages exclusively in //! coverage runs. See `README.md` in this package for the user-facing story. +#![warn(clippy::pedantic)] +// See src/lib.rs in the root crate for why these pedantic lints are not adopted. +#![allow( + clippy::missing_errors_doc, + clippy::missing_panics_doc, + clippy::must_use_candidate, + clippy::similar_names, + clippy::case_sensitive_file_extension_comparisons +)] + pub mod args; pub mod enforce; pub mod lcov; @@ -184,13 +194,12 @@ mod tests { use super::*; use std::sync::atomic::{AtomicU32, Ordering}; - /// A unique scratch directory per test, under TEST_TMPDIR when Bazel + /// A unique scratch directory per test, under `TEST_TMPDIR` when Bazel /// provides it. fn scratch_dir(label: &str) -> PathBuf { static COUNTER: AtomicU32 = AtomicU32::new(0); - let base = std::env::var("TEST_TMPDIR") - .map(PathBuf::from) - .unwrap_or_else(|_| std::env::temp_dir()); + let base = + std::env::var("TEST_TMPDIR").map_or_else(|_| std::env::temp_dir(), PathBuf::from); let dir = base.join(format!( "lcov_merger_test_{}_{label}_{}", std::process::id(), @@ -206,8 +215,8 @@ mod tests { merged: String, } - /// Drive `run()` against a synthetic COVERAGE_DIR the way - /// collect_coverage.sh would. + /// Drive `run()` against a synthetic `COVERAGE_DIR` the way + /// `collect_coverage.sh` would. fn invoke( label: &str, tracefiles: &[(&str, &str)], @@ -234,7 +243,7 @@ mod tests { manifest_path.display() )); } - argv.extend(extra_args.iter().map(|s| s.to_string())); + argv.extend(extra_args.iter().map(ToString::to_string)); let env: BTreeMap = env .iter() .map(|(k, v)| (k.to_string(), v.to_string())) diff --git a/tools/coverage/src/main.rs b/tools/coverage/src/main.rs index df51c015..dc9602eb 100644 --- a/tools/coverage/src/main.rs +++ b/tools/coverage/src/main.rs @@ -1,3 +1,13 @@ +#![warn(clippy::pedantic)] +// See src/lib.rs in the root crate for why these pedantic lints are not adopted. +#![allow( + clippy::missing_errors_doc, + clippy::missing_panics_doc, + clippy::must_use_candidate, + clippy::similar_names, + clippy::case_sensitive_file_extension_comparisons +)] + use std::collections::BTreeMap; fn main() { diff --git a/tools/coverage/src/pattern.rs b/tools/coverage/src/pattern.rs index 62ecceaf..55e53d07 100644 --- a/tools/coverage/src/pattern.rs +++ b/tools/coverage/src/pattern.rs @@ -3,7 +3,7 @@ //! Bazel's `collect_coverage.sh` invokes the LCOV merger with a fixed set of //! filter patterns (`/usr/bin/.+`, `/usr/lib/.+`, `/usr/include.+`, //! `/Applications/.+`), and users may add their own via custom rules. The -//! built-in CoverageOutputGenerator treats these as full-match Java regexes. +//! built-in `CoverageOutputGenerator` treats these as full-match Java regexes. //! This module implements the small subset those patterns actually need — //! literals, `.`, character classes, `*`/`+`/`?` quantifiers, and `\` //! escapes — with full-string anchoring, avoiding a third-party regex crate. From 8cfcf05d1387e2d8f69f832446015e0e9b61491c Mon Sep 17 00:00:00 2001 From: Maxwell Elliott Date: Mon, 16 Nov 2026 09:27:43 -0500 Subject: [PATCH 2/2] Make clippy::pedantic the build-wide default The lint policy moves from five duplicated crate-root attribute blocks to the rules_rust clippy_flag settings in .bazelrc, so every crate the clippy aspects visit, including ones added later, is held to pedantic with warnings denied without opting in. Setting the flags replaces rules_rust's implicit -Dwarnings, so it is listed first. Cargo.toml mirrors the list in [lints.clippy] for `cargo clippy`. The generated protobuf module keeps its local exemption. Co-Authored-By: Claude Fable 5.1 --- .bazelrc | 29 +++++++++++++++++++++++++++++ BUILD | 3 +++ Cargo.toml | 13 +++++++++++++ src/lib.rs | 25 ------------------------- src/main.rs | 25 ------------------------- tests/e2e.rs | 12 ------------ tools/coverage/src/lib.rs | 10 ---------- tools/coverage/src/main.rs | 10 ---------- 8 files changed, 45 insertions(+), 82 deletions(-) diff --git a/.bazelrc b/.bazelrc index 1142f760..8ffbb21a 100644 --- a/.bazelrc +++ b/.bazelrc @@ -30,6 +30,35 @@ common --test_env=PATH # //:rust_clippy_check and //:rust_format_check. build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect build --output_groups=+clippy_checks + +# Lint policy for every first-party Rust crate (the aspect skips external +# crates): clippy::pedantic, with warnings as errors. Cargo.toml [lints.clippy] +# mirrors this list for `cargo clippy`; keep the two in step. Setting any flag +# here replaces rules_rust's implicit -Dwarnings, so it comes first. +# +# Pedantic lints not adopted: +# - The doc lints: this is a CLI crate whose module API is not a stability +# commitment (see src/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. +build --@rules_rust//rust/settings:clippy_flag=-Dwarnings +build --@rules_rust//rust/settings:clippy_flag=-Wclippy::pedantic +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::missing_errors_doc +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::missing_panics_doc +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::must_use_candidate +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::too_many_lines +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::similar_names +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::struct_excessive_bools +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::case_sensitive_file_extension_comparisons +build --@rules_rust//rust/settings:clippy_flag=-Aclippy::implicit_hasher build --aspects=@rules_rust//rust:defs.bzl%rustfmt_aspect build --output_groups=+rustfmt_checks diff --git a/BUILD b/BUILD index e92419f0..816f1695 100644 --- a/BUILD +++ b/BUILD @@ -50,6 +50,9 @@ test_suite( # `transitive` walks deps/crate from each root; external crates are skipped by # the aspects themselves. # +# Lint levels (clippy::pedantic, warnings denied) come from the clippy_flag +# settings in .bazelrc and apply to every crate the aspects visit. +# # Adding a first-party Rust crate? Add its root here. _RUST_LINT_ROOTS = [ "//src:bazel-diff", diff --git a/Cargo.toml b/Cargo.toml index 99ab366c..bcfe4d3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,19 @@ protoc-bin-vendored = { version = "3.2", optional = true } [dev-dependencies] zip = { version = "2.2", default-features = false, features = ["deflate"] } +# Mirrors the clippy policy in .bazelrc (the Bazel build is what CI checks); +# keep the two lists in step. +[lints.clippy] +pedantic = { level = "warn", priority = -1 } +missing_errors_doc = "allow" +missing_panics_doc = "allow" +must_use_candidate = "allow" +too_many_lines = "allow" +similar_names = "allow" +struct_excessive_bools = "allow" +case_sensitive_file_extension_comparisons = "allow" +implicit_hasher = "allow" + [profile.release] lto = "thin" strip = true diff --git a/src/lib.rs b/src/lib.rs index 7aada182..12d3a429 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,31 +4,6 @@ //! 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; diff --git a/src/main.rs b/src/main.rs index bf127334..c9a7fcd4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,28 +1,3 @@ -#![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 -)] - use anyhow::{bail, Context, Result}; use bazel_diff::bazel::BazelOptions; use bazel_diff::explain::{self, ExplainFormat, ExplainLimits}; diff --git a/tests/e2e.rs b/tests/e2e.rs index 96e5db47..f487d067 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -1,17 +1,5 @@ //! End-to-end suite: drives the real `bazel-diff` binary against fixture workspaces. -#![warn(clippy::pedantic)] -// The fixtures are case-sensitive Bazel paths, and the suite is test code with -// long, linear scenarios; see src/lib.rs for the reasoning behind each allow. -#![allow( - clippy::missing_errors_doc, - clippy::missing_panics_doc, - clippy::must_use_candidate, - clippy::too_many_lines, - clippy::similar_names, - clippy::case_sensitive_file_extension_comparisons -)] - #[path = "e2e/core.rs"] mod core; #[path = "e2e/example.rs"] diff --git a/tools/coverage/src/lib.rs b/tools/coverage/src/lib.rs index 0f8d278a..68d612a6 100644 --- a/tools/coverage/src/lib.rs +++ b/tools/coverage/src/lib.rs @@ -8,16 +8,6 @@ //! `bazel test` runs never see it — so enforcement engages exclusively in //! coverage runs. See `README.md` in this package for the user-facing story. -#![warn(clippy::pedantic)] -// See src/lib.rs in the root crate for why these pedantic lints are not adopted. -#![allow( - clippy::missing_errors_doc, - clippy::missing_panics_doc, - clippy::must_use_candidate, - clippy::similar_names, - clippy::case_sensitive_file_extension_comparisons -)] - pub mod args; pub mod enforce; pub mod lcov; diff --git a/tools/coverage/src/main.rs b/tools/coverage/src/main.rs index dc9602eb..df51c015 100644 --- a/tools/coverage/src/main.rs +++ b/tools/coverage/src/main.rs @@ -1,13 +1,3 @@ -#![warn(clippy::pedantic)] -// See src/lib.rs in the root crate for why these pedantic lints are not adopted. -#![allow( - clippy::missing_errors_doc, - clippy::missing_panics_doc, - clippy::must_use_candidate, - clippy::similar_names, - clippy::case_sensitive_file_extension_comparisons -)] - use std::collections::BTreeMap; fn main() {