Skip to content

Commit 7b98113

Browse files
committed
Auto merge of #11727 - kylematsuda:config-env, r=ehuss
Read environment variables through `Config` instead of `std::env::var(_os)` ### What does this PR try to resolve? Adds two new methods `get_env` and `get_env_os` for reading environment variables from the `Config` and uses them to replace the many of the calls to `std::env::var` and `var_os` (see the discussion in #11588). Closes #11588
2 parents e48bc21 + b864262 commit 7b98113

23 files changed

+176
-118
lines changed

src/bin/cargo/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ fn is_executable<P: AsRef<Path>>(path: P) -> bool {
235235
}
236236

237237
fn search_directories(config: &Config) -> Vec<PathBuf> {
238-
let mut path_dirs = if let Some(val) = env::var_os("PATH") {
238+
let mut path_dirs = if let Some(val) = config.get_env_os("PATH") {
239239
env::split_paths(&val).collect()
240240
} else {
241241
vec![]

src/cargo/core/compiler/build_context/target_info.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ use cargo_util::{paths, ProcessBuilder};
2020
use serde::{Deserialize, Serialize};
2121
use std::cell::RefCell;
2222
use std::collections::hash_map::{Entry, HashMap};
23-
use std::env;
2423
use std::path::{Path, PathBuf};
2524
use std::str::{self, FromStr};
2625

@@ -731,7 +730,7 @@ fn extra_args(
731730
// NOTE: It is impossible to have a [host] section and reach this logic with kind.is_host(),
732731
// since [host] implies `target-applies-to-host = false`, which always early-returns above.
733732

734-
if let Some(rustflags) = rustflags_from_env(flags) {
733+
if let Some(rustflags) = rustflags_from_env(config, flags) {
735734
Ok(rustflags)
736735
} else if let Some(rustflags) =
737736
rustflags_from_target(config, host_triple, target_cfg, kind, flags)?
@@ -746,18 +745,18 @@ fn extra_args(
746745

747746
/// Gets compiler flags from environment variables.
748747
/// See [`extra_args`] for more.
749-
fn rustflags_from_env(flags: Flags) -> Option<Vec<String>> {
748+
fn rustflags_from_env(config: &Config, flags: Flags) -> Option<Vec<String>> {
750749
// First try CARGO_ENCODED_RUSTFLAGS from the environment.
751750
// Prefer this over RUSTFLAGS since it's less prone to encoding errors.
752-
if let Ok(a) = env::var(format!("CARGO_ENCODED_{}", flags.as_env())) {
751+
if let Ok(a) = config.get_env(format!("CARGO_ENCODED_{}", flags.as_env())) {
753752
if a.is_empty() {
754753
return Some(Vec::new());
755754
}
756755
return Some(a.split('\x1f').map(str::to_string).collect());
757756
}
758757

759758
// Then try RUSTFLAGS from the environment
760-
if let Ok(a) = env::var(flags.as_env()) {
759+
if let Ok(a) = config.get_env(flags.as_env()) {
761760
let args = a
762761
.split(' ')
763762
.map(str::trim)
@@ -855,7 +854,7 @@ pub struct RustcTargetData<'cfg> {
855854
pub rustc: Rustc,
856855

857856
/// Config
858-
config: &'cfg Config,
857+
pub config: &'cfg Config,
859858
requested_kinds: Vec<CompileKind>,
860859

861860
/// Build information for the "host", which is information about when

src/cargo/core/compiler/compilation.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
//! Type definitions for the result of a compilation.
22
33
use std::collections::{BTreeSet, HashMap};
4-
use std::env;
54
use std::ffi::{OsStr, OsString};
65
use std::path::PathBuf;
76

@@ -295,7 +294,7 @@ impl<'cfg> Compilation<'cfg> {
295294
// These are the defaults when DYLD_FALLBACK_LIBRARY_PATH isn't
296295
// set or set to an empty string. Since Cargo is explicitly setting
297296
// the value, make sure the defaults still work.
298-
if let Some(home) = env::var_os("HOME") {
297+
if let Some(home) = self.config.get_env_os("HOME") {
299298
search_path.push(PathBuf::from(home).join("lib"));
300299
}
301300
search_path.push(PathBuf::from("/usr/local/lib"));
@@ -362,7 +361,7 @@ impl<'cfg> Compilation<'cfg> {
362361
continue;
363362
}
364363

365-
if value.is_force() || env::var_os(key).is_none() {
364+
if value.is_force() || self.config.get_env_os(key).is_none() {
366365
cmd.env(key, value.resolve(self.config));
367366
}
368367
}

src/cargo/core/compiler/context/compilation_files.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
//! See [`CompilationFiles`].
22
33
use std::collections::HashMap;
4-
use std::env;
54
use std::fmt;
65
use std::hash::{Hash, Hasher};
76
use std::path::{Path, PathBuf};
@@ -628,7 +627,7 @@ fn compute_metadata(
628627

629628
// Seed the contents of `__CARGO_DEFAULT_LIB_METADATA` to the hasher if present.
630629
// This should be the release channel, to get a different hash for each channel.
631-
if let Ok(ref channel) = env::var("__CARGO_DEFAULT_LIB_METADATA") {
630+
if let Ok(ref channel) = cx.bcx.config.get_env("__CARGO_DEFAULT_LIB_METADATA") {
632631
channel.hash(&mut hasher);
633632
}
634633

@@ -717,7 +716,7 @@ fn should_use_metadata(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
717716
|| (unit.target.is_executable() && short_name == "wasm32-unknown-emscripten")
718717
|| (unit.target.is_executable() && short_name.contains("msvc")))
719718
&& unit.pkg.package_id().source_id().is_path()
720-
&& env::var("__CARGO_DEFAULT_LIB_METADATA").is_err()
719+
&& bcx.config.get_env("__CARGO_DEFAULT_LIB_METADATA").is_err()
721720
{
722721
return false;
723722
}

src/cargo/core/compiler/standard_lib.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ use crate::ops::{self, Packages};
1111
use crate::util::errors::CargoResult;
1212
use crate::Config;
1313
use std::collections::{HashMap, HashSet};
14-
use std::env;
1514
use std::path::PathBuf;
1615

1716
use super::BuildConfig;
@@ -222,7 +221,7 @@ pub fn generate_std_roots(
222221
}
223222

224223
fn detect_sysroot_src_path(target_data: &RustcTargetData<'_>) -> CargoResult<PathBuf> {
225-
if let Some(s) = env::var_os("__CARGO_TESTS_ONLY_SRC_ROOT") {
224+
if let Some(s) = target_data.config.get_env_os("__CARGO_TESTS_ONLY_SRC_ROOT") {
226225
return Ok(s.into());
227226
}
228227

@@ -241,7 +240,7 @@ fn detect_sysroot_src_path(target_data: &RustcTargetData<'_>) -> CargoResult<Pat
241240
library, try:\n rustup component add rust-src",
242241
lock
243242
);
244-
match env::var("RUSTUP_TOOLCHAIN") {
243+
match target_data.config.get_env("RUSTUP_TOOLCHAIN") {
245244
Ok(rustup_toolchain) => {
246245
anyhow::bail!("{} --toolchain {}", msg, rustup_toolchain);
247246
}

src/cargo/core/profiles.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use crate::util::{closest_msg, config, CargoResult, Config};
3131
use anyhow::{bail, Context as _};
3232
use std::collections::{BTreeMap, HashMap, HashSet};
3333
use std::hash::Hash;
34-
use std::{cmp, env, fmt, hash};
34+
use std::{cmp, fmt, hash};
3535

3636
/// Collection of all profiles.
3737
///
@@ -62,7 +62,7 @@ pub struct Profiles {
6262
impl Profiles {
6363
pub fn new(ws: &Workspace<'_>, requested_profile: InternedString) -> CargoResult<Profiles> {
6464
let config = ws.config();
65-
let incremental = match env::var_os("CARGO_INCREMENTAL") {
65+
let incremental = match config.get_env_os("CARGO_INCREMENTAL") {
6666
Some(v) => Some(v == "1"),
6767
None => config.build_config()?.incremental,
6868
};

src/cargo/ops/cargo_compile/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,14 +215,14 @@ pub fn create_bcx<'a, 'cfg>(
215215
| CompileMode::Check { .. }
216216
| CompileMode::Bench
217217
| CompileMode::RunCustomBuild => {
218-
if std::env::var("RUST_FLAGS").is_ok() {
218+
if ws.config().get_env("RUST_FLAGS").is_ok() {
219219
config.shell().warn(
220220
"Cargo does not read `RUST_FLAGS` environment variable. Did you mean `RUSTFLAGS`?",
221221
)?;
222222
}
223223
}
224224
CompileMode::Doc { .. } | CompileMode::Doctest | CompileMode::Docscrape => {
225-
if std::env::var("RUSTDOC_FLAGS").is_ok() {
225+
if ws.config().get_env("RUSTDOC_FLAGS").is_ok() {
226226
config.shell().warn(
227227
"Cargo does not read `RUSTDOC_FLAGS` environment variable. Did you mean `RUSTDOCFLAGS`?"
228228
)?;

src/cargo/ops/cargo_config.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ fn maybe_env<'config>(
9393
config: &'config Config,
9494
key: &ConfigKey,
9595
cv: &CV,
96-
) -> Option<Vec<(&'config String, &'config String)>> {
96+
) -> Option<Vec<(&'config str, &'config str)>> {
9797
// Only fetching a table is unable to load env values. Leaf entries should
9898
// work properly.
9999
match cv {
@@ -102,7 +102,6 @@ fn maybe_env<'config>(
102102
}
103103
let mut env: Vec<_> = config
104104
.env()
105-
.iter()
106105
.filter(|(env_key, _val)| env_key.starts_with(&format!("{}_", key.as_env_key())))
107106
.collect();
108107
env.sort_by_key(|x| x.0);
@@ -162,7 +161,7 @@ fn print_toml(config: &Config, opts: &GetOptions<'_>, key: &ConfigKey, cv: &CV)
162161
}
163162
}
164163

165-
fn print_toml_env(config: &Config, env: &[(&String, &String)]) {
164+
fn print_toml_env(config: &Config, env: &[(&str, &str)]) {
166165
drop_println!(
167166
config,
168167
"# The following environment variables may affect the loaded values."
@@ -173,7 +172,7 @@ fn print_toml_env(config: &Config, env: &[(&String, &String)]) {
173172
}
174173
}
175174

176-
fn print_json_env(config: &Config, env: &[(&String, &String)]) {
175+
fn print_json_env(config: &Config, env: &[(&str, &str)]) {
177176
drop_eprintln!(
178177
config,
179178
"note: The following environment variables may affect the loaded values."
@@ -287,7 +286,6 @@ fn print_toml_unmerged(config: &Config, opts: &GetOptions<'_>, key: &ConfigKey)
287286
// special, and will just naturally get loaded as part of the config.
288287
let mut env: Vec<_> = config
289288
.env()
290-
.iter()
291289
.filter(|(env_key, _val)| env_key.starts_with(key.as_env_key()))
292290
.collect();
293291
if !env.is_empty() {

src/cargo/ops/cargo_doc.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::core::{Shell, Workspace};
22
use crate::ops;
3-
use crate::util::config::PathAndArgs;
3+
use crate::util::config::{Config, PathAndArgs};
44
use crate::util::CargoResult;
55
use std::path::Path;
66
use std::path::PathBuf;
@@ -37,7 +37,7 @@ pub fn doc(ws: &Workspace<'_>, options: &DocOptions) -> CargoResult<()> {
3737

3838
let mut shell = ws.config().shell();
3939
shell.status("Opening", path.display())?;
40-
open_docs(&path, &mut shell, config_browser)?;
40+
open_docs(&path, &mut shell, config_browser, ws.config())?;
4141
}
4242
}
4343

@@ -48,9 +48,10 @@ fn open_docs(
4848
path: &Path,
4949
shell: &mut Shell,
5050
config_browser: Option<(PathBuf, Vec<String>)>,
51+
config: &Config,
5152
) -> CargoResult<()> {
5253
let browser =
53-
config_browser.or_else(|| Some((PathBuf::from(std::env::var_os("BROWSER")?), Vec::new())));
54+
config_browser.or_else(|| Some((PathBuf::from(config.get_env_os("BROWSER")?), Vec::new())));
5455

5556
match browser {
5657
Some((browser, initial_args)) => {

src/cargo/ops/cargo_install.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -704,7 +704,7 @@ pub fn install(
704704
if installed_anything {
705705
// Print a warning that if this directory isn't in PATH that they won't be
706706
// able to run these commands.
707-
let path = env::var_os("PATH").unwrap_or_default();
707+
let path = config.get_env_os("PATH").unwrap_or_default();
708708
let dst_in_path = env::split_paths(&path).any(|path| path == dst);
709709

710710
if !dst_in_path {

src/cargo/ops/cargo_new.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> {
463463

464464
pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<NewProjectKind> {
465465
// This is here just as a random location to exercise the internal error handling.
466-
if std::env::var_os("__CARGO_TEST_INTERNAL_ERROR").is_some() {
466+
if config.get_env_os("__CARGO_TEST_INTERNAL_ERROR").is_some() {
467467
return Err(crate::util::internal("internal error test"));
468468
}
469469

src/cargo/ops/common_for_install_and_uninstall.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,7 @@ pub fn resolve_root(flag: Option<&str>, config: &Config) -> CargoResult<Filesyst
506506
let config_root = config.get_path("install.root")?;
507507
Ok(flag
508508
.map(PathBuf::from)
509-
.or_else(|| env::var_os("CARGO_INSTALL_ROOT").map(PathBuf::from))
509+
.or_else(|| config.get_env_os("CARGO_INSTALL_ROOT").map(PathBuf::from))
510510
.or_else(move || config_root.map(|v| v.val))
511511
.map(Filesystem::new)
512512
.unwrap_or_else(|| config.home().clone()))

0 commit comments

Comments
 (0)