Skip to content

Commit a755846

Browse files
djcrami3l
authored andcommitted
Deduplicate handling of environnment variables
1 parent eb5601f commit a755846

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

src/config.rs

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use std::borrow::Cow;
22
use std::fmt::{self, Debug, Display};
3-
use std::io;
43
use std::path::{Path, PathBuf};
54
use std::str::FromStr;
65
use std::sync::Arc;
6+
use std::{env, io};
77

88
use anyhow::{anyhow, bail, Context, Result};
99
use serde::Deserialize;
@@ -288,26 +288,20 @@ impl<'a> Cfg<'a> {
288288
let default_host_triple =
289289
settings_file.with(|s| Ok(get_default_host_triple(s, process)))?;
290290
// Environment override
291-
let env_override = process
292-
.var("RUSTUP_TOOLCHAIN")
293-
.ok()
294-
.and_then(if_not_empty)
291+
let env_override = non_empty_env_var("RUSTUP_TOOLCHAIN", process)?
295292
.map(ResolvableLocalToolchainName::try_from)
296293
.transpose()?
297294
.map(|t| t.resolve(&default_host_triple))
298295
.transpose()?;
299296

300-
let dist_root_server = match process.var("RUSTUP_DIST_SERVER") {
301-
Ok(s) if !s.is_empty() => {
297+
let dist_root_server = match non_empty_env_var("RUSTUP_DIST_SERVER", process)? {
298+
Some(s) => {
302299
trace!("`RUSTUP_DIST_SERVER` has been set to `{s}`");
303300
s
304301
}
305-
_ => {
302+
None => {
306303
// For backward compatibility
307-
process
308-
.var("RUSTUP_DIST_ROOT")
309-
.ok()
310-
.and_then(if_not_empty)
304+
non_empty_env_var("RUSTUP_DIST_ROOT", process)?
311305
.inspect(|url| trace!("`RUSTUP_DIST_ROOT` has been set to `{url}`"))
312306
.map_or(Cow::Borrowed(dist::DEFAULT_DIST_ROOT), Cow::Owned)
313307
.as_ref()
@@ -1000,11 +994,12 @@ fn get_default_host_triple(s: &Settings, process: &Process) -> dist::TargetTripl
1000994
.unwrap_or_else(|| dist::TargetTriple::from_host_or_build(process))
1001995
}
1002996

1003-
fn if_not_empty<S: PartialEq<str>>(s: S) -> Option<S> {
1004-
if s == *"" {
1005-
None
1006-
} else {
1007-
Some(s)
997+
fn non_empty_env_var(name: &str, process: &Process) -> anyhow::Result<Option<String>> {
998+
match process.var(name) {
999+
Ok(s) if !s.is_empty() => Ok(Some(s)),
1000+
Ok(_) => Ok(None),
1001+
Err(env::VarError::NotPresent) => Ok(None),
1002+
Err(err) => Err(err.into()),
10081003
}
10091004
}
10101005

0 commit comments

Comments
 (0)