Skip to content

style: migrate the codebase to let-chains #4397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/cli/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
65 changes: 33 additions & 32 deletions src/cli/rustup_mode.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -49,10 +51,10 @@ fn handle_epipe(res: Result<utils::ExitCode>) -> Result<utils::ExitCode> {
match res {
Err(e) => {
let root = e.root_cause();
if let Some(io_err) = root.downcast_ref::<std::io::Error>() {
if io_err.kind() == std::io::ErrorKind::BrokenPipe {
return Ok(utils::ExitCode(0));
}
if let Some(io_err) = root.downcast_ref::<io::Error>()
&& io_err.kind() == io::ErrorKind::BrokenPipe
{
return Ok(utils::ExitCode(0));
}
Err(e)
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1102,9 +1104,9 @@ async fn show(cfg: &Cfg<'_>, verbose: bool) -> Result<utils::ExitCode> {
}
}

fn print_header<E>(t: &mut ColorableTerminal, s: &str) -> std::result::Result<(), E>
fn print_header<E>(t: &mut ColorableTerminal, s: &str) -> Result<(), E>
where
E: From<std::io::Error>,
E: From<io::Error>,
{
t.attr(terminalsource::Attr::Bold)?;
{
Expand Down Expand Up @@ -1631,8 +1633,8 @@ async fn doc(
) -> Result<utils::ExitCode> {
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| {
Expand All @@ -1641,19 +1643,18 @@ async fn doc(
.take(1)
.collect::<Vec<ComponentStatus>>()
.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()) {
Expand Down
2 changes: 1 addition & 1 deletion src/cli/self_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
28 changes: 13 additions & 15 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
}
}
Expand Down Expand Up @@ -558,12 +558,12 @@ impl<'a> Cfg<'a> {
fn find_override_config(&self) -> Result<Option<(OverrideCfg, ActiveReason)>> {
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
Expand Down Expand Up @@ -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}'")));
}
}

Expand Down Expand Up @@ -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)
Expand Down
10 changes: 5 additions & 5 deletions src/diskio/immediate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl ImmediateUnpacker {
fn deque(&self) -> Box<dyn Iterator<Item = CompletedIo>> {
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();
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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
Expand All @@ -200,10 +200,10 @@ impl IncrementalFileWriter {

fn write(&mut self, chunk: Vec<u8>) -> std::result::Result<bool, io::Error> {
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.
Expand Down
4 changes: 2 additions & 2 deletions src/diskio/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,14 +270,14 @@ impl IncrementalFileState {
mode: u32,
) -> Result<(Box<dyn FnMut(FileBuffer) -> bool>, IncrementalFile)> {
use std::sync::mpsc::channel;
match *self {
match self {
IncrementalFileState::Threaded => {
let (tx, rx) = channel::<FileBuffer>();
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);
Expand Down
14 changes: 7 additions & 7 deletions src/dist/component/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
74 changes: 37 additions & 37 deletions src/dist/component/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,26 +254,26 @@ fn trigger_children(
op: CompletedIo,
) -> Result<usize> {
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::<Vec<_>>() {
// 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::<Vec<_>>() {
// TODO capture metrics
filter_result(&mut item)?;
result += trigger_children(io_executor, directories, item)?;
}
}
};
Expand Down Expand Up @@ -363,24 +363,24 @@ fn unpack_without_first_dir<R: Read>(
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)
Expand Down
Loading