-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
mod.rs
2647 lines (2414 loc) · 95.3 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Cargo's config system.
//!
//! The `Config` object contains general information about the environment,
//! and provides access to Cargo's configuration files.
//!
//! ## Config value API
//!
//! The primary API for fetching user-defined config values is the
//! `Config::get` method. It uses `serde` to translate config values to a
//! target type.
//!
//! There are a variety of helper types for deserializing some common formats:
//!
//! - `value::Value`: This type provides access to the location where the
//! config value was defined.
//! - `ConfigRelativePath`: For a path that is relative to where it is
//! defined.
//! - `PathAndArgs`: Similar to `ConfigRelativePath`, but also supports a list
//! of arguments, useful for programs to execute.
//! - `StringList`: Get a value that is either a list or a whitespace split
//! string.
//!
//! ## Map key recommendations
//!
//! Handling tables that have arbitrary keys can be tricky, particularly if it
//! should support environment variables. In general, if possible, the caller
//! should pass the full key path into the `get()` method so that the config
//! deserializer can properly handle environment variables (which need to be
//! uppercased, and dashes converted to underscores).
//!
//! A good example is the `[target]` table. The code will request
//! `target.$TRIPLE` and the config system can then appropriately fetch
//! environment variables like `CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER`.
//! Conversely, it is not possible do the same thing for the `cfg()` target
//! tables (because Cargo must fetch all of them), so those do not support
//! environment variables.
//!
//! Try to avoid keys that are a prefix of another with a dash/underscore. For
//! example `build.target` and `build.target-dir`. This is OK if these are not
//! structs/maps, but if it is a struct or map, then it will not be able to
//! read the environment variable due to ambiguity. (See `ConfigMapAccess` for
//! more details.)
//!
//! ## Internal API
//!
//! Internally config values are stored with the `ConfigValue` type after they
//! have been loaded from disk. This is similar to the `toml::Value` type, but
//! includes the definition location. The `get()` method uses serde to
//! translate from `ConfigValue` and environment variables to the caller's
//! desired type.
use std::borrow::Cow;
use std::cell::{RefCell, RefMut};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::env;
use std::ffi::OsStr;
use std::fmt;
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::{self, SeekFrom};
use std::mem;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Once;
use std::time::Instant;
use self::ConfigValue as CV;
use crate::core::compiler::rustdoc::RustdocExternMap;
use crate::core::shell::Verbosity;
use crate::core::{features, CliUnstable, Shell, SourceId, Workspace, WorkspaceRootConfig};
use crate::ops::{self, RegistryCredentialConfig};
use crate::util::errors::CargoResult;
use crate::util::validate_package_name;
use crate::util::CanonicalUrl;
use crate::util::{internal, toml as cargo_toml};
use crate::util::{FileLock, Filesystem, IntoUrl, IntoUrlWithBase, Rustc};
use anyhow::{anyhow, bail, format_err, Context as _};
use cargo_util::paths;
use curl::easy::Easy;
use lazycell::LazyCell;
use serde::Deserialize;
use toml_edit::{easy as toml, Item};
use url::Url;
mod de;
use de::Deserializer;
mod value;
pub use value::{Definition, OptValue, Value};
mod key;
pub use key::ConfigKey;
mod path;
pub use path::{ConfigRelativePath, PathAndArgs};
mod target;
pub use target::{TargetCfgConfig, TargetConfig};
// Helper macro for creating typed access methods.
macro_rules! get_value_typed {
($name:ident, $ty:ty, $variant:ident, $expected:expr) => {
/// Low-level private method for getting a config value as an OptValue.
fn $name(&self, key: &ConfigKey) -> Result<OptValue<$ty>, ConfigError> {
let cv = self.get_cv(key)?;
let env = self.get_env::<$ty>(key)?;
match (cv, env) {
(Some(CV::$variant(val, definition)), Some(env)) => {
if definition.is_higher_priority(&env.definition) {
Ok(Some(Value { val, definition }))
} else {
Ok(Some(env))
}
}
(Some(CV::$variant(val, definition)), None) => Ok(Some(Value { val, definition })),
(Some(cv), _) => Err(ConfigError::expected(key, $expected, &cv)),
(None, Some(env)) => Ok(Some(env)),
(None, None) => Ok(None),
}
}
};
}
/// Indicates why a config value is being loaded.
#[derive(Clone, Copy, Debug)]
enum WhyLoad {
/// Loaded due to a request from the global cli arg `--config`
///
/// Indirect configs loaded via [`config-include`] are also seen as from cli args,
/// if the initial config is being loaded from cli.
///
/// [`config-include`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#config-include
Cli,
/// Loaded due to config file discovery.
FileDiscovery,
}
/// A previously generated authentication token and the data needed to determine if it can be reused.
pub struct CredentialCacheValue {
/// If the command line was used to override the token then it must always be reused,
/// even if reading the configuration files would lead to a different value.
pub from_commandline: bool,
/// If nothing depends on which endpoint is being hit, then we can reuse the token
/// for any future request even if some of the requests involve mutations.
pub independent_of_endpoint: bool,
pub token_value: String,
}
impl fmt::Debug for CredentialCacheValue {
/// This manual implementation helps ensure that the token value is redacted from all logs.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CredentialCacheValue")
.field("from_commandline", &self.from_commandline)
.field("token_value", &"REDACTED")
.finish()
}
}
/// Configuration information for cargo. This is not specific to a build, it is information
/// relating to cargo itself.
#[derive(Debug)]
pub struct Config {
/// The location of the user's Cargo home directory. OS-dependent.
home_path: Filesystem,
/// Information about how to write messages to the shell
shell: RefCell<Shell>,
/// A collection of configuration options
values: LazyCell<HashMap<String, ConfigValue>>,
/// A collection of configuration options from the credentials file
credential_values: LazyCell<HashMap<String, ConfigValue>>,
/// CLI config values, passed in via `configure`.
cli_config: Option<Vec<String>>,
/// The current working directory of cargo
cwd: PathBuf,
/// Directory where config file searching should stop (inclusive).
search_stop_path: Option<PathBuf>,
/// The location of the cargo executable (path to current process)
cargo_exe: LazyCell<PathBuf>,
/// The location of the rustdoc executable
rustdoc: LazyCell<PathBuf>,
/// Whether we are printing extra verbose messages
extra_verbose: bool,
/// `frozen` is the same as `locked`, but additionally will not access the
/// network to determine if the lock file is out-of-date.
frozen: bool,
/// `locked` is set if we should not update lock files. If the lock file
/// is missing, or needs to be updated, an error is produced.
locked: bool,
/// `offline` is set if we should never access the network, but otherwise
/// continue operating if possible.
offline: bool,
/// A global static IPC control mechanism (used for managing parallel builds)
jobserver: Option<jobserver::Client>,
/// Cli flags of the form "-Z something" merged with config file values
unstable_flags: CliUnstable,
/// Cli flags of the form "-Z something"
unstable_flags_cli: Option<Vec<String>>,
/// A handle on curl easy mode for http calls
easy: LazyCell<RefCell<Easy>>,
/// Cache of the `SourceId` for crates.io
crates_io_source_id: LazyCell<SourceId>,
/// If false, don't cache `rustc --version --verbose` invocations
cache_rustc_info: bool,
/// Creation time of this config, used to output the total build time
creation_time: Instant,
/// Target Directory via resolved Cli parameter
target_dir: Option<Filesystem>,
/// Environment variables, separated to assist testing.
env: HashMap<String, String>,
/// Environment variables, converted to uppercase to check for case mismatch
upper_case_env: HashMap<String, String>,
/// Tracks which sources have been updated to avoid multiple updates.
updated_sources: LazyCell<RefCell<HashSet<SourceId>>>,
/// Cache of credentials from configuration or credential providers.
/// Maps from url to credential value.
credential_cache: LazyCell<RefCell<HashMap<CanonicalUrl, CredentialCacheValue>>>,
/// Lock, if held, of the global package cache along with the number of
/// acquisitions so far.
package_cache_lock: RefCell<Option<(Option<FileLock>, usize)>>,
/// Cached configuration parsed by Cargo
http_config: LazyCell<CargoHttpConfig>,
future_incompat_config: LazyCell<CargoFutureIncompatConfig>,
net_config: LazyCell<CargoNetConfig>,
build_config: LazyCell<CargoBuildConfig>,
target_cfgs: LazyCell<Vec<(String, TargetCfgConfig)>>,
doc_extern_map: LazyCell<RustdocExternMap>,
progress_config: ProgressConfig,
env_config: LazyCell<EnvConfig>,
/// This should be false if:
/// - this is an artifact of the rustc distribution process for "stable" or for "beta"
/// - this is an `#[test]` that does not opt in with `enable_nightly_features`
/// - this is an integration test that uses `ProcessBuilder`
/// that does not opt in with `masquerade_as_nightly_cargo`
/// This should be true if:
/// - this is an artifact of the rustc distribution process for "nightly"
/// - this is being used in the rustc distribution process internally
/// - this is a cargo executable that was built from source
/// - this is an `#[test]` that called `enable_nightly_features`
/// - this is an integration test that uses `ProcessBuilder`
/// that called `masquerade_as_nightly_cargo`
/// It's public to allow tests use nightly features.
/// NOTE: this should be set before `configure()`. If calling this from an integration test,
/// consider using `ConfigBuilder::enable_nightly_features` instead.
pub nightly_features_allowed: bool,
/// WorkspaceRootConfigs that have been found
pub ws_roots: RefCell<HashMap<PathBuf, WorkspaceRootConfig>>,
}
impl Config {
/// Creates a new config instance.
///
/// This is typically used for tests or other special cases. `default` is
/// preferred otherwise.
///
/// This does only minimal initialization. In particular, it does not load
/// any config files from disk. Those will be loaded lazily as-needed.
pub fn new(shell: Shell, cwd: PathBuf, homedir: PathBuf) -> Config {
static mut GLOBAL_JOBSERVER: *mut jobserver::Client = 0 as *mut _;
static INIT: Once = Once::new();
// This should be called early on in the process, so in theory the
// unsafety is ok here. (taken ownership of random fds)
INIT.call_once(|| unsafe {
if let Some(client) = jobserver::Client::from_env() {
GLOBAL_JOBSERVER = Box::into_raw(Box::new(client));
}
});
let env: HashMap<_, _> = env::vars_os()
.filter_map(|(k, v)| {
// Ignore any key/values that are not valid Unicode.
match (k.into_string(), v.into_string()) {
(Ok(k), Ok(v)) => Some((k, v)),
_ => None,
}
})
.collect();
let upper_case_env = env
.clone()
.into_iter()
.map(|(k, _)| (k.to_uppercase().replace("-", "_"), k))
.collect();
let cache_rustc_info = match env.get("CARGO_CACHE_RUSTC_INFO") {
Some(cache) => cache != "0",
_ => true,
};
Config {
home_path: Filesystem::new(homedir),
shell: RefCell::new(shell),
cwd,
search_stop_path: None,
values: LazyCell::new(),
credential_values: LazyCell::new(),
cli_config: None,
cargo_exe: LazyCell::new(),
rustdoc: LazyCell::new(),
extra_verbose: false,
frozen: false,
locked: false,
offline: false,
jobserver: unsafe {
if GLOBAL_JOBSERVER.is_null() {
None
} else {
Some((*GLOBAL_JOBSERVER).clone())
}
},
unstable_flags: CliUnstable::default(),
unstable_flags_cli: None,
easy: LazyCell::new(),
crates_io_source_id: LazyCell::new(),
cache_rustc_info,
creation_time: Instant::now(),
target_dir: None,
env,
upper_case_env,
updated_sources: LazyCell::new(),
credential_cache: LazyCell::new(),
package_cache_lock: RefCell::new(None),
http_config: LazyCell::new(),
future_incompat_config: LazyCell::new(),
net_config: LazyCell::new(),
build_config: LazyCell::new(),
target_cfgs: LazyCell::new(),
doc_extern_map: LazyCell::new(),
progress_config: ProgressConfig::default(),
env_config: LazyCell::new(),
nightly_features_allowed: matches!(&*features::channel(), "nightly" | "dev"),
ws_roots: RefCell::new(HashMap::new()),
}
}
/// Creates a new Config instance, with all default settings.
///
/// This does only minimal initialization. In particular, it does not load
/// any config files from disk. Those will be loaded lazily as-needed.
pub fn default() -> CargoResult<Config> {
let shell = Shell::new();
let cwd = env::current_dir()
.with_context(|| "couldn't get the current directory of the process")?;
let homedir = homedir(&cwd).ok_or_else(|| {
anyhow!(
"Cargo couldn't find your home directory. \
This probably means that $HOME was not set."
)
})?;
Ok(Config::new(shell, cwd, homedir))
}
/// Gets the user's Cargo home directory (OS-dependent).
pub fn home(&self) -> &Filesystem {
&self.home_path
}
/// Returns a path to display to the user with the location of their home
/// config file (to only be used for displaying a diagnostics suggestion,
/// such as recommending where to add a config value).
pub fn diagnostic_home_config(&self) -> String {
let home = self.home_path.as_path_unlocked();
let path = match self.get_file_path(home, "config", false) {
Ok(Some(existing_path)) => existing_path,
_ => home.join("config.toml"),
};
path.to_string_lossy().to_string()
}
/// Gets the Cargo Git directory (`<cargo_home>/git`).
pub fn git_path(&self) -> Filesystem {
self.home_path.join("git")
}
/// Gets the Cargo base directory for all registry information (`<cargo_home>/registry`).
pub fn registry_base_path(&self) -> Filesystem {
self.home_path.join("registry")
}
/// Gets the Cargo registry index directory (`<cargo_home>/registry/index`).
pub fn registry_index_path(&self) -> Filesystem {
self.registry_base_path().join("index")
}
/// Gets the Cargo registry cache directory (`<cargo_home>/registry/path`).
pub fn registry_cache_path(&self) -> Filesystem {
self.registry_base_path().join("cache")
}
/// Gets the Cargo registry source directory (`<cargo_home>/registry/src`).
pub fn registry_source_path(&self) -> Filesystem {
self.registry_base_path().join("src")
}
/// Gets the default Cargo registry.
pub fn default_registry(&self) -> CargoResult<Option<String>> {
Ok(self
.get_string("registry.default")?
.map(|registry| registry.val))
}
/// Gets a reference to the shell, e.g., for writing error messages.
pub fn shell(&self) -> RefMut<'_, Shell> {
self.shell.borrow_mut()
}
/// Gets the path to the `rustdoc` executable.
pub fn rustdoc(&self) -> CargoResult<&Path> {
self.rustdoc
.try_borrow_with(|| Ok(self.get_tool("rustdoc", &self.build_config()?.rustdoc)))
.map(AsRef::as_ref)
}
/// Gets the path to the `rustc` executable.
pub fn load_global_rustc(&self, ws: Option<&Workspace<'_>>) -> CargoResult<Rustc> {
let cache_location = ws.map(|ws| {
ws.target_dir()
.join(".rustc_info.json")
.into_path_unlocked()
});
let wrapper = self.maybe_get_tool("rustc_wrapper", &self.build_config()?.rustc_wrapper);
let rustc_workspace_wrapper = self.maybe_get_tool(
"rustc_workspace_wrapper",
&self.build_config()?.rustc_workspace_wrapper,
);
Rustc::new(
self.get_tool("rustc", &self.build_config()?.rustc),
wrapper,
rustc_workspace_wrapper,
&self
.home()
.join("bin")
.join("rustc")
.into_path_unlocked()
.with_extension(env::consts::EXE_EXTENSION),
if self.cache_rustc_info {
cache_location
} else {
None
},
)
}
/// Gets the path to the `cargo` executable.
pub fn cargo_exe(&self) -> CargoResult<&Path> {
self.cargo_exe
.try_borrow_with(|| {
fn from_env() -> CargoResult<PathBuf> {
// Try re-using the `cargo` set in the environment already. This allows
// commands that use Cargo as a library to inherit (via `cargo <subcommand>`)
// or set (by setting `$CARGO`) a correct path to `cargo` when the current exe
// is not actually cargo (e.g., `cargo-*` binaries, Valgrind, `ld.so`, etc.).
let exe = env::var_os(crate::CARGO_ENV)
.map(PathBuf::from)
.ok_or_else(|| anyhow!("$CARGO not set"))?
.canonicalize()?;
Ok(exe)
}
fn from_current_exe() -> CargoResult<PathBuf> {
// Try fetching the path to `cargo` using `env::current_exe()`.
// The method varies per operating system and might fail; in particular,
// it depends on `/proc` being mounted on Linux, and some environments
// (like containers or chroots) may not have that available.
let exe = env::current_exe()?.canonicalize()?;
Ok(exe)
}
fn from_argv() -> CargoResult<PathBuf> {
// Grab `argv[0]` and attempt to resolve it to an absolute path.
// If `argv[0]` has one component, it must have come from a `PATH` lookup,
// so probe `PATH` in that case.
// Otherwise, it has multiple components and is either:
// - a relative path (e.g., `./cargo`, `target/debug/cargo`), or
// - an absolute path (e.g., `/usr/local/bin/cargo`).
// In either case, `Path::canonicalize` will return the full absolute path
// to the target if it exists.
let argv0 = env::args_os()
.map(PathBuf::from)
.next()
.ok_or_else(|| anyhow!("no argv[0]"))?;
paths::resolve_executable(&argv0)
}
let exe = from_env()
.or_else(|_| from_current_exe())
.or_else(|_| from_argv())
.with_context(|| "couldn't get the path to cargo executable")?;
Ok(exe)
})
.map(AsRef::as_ref)
}
/// Which package sources have been updated, used to ensure it is only done once.
pub fn updated_sources(&self) -> RefMut<'_, HashSet<SourceId>> {
self.updated_sources
.borrow_with(|| RefCell::new(HashSet::new()))
.borrow_mut()
}
/// Cached credentials from credential providers or configuration.
pub fn credential_cache(&self) -> RefMut<'_, HashMap<CanonicalUrl, CredentialCacheValue>> {
self.credential_cache
.borrow_with(|| RefCell::new(HashMap::new()))
.borrow_mut()
}
/// Gets all config values from disk.
///
/// This will lazy-load the values as necessary. Callers are responsible
/// for checking environment variables. Callers outside of the `config`
/// module should avoid using this.
pub fn values(&self) -> CargoResult<&HashMap<String, ConfigValue>> {
self.values.try_borrow_with(|| self.load_values())
}
/// Gets a mutable copy of the on-disk config values.
///
/// This requires the config values to already have been loaded. This
/// currently only exists for `cargo vendor` to remove the `source`
/// entries. This doesn't respect environment variables. You should avoid
/// using this if possible.
pub fn values_mut(&mut self) -> CargoResult<&mut HashMap<String, ConfigValue>> {
let _ = self.values()?;
Ok(self
.values
.borrow_mut()
.expect("already loaded config values"))
}
// Note: this is used by RLS, not Cargo.
pub fn set_values(&self, values: HashMap<String, ConfigValue>) -> CargoResult<()> {
if self.values.borrow().is_some() {
bail!("config values already found")
}
match self.values.fill(values) {
Ok(()) => Ok(()),
Err(_) => bail!("could not fill values"),
}
}
/// Sets the path where ancestor config file searching will stop. The
/// given path is included, but its ancestors are not.
pub fn set_search_stop_path<P: Into<PathBuf>>(&mut self, path: P) {
let path = path.into();
debug_assert!(self.cwd.starts_with(&path));
self.search_stop_path = Some(path);
}
/// Reloads on-disk configuration values, starting at the given path and
/// walking up its ancestors.
pub fn reload_rooted_at<P: AsRef<Path>>(&mut self, path: P) -> CargoResult<()> {
let values = self.load_values_from(path.as_ref())?;
self.values.replace(values);
self.merge_cli_args()?;
self.load_unstable_flags_from_config()?;
Ok(())
}
/// The current working directory.
pub fn cwd(&self) -> &Path {
&self.cwd
}
/// The `target` output directory to use.
///
/// Returns `None` if the user has not chosen an explicit directory.
///
/// Callers should prefer `Workspace::target_dir` instead.
pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
if let Some(dir) = &self.target_dir {
Ok(Some(dir.clone()))
} else if let Some(dir) = self.env.get("CARGO_TARGET_DIR") {
// Check if the CARGO_TARGET_DIR environment variable is set to an empty string.
if dir.is_empty() {
bail!(
"the target directory is set to an empty string in the \
`CARGO_TARGET_DIR` environment variable"
)
}
Ok(Some(Filesystem::new(self.cwd.join(dir))))
} else if let Some(val) = &self.build_config()?.target_dir {
let path = val.resolve_path(self);
// Check if the target directory is set to an empty string in the config.toml file.
if val.raw_value().is_empty() {
bail!(
"the target directory is set to an empty string in {}",
val.value().definition
)
}
Ok(Some(Filesystem::new(path)))
} else {
Ok(None)
}
}
/// Get a configuration value by key.
///
/// This does NOT look at environment variables. See `get_cv_with_env` for
/// a variant that supports environment variables.
fn get_cv(&self, key: &ConfigKey) -> CargoResult<Option<ConfigValue>> {
if let Some(vals) = self.credential_values.borrow() {
let val = self.get_cv_helper(key, vals)?;
if val.is_some() {
return Ok(val);
}
}
self.get_cv_helper(key, self.values()?)
}
fn get_cv_helper(
&self,
key: &ConfigKey,
vals: &HashMap<String, ConfigValue>,
) -> CargoResult<Option<ConfigValue>> {
log::trace!("get cv {:?}", key);
if key.is_root() {
// Returning the entire root table (for example `cargo config get`
// with no key). The definition here shouldn't matter.
return Ok(Some(CV::Table(
vals.clone(),
Definition::Path(PathBuf::new()),
)));
}
let mut parts = key.parts().enumerate();
let mut val = match vals.get(parts.next().unwrap().1) {
Some(val) => val,
None => return Ok(None),
};
for (i, part) in parts {
match val {
CV::Table(map, _) => {
val = match map.get(part) {
Some(val) => val,
None => return Ok(None),
}
}
CV::Integer(_, def)
| CV::String(_, def)
| CV::List(_, def)
| CV::Boolean(_, def) => {
let mut key_so_far = ConfigKey::new();
for part in key.parts().take(i) {
key_so_far.push(part);
}
bail!(
"expected table for configuration key `{}`, \
but found {} in {}",
key_so_far,
val.desc(),
def
)
}
}
}
Ok(Some(val.clone()))
}
/// This is a helper for getting a CV from a file or env var.
pub(crate) fn get_cv_with_env(&self, key: &ConfigKey) -> CargoResult<Option<CV>> {
// Determine if value comes from env, cli, or file, and merge env if
// possible.
let cv = self.get_cv(key)?;
if key.is_root() {
// Root table can't have env value.
return Ok(cv);
}
let env = self.env.get(key.as_env_key());
let env_def = Definition::Environment(key.as_env_key().to_string());
let use_env = match (&cv, env) {
// Lists are always merged.
(Some(CV::List(..)), Some(_)) => true,
(Some(cv), Some(_)) => env_def.is_higher_priority(cv.definition()),
(None, Some(_)) => true,
_ => false,
};
if !use_env {
return Ok(cv);
}
// Future note: If you ever need to deserialize a non-self describing
// map type, this should implement a starts_with check (similar to how
// ConfigMapAccess does).
let env = env.unwrap();
if env == "true" {
Ok(Some(CV::Boolean(true, env_def)))
} else if env == "false" {
Ok(Some(CV::Boolean(false, env_def)))
} else if let Ok(i) = env.parse::<i64>() {
Ok(Some(CV::Integer(i, env_def)))
} else if self.cli_unstable().advanced_env && env.starts_with('[') && env.ends_with(']') {
match cv {
Some(CV::List(mut cv_list, cv_def)) => {
// Merge with config file.
self.get_env_list(key, &mut cv_list)?;
Ok(Some(CV::List(cv_list, cv_def)))
}
Some(cv) => {
// This can't assume StringList or UnmergedStringList.
// Return an error, which is the behavior of merging
// multiple config.toml files with the same scenario.
bail!(
"unable to merge array env for config `{}`\n\
file: {:?}\n\
env: {}",
key,
cv,
env
);
}
None => {
let mut cv_list = Vec::new();
self.get_env_list(key, &mut cv_list)?;
Ok(Some(CV::List(cv_list, env_def)))
}
}
} else {
// Try to merge if possible.
match cv {
Some(CV::List(mut cv_list, cv_def)) => {
// Merge with config file.
self.get_env_list(key, &mut cv_list)?;
Ok(Some(CV::List(cv_list, cv_def)))
}
_ => {
// Note: CV::Table merging is not implemented, as env
// vars do not support table values. In the future, we
// could check for `{}`, and interpret it as TOML if
// that seems useful.
Ok(Some(CV::String(env.to_string(), env_def)))
}
}
}
}
/// Helper primarily for testing.
pub fn set_env(&mut self, env: HashMap<String, String>) {
self.env = env;
}
/// Returns all environment variables.
pub(crate) fn env(&self) -> &HashMap<String, String> {
&self.env
}
fn get_env<T>(&self, key: &ConfigKey) -> Result<OptValue<T>, ConfigError>
where
T: FromStr,
<T as FromStr>::Err: fmt::Display,
{
match self.env.get(key.as_env_key()) {
Some(value) => {
let definition = Definition::Environment(key.as_env_key().to_string());
Ok(Some(Value {
val: value
.parse()
.map_err(|e| ConfigError::new(format!("{}", e), definition.clone()))?,
definition,
}))
}
None => {
self.check_environment_key_case_mismatch(key);
Ok(None)
}
}
}
/// Check if the [`Config`] contains a given [`ConfigKey`].
///
/// See `ConfigMapAccess` for a description of `env_prefix_ok`.
fn has_key(&self, key: &ConfigKey, env_prefix_ok: bool) -> CargoResult<bool> {
if self.env.contains_key(key.as_env_key()) {
return Ok(true);
}
if env_prefix_ok {
let env_prefix = format!("{}_", key.as_env_key());
if self.env.keys().any(|k| k.starts_with(&env_prefix)) {
return Ok(true);
}
}
if self.get_cv(key)?.is_some() {
return Ok(true);
}
self.check_environment_key_case_mismatch(key);
Ok(false)
}
fn check_environment_key_case_mismatch(&self, key: &ConfigKey) {
if let Some(env_key) = self.upper_case_env.get(key.as_env_key()) {
let _ = self.shell().warn(format!(
"Environment variables are expected to use uppercase letters and underscores, \
the variable `{}` will be ignored and have no effect",
env_key
));
}
}
/// Get a string config value.
///
/// See `get` for more details.
pub fn get_string(&self, key: &str) -> CargoResult<OptValue<String>> {
self.get::<Option<Value<String>>>(key)
}
/// Get a config value that is expected to be a path.
///
/// This returns a relative path if the value does not contain any
/// directory separators. See `ConfigRelativePath::resolve_program` for
/// more details.
pub fn get_path(&self, key: &str) -> CargoResult<OptValue<PathBuf>> {
self.get::<Option<Value<ConfigRelativePath>>>(key).map(|v| {
v.map(|v| Value {
val: v.val.resolve_program(self),
definition: v.definition,
})
})
}
fn string_to_path(&self, value: &str, definition: &Definition) -> PathBuf {
let is_path = value.contains('/') || (cfg!(windows) && value.contains('\\'));
if is_path {
definition.root(self).join(value)
} else {
// A pathless name.
PathBuf::from(value)
}
}
/// Get a list of strings.
///
/// DO NOT USE outside of the config module. `pub` will be removed in the
/// future.
///
/// NOTE: this does **not** support environment variables. Use `get` instead
/// if you want that.
pub fn get_list(&self, key: &str) -> CargoResult<OptValue<Vec<(String, Definition)>>> {
let key = ConfigKey::from_str(key);
self._get_list(&key)
}
fn _get_list(&self, key: &ConfigKey) -> CargoResult<OptValue<Vec<(String, Definition)>>> {
match self.get_cv(key)? {
Some(CV::List(val, definition)) => Ok(Some(Value { val, definition })),
Some(val) => self.expected("list", key, &val),
None => Ok(None),
}
}
/// Helper for StringList type to get something that is a string or list.
fn get_list_or_string(
&self,
key: &ConfigKey,
merge: bool,
) -> CargoResult<Vec<(String, Definition)>> {
let mut res = Vec::new();
if !merge {
self.get_env_list(key, &mut res)?;
if !res.is_empty() {
return Ok(res);
}
}
match self.get_cv(key)? {
Some(CV::List(val, _def)) => res.extend(val),
Some(CV::String(val, def)) => {
let split_vs = val.split_whitespace().map(|s| (s.to_string(), def.clone()));
res.extend(split_vs);
}
Some(val) => {
return self.expected("string or array of strings", key, &val);
}
None => {}
}
self.get_env_list(key, &mut res)?;
Ok(res)
}
/// Internal method for getting an environment variable as a list.
fn get_env_list(
&self,
key: &ConfigKey,
output: &mut Vec<(String, Definition)>,
) -> CargoResult<()> {
let env_val = match self.env.get(key.as_env_key()) {
Some(v) => v,
None => {
self.check_environment_key_case_mismatch(key);
return Ok(());
}
};
let def = Definition::Environment(key.as_env_key().to_string());
if self.cli_unstable().advanced_env && env_val.starts_with('[') && env_val.ends_with(']') {
// Parse an environment string as a TOML array.
let toml_s = format!("value={}", env_val);
let toml_v: toml::Value = toml::de::from_str(&toml_s).map_err(|e| {
ConfigError::new(format!("could not parse TOML list: {}", e), def.clone())
})?;
let values = toml_v
.as_table()
.unwrap()
.get("value")
.unwrap()
.as_array()
.expect("env var was not array");
for value in values {
// TODO: support other types.
let s = value.as_str().ok_or_else(|| {
ConfigError::new(
format!("expected string, found {}", value.type_str()),
def.clone(),
)
})?;
output.push((s.to_string(), def.clone()));
}
} else {
output.extend(
env_val
.split_whitespace()
.map(|s| (s.to_string(), def.clone())),
);
}
Ok(())
}
/// Low-level method for getting a config value as an `OptValue<HashMap<String, CV>>`.
///
/// NOTE: This does not read from env. The caller is responsible for that.
fn get_table(&self, key: &ConfigKey) -> CargoResult<OptValue<HashMap<String, CV>>> {
match self.get_cv(key)? {
Some(CV::Table(val, definition)) => Ok(Some(Value { val, definition })),
Some(val) => self.expected("table", key, &val),
None => Ok(None),
}
}
get_value_typed! {get_integer, i64, Integer, "an integer"}
get_value_typed! {get_bool, bool, Boolean, "true/false"}
get_value_typed! {get_string_priv, String, String, "a string"}
/// Generate an error when the given value is the wrong type.
fn expected<T>(&self, ty: &str, key: &ConfigKey, val: &CV) -> CargoResult<T> {
val.expected(ty, &key.to_string())
.map_err(|e| anyhow!("invalid configuration for key `{}`\n{}", key, e))
}
/// Update the Config instance based on settings typically passed in on
/// the command-line.
///
/// This may also load the config from disk if it hasn't already been
/// loaded.
pub fn configure(
&mut self,
verbose: u32,
quiet: bool,
color: Option<&str>,
frozen: bool,
locked: bool,
offline: bool,
target_dir: &Option<PathBuf>,
unstable_flags: &[String],
cli_config: &[String],
) -> CargoResult<()> {
for warning in self
.unstable_flags
.parse(unstable_flags, self.nightly_features_allowed)?
{
self.shell().warn(warning)?;
}
if !unstable_flags.is_empty() {
// store a copy of the cli flags separately for `load_unstable_flags_from_config`
// (we might also need it again for `reload_rooted_at`)
self.unstable_flags_cli = Some(unstable_flags.to_vec());
}
if !cli_config.is_empty() {
self.cli_config = Some(cli_config.iter().map(|s| s.to_string()).collect());
self.merge_cli_args()?;
}
if self.unstable_flags.config_include {
// If the config was already loaded (like when fetching the
// `[alias]` table), it was loaded with includes disabled because
// the `unstable_flags` hadn't been set up, yet. Any values
// fetched before this step will not process includes, but that
// should be fine (`[alias]` is one of the only things loaded
// before configure). This can be removed when stabilized.
self.reload_rooted_at(self.cwd.clone())?;
}
let extra_verbose = verbose >= 2;
let verbose = verbose != 0;