Skip to content

fix(errors)!: improve error messages for RustupError::ToolchainNotInstalled #4258

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
Mar 19, 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 @@ -418,7 +418,7 @@ pub(crate) async fn list_toolchains(
let default_toolchain_name = cfg.get_default()?;
let active_toolchain_name: Option<ToolchainName> =
if let Ok(Some((LocalToolchainName::Named(toolchain), _reason))) =
cfg.find_active_toolchain(None).await
cfg.maybe_ensure_active_toolchain(None).await
{
Some(toolchain)
} else {
Expand Down
12 changes: 5 additions & 7 deletions src/cli/rustup_mode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ async fn default_(
}
};

if let Some((toolchain, reason)) = cfg.find_active_toolchain(None).await? {
if let Some((toolchain, reason)) = cfg.active_toolchain()? {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we're just emitting an info!(), there's no need to install anything.

if !matches!(reason, ActiveReason::Default) {
info!("note that the toolchain '{toolchain}' is currently in use ({reason})");
}
Expand Down Expand Up @@ -899,9 +899,7 @@ async fn update(
exit_code &= common::self_update(|| Ok(()), cfg.process).await?;
}
} else if ensure_active_toolchain {
let (toolchain, reason) = cfg
.find_or_install_active_toolchain(force_non_host, true)
.await?;
let (toolchain, reason) = cfg.ensure_active_toolchain(force_non_host, true).await?;
info!("the active toolchain `{toolchain}` has been installed");
info!("it's active because: {reason}");
} else {
Expand Down Expand Up @@ -974,7 +972,7 @@ async fn show(cfg: &Cfg<'_>, verbose: bool) -> Result<utils::ExitCode> {
let installed_toolchains = cfg.list_toolchains()?;
let active_toolchain_and_reason: Option<(ToolchainName, ActiveReason)> =
if let Ok(Some((LocalToolchainName::Named(toolchain_name), reason))) =
cfg.find_active_toolchain(None).await
cfg.maybe_ensure_active_toolchain(None).await
{
Some((toolchain_name, reason))
} else {
Expand Down Expand Up @@ -1094,7 +1092,7 @@ async fn show(cfg: &Cfg<'_>, verbose: bool) -> Result<utils::ExitCode> {

#[tracing::instrument(level = "trace", skip_all)]
async fn show_active_toolchain(cfg: &Cfg<'_>, verbose: bool) -> Result<utils::ExitCode> {
match cfg.find_active_toolchain(None).await? {
match cfg.maybe_ensure_active_toolchain(None).await? {
Some((toolchain_name, reason)) => {
let toolchain = Toolchain::with_reason(cfg, toolchain_name.clone(), &reason)?;
if verbose {
Expand Down Expand Up @@ -1332,7 +1330,7 @@ async fn toolchain_link(
async fn toolchain_remove(cfg: &mut Cfg<'_>, opts: UninstallOpts) -> Result<utils::ExitCode> {
let default_toolchain = cfg.get_default().ok().flatten();
let active_toolchain = cfg
.find_active_toolchain(Some(false))
.maybe_ensure_active_toolchain(Some(false))
.await
.ok()
.flatten()
Expand Down
96 changes: 32 additions & 64 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,65 +522,37 @@ impl<'a> Cfg<'a> {
self.local_toolchain(toolchain).await
}

pub(crate) async fn find_active_toolchain(
pub(crate) async fn maybe_ensure_active_toolchain(
&self,
force_install_active: Option<bool>,
force_ensure: Option<bool>,
) -> Result<Option<(LocalToolchainName, ActiveReason)>> {
let (components, targets, profile, toolchain, reason) = match self.find_override_config()? {
Some((
OverrideCfg::Official {
components,
targets,
profile,
toolchain,
},
reason,
)) => (components, targets, profile, toolchain, reason),
Some((override_config, reason)) => {
return Ok(Some((override_config.into_local_toolchain_name(), reason)));
}
None => {
return Ok(self
.get_default()?
.map(|x| (x.into(), ActiveReason::Default)));
}
};

let should_install_active = if let Some(force) = force_install_active {
let should_ensure = if let Some(force) = force_ensure {
force
} else {
self.should_auto_install()?
};

if !should_install_active {
return Ok(Some(((&toolchain).into(), reason)));
if !should_ensure {
return self.active_toolchain();
Copy link
Member Author

@rami3l rami3l Mar 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If should_install_active is set to false, we return self.active_toolchain() which was the old behavior of find_active_toolchain() in v1.28.0, corresponding to the last 2 early-returning branch of the previous match that gets deleted in this change:

rustup/src/config.rs

Lines 517 to 528 in e2d9e7e

pub(crate) fn find_active_toolchain(
&self,
) -> Result<Option<(LocalToolchainName, ActiveReason)>> {
Ok(
if let Some((override_config, reason)) = self.find_override_config()? {
Some((override_config.into_local_toolchain_name(), reason))
} else {
self.get_default()?
.map(|x| (x.into(), ActiveReason::Default))
},
)
}

}

let components = components.iter().map(AsRef::as_ref).collect::<Vec<_>>();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If should_install is set to true, we delegate the installation to find_or_install_active_toolchain() which has the same logic:

rustup/src/config.rs

Lines 758 to 765 in e2d9e7e

if let OverrideCfg::Official {
toolchain,
components,
targets,
profile,
} = override_config
{
self.ensure_installed(

rustup/src/config.rs

Lines 813 to 844 in e2d9e7e

let components: Vec<_> = components.iter().map(AsRef::as_ref).collect();
let targets: Vec<_> = targets.iter().map(AsRef::as_ref).collect();
let profile = match profile {
Some(profile) => profile,
None => self.get_profile()?,
};
let (status, toolchain) = match DistributableToolchain::new(self, toolchain.clone()) {
Err(RustupError::ToolchainNotInstalled { .. }) => {
DistributableToolchain::install(
self,
toolchain,
&components,
&targets,
profile,
false,
)
.await?
}
Ok(mut distributable) => {
if verbose {
(self.notify_handler)(Notification::UsingExistingToolchain(toolchain));
}
let status = if !distributable.components_exist(&components, &targets)? {
distributable.update(&components, &targets, profile).await?
} else {
UpdateStatus::Unchanged
};
(status, distributable)
}
Err(e) => return Err(e.into()),
};
Ok((status, toolchain.into()))

let targets = targets.iter().map(AsRef::as_ref).collect::<Vec<_>>();
match DistributableToolchain::new(self, toolchain.clone()) {
Err(RustupError::ToolchainNotInstalled { .. }) => {
DistributableToolchain::install(
self,
&toolchain,
&components,
&targets,
profile.unwrap_or_default(),
false,
)
.await?;
}
Ok(mut distributable) => {
if !distributable.components_exist(&components, &targets)? {
distributable
.update(&components, &targets, profile.unwrap_or_default())
.await?;
}
}
Err(e) => return Err(e.into()),
};
match self.ensure_active_toolchain(true, false).await {
Ok(r) => Ok(Some(r)),
Err(e) => match e.downcast_ref::<RustupError>() {
Some(RustupError::ToolchainNotSelected(_)) => Ok(None),
_ => Err(e),
},
}
}

Ok(Some(((&toolchain).into(), reason)))
pub(crate) fn active_toolchain(&self) -> Result<Option<(LocalToolchainName, ActiveReason)>> {
Copy link
Member Author

@rami3l rami3l Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have to extract a sync function here because v1.28.1 has made the Cfg::find_active_toolchain() async again, but we really need to find the active toolchain in a sync context in the commits that follow... (sigh)

Copy link
Member Author

@rami3l rami3l Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I suggest renaming Cfg::find_active_toolchain() to something else. Any ideas?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be honest I'm struggling to think of a good name.

Copy link
Member Author

@rami3l rami3l Mar 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ChrisDenton I'm currently thinking about something like:

Before After Remarks
find_active_toolchain() maybe_ensure_active_toolchain() Dispatches to one of the following (async)
find_active_toolchain() (old implementation in 1.28.0) active_toolchain() Queries the active toolchain (sync)
find_or_install_active_toolchain() ensure_active_toolchain() Ensures the installation of the active toolchain (async)

... how does that sound?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds good to me. I think those names do make the relationship between them clearer to me at least.

Ok(
if let Some((override_config, reason)) = self.find_override_config()? {
Some((override_config.into_local_toolchain_name(), reason))
} else {
self.get_default()?
.map(|x| (x.into(), ActiveReason::Default))
},
)
}

fn find_override_config(&self) -> Result<Option<(OverrideCfg, ActiveReason)>> {
Expand Down Expand Up @@ -703,17 +675,13 @@ impl<'a> Cfg<'a> {

// XXX: this awkwardness deals with settings file being locked already
let toolchain_name = toolchain_name.resolve(&default_host_triple)?;
match Toolchain::new(self, (&toolchain_name).into()) {
Copy link
Member Author

@rami3l rami3l Mar 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have manually inlined Toolchain::new() here and removed the statement causing an infinite recursion, because it was not needed; in fact, to allow any RustupError::ToolchainNotInstalled to happen with this call, the toolchain must not exist:

rustup/src/toolchain.rs

Lines 106 to 115 in f9edccd

pub(crate) fn new(cfg: &'a Cfg<'a>, name: LocalToolchainName) -> Result<Self, RustupError> {
let path = cfg.toolchain_path(&name);
if !Toolchain::exists(cfg, &name)? {
return Err(match name {
LocalToolchainName::Named(name) => RustupError::ToolchainNotInstalled { name },
LocalToolchainName::Path(name) => RustupError::PathToolchainNotInstalled(name),
});
}
Ok(Self { cfg, name, path })
}

Err(RustupError::ToolchainNotInstalled { .. }) => {
if matches!(toolchain_name, ToolchainName::Custom(_)) {
bail!(
"custom toolchain specified in override file '{}' is not installed",
toolchain_file.display()
)
}
}
Ok(_) => {}
Err(e) => Err(e)?,
if !Toolchain::exists(self, &(&toolchain_name).into())?
&& matches!(toolchain_name, ToolchainName::Custom(_))
{
bail!(
"custom toolchain specified in override file '{}' is not installed",
toolchain_file.display()
)
}
}

Expand Down Expand Up @@ -765,7 +733,7 @@ impl<'a> Cfg<'a> {
self.set_toolchain_override(&ResolvableToolchainName::try_from(&t[1..])?);
}

let Some((name, _)) = self.find_active_toolchain(None).await? else {
let Some((name, _)) = self.maybe_ensure_active_toolchain(None).await? else {
return Ok(None);
};
Ok(Some(Toolchain::new(self, name)?.rustc_version()))
Expand Down Expand Up @@ -799,7 +767,7 @@ impl<'a> Cfg<'a> {
}
None => {
let tc = self
.find_active_toolchain(None)
.maybe_ensure_active_toolchain(None)
.await?
.ok_or_else(|| no_toolchain_error(self.process))?
.0;
Expand All @@ -809,7 +777,7 @@ impl<'a> Cfg<'a> {
}

#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn find_or_install_active_toolchain(
pub(crate) async fn ensure_active_toolchain(
&self,
force_non_host: bool,
verbose: bool,
Expand Down
8 changes: 6 additions & 2 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,16 @@ pub enum RustupError {
#[error(
"toolchain '{name}' is not installed{}",
if let ToolchainName::Official(t) = name {
format!("\nhelp: run `rustup toolchain install {t}` to install it")
let t = if *is_active { "" } else { &format!(" {t}") };
format!("\nhelp: run `rustup toolchain install{t}` to install it")
} else {
String::new()
},
)]
ToolchainNotInstalled { name: ToolchainName },
ToolchainNotInstalled {
name: ToolchainName,
is_active: bool,
},
#[error("path '{0}' not found")]
PathToolchainNotInstalled(PathBasedToolchainName),
#[error(
Expand Down
6 changes: 5 additions & 1 deletion src/toolchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ impl<'a> Toolchain<'a> {
Ok(tc) => Ok(tc),
Err(RustupError::ToolchainNotInstalled {
name: ToolchainName::Official(desc),
..
}) if install_if_missing => {
Ok(
DistributableToolchain::install(cfg, &desc, &[], &[], cfg.get_profile()?, true)
Expand Down Expand Up @@ -107,7 +108,10 @@ impl<'a> Toolchain<'a> {
let path = cfg.toolchain_path(&name);
if !Toolchain::exists(cfg, &name)? {
return Err(match name {
LocalToolchainName::Named(name) => RustupError::ToolchainNotInstalled { name },
LocalToolchainName::Named(name) => {
let is_active = matches!(cfg.active_toolchain(), Ok(Some((t, _))) if t == name);
RustupError::ToolchainNotInstalled { name, is_active }
}
LocalToolchainName::Path(name) => RustupError::PathToolchainNotInstalled(name),
});
}
Expand Down
30 changes: 30 additions & 0 deletions tests/suite/cli_exact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use rustup::for_host;
use rustup::test::{
CROSS_ARCH1, CROSS_ARCH2, CliTestContext, MULTI_ARCH1, Scenario, this_host_triple,
};
use rustup::utils::raw;

#[tokio::test]
async fn update_once() {
Expand Down Expand Up @@ -699,6 +700,35 @@ help: run `rustup toolchain install nightly-{0}` to install it
.await;
}

// issue #4212
#[tokio::test]
async fn show_suggestion_for_missing_toolchain_with_components() {
let cx = CliTestContext::new(Scenario::SimpleV2).await;

let cwd = cx.config.current_dir();
let toolchain_file = cwd.join("rust-toolchain.toml");
raw::write_file(
&toolchain_file,
r#"
[toolchain]
channel = "stable"
components = [ "rust-src" ]
"#,
)
.unwrap();
cx.config
.expect_err_env(
&["cargo", "fmt"],
&[("RUSTUP_AUTO_INSTALL", "0")],
for_host!(
r"error: toolchain 'stable-{0}' is not installed
help: run `rustup toolchain install` to install it
"
),
)
.await;
}

// issue #927
#[tokio::test]
async fn undefined_linked_toolchain() {
Expand Down