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/bazel.rs b/src/bazel.rs index 56913030..085967c7 100644 --- a/src/bazel.rs +++ b/src/bazel.rs @@ -232,7 +232,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 { @@ -381,12 +381,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, + } } fn configured_root_query(expression: &str) -> String { @@ -415,7 +417,7 @@ impl BazelOptions { mut transform: impl FnMut(&mut [Target], Option), ) -> Result { self.query_all_targets_encoded(false, false, |batch, _, inputs, _ordinary_inputs| { - transform(batch, inputs) + transform(batch, inputs); }) } @@ -813,10 +815,10 @@ impl BazelOptions { // can register another toolchain that this ordinary query never loads. targets.extend(repos.into_iter().map(|row| { row.finish(&BTreeSet::new(), &mut |target, group, ordinary| { - transform(std::slice::from_mut(target), &[], group, ordinary) + transform(std::slice::from_mut(target), &[], group, ordinary); }) })); - targets = deduplicate_targets(targets)?; + targets = deduplicate_targets(targets); } self.check_failed_extension_references( &targets, @@ -1190,6 +1192,7 @@ impl BazelOptions { alias_sources: &mut HashMap, transform: &mut impl FnMut(&mut [Target], Option), ) -> Result<()> { + use crate::proto::blaze_query::attribute::Discriminator as Kind; let mapping = root_mapping .map(|raw| crate::hash::parse_apparent_repo_mapping(&String::from_utf8_lossy(raw))) .unwrap_or_default(); @@ -1282,7 +1285,6 @@ impl BazelOptions { } // Follow returned literal aliases until their first missing destination. // Configurable primary aliases retain the existing package boundary. - use crate::proto::blaze_query::attribute::Discriminator as Kind; let mut returned_aliases: BTreeSet<_> = bindings .values() .filter(|actual| { @@ -1695,7 +1697,7 @@ impl BazelOptions { } } targets.extend(bzlmod_repos); - deduplicate_targets(targets) + Ok(deduplicate_targets(targets)) } else { queries.push("'//...:all-targets'".to_owned()); queries.extend( @@ -1707,7 +1709,7 @@ impl BazelOptions { match query(&full, false) { Ok(mut targets) => { targets.extend(bzlmod_repos); - deduplicate_targets(targets) + Ok(deduplicate_targets(targets)) } Err(error) if include_external && is_external_package_error(&error.to_string()) => { let without_external = self.with_exclude_filter( @@ -1722,7 +1724,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), } @@ -1736,12 +1738,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) = @@ -1782,7 +1783,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, @@ -1890,15 +1891,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}")) @@ -2055,21 +2055,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 { @@ -2108,7 +2105,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, @@ -2171,36 +2168,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('+') @@ -2324,7 +2321,7 @@ impl BazelOptions { stderr.trim() ); }; - self.note_failed_extensions(failed, failure.extensions); + failed.note(failure.extensions); if failure.answered { return Ok(Some(value)); } @@ -2375,7 +2372,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); @@ -2386,42 +2383,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`. @@ -3100,11 +3061,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('~')) @@ -3926,7 +3884,7 @@ pub(crate) struct QueriedTargets { pub(crate) struct VerifiedQuery { pub(crate) targets: Vec, pub(crate) aspects: Vec, - /// Locations from genuine SourceFile rows. A missing or conflicting location is unresolved. + /// Locations from genuine `SourceFile` rows. A missing or conflicting location is unresolved. pub(crate) source_locations: BTreeMap>, } @@ -4084,6 +4042,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() @@ -4178,16 +4170,24 @@ fn materialize_repository_inputs_for_batch(batch: &mut [Target], inputs: Option< } } +// The by-value `shared` matches the row-transform callback signature `finish` takes. +#[allow(clippy::needless_pass_by_value)] fn materialize_repository_inputs( target: &mut Target, shared: Option, _ordinary_inputs: Option>, ) { if let Some(inputs) = shared.as_ref().and_then(RepositoryInputs::siblings) { - target.rule.as_option_mut().unwrap().rule_input = inputs.labels.clone(); + target + .rule + .as_option_mut() + .unwrap() + .rule_input + .clone_from(&inputs.labels); } } +#[derive(Clone, Copy)] struct ModuleDependencies<'a> { edges: &'a BTreeMap>, mappings: &'a BTreeMap, @@ -4618,7 +4618,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(); @@ -4629,7 +4629,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> { @@ -5025,10 +5025,10 @@ fn last_payload(bytes: &[u8], number: u32) -> Option<&[u8]> { fn push_wire_varint(out: &mut Vec, mut value: u64) { while value >= 0x80 { - out.push((value as u8) | 0x80); + out.push((value & 0x7f) as u8 | 0x80); value >>= 7; } - out.push(value as u8); + out.push((value & 0x7f) as u8); } /// Decodes a queried `Target` without materializing the rule attributes nothing but hashing @@ -5880,23 +5880,22 @@ pub(crate) 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(), + // cquery follows configured inputs. Package groups always use the null configuration. + configured_rule_input: group + .included_package_group + .iter() + .map(|label| ConfiguredRuleInput { + label: Some(label.clone()), + ..Default::default() + }) + .collect(), ..Default::default() - }; - rule.attribute.push(packages); - rule.rule_input = group.included_package_group.clone(); - // cquery follows configured inputs. Package groups always use the null configuration. - rule.configured_rule_input = group - .included_package_group - .iter() - .map(|label| ConfiguredRuleInput { - label: Some(label.clone()), - ..Default::default() - }) - .collect(); - rule + } } struct RepositoryFiles { @@ -5931,11 +5930,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); @@ -6013,7 +6013,7 @@ fn external_repository_labels(repository: &Repository) -> impl Iterator 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 @@ -6291,7 +6291,7 @@ impl<'a> RepositoryWorkspace<'a> { Entry::Occupied(mut entry) if entry.get() != &overlay => { entry.insert(None); } - _ => (), + Entry::Occupied(_) => {} } } } @@ -6440,7 +6440,7 @@ fn parse_module_dependency_edges(json: &str) -> BTreeMap>, + edges: &BTreeMap>, ) -> BTreeMap> { fn visit( node: &str, @@ -6631,13 +6631,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 } @@ -6659,6 +6653,7 @@ mod tests { }; use crate::proto::blaze_query::{ attribute, EnvironmentGroup, GeneratedFile, LabelDictUnaryEntry, SourceFile, + StringListDictEntry, }; fn lower_repositories( repositories: Vec, @@ -6938,7 +6933,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" @@ -8530,7 +8525,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), @@ -8575,7 +8570,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()]), @@ -8583,7 +8578,7 @@ exit 1 let result = options .extension_repositories( &root, - Vec::new(), + &[], BTreeMap::new(), true, &mut FailedExtensions::default(), @@ -8798,7 +8793,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(), @@ -8987,7 +8982,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", @@ -9078,7 +9073,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() @@ -9125,7 +9120,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(); @@ -9245,7 +9241,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]; @@ -9564,6 +9561,7 @@ exit 1 fn ordinary_hashes_follow_registered_toolchains_and_files_through_an_external_rule() { use crate::hash::{generate_hashes, HashOptions}; use crate::model::impacted_targets; + use std::fmt::Write as _; const APP: &str = "@pypi//:app"; const ALIAS: &str = "@pypi//extra:lookup"; @@ -9584,16 +9582,16 @@ exit 1 }) .collect(); let script = extension_flow_script(dir, &repos, None); - let mut bazel = probe_options(dir, script); + let mut bazel = probe_options(dir, &script); bazel.fine_grained_external_repos.insert("@pypi".into()); let options = HashOptions { bazel, content_hashes: None, - ignored_attributes: Default::default(), - seed_filepaths: Default::default(), - modified_filepaths: Default::default(), + ignored_attributes: HashSet::new(), + seed_filepaths: BTreeSet::new(), + modified_filepaths: BTreeSet::new(), track_deps: true, - always_affected_tags: Default::default(), + always_affected_tags: HashSet::new(), partial_tree: None, }; let rule = |name: &str, inputs: &[&str]| { @@ -9658,9 +9656,9 @@ exit 1 DATA, "//:registration", ] { - dot.push_str(&format!("\"{label}\"\n")); + writeln!(dot, "\"{label}\"").unwrap(); } - dot.push_str(&format!("\"{APP}\" -> \"//:toolchain_type\"\n}}")); + write!(dot, "\"{APP}\" -> \"//:toolchain_type\"\n}}").unwrap(); fs::write(dir.join("reader.dot"), dot).unwrap(); fs::write(dir.join("version"), "1").unwrap(); let hashes = || generate_hashes(&options).unwrap(); @@ -9856,7 +9854,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(); @@ -9993,13 +9991,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()); } @@ -10176,7 +10174,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"), @@ -10223,18 +10221,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( @@ -10242,7 +10241,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 @@ -10348,7 +10347,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 @@ -10384,9 +10383,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}"); @@ -10404,7 +10402,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, @@ -10438,7 +10436,7 @@ exit 1 let disabled = tempfile::tempdir().unwrap(); let script = query_script(disabled.path(), "8.7.0", &[], 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"); } @@ -10460,7 +10458,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!( @@ -10565,7 +10563,7 @@ exit 1 batch .iter() .map(|target| target_name(target).unwrap().to_owned()), - ) + ); }, None, None, @@ -10590,7 +10588,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)]); @@ -10899,6 +10897,7 @@ exit 1 query_exit: i32, cquery_exit: i32, ) -> PathBuf { + use std::fmt::Write as _; let result = results(vec![ configured(rule_target("//app:lib"), Some("abc123"), 1), configured(rule_target("//app:incompatible"), Some("abc123"), 1), @@ -10911,15 +10910,11 @@ exit 1 let query_proto = workspace.join("query-result.pb"); write_delimited(&query_proto, &[rule_target("//app:lib")]); let compatible_file = workspace.join("compatible.txt"); - fs::write( - &compatible_file, - compatible - .iter() - .map(|label| format!("{label}\n")) - .collect::() - .replacen('\n', "\n\n", 1), - ) - .unwrap(); + let mut compatible_text = String::new(); + for label in compatible { + writeln!(compatible_text, "{label}").unwrap(); + } + fs::write(&compatible_file, compatible_text.replacen('\n', "\n\n", 1)).unwrap(); let script = workspace.join("fake-bazel.sh"); let body = format!( r#"#!/bin/sh @@ -11016,7 +11011,7 @@ if [ -f fail ]; then exit 3; fi "#, ) .unwrap(); - let mut options = probe_options(dir, script); + let mut options = probe_options(dir, &script); options.command_options.push("--keep_going".into()); let rows = || { vec![ @@ -11166,7 +11161,7 @@ case "$expression" in *) exit 1 ;; esac "#).unwrap(); - let mut options = probe_options(dir, script); + let mut options = probe_options(dir, &script); options.command_options = vec!["--notool_deps".into(), "--noimplicit_deps".into()]; let mut sources = BTreeMap::new(); let mut parents = BTreeMap::new(); @@ -11255,7 +11250,7 @@ esac 0, 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()]; @@ -11324,7 +11319,7 @@ esac }, ], ); - let mut options = probe_options(workspace.path(), script); + let mut options = probe_options(workspace.path(), &script); options.use_cquery = true; options.keep_going = true; options.cquery_root_expression = Some("//app:lib".into()); @@ -11363,7 +11358,7 @@ esac 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, 0); - 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(); @@ -11393,7 +11388,7 @@ esac let partial = tempfile::tempdir().unwrap(); let script = query_script(partial.path(), "8.7.0", &[], 3, 0); - 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; @@ -11411,7 +11406,7 @@ esac "#!/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/bazel/toolchain_readers.rs b/src/bazel/toolchain_readers.rs index 8cc1f9e0..6cea9ba3 100644 --- a/src/bazel/toolchain_readers.rs +++ b/src/bazel/toolchain_readers.rs @@ -529,7 +529,7 @@ impl BazelOptions { drop(graph); recovered.extend(suppliers); recovered.extend(opaque); - result.sources = super::deduplicate_targets(recovered)?; + result.sources = super::deduplicate_targets(recovered); Ok(result) } @@ -1320,7 +1320,7 @@ impl BazelOptions { super::CqueryCapture::AvailableOrdinaryInputs, |_| true, )?; - super::deduplicate_targets(graph.targets) + Ok(super::deduplicate_targets(graph.targets)) }; if let Some(packages) = alias_packages.filter(|packages| !packages.is_empty()) { let inventory = super::package_targets(packages)?; 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 45a1c054..9a5c130c 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 1bb91db3..bb3faeb1 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -41,8 +41,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() @@ -205,9 +204,9 @@ enum HashTarget { impl HashTarget { fn label(&self) -> &str { match self { - HashTarget::Rule(label) => label, - HashTarget::RepositoryDefinition(label) => label, - HashTarget::Source(label) => label, + HashTarget::Rule(label) + | HashTarget::RepositoryDefinition(label) + | HashTarget::Source(label) => label, HashTarget::Generated { name, generating_rule: _, @@ -231,8 +230,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 { @@ -562,20 +563,17 @@ fn hash_targets_with_environment( hash_targets.push(HashTarget::Rule(rule.name.clone())); // Generated targets are prehashed and deduplicated; raw callers provide no // digests and retain the ordered fallback below, including duplicate names. - match rules + if let Some((id, prepared)) = rules .ids .get(&rule.name) .and_then(|&id| prepared.get_mut(id)?.take().map(|value| (id, value))) { - Some((id, prepared)) => { - rules.slots[id].rule = Some(Rc::new(RuleNode::new(rule, prepared))); - } - None => { - if let Some(id) = rules.ids.get(&rule.name) { - rules.ordinary_inputs.remove(id); - } - decoded_rules.push((rule.name.clone(), rule)); + rules.slots[id].rule = Some(Rc::new(RuleNode::new(rule, prepared))); + } else { + if let Some(id) = rules.ids.get(&rule.name) { + rules.ordinary_inputs.remove(id); } + decoded_rules.push((rule.name.clone(), rule)); } } } @@ -703,13 +701,13 @@ fn hash_targets_with_environment( .iter() .take(8) .map(|(key, node)| { - if !node.covered { - format!("{key}: input or context was not verified") - } else { + if node.covered { format!( "{key}: source location {:?} was not observed", coverage.source_locations.get(*key) ) + } else { + format!("{key}: input or context was not verified") } }) .collect::>(); @@ -1604,7 +1602,7 @@ impl Labels { } /// A native filegroup needs a strict native declaration, a matching ordinary definition, - /// and an observed InputFile or complete filegroup for every input. The definition matches + /// and an observed `InputFile` or complete filegroup for every input. The definition matches /// either the full declaration or a fresh caller-projected row with synthetic hash evidence. /// Cycles and other rule kinds remain unresolved. Native genrule parents additionally require /// complete direct children and an explicitly returned empty toolchains attribute. @@ -1825,24 +1823,25 @@ impl Labels { definition_digest: _, inputs, } => pending.extend(inputs.iter().cloned()), - RepositoryDefinitionState::Visiting => unreachable!("closed repository graph"), - RepositoryDefinitionState::Unavailable => unreachable!("closed repository graph"), + RepositoryDefinitionState::Visiting | RepositoryDefinitionState::Unavailable => { + unreachable!("closed repository graph") + } } } let mut definitions = HashMap::new(); for repository in needed { - let (definition, definition_digest, inputs) = match states - .get(&repository) - .expect("planned repository") - { - RepositoryDefinitionState::Complete { - label, - definition_digest, - inputs, - } => (label, *definition_digest, inputs), - RepositoryDefinitionState::Visiting => unreachable!("closed repository graph"), - RepositoryDefinitionState::Unavailable => unreachable!("closed repository graph"), - }; + let (definition, definition_digest, inputs) = + match states.get(&repository).expect("planned repository") { + RepositoryDefinitionState::Complete { + label, + definition_digest, + inputs, + } => (label, *definition_digest, inputs), + RepositoryDefinitionState::Visiting + | RepositoryDefinitionState::Unavailable => { + unreachable!("closed repository graph") + } + }; let inputs = inputs .iter() .map( @@ -1852,10 +1851,8 @@ impl Labels { definition_digest: _, inputs: _, } => label.clone(), - RepositoryDefinitionState::Visiting => { - unreachable!("closed repository graph") - } - RepositoryDefinitionState::Unavailable => { + RepositoryDefinitionState::Visiting + | RepositoryDefinitionState::Unavailable => { unreachable!("closed repository graph") } }, @@ -1903,8 +1900,8 @@ impl Labels { } BTreeEntry::Occupied(entry) => { return match entry.get() { - RepositoryDefinitionState::Visiting => false, - RepositoryDefinitionState::Unavailable => false, + RepositoryDefinitionState::Visiting + | RepositoryDefinitionState::Unavailable => false, RepositoryDefinitionState::Complete { label: _, definition_digest: _, @@ -1928,8 +1925,9 @@ impl Labels { inputs.clone() } else { match node.prepared.repository_inputs.as_ref()? { - RepositoryInputs::DefinitionOnly => Vec::new(), - RepositoryInputs::WithSiblings(_) => Vec::new(), + RepositoryInputs::DefinitionOnly | RepositoryInputs::WithSiblings(_) => { + Vec::new() + } } }; Some((node.prepared.definition_digest, inputs)) @@ -2656,6 +2654,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 { @@ -3827,21 +3827,20 @@ impl ExternalRepoResolver { root_mapping: Option>, output_base: Option, ) -> Result { - let output_base = match output_base { - Some(output_base) => output_base, - None => { - let mut command = options.command_for_hashing(); - command.arg("info").arg("output_base").stdin(Stdio::null()); - let output = cancel::output(options.cancellation.as_deref(), &mut command) - .context("failed to determine Bazel output_base")?; - if !output.status.success() { - bail!( - "bazel info output_base failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()) + let output_base = if let Some(output_base) = output_base { + output_base + } else { + let mut command = options.command_for_hashing(); + command.arg("info").arg("output_base").stdin(Stdio::null()); + let output = cancel::output(options.cancellation.as_deref(), &mut command) + .context("failed to determine Bazel output_base")?; + if !output.status.success() { + bail!( + "bazel info output_base failed: {}", + String::from_utf8_lossy(&output.stderr) + ); } + PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()) }; Ok(Self { workspace: options.workspace.clone(), @@ -3934,7 +3933,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, @@ -5287,7 +5286,7 @@ esac fn file_hashing_reuses_its_buffer_across_files_of_any_size() { let directory = tempfile::tempdir().unwrap(); let large: Vec = (0..FILE_HASH_BUFFER_SIZE * 2 + 7) - .map(|index| (index % 251) as u8) + .map(|index| u8::try_from(index % 251).unwrap()) .collect(); let cases: [&[u8]; 4] = [&large, b"short", b"", &large[..FILE_HASH_BUFFER_SIZE]]; for (index, content) in cases.into_iter().enumerate() { diff --git a/src/lib.rs b/src/lib.rs index 278495fd..12d3a429 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,6 +18,8 @@ pub mod partial; pub mod toolchain_candidates; 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 86e106b6..c9a7fcd4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -544,7 +544,7 @@ struct ServeArgs { #[arg(long = "s3ForcePathStyle")] s3_force_path_style: bool, - /// STS endpoint where AWS_WEB_IDENTITY_TOKEN_FILE is exchanged for AWS_ROLE_ARN's credentials (MinIO, SeaweedFS) + /// STS endpoint where `AWS_WEB_IDENTITY_TOKEN_FILE` is exchanged for `AWS_ROLE_ARN`'s credentials (`MinIO`, `SeaweedFS`) #[arg(long = "s3StsEndpoint", env = "AWS_ENDPOINT_URL_STS")] s3_sts_endpoint: Option, @@ -571,7 +571,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, @@ -595,7 +595,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 { @@ -623,7 +623,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)) } /// `--repo NAME=PATH`, with the path anchored and normalized like `--workspacePath`. @@ -1145,8 +1145,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)?, @@ -1352,7 +1355,7 @@ impl ServeArgs { if let Some(first) = repositories.first() { // `serve` replaces the workspace per repository; the first stands in for the // validation below, which only reads the shared flags. - hash_options.bazel.workspace = first.workspace.clone(); + hash_options.bazel.workspace.clone_from(&first.workspace); } let config = bazel_diff::server::ServerConfig { hash_options, @@ -1467,11 +1470,12 @@ fn run() -> Result<()> { Commands::Fingerprint(args) => run_fingerprint(args)?, Commands::Warmup(args) => run_warmup(args, cli.verbose)?, Commands::Serve(args) => { - bazel_diff::server::serve(args.to_config(cli.verbose)?)?; + bazel_diff::server::serve(&args.to_config(cli.verbose)?)?; } Commands::ServeMulti(args) => { bazel_diff::server::serve( - args.serve + &args + .serve .to_config_with_repositories(cli.verbose, args.repositories.clone())?, )?; } @@ -1587,7 +1591,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") ); } @@ -2260,7 +2264,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 08161a2f..c37b7ddd 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 @@ -580,8 +580,7 @@ impl<'de> Deserialize<'de> for HashFileData { impl HashFileData { pub fn ensure_same_root_mode(&self, other: &Self) -> Result<()> { match (&self.configured_roots, &other.configured_roots) { - (None, None) => Ok(()), - (Some(_), Some(_)) => Ok(()), + (None, None) | (Some(_), Some(_)) => Ok(()), _ => bail!("incompatible configured-root hash files; generate both in the same mode"), } } @@ -853,10 +852,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, @@ -929,7 +928,7 @@ pub fn impacted_targets_with_distances( dep_edges, target_types, exclude_external, - impact_types, + &impact_types, DistanceOptions::default(), )?; Ok(result.targets) @@ -1248,14 +1247,14 @@ struct DistanceTrace { shared_direct: BTreeSet, } -#[derive(Default)] +#[derive(Clone, Copy, Default)] struct DistanceOptions<'a> { root_direct: Option<&'a HashSet>, shared: Option<&'a HashSet>, capture: bool, } -#[derive(Default)] +#[derive(Clone, Copy, Default)] struct DistanceRequest<'a> { shared: Option<&'a HashSet>, capture: bool, @@ -1307,7 +1306,7 @@ fn hash_file_distance_results( dep_edges, target_types, exclude_external, - changes, + &changes, DistanceOptions { root_direct: to.configured_roots.as_ref().map(|_| &forced_direct), shared: request.shared, @@ -1322,7 +1321,7 @@ fn distances_for_types( dep_edges: &BTreeMap>, target_types: Option<&HashSet>, exclude_external: bool, - impact_types: HashMap, + impact_types: &HashMap, options: DistanceOptions<'_>, ) -> Result { let DistanceOptions { @@ -1332,7 +1331,7 @@ fn distances_for_types( } = options; let mut dependents = HashMap::<&str, Vec<&str>>::new(); let mut roots = Vec::new(); - for (label, impact) in &impact_types { + for (label, impact) in impact_types { if *impact == ImpactType::Direct { roots.push(label.as_str()); if shared.is_none() { diff --git a/src/module_graph.rs b/src/module_graph.rs index 4c3f5cbd..ce01449b 100644 --- a/src/module_graph.rs +++ b/src/module_graph.rs @@ -181,6 +181,11 @@ fn visit_module_overlay( mut query: impl FnMut(&str) -> Result>, mut emit: impl FnMut(String), ) { + fn repo_inventory(file: &HashFileData) -> &BTreeMap { + file.configured_roots + .as_ref() + .map_or(&file.hashes, |view| &view.hashes) + } if from.module_graph_json == to.module_graph_json { return; } @@ -200,12 +205,6 @@ fn visit_module_overlay( } return; } - fn repo_inventory(file: &HashFileData) -> &BTreeMap { - file.configured_roots - .as_ref() - .map(|view| &view.hashes) - .unwrap_or(&file.hashes) - } let canonical_repos = repo_inventory(from) .keys() .chain(repo_inventory(to).keys()) @@ -678,7 +677,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 8e72efbe..aab41d57 100644 --- a/src/partial.rs +++ b/src/partial.rs @@ -95,7 +95,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, @@ -109,6 +109,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 @@ -187,24 +188,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); @@ -468,12 +468,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() @@ -664,19 +663,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); @@ -1760,7 +1758,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 c2b6472d..e48b6cdc 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, hash_file_distances, HashFileData}; use crate::module_graph::{bzlmod_enabled_for, impacted_with_module_changes}; use crate::partial::{self, Classification, Glob, TreeIndex, TreeKind}; @@ -223,6 +223,8 @@ impl ComputeSlotDemandAverage { self.prune(now); } + // Slot demand counts are small integers, which f64 represents exactly. + #[allow(clippy::cast_precision_loss)] fn current_average(&mut self, now: Instant) -> f64 { self.prune(now); let start = self.window_start(now); @@ -235,11 +237,7 @@ impl ComputeSlotDemandAverage { for index in 0..self.levels.len() { let level = self.levels[index]; let segment_start = if level.at < start { start } else { level.at }; - let segment_end = self - .levels - .get(index + 1) - .map(|next| next.at) - .unwrap_or(now); + let segment_end = self.levels.get(index + 1).map_or(now, |next| next.at); if segment_end > segment_start { weighted_value_seconds += level.value as f64 * segment_end.duration_since(segment_start).as_secs_f64(); @@ -272,7 +270,7 @@ impl<'a> ComputeSlotDemandGuard<'a> { fn start(metrics: &'a Mutex) -> Self { let mut state = metrics .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); + .unwrap_or_else(std::sync::PoisonError::into_inner); state.compute_slot_demand += 1; let current = state.compute_slot_demand; state @@ -288,7 +286,7 @@ impl Drop for ComputeSlotDemandGuard<'_> { let mut metrics = self .0 .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); + .unwrap_or_else(std::sync::PoisonError::into_inner); metrics.compute_slot_demand -= 1; let current = metrics.compute_slot_demand; metrics @@ -370,7 +368,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 { @@ -467,10 +465,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 @@ -1259,26 +1254,30 @@ pub fn validate_partial_graph(config: &ServerConfig) -> Result<()> { partial::validate_hash_options(&config.hash_options) } -pub fn serve(config: ServerConfig) -> Result<()> { +pub fn serve(config: &ServerConfig) -> Result<()> { if let Some(root) = &config.hash_options.bazel.isolated_dependency_root { bail!("serve does not support --isolatedDependencyRoot={root}"); } - validate_partial_graph(&config)?; - let repositories = repositories(&config)?; + validate_partial_graph(config)?; + let repositories = repositories(config)?; fs::create_dir_all(&config.cache_dir)?; - let remote = RemoteCache::new(&config)?; - let shared = Shared::new(&config, remote); + let remote = RemoteCache::new(config)?; + let shared = Shared::new(config, remote); let port = config.port; let states = repositories .iter() .map(|repository| { let mut config = config.clone(); - config.hash_options.bazel.workspace = repository.workspace.clone(); + config + .hash_options + .bazel + .workspace + .clone_from(&repository.workspace); Arc::new(State::with_shared(&repository.name, config, &shared)) }) .collect::>(); // Every repository prunes the same `--cacheDir`, so one pruner is enough. - prune_cache(&states[0])?; + prune_cache(&states[0]); start_cache_pruner(&states[0])?; perform_initial_fetches(&states); let service = Arc::new(Service::new(states)); @@ -1294,7 +1293,7 @@ pub fn serve(config: ServerConfig) -> Result<()> { ); for request in server.incoming_requests() { let service = Arc::clone(&service); - std::thread::spawn(move || handle_request(request, service)); + std::thread::spawn(move || handle_request(request, &service)); } Ok(()) } @@ -1388,16 +1387,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, service: Arc) { - if let Err(error) = route(request, &service) { +fn handle_request(request: Request, service: &Service) { + if let Err(error) = route(request, service) { eprintln!("[Error] failed to handle HTTP request: {error:#}"); } } @@ -1500,7 +1497,7 @@ fn route(mut request: Request, service: &Service) -> 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); @@ -1653,7 +1650,7 @@ fn normalized_types(types: Option>) -> Option> { fn compute_query( state: &Arc, - inputs: QueryInputs, + inputs: &QueryInputs, kind: QueryKind, token: &Arc, ) -> Result { @@ -1661,13 +1658,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(); @@ -1708,7 +1705,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())), @@ -1718,7 +1715,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, @@ -1738,7 +1735,7 @@ fn compute_query( }), ); } - prune_cache(state)?; + prune_cache(state); Ok(Value::Object(result)) } @@ -1753,7 +1750,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 @@ -1812,10 +1809,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 { @@ -1929,7 +1922,7 @@ fn retrieve_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() { @@ -2023,22 +2016,21 @@ fn retrieve_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. @@ -2159,24 +2151,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 { @@ -2474,7 +2462,7 @@ fn metrics_prometheus(service: &Service) -> String { .as_ref() .expect("metrics enabled") .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) + .unwrap_or_else(std::sync::PoisonError::into_inner) .compute_slot_demand_average .current_average(Instant::now()); // Repository names are validated as ASCII alphanumeric, '.', '_' or '-'. @@ -2531,7 +2519,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(); @@ -2558,7 +2546,6 @@ fn prune_cache(state: &State) -> Result<()> { let _ = fs::remove_file(entry.path); } } - Ok(()) } fn touch(path: &Path) { @@ -2574,6 +2561,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 { @@ -3245,7 +3234,7 @@ mod tests { config.hash_options.bazel.isolated_dependency_root = Some("@hub".into()); assert!(validate_partial_graph(&config).is_ok()); assert_eq!( - serve(config).unwrap_err().to_string(), + serve(&config).unwrap_err().to_string(), "serve does not support --isolatedDependencyRoot=@hub" ); assert_eq!(fs::read(cache.path()).unwrap(), b"preserved"); @@ -3636,11 +3625,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. @@ -4302,7 +4293,7 @@ nQBeQ4AIl47nDOrFeVnvse8R9IHJ assert_eq!( normalized_types(Some(vec![ " Rule ".into(), - "".into(), + String::new(), "SourceFile".into(), "Rule".into(), ])), @@ -4757,7 +4748,7 @@ esac }; let result = compute_query( &state, - inputs, + &inputs, QueryKind::Distances, &Arc::new(Cancellation::new()), ) @@ -4788,11 +4779,11 @@ esac 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() @@ -4803,7 +4794,7 @@ esac 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()); } @@ -4957,16 +4948,18 @@ esac // Deterministic time-weighted average, including startup and window expiry. let started = Instant::now(); let mut average = ComputeSlotDemandAverage::new(Duration::from_secs(20), started); - assert_eq!(average.current_average(started), 0.0); + assert!(average.current_average(started).abs() < 1e-9); average.record(1, started + Duration::from_secs(5)); assert!((average.current_average(started + Duration::from_secs(10)) - 0.5).abs() < 1e-9); average.record(3, started + Duration::from_secs(10)); average.record(0, started + Duration::from_secs(15)); assert!((average.current_average(started + Duration::from_secs(20)) - 1.0).abs() < 1e-9); assert!((average.current_average(started + Duration::from_secs(30)) - 0.75).abs() < 1e-9); - assert_eq!( - average.current_average(started + Duration::from_secs(35)), - 0.0 + assert!( + average + .current_average(started + Duration::from_secs(35)) + .abs() + < 1e-9 ); let config = test_config(); @@ -5018,7 +5011,7 @@ esac ); // Give each repository a deterministic, distinct history without sleeps. - let started = Instant::now() - Duration::from_secs(5); + let started = Instant::now().checked_sub(Duration::from_secs(5)).unwrap(); for (state, demand) in [(&first, 2), (&second, 0)] { let mut average = ComputeSlotDemandAverage::new(Duration::from_secs(5), started); average.record(demand, started); @@ -5070,6 +5063,8 @@ esac } #[test] + // The guard's demand slot is intentionally only dropped; this test asserts it stays empty. + #[allow(clippy::used_underscore_binding)] fn disabled_prometheus_does_not_track_workspace_demand() { let mut config = test_config(); config.compute_slot_demand_average_window = None; diff --git a/src/toolchain_candidates.rs b/src/toolchain_candidates.rs index aed1e6a0..edd70291 100644 --- a/src/toolchain_candidates.rs +++ b/src/toolchain_candidates.rs @@ -90,12 +90,11 @@ pub fn compare(from: &HashFileData, to: &HashFileData) -> CandidateReport { } for operand in operands { possible |= result.unresolved.contains(operand); - match hash_pair(operand) { - (Some(a), Some(b)) => possible |= !a.same_as(b), - _ => { - possible = true; - result.unresolved.insert(operand.clone()); - } + if let (Some(a), Some(b)) = hash_pair(operand) { + possible |= !a.same_as(b); + } else { + possible = true; + result.unresolved.insert(operand.clone()); } } let types = old diff --git a/src/web_identity.rs b/src/web_identity.rs index 6b0de178..6d2cc052 100644 --- a/src/web_identity.rs +++ b/src/web_identity.rs @@ -1,7 +1,7 @@ //! Temporary S3 credentials from `AssumeRoleWithWebIdentity` at a configurable STS endpoint. //! //! `aws-creds` sends web-identity exchanges only to `https://sts.amazonaws.com/`. S3-compatible -//! stores (MinIO, SeaweedFS) serve STS themselves, so with an STS endpoint configured the S3 tier +//! stores (`MinIO`, `SeaweedFS`) serve STS themselves, so with an STS endpoint configured the S3 tier //! makes the exchange here and renews the session before it expires. use anyhow::{bail, Context, Result}; @@ -21,7 +21,7 @@ const DEFAULT_SESSION_NAME: &str = "bazel-diff"; const STS_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const STS_READ_TIMEOUT: Duration = Duration::from_secs(30); -/// Exchanges a web identity token (a Kubernetes ServiceAccount token, say) for S3 credentials and +/// Exchanges a web identity token (a Kubernetes `ServiceAccount` token, say) for S3 credentials and /// reuses them until [`RENEWAL_MARGIN`] before they expire. pub struct WebIdentitySessions { endpoint: Url, @@ -95,7 +95,7 @@ impl WebIdentitySessions { } /// One `AssumeRoleWithWebIdentity` call. The token file is read every time because kubelet - /// rotates a projected ServiceAccount token before it expires. + /// rotates a projected `ServiceAccount` token before it expires. fn assume_role(&self) -> Result { let token = fs::read_to_string(&self.token_file).with_context(|| { format!( @@ -279,8 +279,7 @@ mod tests { .form .iter() .find(|(key, _)| key == name) - .map(|(_, value)| value.as_str()) - .unwrap_or_else(|| panic!("form has no {name}")) + .map_or_else(|| panic!("form has no {name}"), |(_, value)| value.as_str()) } #[test] diff --git a/tests/e2e.rs b/tests/e2e.rs index f89742a7..f487d067 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -1,3 +1,5 @@ +//! End-to-end suite: drives the real `bazel-diff` binary against fixture workspaces. + #[path = "e2e/core.rs"] mod core; #[path = "e2e/example.rs"] diff --git a/tests/e2e/external.rs b/tests/e2e/external.rs index cfbaa006..a9cd209f 100644 --- a/tests/e2e/external.rs +++ b/tests/e2e/external.rs @@ -243,7 +243,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() { @@ -629,7 +629,7 @@ fn label_only_extension_bump_does_not_reach_users_of_the_owner_or_its_dependents .collect() }; let set = |labels: &[&str]| -> BTreeSet { - labels.iter().map(|label| label.to_string()).collect() + labels.iter().copied().map(str::to_owned).collect() }; let first = copy_workspace("extension_owner_dependent_module"); let bumped = copy_workspace("extension_owner_dependent_module"); @@ -686,9 +686,6 @@ fn partial_hashes( #[test] fn fine_aliases_acquire_hidden_libraries_and_definition_sources() { - if !supports_mod_show_repo() { - return; - } fn external_key(map: &std::collections::BTreeMap, suffix: &str) -> String { let keys = map .keys() @@ -700,6 +697,9 @@ fn fine_aliases_acquire_hidden_libraries_and_definition_sources() { fn direct(hash: &str) -> &str { hash.rsplit_once('~').unwrap().1 } + if !supports_mod_show_repo() { + return; + } let workspace = copy_workspace("fine_alias_acquisition"); let root = workspace.path(); @@ -841,6 +841,9 @@ fn fine_aliases_acquire_hidden_libraries_and_definition_sources() { #[test] fn ordinary_alias_can_use_a_matcher_from_a_reached_external_package() { + fn direct(value: &str) -> &str { + value.rsplit_once('~').unwrap().1 + } if !supports_mod_show_repo() { return; } @@ -926,9 +929,6 @@ config_setting(name = "second", constraint_values = ["@@//:special"]) let after = snapshot("after", "after"); let before_hashes = hashes(&before.0); let after_hashes = hashes(&after.0); - fn direct(value: &str) -> &str { - value.rsplit_once('~').unwrap().1 - } assert_ne!( direct(&before_hashes["//:system"]), direct(&after_hashes["//:system"]) @@ -1965,7 +1965,7 @@ genrule(name = "normal", srcs = ["@app//:lib"], outs = ["normal.txt"], cmd = "ca let update = |path: &str| { edit(&changed.path().join(path), |build| { build.replace("@outside//:alternate", "@outside//:other") - }) + }); }; update(other); assert_product(changed.path(), "//:switched", "switched.txt", "outside-1"); diff --git a/tests/e2e/regressions.rs b/tests/e2e/regressions.rs index 802a6dc3..4513c64e 100644 --- a/tests/e2e/regressions.rs +++ b/tests/e2e/regressions.rs @@ -250,7 +250,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] @@ -350,7 +350,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 @@ -403,9 +403,6 @@ fn single_version_override_patch_change_reaches_consumer_cquery() { /// the head, even when its configured hash was already present and unchanged at the base. #[test] fn configured_roots_preserve_module_obligations() { - if !supports_mod_show_repo() { - return; - } struct Snapshot { workspace: TestWorkspace, hashes: PathBuf, @@ -416,6 +413,9 @@ fn configured_roots_preserve_module_obligations() { product: Vec, overlap_product: Vec, } + if !supports_mod_show_repo() { + return; + } let output = tempfile::tempdir().unwrap(); let capture = |name: &str, version: &str, change_source: bool, head: bool| { let workspace = copy_workspace("single_version_override_patch"); @@ -759,7 +759,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 @@ -1996,7 +1996,7 @@ fn cquery_verifies_covered_configured_roots() { assert_eq!(malformed["targets"], report["targets"]); } -/// 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 @@ -2112,7 +2112,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 @@ -2302,7 +2302,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..35e648a5 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::*; @@ -166,7 +173,7 @@ mod tests { fn env(pairs: &[(&str, &str)]) -> BTreeMap { pairs .iter() - .map(|(k, v)| (k.to_string(), v.to_string())) + .map(|&(k, v)| (k.to_owned(), v.to_owned())) .collect() } @@ -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..68d612a6 100644 --- a/tools/coverage/src/lib.rs +++ b/tools/coverage/src/lib.rs @@ -184,13 +184,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 +205,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,10 +233,10 @@ 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())) + .map(|&(k, v)| (k.to_owned(), v.to_owned())) .collect(); let mut log = Vec::new(); let code = run(&argv, &env, &mut log); 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.