Skip to content

Commit

Permalink
refactor: use #[cfg()] instead of cfg!() when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
rami3l committed Jul 12, 2024
1 parent ebe1ba8 commit fede22f
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 79 deletions.
48 changes: 27 additions & 21 deletions src/cli/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
use std::cell::RefCell;
use std::fmt::Display;
use std::fs;
use std::io::{BufRead, ErrorKind, Write};
#[cfg(not(windows))]
use std::io::ErrorKind;
use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{cmp, env};
Expand Down Expand Up @@ -319,35 +321,38 @@ pub(crate) async fn update_all_channels(
#[derive(Clone, Copy, Debug)]
pub(crate) enum SelfUpdatePermission {
HardFail,
#[cfg(not(windows))]
Skip,
Permit,
}

#[cfg(windows)]
pub(crate) fn self_update_permitted(_explicit: bool) -> Result<SelfUpdatePermission> {
Ok(SelfUpdatePermission::Permit)
}

#[cfg(not(windows))]
pub(crate) fn self_update_permitted(explicit: bool) -> Result<SelfUpdatePermission> {
if cfg!(windows) {
Ok(SelfUpdatePermission::Permit)
} else {
// Detect if rustup is not meant to self-update
let current_exe = env::current_exe()?;
let current_exe_dir = current_exe.parent().expect("Rustup isn't in a directory‽");
if let Err(e) = tempfile::Builder::new()
.prefix("updtest")
.tempdir_in(current_exe_dir)
{
match e.kind() {
ErrorKind::PermissionDenied => {
trace!("Skipping self-update because we cannot write to the rustup dir");
if explicit {
return Ok(SelfUpdatePermission::HardFail);
} else {
return Ok(SelfUpdatePermission::Skip);
}
// Detect if rustup is not meant to self-update
let current_exe = env::current_exe()?;
let current_exe_dir = current_exe.parent().expect("Rustup isn't in a directory‽");
if let Err(e) = tempfile::Builder::new()
.prefix("updtest")
.tempdir_in(current_exe_dir)
{
match e.kind() {
ErrorKind::PermissionDenied => {
trace!("Skipping self-update because we cannot write to the rustup dir");
if explicit {
return Ok(SelfUpdatePermission::HardFail);
} else {
return Ok(SelfUpdatePermission::Skip);
}
_ => return Err(e.into()),
}
_ => return Err(e.into()),
}
Ok(SelfUpdatePermission::Permit)
}
Ok(SelfUpdatePermission::Permit)
}

/// Performs all of a self-update: check policy, download, apply and exit.
Expand All @@ -360,6 +365,7 @@ where
error!("Unable to self-update. STOP");
return Ok(utils::ExitCode(1));
}
#[cfg(not(windows))]
SelfUpdatePermission::Skip => return Ok(utils::ExitCode(0)),
SelfUpdatePermission::Permit => {}
}
Expand Down
1 change: 1 addition & 0 deletions src/cli/self_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -990,6 +990,7 @@ pub(crate) async fn update(cfg: &Cfg<'_>) -> Result<utils::ExitCode> {
error!("you should probably use your system package manager to update rustup");
return Ok(utils::ExitCode(1));
}
#[cfg(not(windows))]
Skip => {
info!("Skipping self-update at this time");
return Ok(utils::ExitCode(0));
Expand Down
20 changes: 10 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ impl From<LocalToolchainName> for OverrideCfg {
}
}

#[cfg(unix)]
pub(crate) const UNIX_FALLBACK_SETTINGS: &str = "/etc/rustup/settings.toml";

pub(crate) struct Cfg<'a> {
Expand Down Expand Up @@ -266,18 +267,17 @@ impl<'a> Cfg<'a> {
})?;

// Centralised file for multi-user systems to provide admin/distributor set initial values.
let fallback_settings = if cfg!(not(windows)) {
#[cfg(unix)]
let fallback_settings = FallbackSettings::new(
// If present, use the RUSTUP_OVERRIDE_UNIX_FALLBACK_SETTINGS environment
// variable as settings path, or UNIX_FALLBACK_SETTINGS otherwise
FallbackSettings::new(
match process.var("RUSTUP_OVERRIDE_UNIX_FALLBACK_SETTINGS") {
Ok(s) => PathBuf::from(s),
Err(_) => PathBuf::from(UNIX_FALLBACK_SETTINGS),
},
)?
} else {
None
};
match process.var("RUSTUP_OVERRIDE_UNIX_FALLBACK_SETTINGS") {
Ok(s) => PathBuf::from(s),
Err(_) => PathBuf::from(UNIX_FALLBACK_SETTINGS),
},
)?;
#[cfg(windows)]
let fallback_settings = None;

let toolchains_dir = rustup_dir.join("toolchains");
let update_hash_dir = rustup_dir.join("update-hashes");
Expand Down
18 changes: 12 additions & 6 deletions src/dist/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,12 +490,18 @@ impl TargetTriple {
};

let host_triple = match (sysname, machine) {
(_, b"arm") if cfg!(target_os = "android") => Some("arm-linux-androideabi"),
(_, b"armv7l") if cfg!(target_os = "android") => Some("armv7-linux-androideabi"),
(_, b"armv8l") if cfg!(target_os = "android") => Some("armv7-linux-androideabi"),
(_, b"aarch64") if cfg!(target_os = "android") => Some("aarch64-linux-android"),
(_, b"i686") if cfg!(target_os = "android") => Some("i686-linux-android"),
(_, b"x86_64") if cfg!(target_os = "android") => Some("x86_64-linux-android"),
#[cfg(target_os = "android")]
(_, b"arm") => Some("arm-linux-androideabi"),
#[cfg(target_os = "android")]
(_, b"armv7l") => Some("armv7-linux-androideabi"),
#[cfg(target_os = "android")]
(_, b"armv8l") => Some("armv7-linux-androideabi"),
#[cfg(target_os = "android")]
(_, b"aarch64") => Some("aarch64-linux-android"),
#[cfg(target_os = "android")]
(_, b"i686") => Some("i686-linux-android"),
#[cfg(target_os = "android")]
(_, b"x86_64") => Some("x86_64-linux-android"),
(b"Linux", b"x86_64") => Some(TRIPLE_X86_64_UNKNOWN_LINUX),
(b"Linux", b"i686") => Some("i686-unknown-linux-gnu"),
(b"Linux", b"mips") => Some(TRIPLE_MIPS_UNKNOWN_LINUX_GNU),
Expand Down
9 changes: 6 additions & 3 deletions src/fallback_settings.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use serde::Deserialize;
use std::io;
use std::path::Path;
#[cfg(unix)]
use std::{io, path::Path};

#[cfg(unix)]
use anyhow::{Context, Result};
use serde::Deserialize;

#[cfg(unix)]
use crate::utils::utils;

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Default)]
Expand All @@ -12,6 +14,7 @@ pub struct FallbackSettings {
}

impl FallbackSettings {
#[cfg(unix)]
pub(crate) fn new<P: AsRef<Path>>(path: P) -> Result<Option<Self>> {
// Users cannot fix issues with missing/unreadable/invalid centralised files, but logging isn't setup early so
// we can't simply trap all errors and log diagnostics. Ideally we would, and then separate these into different
Expand Down
59 changes: 30 additions & 29 deletions src/toolchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ impl<'a> Toolchain<'a> {

/// Apply the appropriate LD path for a command being run from a toolchain.
fn set_ldpath(&self, cmd: &mut Command) {
#[cfg_attr(not(target_os = "macos"), allow(unused_mut))]
let mut new_path = vec![self.path.join("lib")];

#[cfg(not(target_os = "macos"))]
Expand All @@ -196,13 +197,14 @@ impl<'a> Toolchain<'a> {
// consequences.
pub const LOADER_PATH: &str = "DYLD_FALLBACK_LIBRARY_PATH";
}
if cfg!(target_os = "macos")
&& self
.cfg
.process
.var_os(sysenv::LOADER_PATH)
.filter(|x| x.len() > 0)
.is_none()

#[cfg(target_os = "macos")]
if self
.cfg
.process
.var_os(sysenv::LOADER_PATH)
.filter(|x| x.len() > 0)
.is_none()
{
// These are the defaults when DYLD_FALLBACK_LIBRARY_PATH isn't
// set or set to an empty string. Since we are explicitly setting
Expand All @@ -225,28 +227,27 @@ impl<'a> Toolchain<'a> {
path_entries.push(cargo_home.join("bin"));
}

if cfg!(target_os = "windows") {
// Historically rustup included the bin directory in PATH to
// work around some bugs (see
// https://github.com/rust-lang/rustup/pull/3178 for more
// information). This shouldn't be needed anymore, and it causes
// problems because calling tools recursively (like `cargo
// +nightly metadata` from within a cargo subcommand). The
// recursive call won't work because it is not executing the
// proxy, so the `+` toolchain override doesn't work.
//
// The RUSTUP_WINDOWS_PATH_ADD_BIN env var was added to opt-in to
// testing the fix. The default is now off, but this is left here
// just in case there are problems. Consider removing in the
// future if it doesn't seem necessary.
if self
.cfg
.process
.var_os("RUSTUP_WINDOWS_PATH_ADD_BIN")
.map_or(false, |s| s == "1")
{
path_entries.push(self.path.join("bin"));
}
// Historically rustup included the bin directory in PATH to
// work around some bugs (see
// https://github.com/rust-lang/rustup/pull/3178 for more
// information). This shouldn't be needed anymore, and it causes
// problems because calling tools recursively (like `cargo
// +nightly metadata` from within a cargo subcommand). The
// recursive call won't work because it is not executing the
// proxy, so the `+` toolchain override doesn't work.
//
// The RUSTUP_WINDOWS_PATH_ADD_BIN env var was added to opt-in to
// testing the fix. The default is now off, but this is left here
// just in case there are problems. Consider removing in the
// future if it doesn't seem necessary.
#[cfg(target_os = "windows")]
if self
.cfg
.process
.var_os("RUSTUP_WINDOWS_PATH_ADD_BIN")
.map_or(false, |s| s == "1")
{
path_entries.push(self.path.join("bin"));
}

env_var::prepend_path("PATH", path_entries, cmd, self.cfg.process);
Expand Down
20 changes: 12 additions & 8 deletions src/toolchain/distributable.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::{
convert::Infallible, env::consts::EXE_SUFFIX, ffi::OsStr, fs, path::Path, process::Command,
};
#[cfg(windows)]
use std::fs;
use std::{convert::Infallible, env::consts::EXE_SUFFIX, ffi::OsStr, path::Path, process::Command};

use anyhow::{anyhow, Context};
use anyhow::anyhow;
#[cfg(windows)]
use anyhow::Context;

use crate::{
component_for_bin,
Expand Down Expand Up @@ -198,19 +200,21 @@ impl<'a> DistributableToolchain<'a> {
// directory for the exe to spawn before searching PATH, and we don't want
// it to do that, because cargo's directory contains the _wrong_ rustc. See
// the documentation for the lpCommandLine argument of CreateProcess.
let exe_path = if cfg!(windows) {
#[cfg(windows)]
let exe_path = {
let fallback_dir = self.toolchain.cfg.rustup_dir.join("fallback");
fs::create_dir_all(&fallback_dir)
.context("unable to create dir to hold fallback exe")?;
let fallback_file = fallback_dir.join("cargo.exe");
if fallback_file.exists() {
fs::remove_file(&fallback_file).context("unable to unlink old fallback exe")?;
}
fs::hard_link(&src_file, &fallback_file).context("unable to hard link fallback exe")?;
fs::hard_link(src_file, &fallback_file).context("unable to hard link fallback exe")?;
fallback_file
} else {
src_file
};
#[cfg(not(windows))]
let exe_path = src_file;

let mut cmd = Command::new(exe_path);
installed_primary.set_env(&mut cmd); // set up the environment to match rustc, not cargo
cmd.env("RUSTUP_TOOLCHAIN", installed_primary.name().to_string());
Expand Down
7 changes: 5 additions & 2 deletions src/utils/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,12 @@ pub(crate) fn hardlink(src: &Path, dest: &Path) -> io::Result<()> {

pub fn remove_dir(path: &Path) -> io::Result<()> {
if fs::symlink_metadata(path)?.file_type().is_symlink() {
if cfg!(windows) {
#[cfg(windows)]
{
fs::remove_dir(path)
} else {
}
#[cfg(not(windows))]
{
fs::remove_file(path)
}
} else {
Expand Down

0 comments on commit fede22f

Please sign in to comment.