Skip to content
7 changes: 4 additions & 3 deletions src/cli/common.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Just a dumping ground for cli stuff

use std::{
borrow::Cow,
cmp, env,
fmt::Display,
fs,
Expand Down Expand Up @@ -172,7 +173,7 @@ fn show_channel_updates(

let (previous_version, version) = match &pkg {
PackageUpdate::Rustup => {
let previous_version: Option<String> = match result {
let previous_version = match result {
Ok(UpdateStatus::Installed) | Ok(UpdateStatus::Unchanged) | Err(_) => None,
_ => Some(env!("CARGO_PKG_VERSION").into()),
};
Expand All @@ -190,9 +191,9 @@ fn show_channel_updates(
// again. Perhaps we can do better.
let version = match Toolchain::new(cfg, name.clone().into()) {
Ok(t) => t.rustc_version(),
Err(_) => String::from("(toolchain not installed)"),
Err(_) => Cow::Borrowed("(toolchain not installed)"),
};
let previous_version: Option<String> = match result {
let previous_version = match result {
Ok(UpdateStatus::Installed) | Ok(UpdateStatus::Unchanged) | Err(_) => None,
Ok(UpdateStatus::Updated(v)) => Some(v),
};
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 @@ -1175,7 +1175,7 @@ pub(crate) async fn update(cfg: &Cfg<'_>) -> anyhow::Result<ExitCode> {
let _ = common::show_channel_update(
cfg,
PackageUpdate::Rustup,
Ok(UpdateStatus::Updated(version)),
Ok(UpdateStatus::Updated(Cow::Owned(version))),
);
return run_update(prepared_updater, cfg.process);
}
Expand Down
8 changes: 4 additions & 4 deletions src/dist/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! Installation from a Rust distribution server

use std::{
collections::HashSet, env, fmt, io::Write, ops::Deref, path::PathBuf, str::FromStr,
sync::LazyLock,
borrow::Cow, collections::HashSet, env, fmt, io::Write, ops::Deref, path::PathBuf,
str::FromStr, sync::LazyLock,
};

use anyhow::{Context, anyhow};
Expand Down Expand Up @@ -853,7 +853,7 @@ pub(crate) struct DistOptions<'cfg, 'a> {
/// toolchain already exists
pub(super) exists: bool,
/// currently installed date and version
pub(super) old_date_version: Option<(String, String)>,
pub(super) old_date_version: Option<(Cow<'static, str>, Cow<'static, str>)>,
/// Extra components to install from dist
components: &'a [&'a str],
/// Extra targets to install from dist
Expand Down Expand Up @@ -898,7 +898,7 @@ impl<'cfg, 'a> DistOptions<'cfg, 'a> {
toolchain.get_manifest()
.map(|m| {
(
m.date,
Cow::Owned(m.date),
// should rustc_version be a free function on a trait?
// note that prev_version can be junk if the rustc component is missing ...
toolchain.toolchain.rustc_version(),
Expand Down
4 changes: 2 additions & 2 deletions src/install.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Installation and upgrade of both distribution-managed and local
//! toolchains
use std::path::Path;
use std::{borrow::Cow, path::Path};

use tracing::debug;

Expand All @@ -15,7 +15,7 @@ use crate::{
#[derive(Clone, Debug)]
pub(crate) enum UpdateStatus {
Installed,
Updated(String), // Stores the version of rustc *before* the update
Updated(Cow<'static, str>), // Stores the version of rustc *before* the update
Unchanged,
}

Expand Down
91 changes: 50 additions & 41 deletions src/toolchain.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{
borrow::Cow,
env::{self, consts::EXE_SUFFIX},
ffi::{OsStr, OsString},
fmt::Debug,
Expand Down Expand Up @@ -256,49 +257,57 @@ impl<'a> Toolchain<'a> {

/// Infallible function that describes the version of rustc in an installed distribution
#[tracing::instrument(level = "trace")]
pub fn rustc_version(&self) -> String {
match self.create_command("rustc") {
Ok(mut cmd) => {
cmd.arg("--version");
cmd.stdin(Stdio::null());
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
self.set_ldpath(&mut cmd);

// some toolchains are faulty with some combinations of platforms and
// may fail to launch but also to timely terminate.
// (known cases include Rust 1.3.0 through 1.10.0 in recent macOS Sierra.)
// we guard against such cases by enforcing a reasonable timeout to read.
let mut line1 = None;
if let Ok(mut child) = cmd.spawn() {
let timeout = Duration::new(10, 0);
match child.wait_timeout(timeout) {
Ok(Some(status)) if status.success() => {
let out = child
.stdout
.expect("Child::stdout requested but not present");
let mut line = String::new();
if BufReader::new(out).read_line(&mut line).is_ok() {
let lineend = line.trim_end_matches(&['\r', '\n'][..]).len();
line.truncate(lineend);
line1 = Some(line);
}
}
Ok(None) => {
let _ = child.kill();
return String::from("(timeout reading rustc version)");
}
Ok(Some(_)) | Err(_) => {}
}
}
pub fn rustc_version(&self) -> Cow<'static, str> {
let mut cmd = match self.create_command("rustc") {
Ok(cmd) => cmd,
Err(e) => {
let e = format!("{e:#}");
return Cow::Owned(format!(
"(could not create proxy command to rustc: {})",
e.lines().next().unwrap_or_default(),
));
}
};

if let Some(line1) = line1 {
line1
} else {
String::from("(error reading rustc version)")
cmd.arg("--version");
cmd.stdin(Stdio::null());
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
self.set_ldpath(&mut cmd);

// some toolchains are faulty with some combinations of platforms and
// may fail to launch but also to timely terminate.
// (known cases include Rust 1.3.0 through 1.10.0 in recent macOS Sierra.)
// we guard against such cases by enforcing a reasonable timeout to read.
let mut child = match cmd.spawn() {
Err(e) => return Cow::Owned(format!("(error reading rustc version: {e})")),
Ok(child) => child,
};

let generic_error = Cow::Borrowed("(error reading rustc version)");
match child.wait_timeout(Duration::from_secs(10)) {
Ok(None) => {
let _ = child.kill();
Cow::Borrowed("(timeout reading rustc version)")
}
Ok(Some(status)) if status.success() => {
let out = child
.stdout
.expect("Child::stdout requested but not present");
let mut line = String::new();
match BufReader::new(out).read_line(&mut line) {
Err(_) => generic_error,
Ok(_) => {
let lineend = line.trim_end_matches(&['\r', '\n'][..]).len();
line.truncate(lineend);
Cow::Owned(line)
}
}
}
Err(_) => String::from("(rustc does not exist)"),
Ok(Some(status)) => Cow::Owned(format!(
"(error reading rustc version: rustc quit with {status})"
)),
Err(_) => generic_error,
}
}

Expand Down Expand Up @@ -469,7 +478,7 @@ impl<'a> Toolchain<'a> {
} else {
let t = &self.name;
return Err(anyhow!(
"'{binary_lossy}' is not installed for the custom toolchain '{t}'.\nnote: this is a custom toolchain, which cannot use `rustup component add`\n\
"'{binary_lossy}' is not installed for the custom toolchain '{t}'\nnote: this is a custom toolchain, which cannot use `rustup component add`\n\
help: if you built this toolchain from source, and used `rustup toolchain link`, then you may be able to build the component with `x.py`"
));
}
Expand Down
132 changes: 132 additions & 0 deletions tests/suite/cli_rustup.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Test cases for new rustup UI

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::{
env::consts::EXE_SUFFIX,
fs,
Expand Down Expand Up @@ -1814,6 +1816,136 @@ path: [RUSTUP_DIR]/toolchains/nightly-[HOST_TUPLE]
.is_ok();
}

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

let path = cx.config.customdir.join("custom-1");
let path_str = path.to_string_lossy();
cx.config
.expect(["rustup", "toolchain", "link", "custom", &path_str])
.await
.is_ok();
cx.config
.expect(["rustup", "default", "custom"])
.await
.is_ok();
fs::remove_file(path.join(format!("bin/rustc{EXE_SUFFIX}"))).unwrap();
cx.config
.expect(["rustup", "show", "active-toolchain", "--verbose"])
.await
.extend_redactions([("[RUSTUP_DIR]", &cx.config.rustupdir.to_string())])
.extend_redactions([("[STATUS]", "exit status"), ("[STATUS]", "exit code")])
.with_stdout(snapbox::str![[r#"
custom
active because: it's the default toolchain
compiler: (error reading rustc version: rustc quit with [STATUS]: 1)
path: [RUSTUP_DIR]/toolchains/custom

"#]])
.is_ok();
}

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

let path = cx.config.customdir.join("custom-1");
let path_str = path.to_string_lossy();
cx.config
.expect(["rustup", "toolchain", "link", "custom", &path_str])
.await
.is_ok();
cx.config
.expect(["rustup", "default", "custom"])
.await
.is_ok();
fs::remove_file(path.join(format!("bin/rustc{EXE_SUFFIX}"))).unwrap();
cx.config
.expect_with_env(
["rustup", "show", "active-toolchain", "--verbose"],
[(
"RUST_RECURSION_COUNT",
&*RUST_RECURSION_COUNT_MAX.to_string(),
)],
)
.await
.extend_redactions([("[RUSTUP_DIR]", &cx.config.rustupdir.to_string())])
.with_stdout(snapbox::str![[r#"
custom
active because: it's the default toolchain
compiler: (could not create proxy command to rustc: 'rustc[EXE]' is not installed for the custom toolchain 'custom')
path: [RUSTUP_DIR]/toolchains/custom

"#]])
.is_ok();
}

#[cfg(unix)]
#[tokio::test]
async fn show_active_toolchain_with_verbose_rustc_error() {
let cx = CliTestContext::new(Scenario::SimpleV2).await;
let path = cx.config.customdir.join("custom-1");
let path_str = path.to_string_lossy();
cx.config
.expect(["rustup", "toolchain", "link", "custom", &path_str])
.await
.is_ok();
cx.config
.expect(["rustup", "default", "custom"])
.await
.is_ok();
// Replace mock rustc with a shell script that exits 1
let rustc_path = path.join(format!("bin/rustc{EXE_SUFFIX}"));
fs::write(&rustc_path, "#!/bin/sh\nexit 1\n").unwrap();
cx.config
.expect(["rustup", "show", "active-toolchain", "--verbose"])
.await
.extend_redactions([("[RUSTUP_DIR]", &cx.config.rustupdir.to_string())])
.extend_redactions([("[STATUS]", "exit status"), ("[STATUS]", "exit code")])
.with_stdout(snapbox::str![[r#"
custom
active because: it's the default toolchain
compiler: (error reading rustc version: rustc quit with [STATUS]: 1)
path: [RUSTUP_DIR]/toolchains/custom

"#]])
.is_ok();
}

#[cfg(unix)]
#[tokio::test]
async fn show_active_toolchain_with_verbose_rustc_permission_denied() {
let cx = CliTestContext::new(Scenario::SimpleV2).await;
let path = cx.config.customdir.join("custom-1");
let path_str = path.to_string_lossy();
cx.config
.expect(["rustup", "toolchain", "link", "custom", &path_str])
.await
.is_ok();
cx.config
.expect(["rustup", "default", "custom"])
.await
.is_ok();
// Remove the executable bit so that spawn() fails with a permission error.
let rustc_path = path.join(format!("bin/rustc{EXE_SUFFIX}"));
let mut perms = fs::metadata(&rustc_path).unwrap().permissions();
perms.set_mode(0o644);
fs::set_permissions(&rustc_path, perms).unwrap();
cx.config
.expect(["rustup", "show", "active-toolchain", "--verbose"])
.await
.extend_redactions([("[RUSTUP_DIR]", &cx.config.rustupdir.to_string())])
.with_stdout(snapbox::str![[r#"
custom
active because: it's the default toolchain
compiler: (error reading rustc version: Permission denied (os error 13))
path: [RUSTUP_DIR]/toolchains/custom

"#]])
.is_ok();
}

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