diff --git a/src/cli/common.rs b/src/cli/common.rs index cc554a38df..a4db27ee75 100644 --- a/src/cli/common.rs +++ b/src/cli/common.rs @@ -368,7 +368,7 @@ where before_restart()?; - if let Some(ref setup_path) = setup_path { + if let Some(setup_path) = &setup_path { return self_update::run_update(setup_path); } else { // Try again in case we emitted "tool `{}` is already installed" last time. diff --git a/src/cli/rustup_mode.rs b/src/cli/rustup_mode.rs index 92faef6044..b113d6c495 100644 --- a/src/cli/rustup_mode.rs +++ b/src/cli/rustup_mode.rs @@ -1,10 +1,12 @@ -use std::borrow::Cow; -use std::env::consts::EXE_SUFFIX; -use std::fmt; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::ExitStatus; -use std::str::FromStr; +use std::{ + borrow::Cow, + env::consts::EXE_SUFFIX, + fmt, + io::{self, Write}, + path::{Path, PathBuf}, + process::ExitStatus, + str::FromStr, +}; use anyhow::{Context, Error, Result, anyhow}; use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum, builder::PossibleValue}; @@ -49,10 +51,10 @@ fn handle_epipe(res: Result) -> Result { match res { Err(e) => { let root = e.root_cause(); - if let Some(io_err) = root.downcast_ref::() { - if io_err.kind() == std::io::ErrorKind::BrokenPipe { - return Ok(utils::ExitCode(0)); - } + if let Some(io_err) = root.downcast_ref::() + && io_err.kind() == io::ErrorKind::BrokenPipe + { + return Ok(utils::ExitCode(0)); } Err(e) } @@ -774,10 +776,10 @@ async fn default_( } }; - if let Some((toolchain, reason)) = cfg.active_toolchain()? { - if !matches!(reason, ActiveReason::Default) { - info!("note that the toolchain '{toolchain}' is currently in use ({reason})"); - } + if let Some((toolchain, reason)) = cfg.active_toolchain()? + && !matches!(reason, ActiveReason::Default) + { + info!("note that the toolchain '{toolchain}' is currently in use ({reason})"); } } else { let default_toolchain = cfg @@ -1102,9 +1104,9 @@ async fn show(cfg: &Cfg<'_>, verbose: bool) -> Result { } } - fn print_header(t: &mut ColorableTerminal, s: &str) -> std::result::Result<(), E> + fn print_header(t: &mut ColorableTerminal, s: &str) -> Result<(), E> where - E: From, + E: From, { t.attr(terminalsource::Attr::Bold)?; { @@ -1631,8 +1633,8 @@ async fn doc( ) -> Result { let toolchain = cfg.toolchain_from_partial(toolchain).await?; - if let Ok(distributable) = DistributableToolchain::try_from(&toolchain) { - if let [_] = distributable + if let Ok(distributable) = DistributableToolchain::try_from(&toolchain) + && let [_] = distributable .components()? .into_iter() .filter(|cstatus| { @@ -1641,19 +1643,18 @@ async fn doc( .take(1) .collect::>() .as_slice() - { - info!( - "`rust-docs` not installed in toolchain `{}`", - distributable.desc() - ); - info!( - "To install, try `rustup component add --toolchain {} rust-docs`", - distributable.desc() - ); - return Err(anyhow!( - "unable to view documentation which is not installed" - )); - } + { + info!( + "`rust-docs` not installed in toolchain `{}`", + distributable.desc() + ); + info!( + "To install, try `rustup component add --toolchain {} rust-docs`", + distributable.desc() + ); + return Err(anyhow!( + "unable to view documentation which is not installed" + )); }; let (doc_path, fragment) = match (topic, doc_page.name()) { diff --git a/src/cli/self_update.rs b/src/cli/self_update.rs index e347556138..0da9678865 100644 --- a/src/cli/self_update.rs +++ b/src/cli/self_update.rs @@ -905,7 +905,7 @@ async fn maybe_install_rust( let (components, targets) = (opts.components, opts.targets); let toolchain = opts.install(&mut cfg)?; - if let Some(ref desc) = toolchain { + if let Some(desc) = &toolchain { let status = if Toolchain::exists(&cfg, &desc.into())? { warn!("Updating existing toolchain, profile choice will be ignored"); // If we have a partial install we might not be able to read content here. We could: diff --git a/src/config.rs b/src/config.rs index 635c8eade8..8d14448bc1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -190,7 +190,7 @@ impl OverrideCfg { match self { Self::PathBased(path_based_name) => path_based_name.into(), Self::Custom(custom_name) => custom_name.into(), - Self::Official { ref toolchain, .. } => toolchain.into(), + Self::Official { toolchain, .. } => (&toolchain).into(), } } } @@ -558,12 +558,12 @@ impl<'a> Cfg<'a> { fn find_override_config(&self) -> Result> { let override_config: Option<(OverrideCfg, ActiveReason)> = // First check +toolchain override from the command line - if let Some(ref name) = self.toolchain_override { + if let Some(name) = &self.toolchain_override { let override_config = name.resolve(&self.get_default_host_triple()?)?.into(); Some((override_config, ActiveReason::CommandLine)) } // Then check the RUSTUP_TOOLCHAIN environment variable - else if let Some(ref name) = self.env_override { + else if let Some(name) = &self.env_override { // Because path based toolchain files exist, this has to support // custom, distributable, and absolute path toolchains otherwise // rustup's export of a RUSTUP_TOOLCHAIN when running a process will @@ -659,17 +659,15 @@ impl<'a> Cfg<'a> { let default_host_triple = get_default_host_triple(settings, self.process); // Do not permit architecture/os selection in channels as // these are host specific and toolchain files are portable. - if let ResolvableToolchainName::Official(ref name) = toolchain_name { - if name.has_triple() { - // Permit fully qualified names IFF the toolchain is installed. TODO(robertc): consider - // disabling this and backing out https://github.com/rust-lang/rustup/pull/2141 (but provide - // the base name in the error to help users) - let resolved_name = &ToolchainName::try_from(toolchain_name_str)?; - if !self.list_toolchains()?.iter().any(|s| s == resolved_name) { - return Err(anyhow!(format!( - "target triple in channel name '{name}'" - ))); - } + if let ResolvableToolchainName::Official(name) = &toolchain_name + && name.has_triple() + { + // Permit fully qualified names IFF the toolchain is installed. TODO(robertc): consider + // disabling this and backing out https://github.com/rust-lang/rustup/pull/2141 (but provide + // the base name in the error to help users) + let resolved_name = &ToolchainName::try_from(toolchain_name_str)?; + if !self.list_toolchains()?.iter().any(|s| s == resolved_name) { + return Err(anyhow!(format!("target triple in channel name '{name}'"))); } } @@ -960,7 +958,7 @@ impl<'a> Cfg<'a> { let st = distributable .update_extra(&[], &[], profile, force_update, false) .await; - if let Err(ref e) = st { + if let Err(e) = &st { (self.notify_handler)(Notification::NonFatalError(e)); } (desc, st) diff --git a/src/diskio/immediate.rs b/src/diskio/immediate.rs index 991248bc16..8f27cfa2d6 100644 --- a/src/diskio/immediate.rs +++ b/src/diskio/immediate.rs @@ -38,7 +38,7 @@ impl ImmediateUnpacker { fn deque(&self) -> Box> { let mut guard = self.incremental_state.lock().unwrap(); // incremental file in progress - if let Some(ref mut state) = *guard { + if let Some(state) = &mut *guard { // Case 1: pending errors if state.finished { let mut item = state.item.take().unwrap(); @@ -81,7 +81,7 @@ impl Executor for ImmediateUnpacker { // If there is a pending error, return it, otherwise stash the // Item for eventual return when the file is finished. let mut guard = self.incremental_state.lock().unwrap(); - let Some(ref mut state) = *guard else { + let Some(state) = &mut *guard else { unreachable!() }; if state.err.is_some() { @@ -187,7 +187,7 @@ impl IncrementalFileWriter { Ok(v) => v, Err(e) => { let mut state = self.state.lock().unwrap(); - if let Some(ref mut state) = *state { + if let Some(state) = &mut *state { state.err.replace(Err(e)); state.finished = true; false @@ -200,10 +200,10 @@ impl IncrementalFileWriter { fn write(&mut self, chunk: Vec) -> std::result::Result { let mut state = self.state.lock().unwrap(); - let Some(ref mut state) = *state else { + let Some(state) = &mut *state else { unreachable!() }; - let Some(ref mut file) = self.file.as_mut() else { + let Some(file) = &mut self.file else { return Ok(false); }; // Length 0 vector is used for clean EOF signalling. diff --git a/src/diskio/mod.rs b/src/diskio/mod.rs index 0fea84dd7d..4e1d511768 100644 --- a/src/diskio/mod.rs +++ b/src/diskio/mod.rs @@ -270,14 +270,14 @@ impl IncrementalFileState { mode: u32, ) -> Result<(Box bool>, IncrementalFile)> { use std::sync::mpsc::channel; - match *self { + match self { IncrementalFileState::Threaded => { let (tx, rx) = channel::(); let content_callback = IncrementalFile::ThreadedReceiver(rx); let chunk_submit = move |chunk: FileBuffer| tx.send(chunk).is_ok(); Ok((Box::new(chunk_submit), content_callback)) } - IncrementalFileState::Immediate(ref state) => { + IncrementalFileState::Immediate(state) => { let content_callback = IncrementalFile::ImmediateReceiver; let mut writer = immediate::IncrementalFileWriter::new(path, mode, state.clone())?; let chunk_submit = move |chunk: FileBuffer| writer.chunk_submit(chunk); diff --git a/src/dist/component/components.rs b/src/dist/component/components.rs index 74b8db91e5..a956f6c724 100644 --- a/src/dist/component/components.rs +++ b/src/dist/component/components.rs @@ -30,13 +30,13 @@ impl Components { let c = Self { prefix }; // Validate that the metadata uses a format we know - if let Some(v) = c.read_version()? { - if v != INSTALLER_VERSION { - bail!( - "unsupported metadata version in existing installation: {}", - v - ); - } + if let Some(v) = c.read_version()? + && v != INSTALLER_VERSION + { + bail!( + "unsupported metadata version in existing installation: {}", + v + ); } Ok(c) diff --git a/src/dist/component/package.rs b/src/dist/component/package.rs index 82bc823862..9a77efc1ae 100644 --- a/src/dist/component/package.rs +++ b/src/dist/component/package.rs @@ -254,26 +254,26 @@ fn trigger_children( op: CompletedIo, ) -> Result { let mut result = 0; - if let CompletedIo::Item(item) = op { - if let Kind::Directory = item.kind { - let mut pending = Vec::new(); - directories - .entry(item.full_path) - .and_modify(|status| match status { - DirStatus::Exists => unreachable!(), - DirStatus::Pending(pending_inner) => { - pending.append(pending_inner); - *status = DirStatus::Exists; - } - }) - .or_insert_with(|| unreachable!()); - result += pending.len(); - for pending_item in pending.into_iter() { - for mut item in io_executor.execute(pending_item).collect::>() { - // TODO capture metrics - filter_result(&mut item)?; - result += trigger_children(io_executor, directories, item)?; + if let CompletedIo::Item(item) = op + && let Kind::Directory = item.kind + { + let mut pending = Vec::new(); + directories + .entry(item.full_path) + .and_modify(|status| match status { + DirStatus::Exists => unreachable!(), + DirStatus::Pending(pending_inner) => { + pending.append(pending_inner); + *status = DirStatus::Exists; } + }) + .or_insert_with(|| unreachable!()); + result += pending.len(); + for pending_item in pending.into_iter() { + for mut item in io_executor.execute(pending_item).collect::>() { + // TODO capture metrics + filter_result(&mut item)?; + result += trigger_children(io_executor, directories, item)?; } } }; @@ -363,24 +363,24 @@ fn unpack_without_first_dir( trigger_children(&*io_executor, directories, op)?; } // Maybe stream a file incrementally - if let Some(sender) = sender_entry.as_mut() { - if io_executor.buffer_available(IO_CHUNK_SIZE) { - let mut buffer = io_executor.get_buffer(IO_CHUNK_SIZE); - let len = sender - .entry - .by_ref() - .take(IO_CHUNK_SIZE as u64) - .read_to_end(&mut buffer)?; - buffer = buffer.finished(); - if len == 0 { - result = true; - } - if !(sender.sender)(buffer) { - bail!(format!( - "IO receiver for '{}' disconnected", - full_path.as_ref().display() - )) - } + if let Some(sender) = sender_entry.as_mut() + && io_executor.buffer_available(IO_CHUNK_SIZE) + { + let mut buffer = io_executor.get_buffer(IO_CHUNK_SIZE); + let len = sender + .entry + .by_ref() + .take(IO_CHUNK_SIZE as u64) + .read_to_end(&mut buffer)?; + buffer = buffer.finished(); + if len == 0 { + result = true; + } + if !(sender.sender)(buffer) { + bail!(format!( + "IO receiver for '{}' disconnected", + full_path.as_ref().display() + )) } } Ok(result) diff --git a/src/dist/manifest.rs b/src/dist/manifest.rs index f3c5b10afd..d70e81e489 100644 --- a/src/dist/manifest.rs +++ b/src/dist/manifest.rs @@ -357,11 +357,11 @@ impl Manifest { fn validate(&self) -> Result<()> { // Every component mentioned must have an actual package to download for pkg in self.packages.values() { - match pkg.targets { - PackageTargets::Wildcard(ref tpkg) => { + match &pkg.targets { + PackageTargets::Wildcard(tpkg) => { self.validate_targeted_package(tpkg)?; } - PackageTargets::Targeted(ref tpkgs) => { + PackageTargets::Targeted(tpkgs) => { for tpkg in tpkgs.values() { self.validate_targeted_package(tpkg)?; } @@ -447,9 +447,9 @@ impl Manifest { impl Package { pub fn get_target(&self, target: Option<&TargetTriple>) -> Result<&TargetedPackage> { - match self.targets { - PackageTargets::Wildcard(ref tpkg) => Ok(tpkg), - PackageTargets::Targeted(ref tpkgs) => { + match &self.targets { + PackageTargets::Wildcard(tpkg) => Ok(tpkg), + PackageTargets::Targeted(tpkgs) => { if let Some(t) = target { tpkgs .get(t) @@ -523,7 +523,7 @@ impl Component { pub(crate) fn name(&self, manifest: &Manifest) -> String { let pkg = self.short_name(manifest); - if let Some(ref t) = self.target { + if let Some(t) = &self.target { format!("{pkg}-{t}") } else { pkg @@ -538,7 +538,7 @@ impl Component { } pub(crate) fn description(&self, manifest: &Manifest) -> String { let pkg = self.short_name(manifest); - if let Some(ref t) = self.target { + if let Some(t) = &self.target { format!("'{pkg}' for target '{t}'") } else { format!("'{pkg}'") @@ -549,7 +549,7 @@ impl Component { } pub(crate) fn name_in_manifest(&self) -> String { let pkg = self.short_name_in_manifest(); - if let Some(ref t) = self.target { + if let Some(t) = &self.target { format!("{pkg}-{t}") } else { pkg.to_string() diff --git a/src/dist/mod.rs b/src/dist/mod.rs index 75f969127d..516369d17f 100644 --- a/src/dist/mod.rs +++ b/src/dist/mod.rs @@ -229,13 +229,13 @@ impl FromStr for PartialVersion { // `semver::Comparator::from_str` supports an optional operator // (e.g. `=`, `>`, `>=`, `<`, `<=`, `~`, `^`, `*`) before the // partial version, so we should exclude that case first. - if let Some(ch) = ver.chars().nth(0) { - if !ch.is_ascii_digit() { - return Err(anyhow!( - "expected ASCII digit at the beginning of `{ver}`, found `{ch}`" - ) - .context("error parsing `PartialVersion`")); - } + if let Some(ch) = ver.chars().nth(0) + && !ch.is_ascii_digit() + { + return Err( + anyhow!("expected ASCII digit at the beginning of `{ver}`, found `{ch}`") + .context("error parsing `PartialVersion`"), + ); } let (ver, pre) = ver.split_once('-').unwrap_or((ver, "")); let comparator = @@ -694,16 +694,16 @@ impl ToolchainDesc { } /// Either "$channel" or "channel-$date" pub fn manifest_name(&self) -> String { - match self.date { + match &self.date { None => self.channel.to_string(), - Some(ref date) => format!("{}-{}", self.channel, date), + Some(date) => format!("{}-{}", self.channel, date), } } pub(crate) fn package_dir(&self, dist_root: &str) -> String { - match self.date { + match &self.date { None => dist_root.to_string(), - Some(ref date) => format!("{dist_root}/{date}"), + Some(date) => format!("{dist_root}/{date}"), } } @@ -843,16 +843,16 @@ impl fmt::Display for PartialToolchainDesc { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", &self.channel)?; - if let Some(ref date) = self.date { + if let Some(date) = &self.date { write!(f, "-{date}")?; } - if let Some(ref arch) = self.target.arch { + if let Some(arch) = &self.target.arch { write!(f, "-{arch}")?; } - if let Some(ref os) = self.target.os { + if let Some(os) = &self.target.os { write!(f, "-{os}")?; } - if let Some(ref env) = self.target.env { + if let Some(env) = &self.target.env { write!(f, "-{env}")?; } @@ -864,7 +864,7 @@ impl fmt::Display for ToolchainDesc { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", &self.channel)?; - if let Some(ref date) = self.date { + if let Some(date) = &self.date { write!(f, "-{date}")?; } write!(f, "-{}", self.target)?; @@ -1017,12 +1017,12 @@ pub(crate) async fn update_from_dist( } }; - if let Some(backtrack_limit) = backtrack_limit { - if backtrack_limit < 1 { - // This unwrap is safe because we can only hit this if we've - // had a chance to set first_err - break Err(first_err.unwrap()); - } + if let Some(backtrack_limit) = backtrack_limit + && backtrack_limit < 1 + { + // This unwrap is safe because we can only hit this if we've + // had a chance to set first_err + break Err(first_err.unwrap()); } // The user asked to update their nightly, but the latest nightly does not have all @@ -1118,10 +1118,9 @@ async fn try_update_from_dist_( .components .iter() .find(|c| c.short_name_in_manifest() == component.short_name_in_manifest()) + && c.target.is_none() { - if c.target.is_none() { - component = component.wildcard(); - } + component = component.wildcard(); } all_components.insert(component); } @@ -1215,12 +1214,12 @@ async fn try_update_from_dist_( .await; // inspect, determine what context to add, then process afterwards. - if let Err(e) = &result { - if let Some(RustupError::DownloadNotExists { .. }) = e.downcast_ref::() { - return result.with_context(|| { - format!("could not download nonexistent rust version `{toolchain_str}`") - }); - } + if let Err(e) = &result + && let Some(RustupError::DownloadNotExists { .. }) = e.downcast_ref::() + { + return result.with_context(|| { + format!("could not download nonexistent rust version `{toolchain_str}`") + }); } result diff --git a/src/download/mod.rs b/src/download/mod.rs index c732d2e153..348c8fbc39 100644 --- a/src/download/mod.rs +++ b/src/download/mod.rs @@ -100,10 +100,10 @@ async fn download_file_( // This callback will write the download to disk and optionally // hash the contents, then forward the notification up the stack let callback: &dyn Fn(Event<'_>) -> anyhow::Result<()> = &|msg| { - if let Event::DownloadDataReceived(data) = msg { - if let Some(h) = hasher.borrow_mut().as_mut() { - h.update(data); - } + if let Event::DownloadDataReceived(data) = msg + && let Some(h) = hasher.borrow_mut().as_mut() + { + h.update(data); } match msg { @@ -469,20 +469,23 @@ mod curl { // Listen for headers and parse out a `Content-Length` (case-insensitive) if it // comes so we know how much we're downloading. transfer.header_function(|header| { - if let Ok(data) = str::from_utf8(header) { - let prefix = "content-length: "; - if data.to_ascii_lowercase().starts_with(prefix) { - if let Ok(s) = data[prefix.len()..].trim().parse::() { - let msg = Event::DownloadContentLengthReceived(s + resume_from); - match callback(msg) { - Ok(()) => (), - Err(e) => { - *cberr.borrow_mut() = Some(e); - return false; - } - } - } - } + let Ok(data) = str::from_utf8(header) else { + return true; + }; + let prefix = "content-length: "; + let Some((dp, ds)) = data.split_at_checked(prefix.len()) else { + return true; + }; + if !dp.eq_ignore_ascii_case(prefix) { + return true; + } + let Ok(s) = ds.trim().parse::() else { + return true; + }; + let msg = Event::DownloadContentLengthReceived(s + resume_from); + if let Err(e) = callback(msg) { + *cberr.borrow_mut() = Some(e); + return false; } true })?; diff --git a/src/env_var.rs b/src/env_var.rs index ed2eb44602..45b19c6389 100644 --- a/src/env_var.rs +++ b/src/env_var.rs @@ -27,10 +27,10 @@ pub(crate) fn insert_path( prepend.into() }; - if let Some(path) = append { - if !parts.contains(&path) { - parts.push_back(path); - } + if let Some(path) = append + && !parts.contains(&path) + { + parts.push_back(path); } if let Ok(new_value) = env::join_paths(parts) { diff --git a/src/test/clitools.rs b/src/test/clitools.rs index e6bf2c020e..4501e1db8a 100644 --- a/src/test/clitools.rs +++ b/src/test/clitools.rs @@ -229,7 +229,7 @@ impl Config { // Ensure PATH is prefixed with the rustup-exe directory let prev_path = env::var_os("PATH"); let mut new_path = self.exedir.clone().into_os_string(); - if let Some(ref p) = prev_path { + if let Some(p) = &prev_path { new_path.push(if cfg!(windows) { ";" } else { ":" }); new_path.push(p); } @@ -697,16 +697,15 @@ impl ConstState { { // fast path: the dist already exists let lock = self.scenarios[s].read().unwrap(); - if let Some(ref path) = *lock { + if let Some(path) = &*lock { return Ok(path.clone()); } } { let mut lock = self.scenarios[s].write().unwrap(); // another writer may have initialized it - match *lock { - Some(ref path) => Ok(path.clone()), - + match &*lock { + Some(path) => Ok(path.clone()), None => { let dist_path = self.const_dist_dir.path().join(format!("{s:?}")); s.write_to(&dist_path); diff --git a/src/test/dist.rs b/src/test/dist.rs index a2e8398acb..ab5041fb9a 100644 --- a/src/test/dist.rs +++ b/src/test/dist.rs @@ -637,7 +637,7 @@ impl MockDistServer { ); let tarballs = TARBALLS.lock().unwrap(); let hash = if tarballs.contains_key(&key) { - let (ref contents, ref hash) = tarballs[&key]; + let (contents, hash) = &tarballs[&key]; File::create(&installer_tarball) .unwrap() .write_all(contents) diff --git a/src/test/mock.rs b/src/test/mock.rs index 1f4f09ab00..37162c3498 100644 --- a/src/test/mock.rs +++ b/src/test/mock.rs @@ -238,14 +238,14 @@ impl MockFile { pub fn build(&self, path: &Path) { let path = path.join(&self.path); - match self.contents { - Contents::Dir(ref files) => { + match &self.contents { + Contents::Dir(files) => { for (name, contents) in files { let fname = path.join(name); contents.build(&fname); } } - Contents::File(ref contents) => contents.build(&path), + Contents::File(contents) => contents.build(&path), } } } diff --git a/src/toolchain.rs b/src/toolchain.rs index 4dc1fe6073..30ae066fd7 100644 --- a/src/toolchain.rs +++ b/src/toolchain.rs @@ -345,15 +345,15 @@ impl<'a> Toolchain<'a> { ); return Ok(cmd); } - } else if let "rust-analyzer" | "rust-analyzer.exe" = binary { - if let Some(cmd) = self.maybe_do_rust_analyzer_fallback(binary)? { - info!("`rust-analyzer` is unavailable for the active toolchain"); - info!( - r#"falling back to "{}""#, - Path::new(cmd.get_program()).display() - ); - return Ok(cmd); - } + } else if let "rust-analyzer" | "rust-analyzer.exe" = binary + && let Some(cmd) = self.maybe_do_rust_analyzer_fallback(binary)? + { + info!("`rust-analyzer` is unavailable for the active toolchain"); + info!( + r#"falling back to "{}""#, + Path::new(cmd.get_program()).display() + ); + return Ok(cmd); } self.create_command(binary) @@ -490,12 +490,12 @@ impl<'a> Toolchain<'a> { // but only if we know the absolute path to cargo. // This works around an issue with old versions of cargo not updating // the environment variable itself. - if Path::new(&binary).file_stem() == Some("cargo".as_ref()) && path.is_absolute() { - if let Some(cargo) = self.cfg.process.var_os("CARGO") { - if fs::read_link(&cargo).is_ok_and(|p| p.file_stem() == Some("rustup".as_ref())) { - cmd.env("CARGO", path); - } - } + if Path::new(&binary).file_stem() == Some("cargo".as_ref()) + && path.is_absolute() + && let Some(cargo) = self.cfg.process.var_os("CARGO") + && fs::read_link(&cargo).is_ok_and(|p| p.file_stem() == Some("rustup".as_ref())) + { + cmd.env("CARGO", path); } Ok(cmd) } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index faecdcc407..de0b60df6a 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -310,12 +310,11 @@ pub fn remove_file(name: &'static str, path: &Path) -> Result<()> { pub(crate) fn ensure_file_removed(name: &'static str, path: &Path) -> Result<()> { let result = remove_file(name, path); - if let Err(err) = &result { - if let Some(retry::Error { error: e, .. }) = err.downcast_ref::>() { - if e.kind() == io::ErrorKind::NotFound { - return Ok(()); - } - } + if let Err(err) = &result + && let Some(retry::Error { error: e, .. }) = err.downcast_ref::>() + && e.kind() == io::ErrorKind::NotFound + { + return Ok(()); } result.with_context(|| RustupError::RemovingFile { name,