From 4b84887848a31c6f83434cee2135f4fb0e2c9cf3 Mon Sep 17 00:00:00 2001 From: Jacob Finkelman Date: Wed, 13 Sep 2023 19:54:23 +0000 Subject: [PATCH 1/6] use let else where clippy::manual_let_else --- .../compiler/build_context/target_info.rs | 22 ++--- src/cargo/core/compiler/build_plan.rs | 5 +- src/cargo/core/compiler/fingerprint/mod.rs | 44 ++++----- src/cargo/core/compiler/future_incompat.rs | 10 +-- src/cargo/core/compiler/job_queue/mod.rs | 5 +- src/cargo/core/compiler/links.rs | 5 +- src/cargo/core/compiler/mod.rs | 9 +- src/cargo/core/compiler/timings.rs | 15 ++-- src/cargo/core/compiler/unit_dependencies.rs | 26 +++--- src/cargo/core/features.rs | 15 ++-- src/cargo/core/package_id.rs | 10 +-- src/cargo/core/package_id_spec.rs | 89 +++++++++---------- src/cargo/core/profiles.rs | 20 ++--- src/cargo/core/resolver/dep_cache.rs | 5 +- src/cargo/core/resolver/encode.rs | 15 ++-- src/cargo/core/resolver/features.rs | 23 +++-- src/cargo/core/resolver/mod.rs | 5 +- src/cargo/core/source_id.rs | 27 +++--- src/cargo/core/workspace.rs | 24 +++-- src/cargo/ops/cargo_add/mod.rs | 9 +- src/cargo/ops/cargo_compile/mod.rs | 5 +- src/cargo/ops/cargo_generate_lockfile.rs | 5 +- src/cargo/ops/cargo_package.rs | 12 ++- src/cargo/ops/cargo_pkgid.rs | 5 +- src/cargo/ops/fix.rs | 13 ++- src/cargo/ops/registry/yank.rs | 5 +- src/cargo/ops/resolve.rs | 20 ++--- src/cargo/ops/tree/graph.rs | 5 +- src/cargo/sources/config.rs | 32 +++---- src/cargo/sources/directory.rs | 5 +- src/cargo/sources/git/utils.rs | 19 ++-- src/cargo/sources/path.rs | 5 +- src/cargo/sources/registry/remote.rs | 5 +- src/cargo/util/config/mod.rs | 39 ++++---- src/cargo/util/dependency_queue.rs | 5 +- src/cargo/util/flock.rs | 5 +- src/cargo/util/profile.rs | 5 +- src/cargo/util/progress.rs | 10 +-- src/cargo/util/toml/mod.rs | 10 +-- src/cargo/util/toml/targets.rs | 5 +- 40 files changed, 245 insertions(+), 353 deletions(-) diff --git a/src/cargo/core/compiler/build_context/target_info.rs b/src/cargo/core/compiler/build_context/target_info.rs index 7c02d9009ef..555a41b7544 100644 --- a/src/cargo/core/compiler/build_context/target_info.rs +++ b/src/cargo/core/compiler/build_context/target_info.rs @@ -367,9 +367,8 @@ impl TargetInfo { &*v.insert(value) } }; - let (prefix, suffix) = match *crate_type_info { - Some((ref prefix, ref suffix)) => (prefix, suffix), - None => return Ok(None), + let Some((prefix, suffix)) = crate_type_info else { + return Ok(None); }; let mut ret = vec![FileType { suffix: suffix.clone(), @@ -612,13 +611,12 @@ fn parse_crate_type( if not_supported { return Ok(None); } - let line = match lines.next() { - Some(line) => line, - None => anyhow::bail!( + let Some(line) = lines.next() else { + anyhow::bail!( "malformed output when learning about crate-type {} information\n{}", crate_type, output_err_info(cmd, output, error) - ), + ) }; let mut parts = line.trim().split("___"); let prefix = parts.next().unwrap(); @@ -978,9 +976,8 @@ impl<'cfg> RustcTargetData<'cfg> { pub fn dep_platform_activated(&self, dep: &Dependency, kind: CompileKind) -> bool { // If this dependency is only available for certain platforms, // make sure we're only enabling it for that platform. - let platform = match dep.platform() { - Some(p) => p, - None => return true, + let Some(platform) = dep.platform() else { + return true; }; let name = self.short_name(&kind); platform.matches(name, self.cfg(kind)) @@ -1058,13 +1055,12 @@ impl RustDocFingerprint { serde_json::to_string(&actual_rustdoc_target_data)?, ) }; - let rustdoc_data = match paths::read(&fingerprint_path) { - Ok(rustdoc_data) => rustdoc_data, + let Ok(rustdoc_data) = paths::read(&fingerprint_path) else { // If the fingerprint does not exist, do not clear out the doc // directories. Otherwise this ran into problems where projects // like rustbuild were creating the doc directory before running // `cargo doc` in a way that deleting it would break it. - Err(_) => return write_fingerprint(), + return write_fingerprint(); }; match serde_json::from_str::(&rustdoc_data) { Ok(fingerprint) => { diff --git a/src/cargo/core/compiler/build_plan.rs b/src/cargo/core/compiler/build_plan.rs index a823aa95232..a024d49908a 100644 --- a/src/cargo/core/compiler/build_plan.rs +++ b/src/cargo/core/compiler/build_plan.rs @@ -86,10 +86,7 @@ impl Invocation { ); } for (var, value) in cmd.get_envs() { - let value = match value { - Some(s) => s, - None => continue, - }; + let Some(value) = value else { continue }; self.env.insert( var.clone(), value diff --git a/src/cargo/core/compiler/fingerprint/mod.rs b/src/cargo/core/compiler/fingerprint/mod.rs index 1a2dfe4eee5..c8bf23c8632 100644 --- a/src/cargo/core/compiler/fingerprint/mod.rs +++ b/src/cargo/core/compiler/fingerprint/mod.rs @@ -811,9 +811,8 @@ impl LocalFingerprint { // rustc. LocalFingerprint::CheckDepInfo { dep_info } => { let dep_info = target_root.join(dep_info); - let info = match parse_dep_info(pkg_root, target_root, &dep_info)? { - Some(info) => info, - None => return Ok(Some(StaleItem::MissingFile(dep_info))), + let Some(info) = parse_dep_info(pkg_root, target_root, &dep_info)? else { + return Ok(Some(StaleItem::MissingFile(dep_info))); }; for (key, previous) in info.env.iter() { let current = if key == CARGO_ENV { @@ -1103,16 +1102,12 @@ impl Fingerprint { } let opt_max = mtimes.iter().max_by_key(|kv| kv.1); - let (max_path, max_mtime) = match opt_max { - Some(mtime) => mtime, - + let Some((max_path, max_mtime)) = opt_max else { // We had no output files. This means we're an overridden build // script and we're just always up to date because we aren't // watching the filesystem. - None => { - self.fs_status = FsStatus::UpToDate { mtimes }; - return Ok(()); - } + self.fs_status = FsStatus::UpToDate { mtimes }; + return Ok(()); }; debug!( "max output mtime for {:?} is {:?} {}", @@ -1808,16 +1803,12 @@ pub fn parse_dep_info( target_root: &Path, dep_info: &Path, ) -> CargoResult> { - let data = match paths::read_bytes(dep_info) { - Ok(data) => data, - Err(_) => return Ok(None), + let Ok(data) = paths::read_bytes(dep_info) else { + return Ok(None); }; - let info = match EncodedDepInfo::parse(&data) { - Some(info) => info, - None => { - tracing::warn!("failed to parse cargo's dep-info at {:?}", dep_info); - return Ok(None); - } + let Some(info) = EncodedDepInfo::parse(&data) else { + tracing::warn!("failed to parse cargo's dep-info at {:?}", dep_info); + return Ok(None); }; let mut ret = RustcDepInfo::default(); ret.env = info.env; @@ -1852,9 +1843,8 @@ where I: IntoIterator, I::Item: AsRef, { - let reference_mtime = match paths::mtime(reference) { - Ok(mtime) => mtime, - Err(..) => return Some(StaleItem::MissingFile(reference.to_path_buf())), + let Ok(reference_mtime) = paths::mtime(reference) else { + return Some(StaleItem::MissingFile(reference.to_path_buf())); }; let skipable_dirs = if let Ok(cargo_home) = home::cargo_home() { @@ -1882,9 +1872,8 @@ where let path_mtime = match mtime_cache.entry(path.to_path_buf()) { Entry::Occupied(o) => *o.get(), Entry::Vacant(v) => { - let mtime = match paths::mtime_recursive(path) { - Ok(mtime) => mtime, - Err(..) => return Some(StaleItem::MissingFile(path.to_path_buf())), + let Ok(mtime) = paths::mtime_recursive(path) else { + return Some(StaleItem::MissingFile(path.to_path_buf())); }; *v.insert(mtime) } @@ -2156,9 +2145,8 @@ pub fn parse_rustc_dep_info(rustc_dep_info: &Path) -> CargoResult for line in contents.lines() { if let Some(rest) = line.strip_prefix("# env-dep:") { let mut parts = rest.splitn(2, '='); - let env_var = match parts.next() { - Some(s) => s, - None => continue, + let Some(env_var) = parts.next() else { + continue; }; let env_val = match parts.next() { Some(s) => Some(unescape_env(s)?), diff --git a/src/cargo/core/compiler/future_incompat.rs b/src/cargo/core/compiler/future_incompat.rs index c1868d92abf..cfc028cf00a 100644 --- a/src/cargo/core/compiler/future_incompat.rs +++ b/src/cargo/core/compiler/future_incompat.rs @@ -333,13 +333,11 @@ fn get_updates(ws: &Workspace<'_>, package_ids: &BTreeSet) -> Option< let mut summaries = Vec::new(); while !package_ids.is_empty() { package_ids.retain(|&pkg_id| { - let source = match sources.get_mut(&pkg_id.source_id()) { - Some(s) => s, - None => return false, + let Some(source) = sources.get_mut(&pkg_id.source_id()) else { + return false; }; - let dep = match Dependency::parse(pkg_id.name(), None, pkg_id.source_id()) { - Ok(dep) => dep, - Err(_) => return false, + let Ok(dep) = Dependency::parse(pkg_id.name(), None, pkg_id.source_id()) else { + return false; }; match source.query_vec(&dep, QueryKind::Exact) { Poll::Ready(Ok(sum)) => { diff --git a/src/cargo/core/compiler/job_queue/mod.rs b/src/cargo/core/compiler/job_queue/mod.rs index 26fcd482692..738c8c267a9 100644 --- a/src/cargo/core/compiler/job_queue/mod.rs +++ b/src/cargo/core/compiler/job_queue/mod.rs @@ -941,9 +941,8 @@ impl<'cfg> DrainState<'cfg> { cx: &mut Context<'_, '_>, ) -> CargoResult<()> { let outputs = cx.build_script_outputs.lock().unwrap(); - let metadata = match cx.find_build_script_metadata(unit) { - Some(metadata) => metadata, - None => return Ok(()), + let Some(metadata) = cx.find_build_script_metadata(unit) else { + return Ok(()); }; let bcx = &mut cx.bcx; if let Some(output) = outputs.get(metadata) { diff --git a/src/cargo/core/compiler/links.rs b/src/cargo/core/compiler/links.rs index 4cef2eb39e2..cfbf92ef0bc 100644 --- a/src/cargo/core/compiler/links.rs +++ b/src/cargo/core/compiler/links.rs @@ -27,9 +27,8 @@ pub fn validate_links(resolve: &Resolve, unit_graph: &UnitGraph) -> CargoResult< if !validated.insert(unit.pkg.package_id()) { continue; } - let lib = match unit.pkg.manifest().links() { - Some(lib) => lib, - None => continue, + let Some(lib) = unit.pkg.manifest().links() else { + continue; }; if let Some(&prev) = links.get(lib) { let prev_path = resolve diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs index ab49e65e4f6..a847d2cc1e7 100644 --- a/src/cargo/core/compiler/mod.rs +++ b/src/cargo/core/compiler/mod.rs @@ -543,12 +543,9 @@ fn link_targets(cx: &mut Context<'_, '_>, unit: &Unit, fresh: bool) -> CargoResu if !src.exists() { continue; } - let dst = match output.hardlink.as_ref() { - Some(dst) => dst, - None => { - destinations.push(src.clone()); - continue; - } + let Some(dst) = output.hardlink.as_ref() else { + destinations.push(src.clone()); + continue; }; destinations.push(dst.clone()); paths::link_or_copy(src, dst)?; diff --git a/src/cargo/core/compiler/timings.rs b/src/cargo/core/compiler/timings.rs index 300719438ea..7c388bd103b 100644 --- a/src/cargo/core/compiler/timings.rs +++ b/src/cargo/core/compiler/timings.rs @@ -194,9 +194,8 @@ impl<'cfg> Timings<'cfg> { // `id` may not always be active. "fresh" units unconditionally // generate `Message::Finish`, but this active map only tracks dirty // units. - let unit_time = match self.active.get_mut(&id) { - Some(ut) => ut, - None => return, + let Some(unit_time) = self.active.get_mut(&id) else { + return; }; let t = self.start.elapsed().as_secs_f64(); unit_time.rmeta_time = Some(t - unit_time.start); @@ -212,9 +211,8 @@ impl<'cfg> Timings<'cfg> { return; } // See note above in `unit_rmeta_finished`, this may not always be active. - let mut unit_time = match self.active.remove(&id) { - Some(ut) => ut, - None => return, + let Some(mut unit_time) = self.active.remove(&id) else { + return; }; let t = self.start.elapsed().as_secs_f64(); unit_time.duration = t - unit_time.start; @@ -265,9 +263,8 @@ impl<'cfg> Timings<'cfg> { if !self.enabled { return; } - let prev = match &mut self.last_cpu_state { - Some(state) => state, - None => return, + let Some(prev) = &mut self.last_cpu_state else { + return; }; // Don't take samples too frequently, even if requested. let now = Instant::now(); diff --git a/src/cargo/core/compiler/unit_dependencies.rs b/src/cargo/core/compiler/unit_dependencies.rs index 68682235605..7116ba2070d 100644 --- a/src/cargo/core/compiler/unit_dependencies.rs +++ b/src/cargo/core/compiler/unit_dependencies.rs @@ -273,10 +273,9 @@ fn compute_deps( let mut ret = Vec::new(); let mut dev_deps = Vec::new(); for (dep_pkg_id, deps) in state.deps(unit, unit_for) { - let dep_lib = match calc_artifact_deps(unit, unit_for, dep_pkg_id, &deps, state, &mut ret)? - { - Some(lib) => lib, - None => continue, + let Some(dep_lib) = calc_artifact_deps(unit, unit_for, dep_pkg_id, &deps, state, &mut ret)? + else { + continue; }; let dep_pkg = state.get(dep_pkg_id); let mode = check_or_build_mode(unit.mode, dep_lib); @@ -412,12 +411,9 @@ fn calc_artifact_deps<'a>( let mut maybe_non_artifact_lib = false; let artifact_pkg = state.get(dep_id); for dep in deps { - let artifact = match dep.artifact() { - Some(a) => a, - None => { - maybe_non_artifact_lib = true; - continue; - } + let Some(artifact) = dep.artifact() else { + maybe_non_artifact_lib = true; + continue; }; has_artifact_lib |= artifact.is_lib(); // Custom build scripts (build/compile) never get artifact dependencies, @@ -611,9 +607,8 @@ fn compute_deps_doc( // the documentation of the library being built. let mut ret = Vec::new(); for (id, deps) in state.deps(unit, unit_for) { - let dep_lib = match calc_artifact_deps(unit, unit_for, id, &deps, state, &mut ret)? { - Some(lib) => lib, - None => continue, + let Some(dep_lib) = calc_artifact_deps(unit, unit_for, id, &deps, state, &mut ret)? else { + continue; }; let dep_pkg = state.get(id); // Rustdoc only needs rmeta files for regular dependencies. @@ -923,9 +918,8 @@ fn connect_run_custom_build_deps(state: &mut State<'_, '_>) { { // This list of dependencies all depend on `unit`, an execution of // the build script. - let reverse_deps = match reverse_deps_map.get(unit) { - Some(set) => set, - None => continue, + let Some(reverse_deps) = reverse_deps_map.get(unit) else { + continue; }; let to_add = reverse_deps diff --git a/src/cargo/core/features.rs b/src/cargo/core/features.rs index ea6560edea7..7a8d007c7e1 100644 --- a/src/cargo/core/features.rs +++ b/src/cargo/core/features.rs @@ -518,9 +518,8 @@ impl Features { ) -> CargoResult<()> { let nightly_features_allowed = self.nightly_features_allowed; let is_local = self.is_local; - let (slot, feature) = match self.status(feature_name) { - Some(p) => p, - None => bail!("unknown cargo feature `{}`", feature_name), + let Some((slot, feature)) = self.status(feature_name) else { + bail!("unknown cargo feature `{}`", feature_name) }; if *slot { @@ -823,9 +822,8 @@ fn deserialize_build_std<'de, D>(deserializer: D) -> Result>, where D: serde::Deserializer<'de>, { - let crates = match >>::deserialize(deserializer)? { - Some(list) => list, - None => return Ok(None), + let Some(crates) = >>::deserialize(deserializer)? else { + return Ok(None); }; let v = crates.join(","); Ok(Some( @@ -840,9 +838,8 @@ where D: serde::Deserializer<'de>, { use serde::de::Error; - let crates = match >>::deserialize(deserializer)? { - Some(list) => list, - None => return Ok(None), + let Some(crates) = >>::deserialize(deserializer)? else { + return Ok(None); }; parse_check_cfg(crates.into_iter()).map_err(D::Error::custom) diff --git a/src/cargo/core/package_id.rs b/src/cargo/core/package_id.rs index d1bcb448e6f..c11102017af 100644 --- a/src/cargo/core/package_id.rs +++ b/src/cargo/core/package_id.rs @@ -85,14 +85,12 @@ impl<'de> de::Deserialize<'de> for PackageId { let mut s = string.splitn(3, ' '); let name = s.next().unwrap(); let name = InternedString::new(name); - let version = match s.next() { - Some(s) => s, - None => return Err(de::Error::custom("invalid serialized PackageId")), + let Some(version) = s.next() else { + return Err(de::Error::custom("invalid serialized PackageId")); }; let version = version.to_semver().map_err(de::Error::custom)?; - let url = match s.next() { - Some(s) => s, - None => return Err(de::Error::custom("invalid serialized PackageId")), + let Some(url) = s.next() else { + return Err(de::Error::custom("invalid serialized PackageId")); }; let url = if url.starts_with('(') && url.ends_with(')') { &url[1..url.len() - 1] diff --git a/src/cargo/core/package_id_spec.rs b/src/cargo/core/package_id_spec.rs index 68561aecc7d..ec5918b0f85 100644 --- a/src/cargo/core/package_id_spec.rs +++ b/src/cargo/core/package_id_spec.rs @@ -189,55 +189,52 @@ impl PackageIdSpec { { let all_ids: Vec<_> = i.into_iter().collect(); let mut ids = all_ids.iter().copied().filter(|&id| self.matches(id)); - let ret = match ids.next() { - Some(id) => id, - None => { - let mut suggestion = String::new(); - let try_spec = |spec: PackageIdSpec, suggestion: &mut String| { - let try_matches: Vec<_> = all_ids - .iter() - .copied() - .filter(|&id| spec.matches(id)) - .collect(); - if !try_matches.is_empty() { - suggestion.push_str("\nDid you mean one of these?\n"); - minimize(suggestion, &try_matches, self); - } - }; - if self.url.is_some() { - try_spec( - PackageIdSpec { - name: self.name, - version: self.version.clone(), - url: None, - }, - &mut suggestion, - ); - } - if suggestion.is_empty() && self.version.is_some() { - try_spec( - PackageIdSpec { - name: self.name, - version: None, - url: None, - }, - &mut suggestion, - ); + let Some(ret) = ids.next() else { + let mut suggestion = String::new(); + let try_spec = |spec: PackageIdSpec, suggestion: &mut String| { + let try_matches: Vec<_> = all_ids + .iter() + .copied() + .filter(|&id| spec.matches(id)) + .collect(); + if !try_matches.is_empty() { + suggestion.push_str("\nDid you mean one of these?\n"); + minimize(suggestion, &try_matches, self); } - if suggestion.is_empty() { - suggestion.push_str(&edit_distance::closest_msg( - &self.name, - all_ids.iter(), - |id| id.name().as_str(), - )); - } - - bail!( - "package ID specification `{}` did not match any packages{}", - self, - suggestion + }; + if self.url.is_some() { + try_spec( + PackageIdSpec { + name: self.name, + version: self.version.clone(), + url: None, + }, + &mut suggestion, + ); + } + if suggestion.is_empty() && self.version.is_some() { + try_spec( + PackageIdSpec { + name: self.name, + version: None, + url: None, + }, + &mut suggestion, ); } + if suggestion.is_empty() { + suggestion.push_str(&edit_distance::closest_msg( + &self.name, + all_ids.iter(), + |id| id.name().as_str(), + )); + } + + bail!( + "package ID specification `{}` did not match any packages{}", + self, + suggestion + ); }; return match ids.next() { Some(other) => { diff --git a/src/cargo/core/profiles.rs b/src/cargo/core/profiles.rs index 5c7d3e2488e..1ad9ed5f725 100644 --- a/src/cargo/core/profiles.rs +++ b/src/cargo/core/profiles.rs @@ -1205,9 +1205,8 @@ fn merge_config_profiles( fn get_config_profile(ws: &Workspace<'_>, name: &str) -> CargoResult> { let profile: Option> = ws.config().get(&format!("profile.{}", name))?; - let profile = match profile { - Some(profile) => profile, - None => return Ok(None), + let Some(profile) = profile else { + return Ok(None); }; let mut warnings = Vec::new(); profile @@ -1239,13 +1238,11 @@ fn validate_packages_unique( name: &str, toml: &Option, ) -> CargoResult> { - let toml = match toml { - Some(ref toml) => toml, - None => return Ok(HashSet::new()), + let Some(toml) = toml else { + return Ok(HashSet::new()); }; - let overrides = match toml.package.as_ref() { - Some(overrides) => overrides, - None => return Ok(HashSet::new()), + let Some(overrides) = toml.package.as_ref() else { + return Ok(HashSet::new()); }; // Verify that a package doesn't match multiple spec overrides. let mut found = HashSet::new(); @@ -1297,9 +1294,8 @@ fn validate_packages_unmatched( toml: &TomlProfile, found: &HashSet, ) -> CargoResult<()> { - let overrides = match toml.package.as_ref() { - Some(overrides) => overrides, - None => return Ok(()), + let Some(overrides) = toml.package.as_ref() else { + return Ok(()); }; // Verify every override matches at least one package. diff --git a/src/cargo/core/resolver/dep_cache.rs b/src/cargo/core/resolver/dep_cache.rs index 8c9fcebb475..bf8b22ed7ce 100644 --- a/src/cargo/core/resolver/dep_cache.rs +++ b/src/cargo/core/resolver/dep_cache.rs @@ -481,9 +481,8 @@ impl Requirements<'_> { return Ok(()); } - let fvs = match self.summary.features().get(&feat) { - Some(fvs) => fvs, - None => return Err(RequirementError::MissingFeature(feat)), + let Some(fvs) = self.summary.features().get(&feat) else { + return Err(RequirementError::MissingFeature(feat)); }; for fv in fvs { diff --git a/src/cargo/core/resolver/encode.rs b/src/cargo/core/resolver/encode.rs index dbbe11f4e10..d0eebd41226 100644 --- a/src/cargo/core/resolver/encode.rs +++ b/src/cargo/core/resolver/encode.rs @@ -304,9 +304,8 @@ impl EncodableResolve { } for &(ref id, pkg) in live_pkgs.values() { - let deps = match pkg.dependencies { - Some(ref deps) => deps, - None => continue, + let Some(ref deps) = pkg.dependencies else { + continue; }; for edge in deps.iter() { @@ -342,9 +341,8 @@ impl EncodableResolve { let enc_id: EncodablePackageId = k .parse() .with_context(|| internal("invalid encoding of checksum in lockfile"))?; - let id = match lookup_id(&enc_id) { - Some(id) => id, - _ => continue, + let Some(id) = lookup_id(&enc_id) else { + continue; }; let v = if v == "" { @@ -468,10 +466,7 @@ fn build_path_deps(ws: &Workspace<'_>) -> CargoResult> Ok(p) => p.join("Cargo.toml"), Err(_) => return, }; - let pkg = match ws.load(&path) { - Ok(p) => p, - Err(_) => return, - }; + let Ok(pkg) = ws.load(&path) else { return }; ret.insert(pkg.name().to_string(), pkg.package_id().source_id()); visited.insert(pkg.package_id().source_id()); build_pkg(&pkg, ws, ret, visited); diff --git a/src/cargo/core/resolver/features.rs b/src/cargo/core/resolver/features.rs index b3ece7d05ab..f1c2aebcc98 100644 --- a/src/cargo/core/resolver/features.rs +++ b/src/cargo/core/resolver/features.rs @@ -610,19 +610,16 @@ impl<'a, 'cfg> FeatureResolver<'a, 'cfg> { } let summary = self.resolve.summary(pkg_id); let feature_map = summary.features(); - let fvs = match feature_map.get(&feature_to_enable) { - Some(fvs) => fvs, - None => { - // TODO: this should only happen for optional dependencies. - // Other cases should be validated by Summary's `build_feature_map`. - // Figure out some way to validate this assumption. - tracing::debug!( - "pkg {:?} does not define feature {}", - pkg_id, - feature_to_enable - ); - return Ok(()); - } + let Some(fvs) = feature_map.get(&feature_to_enable) else { + // TODO: this should only happen for optional dependencies. + // Other cases should be validated by Summary's `build_feature_map`. + // Figure out some way to validate this assumption. + tracing::debug!( + "pkg {:?} does not define feature {}", + pkg_id, + feature_to_enable + ); + return Ok(()); }; for fv in fvs { self.activate_fv(pkg_id, fk, fv)?; diff --git a/src/cargo/core/resolver/mod.rs b/src/cargo/core/resolver/mod.rs index a7923427cb6..87f7e1ee1d8 100644 --- a/src/cargo/core/resolver/mod.rs +++ b/src/cargo/core/resolver/mod.rs @@ -1031,9 +1031,8 @@ fn find_candidate( &frame.dep, frame.parent.package_id(), ); - let (candidate, has_another) = match next { - Some(pair) => pair, - None => continue, + let Some((candidate, has_another)) = next else { + continue; }; // If all members of `conflicting_activations` are still diff --git a/src/cargo/core/source_id.rs b/src/cargo/core/source_id.rs index 8424f9a3737..cec16f6e35d 100644 --- a/src/cargo/core/source_id.rs +++ b/src/cargo/core/source_id.rs @@ -401,20 +401,22 @@ impl SourceId { match self.inner.kind { SourceKind::Git(..) => Ok(Box::new(GitSource::new(self, config)?)), SourceKind::Path => { - let path = match self.inner.url.to_file_path() { - Ok(p) => p, - Err(()) => panic!("path sources cannot be remote"), - }; + let path = self + .inner + .url + .to_file_path() + .expect("path sources cannot be remote"); Ok(Box::new(PathSource::new(&path, self, config))) } SourceKind::Registry | SourceKind::SparseRegistry => Ok(Box::new( RegistrySource::remote(self, yanked_whitelist, config)?, )), SourceKind::LocalRegistry => { - let path = match self.inner.url.to_file_path() { - Ok(p) => p, - Err(()) => panic!("path sources cannot be remote"), - }; + let path = self + .inner + .url + .to_file_path() + .expect("path sources cannot be remote"); Ok(Box::new(RegistrySource::local( self, &path, @@ -423,10 +425,11 @@ impl SourceId { ))) } SourceKind::Directory => { - let path = match self.inner.url.to_file_path() { - Ok(p) => p, - Err(()) => panic!("path sources cannot be remote"), - }; + let path = self + .inner + .url + .to_file_path() + .expect("path sources cannot be remote"); Ok(Box::new(DirectorySource::new(&path, self, config))) } } diff --git a/src/cargo/core/workspace.rs b/src/cargo/core/workspace.rs index 7753b585f6e..8a45def1192 100644 --- a/src/cargo/core/workspace.rs +++ b/src/cargo/core/workspace.rs @@ -663,18 +663,15 @@ impl<'cfg> Workspace<'cfg> { /// will transitively follow all `path` dependencies looking for members of /// the workspace. fn find_members(&mut self) -> CargoResult<()> { - let workspace_config = match self.load_workspace_config()? { - Some(workspace_config) => workspace_config, - None => { - debug!("find_members - only me as a member"); - self.members.push(self.current_manifest.clone()); - self.default_members.push(self.current_manifest.clone()); - if let Ok(pkg) = self.current() { - let id = pkg.package_id(); - self.member_ids.insert(id); - } - return Ok(()); + let Some(workspace_config) = self.load_workspace_config()? else { + debug!("find_members - only me as a member"); + self.members.push(self.current_manifest.clone()); + self.default_members.push(self.current_manifest.clone()); + if let Ok(pkg) = self.current() { + let id = pkg.package_id(); + self.member_ids.insert(id); } + return Ok(()); }; // self.root_manifest must be Some to have retrieved workspace_config @@ -1693,9 +1690,8 @@ impl WorkspaceRootConfig { } fn expand_member_path(path: &Path) -> CargoResult> { - let path = match path.to_str() { - Some(p) => p, - None => return Ok(Vec::new()), + let Some(path) = path.to_str() else { + return Ok(Vec::new()); }; let res = glob(path).with_context(|| format!("could not parse pattern `{}`", &path))?; let res = res diff --git a/src/cargo/ops/cargo_add/mod.rs b/src/cargo/ops/cargo_add/mod.rs index 2fbc3233864..93a00136fcb 100644 --- a/src/cargo/ops/cargo_add/mod.rs +++ b/src/cargo/ops/cargo_add/mod.rs @@ -502,9 +502,7 @@ fn get_existing_dependency( }) .collect(); possible.sort_by_key(|(key, _)| *key); - let (key, dep) = if let Some(item) = possible.pop() { - item - } else { + let Some((key, dep)) = possible.pop() else { return Ok(None); }; let mut dep = dep?; @@ -984,9 +982,8 @@ fn print_dep_table_msg(shell: &mut Shell, dep: &DependencyUI) -> CargoResult<()> // Based on Iterator::is_sorted from nightly std; remove in favor of that when stabilized. fn is_sorted(mut it: impl Iterator) -> bool { - let mut last = match it.next() { - Some(e) => e, - None => return true, + let Some(mut last) = it.next() else { + return true; }; for curr in it { diff --git a/src/cargo/ops/cargo_compile/mod.rs b/src/cargo/ops/cargo_compile/mod.rs index ba677032d70..1a40e22705d 100644 --- a/src/cargo/ops/cargo_compile/mod.rs +++ b/src/cargo/ops/cargo_compile/mod.rs @@ -489,9 +489,8 @@ pub fn create_bcx<'a, 'cfg>( ); for unit in unit_graph.keys() { - let version = match unit.pkg.rust_version() { - Some(v) => v, - None => continue, + let Some(version) = unit.pkg.rust_version() else { + continue; }; let req = version.caret_req(); diff --git a/src/cargo/ops/cargo_generate_lockfile.rs b/src/cargo/ops/cargo_generate_lockfile.rs index 5b5f177b187..a83a92ccccf 100644 --- a/src/cargo/ops/cargo_generate_lockfile.rs +++ b/src/cargo/ops/cargo_generate_lockfile.rs @@ -204,9 +204,8 @@ pub fn update_lockfile(ws: &Workspace<'_>, opts: &UpdateOptions<'_>) -> CargoRes .filter(|a| { // If this package ID is not found in `b`, then it's definitely // in the subtracted set. - let i = match b.binary_search(a) { - Ok(i) => i, - Err(..) => return true, + let Ok(i) = b.binary_search(a) else { + return true; }; // If we've found `a` in `b`, then we iterate over all instances diff --git a/src/cargo/ops/cargo_package.rs b/src/cargo/ops/cargo_package.rs index 2f9f770be51..4bdc150b886 100644 --- a/src/cargo/ops/cargo_package.rs +++ b/src/cargo/ops/cargo_package.rs @@ -994,17 +994,15 @@ fn report_hash_difference(orig: &HashMap, after: &HashMap CargoResult<()> { - let name = match file.file_name() { - Some(name) => name, - None => return Ok(()), + let Some(name) = file.file_name() else { + return Ok(()); }; - let name = match name.to_str() { - Some(name) => name, - None => anyhow::bail!( + let Some(name) = name.to_str() else { + anyhow::bail!( "path does not have a unicode filename which may not unpack \ on all platforms: {}", file.display() - ), + ) }; let bad_chars = ['/', '\\', '<', '>', ':', '"', '|', '?', '*']; if let Some(c) = bad_chars.iter().find(|c| name.contains(**c)) { diff --git a/src/cargo/ops/cargo_pkgid.rs b/src/cargo/ops/cargo_pkgid.rs index eeed6ac0206..bbae154a736 100644 --- a/src/cargo/ops/cargo_pkgid.rs +++ b/src/cargo/ops/cargo_pkgid.rs @@ -3,9 +3,8 @@ use crate::ops; use crate::util::CargoResult; pub fn pkgid(ws: &Workspace<'_>, spec: Option<&str>) -> CargoResult { - let resolve = match ops::load_pkg_lockfile(ws)? { - Some(resolve) => resolve, - None => anyhow::bail!("a Cargo.lock must exist for this command"), + let Some(resolve) = ops::load_pkg_lockfile(ws)? else { + anyhow::bail!("a Cargo.lock must exist for this command") }; let pkgid = match spec { diff --git a/src/cargo/ops/fix.rs b/src/cargo/ops/fix.rs index 2cae411a070..9d645929426 100644 --- a/src/cargo/ops/fix.rs +++ b/src/cargo/ops/fix.rs @@ -920,15 +920,12 @@ impl FixArgs { /// Validates the edition, and sends a message indicating what is being /// done. Returns a flag indicating whether this fix should be run. fn can_run_rustfix(&self, config: &Config) -> CargoResult { - let to_edition = match self.prepare_for_edition { - Some(s) => s, - None => { - return Message::Fixing { - file: self.file.display().to_string(), - } - .post(config) - .and(Ok(true)); + let Some(to_edition) = self.prepare_for_edition else { + return Message::Fixing { + file: self.file.display().to_string(), } + .post(config) + .and(Ok(true)); }; // Unfortunately determining which cargo targets are being built // isn't easy, and each target can be a different edition. The diff --git a/src/cargo/ops/registry/yank.rs b/src/cargo/ops/registry/yank.rs index 8a961b990e7..d286093b6fd 100644 --- a/src/cargo/ops/registry/yank.rs +++ b/src/cargo/ops/registry/yank.rs @@ -30,9 +30,8 @@ pub fn yank( ws.current()?.package_id().name().to_string() } }; - let version = match version { - Some(v) => v, - None => bail!("a version must be specified to yank"), + let Some(version) = version else { + bail!("a version must be specified to yank") }; let message = if undo { diff --git a/src/cargo/ops/resolve.rs b/src/cargo/ops/resolve.rs index 0d9f11068c6..a690bd69a5e 100644 --- a/src/cargo/ops/resolve.rs +++ b/src/cargo/ops/resolve.rs @@ -329,15 +329,12 @@ pub fn resolve_with_previous<'cfg>( for patch in patches { version_prefs.prefer_dependency(patch.clone()); } - let previous = match previous { - Some(r) => r, - None => { - let patches: Vec<_> = patches.iter().map(|p| (p, None)).collect(); - let unlock_ids = registry.patch(url, &patches)?; - // Since nothing is locked, this shouldn't possibly return anything. - assert!(unlock_ids.is_empty()); - continue; - } + let Some(previous) = previous else { + let patches: Vec<_> = patches.iter().map(|p| (p, None)).collect(); + let unlock_ids = registry.patch(url, &patches)?; + // Since nothing is locked, this shouldn't possibly return anything. + assert!(unlock_ids.is_empty()); + continue; }; // This is a list of pairs where the first element of the pair is @@ -539,9 +536,8 @@ pub fn add_overrides<'a>( ws: &Workspace<'a>, ) -> CargoResult<()> { let config = ws.config(); - let paths = match config.get_list("paths")? { - Some(list) => list, - None => return Ok(()), + let Some(paths) = config.get_list("paths")? else { + return Ok(()); }; let paths = paths.val.iter().map(|(s, def)| { diff --git a/src/cargo/ops/tree/graph.rs b/src/cargo/ops/tree/graph.rs index f0dad4e5d3f..31276f10416 100644 --- a/src/cargo/ops/tree/graph.rs +++ b/src/cargo/ops/tree/graph.rs @@ -598,9 +598,8 @@ fn add_feature_rec( package_index: usize, ) { let feature_map = resolve.summary(package_id).features(); - let fvs = match feature_map.get(&feature_name) { - Some(fvs) => fvs, - None => return, + let Some(fvs) = feature_map.get(&feature_name) else { + return; }; for fv in fvs { match fv { diff --git a/src/cargo/sources/config.rs b/src/cargo/sources/config.rs index ebe43906219..f0c214e16d6 100644 --- a/src/cargo/sources/config.rs +++ b/src/cargo/sources/config.rs @@ -135,30 +135,26 @@ impl<'cfg> SourceConfigMap<'cfg> { ) -> CargoResult> { debug!("loading: {}", id); - let mut name = match self.id2name.get(&id) { - Some(name) => name, - None => return id.load(self.config, yanked_whitelist), + let Some(mut name) = self.id2name.get(&id) else { + return id.load(self.config, yanked_whitelist); }; let mut cfg_loc = ""; let orig_name = name; let new_id = loop { - let cfg = match self.cfgs.get(name) { - Some(cfg) => cfg, - None => { - // Attempt to interpret the source name as an alt registry name - if let Ok(alt_id) = SourceId::alt_registry(self.config, name) { - debug!("following pointer to registry {}", name); - break alt_id.with_precise(id.precise().map(str::to_string)); - } - bail!( - "could not find a configured source with the \ + let Some(cfg) = self.cfgs.get(name) else { + // Attempt to interpret the source name as an alt registry name + if let Ok(alt_id) = SourceId::alt_registry(self.config, name) { + debug!("following pointer to registry {}", name); + break alt_id.with_precise(id.precise().map(str::to_string)); + } + bail!( + "could not find a configured source with the \ name `{}` when attempting to lookup `{}` \ (configuration in `{}`)", - name, - orig_name, - cfg_loc - ); - } + name, + orig_name, + cfg_loc + ); }; match &cfg.replace_with { Some((s, c)) => { diff --git a/src/cargo/sources/directory.rs b/src/cargo/sources/directory.rs index 91c7802f22b..7195fd72d65 100644 --- a/src/cargo/sources/directory.rs +++ b/src/cargo/sources/directory.rs @@ -223,9 +223,8 @@ impl<'cfg> Source for DirectorySource<'cfg> { } fn verify(&self, id: PackageId) -> CargoResult<()> { - let (pkg, cksum) = match self.packages.get(&id) { - Some(&(ref pkg, ref cksum)) => (pkg, cksum), - None => anyhow::bail!("failed to find entry for `{}` in directory source", id), + let Some((pkg, cksum)) = self.packages.get(&id) else { + anyhow::bail!("failed to find entry for `{}` in directory source", id); }; for (file, cksum) in cksum.files.iter() { diff --git a/src/cargo/sources/git/utils.rs b/src/cargo/sources/git/utils.rs index 09363109184..2422bf631be 100644 --- a/src/cargo/sources/git/utils.rs +++ b/src/cargo/sources/git/utils.rs @@ -444,9 +444,8 @@ impl<'a> GitCheckout<'a> { // A submodule which is listed in .gitmodules but not actually // checked out will not have a head id, so we should ignore it. - let head = match child.head_id() { - Some(head) => head, - None => return Ok(()), + let Some(head) = child.head_id() else { + return Ok(()); }; // If the submodule hasn't been checked out yet, we need to @@ -1313,16 +1312,12 @@ fn maybe_gc_repo(repo: &mut git2::Repository, config: &Config) -> CargoResult<() /// filenames, so they never get cleaned up. fn clean_repo_temp_files(repo: &git2::Repository) { let path = repo.path().join("objects/pack/pack_git2_*"); - let pattern = match path.to_str() { - Some(p) => p, - None => { - tracing::warn!("cannot convert {path:?} to a string"); - return; - } + let Some(pattern) = path.to_str() else { + tracing::warn!("cannot convert {path:?} to a string"); + return; }; - let paths = match glob::glob(pattern) { - Ok(paths) => paths, - Err(_) => return, + let Ok(paths) = glob::glob(pattern) else { + return; }; for path in paths { if let Ok(path) = path { diff --git a/src/cargo/sources/path.rs b/src/cargo/sources/path.rs index 8c54514fa13..0cc6399766e 100644 --- a/src/cargo/sources/path.rs +++ b/src/cargo/sources/path.rs @@ -175,9 +175,8 @@ impl<'cfg> PathSource<'cfg> { }; let filter = |path: &Path, is_dir: bool| { - let relative_path = match path.strip_prefix(root) { - Ok(p) => p, - Err(_) => return false, + let Ok(relative_path) = path.strip_prefix(root) else { + return false; }; let rel = relative_path.as_os_str(); diff --git a/src/cargo/sources/registry/remote.rs b/src/cargo/sources/registry/remote.rs index aa6ebb94d30..78bf9affc94 100644 --- a/src/cargo/sources/registry/remote.rs +++ b/src/cargo/sources/registry/remote.rs @@ -269,9 +269,8 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> { } let object = entry.to_object(repo)?; - let blob = match object.as_blob() { - Some(blob) => blob, - None => anyhow::bail!("path `{}` is not a blob in the git repo", path.display()), + let Some(blob) = object.as_blob() else { + anyhow::bail!("path `{}` is not a blob in the git repo", path.display()) }; Ok(LoadResponse::Data { diff --git a/src/cargo/util/config/mod.rs b/src/cargo/util/config/mod.rs index 1037e47a903..d6fba5db9de 100644 --- a/src/cargo/util/config/mod.rs +++ b/src/cargo/util/config/mod.rs @@ -622,9 +622,8 @@ impl Config { ))); } let mut parts = key.parts().enumerate(); - let mut val = match vals.get(parts.next().unwrap().1) { - Some(val) => val, - None => return Ok(None), + let Some(mut val) = vals.get(parts.next().unwrap().1) else { + return Ok(None); }; for (i, part) in parts { match val { @@ -906,12 +905,9 @@ impl Config { key: &ConfigKey, output: &mut Vec<(String, Definition)>, ) -> CargoResult<()> { - let env_val = match self.env.get_str(key.as_env_key()) { - Some(v) => v, - None => { - self.check_environment_key_case_mismatch(key); - return Ok(()); - } + let Some(env_val) = self.env.get_str(key.as_env_key()) else { + self.check_environment_key_case_mismatch(key); + return Ok(()); }; let def = Definition::Environment(key.as_env_key().to_string()); @@ -1261,9 +1257,8 @@ impl Config { }; (path.to_string(), abs_path, def.clone()) }; - let table = match cv { - CV::Table(table, _def) => table, - _ => unreachable!(), + let CV::Table(table, _def) = cv else { + unreachable!() }; let owned; let include = if remove { @@ -1302,9 +1297,8 @@ impl Config { /// Parses the CLI config args and returns them as a table. pub(crate) fn cli_args_as_table(&self) -> CargoResult { let mut loaded_args = CV::Table(HashMap::new(), Definition::Cli(None)); - let cli_args = match &self.cli_config { - Some(cli_args) => cli_args, - None => return Ok(loaded_args), + let Some(cli_args) = &self.cli_config else { + return Ok(loaded_args); }; let mut seen = HashSet::new(); for arg in cli_args { @@ -1450,9 +1444,8 @@ impl Config { /// Add config arguments passed on the command line. fn merge_cli_args(&mut self) -> CargoResult<()> { - let loaded_map = match self.cli_args_as_table()? { - CV::Table(table, _def) => table, - _ => unreachable!(), + let CV::Table(loaded_map, _def) = self.cli_args_as_table()? else { + unreachable!() }; let values = self.values_mut()?; for (key, value) in loaded_map.into_iter() { @@ -1596,17 +1589,15 @@ impl Config { } let home_path = self.home_path.clone().into_path_unlocked(); - let credentials = match self.get_file_path(&home_path, "credentials", true)? { - Some(credentials) => credentials, - None => return Ok(()), + let Some(credentials) = self.get_file_path(&home_path, "credentials", true)? else { + return Ok(()); }; let mut value = self.load_file(&credentials)?; // Backwards compatibility for old `.cargo/credentials` layout. { - let (value_map, def) = match value { - CV::Table(ref mut value, ref def) => (value, def), - _ => unreachable!(), + let CV::Table(ref mut value_map, ref def) = value else { + unreachable!(); }; if let Some(token) = value_map.remove("token") { diff --git a/src/cargo/util/dependency_queue.rs b/src/cargo/util/dependency_queue.rs index 33e8bf28e84..5650f4b251e 100644 --- a/src/cargo/util/dependency_queue.rs +++ b/src/cargo/util/dependency_queue.rs @@ -181,9 +181,8 @@ impl DependencyQueue { pub fn finish(&mut self, node: &N, edge: &E) -> Vec<&N> { // hashset let reverse_deps = self.reverse_dep_map.get(node).and_then(|map| map.get(edge)); - let reverse_deps = match reverse_deps { - Some(deps) => deps, - None => return Vec::new(), + let Some(reverse_deps) = reverse_deps else { + return Vec::new(); }; let key = (node.clone(), edge.clone()); let mut result = Vec::new(); diff --git a/src/cargo/util/flock.rs b/src/cargo/util/flock.rs index 32ad2c90b34..aa056c96579 100644 --- a/src/cargo/util/flock.rs +++ b/src/cargo/util/flock.rs @@ -325,9 +325,8 @@ fn acquire( use std::mem; use std::os::unix::prelude::*; - let path = match CString::new(path.as_os_str().as_bytes()) { - Ok(path) => path, - Err(_) => return false, + let Ok(path) = CString::new(path.as_os_str().as_bytes()) else { + return false; }; unsafe { diff --git a/src/cargo/util/profile.rs b/src/cargo/util/profile.rs index 29b110492bf..ede8db1913b 100644 --- a/src/cargo/util/profile.rs +++ b/src/cargo/util/profile.rs @@ -43,9 +43,8 @@ pub fn start(desc: T) -> Profiler { impl Drop for Profiler { fn drop(&mut self) { - let enabled = match enabled_level() { - Some(i) => i, - None => return, + let Some(enabled) = enabled_level() else { + return; }; let (start, stack_len) = PROFILE_STACK.with(|stack| { diff --git a/src/cargo/util/progress.rs b/src/cargo/util/progress.rs index bcbc1bc0edc..374f782bb34 100644 --- a/src/cargo/util/progress.rs +++ b/src/cargo/util/progress.rs @@ -160,9 +160,8 @@ impl<'cfg> Progress<'cfg> { /// This may not actually update the display if `tick` is being called too /// quickly. pub fn tick(&mut self, cur: usize, max: usize, msg: &str) -> CargoResult<()> { - let s = match &mut self.state { - Some(s) => s, - None => return Ok(()), + let Some(s) = &mut self.state else { + return Ok(()); }; // Don't update too often as it can cause excessive performance loss @@ -340,9 +339,8 @@ impl Format { ProgressStyle::Indeterminate => String::new(), }; let extra_len = stats.len() + 2 /* [ and ] */ + 15 /* status header */; - let display_width = match self.width().checked_sub(extra_len) { - Some(n) => n, - None => return None, + let Some(display_width) = self.width().checked_sub(extra_len) else { + return None; }; let mut string = String::with_capacity(self.max_width); diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index 4e2002f8f24..a3797c1792a 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -1760,10 +1760,7 @@ impl TomlManifest { deps: Option<&BTreeMap>, filter: impl Fn(&TomlDependency) -> bool, ) -> CargoResult>> { - let deps = match deps { - Some(deps) => deps, - None => return Ok(None), - }; + let Some(deps) = deps else { return Ok(None) }; let deps = deps .iter() .filter(|(_k, v)| { @@ -2071,9 +2068,8 @@ impl TomlManifest { workspace_config: &WorkspaceConfig, inherit_cell: &LazyCell, ) -> CargoResult>> { - let dependencies = match new_deps { - Some(dependencies) => dependencies, - None => return Ok(None), + let Some(dependencies) = new_deps else { + return Ok(None); }; let inheritable = || { diff --git a/src/cargo/util/toml/targets.rs b/src/cargo/util/toml/targets.rs index a7e30c61bce..720ae495c7e 100644 --- a/src/cargo/util/toml/targets.rs +++ b/src/cargo/util/toml/targets.rs @@ -171,10 +171,7 @@ fn clean_lib( }), }; - let lib = match lib { - Some(ref lib) => lib, - None => return Ok(None), - }; + let Some(ref lib) = lib else { return Ok(None) }; lib.validate_proc_macro(warnings); lib.validate_crate_types("library", warnings); From 84456a0a7ed1f45a83e893d296390a4e2226be39 Mon Sep 17 00:00:00 2001 From: Jacob Finkelman Date: Wed, 13 Sep 2023 20:00:37 +0000 Subject: [PATCH 2/6] use copied where clippy::map_clone --- src/cargo/util/auth/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cargo/util/auth/mod.rs b/src/cargo/util/auth/mod.rs index cc8128d6ca4..0d522d58686 100644 --- a/src/cargo/util/auth/mod.rs +++ b/src/cargo/util/auth/mod.rs @@ -493,7 +493,7 @@ fn credential_action( let args: Vec<&str> = provider .iter() .map(String::as_str) - .chain(args.iter().map(|s| *s)) + .chain(args.iter().copied()) .collect(); let process = args[0]; tracing::debug!("attempting credential provider: {args:?}"); From 0ed01489d8d29d5335bd8b66899c988dd7386693 Mon Sep 17 00:00:00 2001 From: Jacob Finkelman Date: Wed, 13 Sep 2023 20:14:06 +0000 Subject: [PATCH 3/6] remove ref where needless_borrowed_reference --- src/cargo/core/compiler/custom_build.rs | 2 +- src/cargo/core/compiler/mod.rs | 2 +- src/cargo/core/resolver/dep_cache.rs | 8 ++++---- src/cargo/core/resolver/encode.rs | 4 ++-- src/cargo/core/resolver/mod.rs | 6 ++---- src/cargo/core/workspace.rs | 6 +++--- src/cargo/ops/cargo_compile/mod.rs | 4 ++-- src/cargo/ops/resolve.rs | 4 ++-- src/cargo/util/toml/targets.rs | 6 +++--- 9 files changed, 20 insertions(+), 22 deletions(-) diff --git a/src/cargo/core/compiler/custom_build.rs b/src/cargo/core/compiler/custom_build.rs index 427656f8e84..df658e95e5a 100644 --- a/src/cargo/core/compiler/custom_build.rs +++ b/src/cargo/core/compiler/custom_build.rs @@ -443,7 +443,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult { )) })?; let data = &script_output.metadata; - for &(ref key, ref value) in data.iter() { + for (key, value) in data.iter() { cmd.env( &format!("DEP_{}_{}", super::envify(&name), super::envify(key)), value, diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs index a847d2cc1e7..9508a0804d1 100644 --- a/src/cargo/core/compiler/mod.rs +++ b/src/cargo/core/compiler/mod.rs @@ -1318,7 +1318,7 @@ fn add_custom_flags( cmd.arg("--check-cfg").arg(check_cfg); } } - for &(ref name, ref value) in output.env.iter() { + for (name, value) in output.env.iter() { cmd.env(name, value); } } diff --git a/src/cargo/core/resolver/dep_cache.rs b/src/cargo/core/resolver/dep_cache.rs index bf8b22ed7ce..f4e1cfc126f 100644 --- a/src/cargo/core/resolver/dep_cache.rs +++ b/src/cargo/core/resolver/dep_cache.rs @@ -128,9 +128,9 @@ impl<'a> RegistryQueryer<'a> { let mut potential_matches = self .replacements .iter() - .filter(|&&(ref spec, _)| spec.matches(summary.package_id())); + .filter(|(spec, _)| spec.matches(summary.package_id())); - let &(ref spec, ref dep) = match potential_matches.next() { + let (spec, dep) = match potential_matches.next() { None => continue, Some(replacement) => replacement, }; @@ -188,7 +188,7 @@ impl<'a> RegistryQueryer<'a> { let matched_spec = spec.clone(); // Make sure no duplicates - if let Some(&(ref spec, _)) = potential_matches.next() { + if let Some((spec, _)) = potential_matches.next() { return Poll::Ready(Err(anyhow::anyhow!( "overlapping replacement specifications found:\n\n \ * {}\n * {}\n\nboth specifications match: {}", @@ -278,7 +278,7 @@ impl<'a> RegistryQueryer<'a> { // dependencies with more candidates. This way if the dependency with // only one candidate can't be resolved we don't have to do a bunch of // work before we figure that out. - deps.sort_by_key(|&(_, ref a, _)| a.len()); + deps.sort_by_key(|(_, a, _)| a.len()); let out = Rc::new((used_features, Rc::new(deps))); diff --git a/src/cargo/core/resolver/encode.rs b/src/cargo/core/resolver/encode.rs index d0eebd41226..7835c22197c 100644 --- a/src/cargo/core/resolver/encode.rs +++ b/src/cargo/core/resolver/encode.rs @@ -299,7 +299,7 @@ impl EncodableResolve { let mut g = Graph::new(); - for &(ref id, _) in live_pkgs.values() { + for (id, _) in live_pkgs.values() { g.add(*id); } @@ -435,7 +435,7 @@ fn build_path_deps(ws: &Workspace<'_>) -> CargoResult> build_dep(dep, ws, &mut ret, &mut visited); } } - for &(_, ref dep) in ws.root_replace() { + for (_, dep) in ws.root_replace() { build_dep(dep, ws, &mut ret, &mut visited); } diff --git a/src/cargo/core/resolver/mod.rs b/src/cargo/core/resolver/mod.rs index 87f7e1ee1d8..9e7d41f60cd 100644 --- a/src/cargo/core/resolver/mod.rs +++ b/src/cargo/core/resolver/mod.rs @@ -234,7 +234,7 @@ fn activate_deps_loop( let mut past_conflicting_activations = conflict_cache::ConflictCache::new(); // Activate all the initial summaries to kick off some work. - for &(ref summary, ref opts) in summaries { + for (summary, opts) in summaries { debug!("initial activation: {}", summary.package_id()); let res = activate( &mut cx, @@ -514,9 +514,7 @@ fn activate_deps_loop( if let Some((other_parent, conflict)) = remaining_deps .iter() // for deps related to us - .filter(|&(_, ref other_dep)| { - known_related_bad_deps.contains(other_dep) - }) + .filter(|(_, other_dep)| known_related_bad_deps.contains(other_dep)) .filter_map(|(other_parent, other_dep)| { past_conflicting_activations .find_conflicting(&cx, &other_dep, Some(pid)) diff --git a/src/cargo/core/workspace.rs b/src/cargo/core/workspace.rs index 8a45def1192..2d41e095625 100644 --- a/src/cargo/core/workspace.rs +++ b/src/cargo/core/workspace.rs @@ -510,7 +510,7 @@ impl<'cfg> Workspace<'cfg> { self.members .iter() .filter_map(move |path| match packages.get(path) { - &MaybePackage::Package(ref p) => Some(p), + MaybePackage::Package(p) => Some(p), _ => None, }) } @@ -541,7 +541,7 @@ impl<'cfg> Workspace<'cfg> { self.default_members .iter() .filter_map(move |path| match packages.get(path) { - &MaybePackage::Package(ref p) => Some(p), + MaybePackage::Package(p) => Some(p), _ => None, }) } @@ -1046,7 +1046,7 @@ impl<'cfg> Workspace<'cfg> { pub fn load(&self, manifest_path: &Path) -> CargoResult { match self.packages.maybe_get(manifest_path) { - Some(&MaybePackage::Package(ref p)) => return Ok(p.clone()), + Some(MaybePackage::Package(p)) => return Ok(p.clone()), Some(&MaybePackage::Virtual(_)) => bail!("cannot load workspace root"), None => {} } diff --git a/src/cargo/ops/cargo_compile/mod.rs b/src/cargo/ops/cargo_compile/mod.rs index 1a40e22705d..bd8c4fbfa85 100644 --- a/src/cargo/ops/cargo_compile/mod.rs +++ b/src/cargo/ops/cargo_compile/mod.rs @@ -318,8 +318,8 @@ pub fn create_bcx<'a, 'cfg>( } let (extra_args, extra_args_name) = match (target_rustc_args, target_rustdoc_args) { - (&Some(ref args), _) => (Some(args.clone()), "rustc"), - (_, &Some(ref args)) => (Some(args.clone()), "rustdoc"), + (Some(args), _) => (Some(args.clone()), "rustc"), + (_, Some(args)) => (Some(args.clone()), "rustdoc"), _ => (None, ""), }; diff --git a/src/cargo/ops/resolve.rs b/src/cargo/ops/resolve.rs index a690bd69a5e..934eb3571d4 100644 --- a/src/cargo/ops/resolve.rs +++ b/src/cargo/ops/resolve.rs @@ -153,7 +153,7 @@ pub fn resolve_ws_with_opts<'cfg>( add_overrides(&mut registry, ws)?; - for &(ref replace_spec, ref dep) in ws.root_replace() { + for (replace_spec, dep) in ws.root_replace() { if !resolve .iter() .any(|r| replace_spec.matches(r) && !dep.matches_id(r)) @@ -486,7 +486,7 @@ pub fn resolve_with_previous<'cfg>( let replace = match previous { Some(r) => root_replace .iter() - .map(|&(ref spec, ref dep)| { + .map(|(spec, dep)| { for (&key, &val) in r.replacements().iter() { if spec.matches(key) && dep.matches_id(val) && keep(&val) { let mut dep = dep.clone(); diff --git a/src/cargo/util/toml/targets.rs b/src/cargo/util/toml/targets.rs index 720ae495c7e..afc4f258f69 100644 --- a/src/cargo/util/toml/targets.rs +++ b/src/cargo/util/toml/targets.rs @@ -744,7 +744,7 @@ https://github.com/rust-lang/cargo/issues/5330", fn inferred_to_toml_targets(inferred: &[(String, PathBuf)]) -> Vec { inferred .iter() - .map(|&(ref name, ref path)| TomlTarget { + .map(|(name, path)| TomlTarget { name: Some(name.clone()), path: Some(PathValue(path.clone())), ..TomlTarget::new() @@ -926,8 +926,8 @@ fn target_path( let mut matching = inferred .iter() - .filter(|&&(ref n, _)| n == &name) - .map(|&(_, ref p)| p.clone()); + .filter(|(n, _)| n == &name) + .map(|(_, p)| p.clone()); let first = matching.next(); let second = matching.next(); From 0a6f67109cd7d39b5b46d7d3e5863fc3a743fe13 Mon Sep 17 00:00:00 2001 From: Jacob Finkelman Date: Wed, 13 Sep 2023 20:19:57 +0000 Subject: [PATCH 4/6] remove as_ref where clippy::useless_asref --- src/cargo/ops/cargo_package.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cargo/ops/cargo_package.rs b/src/cargo/ops/cargo_package.rs index 4bdc150b886..1a82cbd6b5b 100644 --- a/src/cargo/ops/cargo_package.rs +++ b/src/cargo/ops/cargo_package.rs @@ -237,7 +237,7 @@ fn build_ar_list( let rel_str = rel_path.to_str().ok_or_else(|| { anyhow::format_err!("non-utf8 path in source directory: {}", rel_path.display()) })?; - match rel_str.as_ref() { + match rel_str { "Cargo.lock" => continue, VCS_INFO_FILE | ORIGINAL_MANIFEST_FILE => anyhow::bail!( "invalid inclusion of reserved file name {} in package source", From 97bf02bef3b50a8863dc54140a73f3d044bf8db7 Mon Sep 17 00:00:00 2001 From: Jacob Finkelman Date: Wed, 13 Sep 2023 20:24:49 +0000 Subject: [PATCH 5/6] Use Rc insted of Arc when clippy::arc_with_non_send_sync --- src/cargo/core/compiler/build_config.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cargo/core/compiler/build_config.rs b/src/cargo/core/compiler/build_config.rs index 5d4d754bff1..f091df2ad84 100644 --- a/src/cargo/core/compiler/build_config.rs +++ b/src/cargo/core/compiler/build_config.rs @@ -7,7 +7,7 @@ use cargo_util::ProcessBuilder; use serde::ser; use std::cell::RefCell; use std::path::PathBuf; -use std::sync::Arc; +use std::rc::Rc; use std::thread::available_parallelism; /// Configuration information for a rustc build. @@ -35,7 +35,7 @@ pub struct BuildConfig { pub primary_unit_rustc: Option, /// A thread used by `cargo fix` to receive messages on a socket regarding /// the success/failure of applying fixes. - pub rustfix_diagnostic_server: Arc>>, + pub rustfix_diagnostic_server: Rc>>, /// The directory to copy final artifacts to. Note that even if `out_dir` is /// set, a copy of artifacts still could be found a `target/(debug\release)` /// as usual. @@ -113,7 +113,7 @@ impl BuildConfig { build_plan: false, unit_graph: false, primary_unit_rustc: None, - rustfix_diagnostic_server: Arc::new(RefCell::new(None)), + rustfix_diagnostic_server: Rc::new(RefCell::new(None)), export_dir: None, future_incompat_report: false, timing_outputs: Vec::new(), From afe5333d86632a887090b8a220885004f464cb95 Mon Sep 17 00:00:00 2001 From: Jacob Finkelman Date: Wed, 13 Sep 2023 20:32:33 +0000 Subject: [PATCH 6/6] Remove most clone where clippy::clone_on_copy --- src/cargo/core/compiler/fingerprint/mod.rs | 14 ++++++-------- src/cargo/util/toml/mod.rs | 8 ++++---- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/cargo/core/compiler/fingerprint/mod.rs b/src/cargo/core/compiler/fingerprint/mod.rs index c8bf23c8632..08474448083 100644 --- a/src/cargo/core/compiler/fingerprint/mod.rs +++ b/src/cargo/core/compiler/fingerprint/mod.rs @@ -1037,16 +1037,16 @@ impl Fingerprint { for (a, b) in self.deps.iter().zip(old.deps.iter()) { if a.name != b.name { return DirtyReason::UnitDependencyNameChanged { - old: b.name.clone(), - new: a.name.clone(), + old: b.name, + new: a.name, }; } if a.fingerprint.hash_u64() != b.fingerprint.hash_u64() { return DirtyReason::UnitDependencyInfoChanged { - new_name: a.name.clone(), + new_name: a.name, new_fingerprint: a.fingerprint.hash_u64(), - old_name: b.name.clone(), + old_name: b.name, old_fingerprint: b.fingerprint.hash_u64(), }; } @@ -1122,9 +1122,7 @@ impl Fingerprint { | FsStatus::StaleItem(_) | FsStatus::StaleDependency { .. } | FsStatus::StaleDepFingerprint { .. } => { - self.fs_status = FsStatus::StaleDepFingerprint { - name: dep.name.clone(), - }; + self.fs_status = FsStatus::StaleDepFingerprint { name: dep.name }; return Ok(()); } }; @@ -1166,7 +1164,7 @@ impl Fingerprint { ); self.fs_status = FsStatus::StaleDependency { - name: dep.name.clone(), + name: dep.name, dep_mtime: *dep_mtime, max_mtime: *max_mtime, }; diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index a3797c1792a..ebd56fa884d 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -800,8 +800,8 @@ impl TomlProfile { self.codegen_units = Some(v); } - if let Some(v) = &profile.debug { - self.debug = Some(v.clone()); + if let Some(v) = profile.debug { + self.debug = Some(v); } if let Some(v) = profile.debug_assertions { @@ -1978,7 +1978,7 @@ impl TomlManifest { ) } } - Some(rust_version.clone()) + Some(rust_version) } else { None }; @@ -2358,7 +2358,7 @@ impl TomlManifest { .categories .as_ref() .map(|_| MaybeWorkspace::Defined(metadata.categories.clone())); - package.rust_version = rust_version.clone().map(|rv| MaybeWorkspace::Defined(rv)); + package.rust_version = rust_version.map(|rv| MaybeWorkspace::Defined(rv)); package.exclude = package .exclude .as_ref()