Skip to content
Open
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
24 changes: 14 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1033,17 +1033,21 @@ impl<'a> Cfg<'a> {
Ok(toolchains)
}

pub(crate) fn list_channels(
&self,
) -> anyhow::Result<impl Iterator<Item = ChannelToolchain<'_>>> {
let toolchains = self.list_toolchains(true)?;
Ok(toolchains.into_iter().filter_map(|t| match t {
ToolchainName::Channel(n) => ChannelToolchain::new(self, n).ok(),
_ => None,
}))
}

pub(crate) fn list_tracking_channels(&self) -> anyhow::Result<Vec<ChannelToolchain<'_>>> {
let mut channels = self
.list_toolchains(true)?
.into_iter()
.filter_map(|t| match t {
ToolchainName::Channel(n) if n.is_tracking() => {
Some(ChannelToolchain::new(self, n))
}
_ => None,
})
.collect::<Result<Vec<_>, _>>()?;
let mut channels: Vec<_> = self
.list_channels()?
.filter(|c| c.desc().is_tracking())
.collect();

// HACK: `.sort_by_key()` is impossible here without cloning.
// See: <https://users.rust-lang.org/t/cannot-call-vec-sort-by-key-without-cloning-data/60455/4>
Expand Down
102 changes: 61 additions & 41 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::{
config::Config as DistConfig,
manifest::{Component, Manifest},
},
toolchain::{Toolchain, ToolchainName, ToolchainPath},
toolchain::{ChannelToolchain, ToolchainName, ToolchainPath},
};

pub(crate) const DEFAULT_STABLE_HINT: &str = "help: run 'rustup default stable' to download the latest stable release of Rust and set it as your default toolchain.";
Expand All @@ -40,28 +40,14 @@ impl TargetSuggestion {
manifest: &Manifest,
cfg: &Cfg<'_>,
) -> Option<Self> {
let Ok(toolchains) = cfg.list_toolchains(true) else {
return component_suggestion(desc, component, config, manifest, true)
.map(Self::Component);
};

for toolchain_name in toolchains {
if let ToolchainName::Channel(toolchain_desc) = &toolchain_name
&& toolchain_desc == desc
{
continue;
}

let Ok(toolchain) = Toolchain::new(cfg, toolchain_name.clone().into()) else {
continue;
};
let Ok(installed_targets) = toolchain.installed_targets() else {
for channel_toolchain in other_channel_toolchains(desc, cfg) {
let Ok(installed_targets) = channel_toolchain.toolchain.installed_targets() else {
continue;
};

if installed_targets.contains(target) {
return Some(Self::Toolchain {
name: toolchain_name.to_string(),
name: channel_toolchain.desc().to_string(),
target: target.clone(),
});
}
Expand All @@ -84,7 +70,11 @@ impl fmt::Display for TargetSuggestion {

#[derive(Debug, Clone)]
pub enum ComponentSuggestion {
Toolchain { name: String, component: String },
Toolchain {
name: String,
component: String,
action: &'static str,
},
Component(String),
}

Expand All @@ -96,46 +86,76 @@ impl ComponentSuggestion {
manifest: &Manifest,
cfg: &Cfg<'_>,
) -> Option<Self> {
let Ok(toolchains) = cfg.list_toolchains(true) else {
return component_suggestion(desc, component, config, manifest, true)
.map(Self::Component);
};

let names = [component.name(), component.wildcard().name()];
for toolchain_name in toolchains {
if let ToolchainName::Channel(toolchain_desc) = &toolchain_name
&& toolchain_desc == desc
{
continue;
}

let Ok(toolchain) = Toolchain::new(cfg, toolchain_name.clone().into()) else {
for channel_toolchain in other_channel_toolchains(desc, cfg) {
let Ok(installed_components) = channel_toolchain.toolchain.installed_components()
else {
continue;
};
let Ok(installed_components) = toolchain.installed_components() else {
continue;
};

if installed_components
.iter()
.any(|c| names.iter().any(|n| n == c.name()))
.any(|installed| component_matches(component, installed.name()))
{
return Some(Self::Toolchain {
name: toolchain_name.to_string(),
name: channel_toolchain.desc().to_string(),
component: manifest.short_name(component).to_string(),
action: "remove",
});
}
}

component_suggestion(desc, component, config, manifest, true).map(Self::Component)
}

pub(crate) fn for_addition(
Comment thread
djc marked this conversation as resolved.
Resolved
desc: &ChannelToolchainName,
component: &Component,
config: &DistConfig,
manifest: &Manifest,
cfg: &Cfg<'_>,
) -> Option<Self> {
for channel_toolchain in other_channel_toolchains(desc, cfg) {
let Ok(components) = channel_toolchain.components() else {
continue;
};
if components.iter().any(|status| {
status.available && component_matches(component, &status.component.name())
}) {
return Some(Self::Toolchain {
name: channel_toolchain.desc().to_string(),
component: manifest.short_name(component).to_string(),
action: "add",
});
}
}

component_suggestion(desc, component, config, manifest, false).map(Self::Component)
}
}

fn other_channel_toolchains<'a>(
desc: &ChannelToolchainName,
cfg: &'a Cfg<'a>,
) -> impl Iterator<Item = ChannelToolchain<'a>> {
cfg.list_channels()
.ok()
.into_iter()
.flatten()
.filter(move |c| c.desc() != desc)
}

fn component_matches(component: &Component, candidate_name: &str) -> bool {
candidate_name == component.name() || candidate_name == component.wildcard().name()
}

impl fmt::Display for ComponentSuggestion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Toolchain { name, component } => {
write!(f, "try `rustup +{name} component remove {component}`")
Self::Toolchain {
name,
component,
action,
} => {
write!(f, "try `rustup +{name} component {action} {component}`")
}
Self::Component(name) => write!(f, "did you mean '{name}'?"),
}
Expand Down
11 changes: 9 additions & 2 deletions src/toolchain/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,24 +96,31 @@ impl<'a> ChannelToolchain<'a> {
}

let config = manifestation.read_config()?.unwrap_or_default();
let suggestion = component_suggestion(desc, &component, &config, &manifest, false);

if targ_pkg
.components
.iter()
.any(|c| c.target() == component.target())
{
let suggestion = ComponentSuggestion::for_addition(
desc,
&component,
&config,
&manifest,
self.toolchain.cfg,
);
return Err(RustupError::UnknownComponents {
desc: desc.clone(),
components: vec![UnknownComponentInfo {
name: manifest.short_name(&component).to_string(),
description: manifest.description(&component),
suggestion: suggestion.map(ComponentSuggestion::Component),
suggestion,
}],
}
.into());
}

let suggestion = component_suggestion(desc, &component, &config, &manifest, false);
let target = component.target.expect("component target should be known");
if let Some(platform) = Platform::find(&target) {
return Err(RustupError::UnavailableTarget {
Expand Down
39 changes: 39 additions & 0 deletions tests/suite/cli_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1923,6 +1923,45 @@ error: toolchain 'stable-[HOST_TUPLE]' does not contain component 'rust-analysis
.is_err();
}

#[tokio::test]
async fn add_component_not_available_with_suggestion() {
let cx = CliTestContext::new(Scenario::SimpleV2).await;
cx.config
.expect(["rustup", "toolchain", "install", "nightly"])
.await
.is_ok();
cx.config
.expect(["rustup", "default", "stable"])
.await
.is_ok();
cx.config
.expect(["rustup", "component", "add", "rls-preview"])
.await
.with_stderr(snapbox::str![[r#"
error: toolchain 'stable-[HOST_TUPLE]' does not contain component 'rls-preview' for target '[HOST_TUPLE]'
help: try `rustup +nightly-[HOST_TUPLE] component add rls-preview`

"#]])
.is_err();
}

#[tokio::test]
async fn add_component_not_available_no_alternative() {
let cx = CliTestContext::new(Scenario::SimpleV2).await;
cx.config
.expect(["rustup", "default", "stable"])
.await
.is_ok();
cx.config
.expect(["rustup", "component", "add", "rls-preview"])
.await
.with_stderr(snapbox::str![[r#"
error: toolchain 'stable-[HOST_TUPLE]' does not contain component 'rls-preview' for target '[HOST_TUPLE]'

"#]])
.is_err();
}

#[tokio::test]
async fn remove_target_no_toolchain() {
let cx = CliTestContext::new(Scenario::SimpleV2).await;
Expand Down
Loading