1use std::cell::{RefCell, RefMut};
2use std::collections::hash_map::Entry::{Occupied, Vacant};
3use std::collections::hash_map::HashMap;
4use std::collections::HashSet;
5use std::env;
6use std::fmt;
7use std::fs::{self, File};
8use std::io::prelude::*;
9use std::io::SeekFrom;
10use std::mem;
11use std::path::{Path, PathBuf};
12use std::str::FromStr;
13use std::sync::{Once, ONCE_INIT};
14use std::time::Instant;
15use std::vec;
16
17use curl::easy::Easy;
18use lazycell::LazyCell;
19use serde::Deserialize;
20use serde::{de, de::IntoDeserializer};
21
22use crate::core::profiles::ConfigProfiles;
23use crate::core::shell::Verbosity;
24use crate::core::{CliUnstable, Shell, SourceId, Workspace};
25use crate::ops;
26use crate::util::errors::{internal, CargoResult, CargoResultExt};
27use crate::util::toml as cargo_toml;
28use crate::util::Filesystem;
29use crate::util::Rustc;
30use crate::util::ToUrl;
31use crate::util::{paths, validate_package_name};
32use url::Url;
33
34use self::ConfigValue as CV;
35
36#[derive(Debug)]
41pub struct Config {
42 home_path: Filesystem,
44 shell: RefCell<Shell>,
46 values: LazyCell<HashMap<String, ConfigValue>>,
48 cwd: PathBuf,
50 cargo_exe: LazyCell<PathBuf>,
52 rustdoc: LazyCell<PathBuf>,
54 extra_verbose: bool,
56 frozen: bool,
58 locked: bool,
60 jobserver: Option<jobserver::Client>,
62 cli_flags: CliUnstable,
64 easy: LazyCell<RefCell<Easy>>,
66 crates_io_source_id: LazyCell<SourceId>,
68 cache_rustc_info: bool,
70 creation_time: Instant,
72 target_dir: Option<Filesystem>,
74 env: HashMap<String, String>,
76 profiles: LazyCell<ConfigProfiles>,
78}
79
80impl Config {
81 pub fn new(shell: Shell, cwd: PathBuf, homedir: PathBuf) -> Config {
82 static mut GLOBAL_JOBSERVER: *mut jobserver::Client = 0 as *mut _;
83 static INIT: Once = ONCE_INIT;
84
85 INIT.call_once(|| unsafe {
88 if let Some(client) = jobserver::Client::from_env() {
89 GLOBAL_JOBSERVER = Box::into_raw(Box::new(client));
90 }
91 });
92
93 let env: HashMap<_, _> = env::vars_os()
94 .filter_map(|(k, v)| {
95 match (k.into_string(), v.into_string()) {
97 (Ok(k), Ok(v)) => Some((k, v)),
98 _ => None,
99 }
100 })
101 .collect();
102
103 let cache_rustc_info = match env.get("CARGO_CACHE_RUSTC_INFO") {
104 Some(cache) => cache != "0",
105 _ => true,
106 };
107
108 Config {
109 home_path: Filesystem::new(homedir),
110 shell: RefCell::new(shell),
111 cwd,
112 values: LazyCell::new(),
113 cargo_exe: LazyCell::new(),
114 rustdoc: LazyCell::new(),
115 extra_verbose: false,
116 frozen: false,
117 locked: false,
118 jobserver: unsafe {
119 if GLOBAL_JOBSERVER.is_null() {
120 None
121 } else {
122 Some((*GLOBAL_JOBSERVER).clone())
123 }
124 },
125 cli_flags: CliUnstable::default(),
126 easy: LazyCell::new(),
127 crates_io_source_id: LazyCell::new(),
128 cache_rustc_info,
129 creation_time: Instant::now(),
130 target_dir: None,
131 env,
132 profiles: LazyCell::new(),
133 }
134 }
135
136 pub fn default() -> CargoResult<Config> {
137 let shell = Shell::new();
138 let cwd =
139 env::current_dir().chain_err(|| "couldn't get the current directory of the process")?;
140 let homedir = homedir(&cwd).ok_or_else(|| {
141 failure::format_err!(
142 "Cargo couldn't find your home directory. \
143 This probably means that $HOME was not set."
144 )
145 })?;
146 Ok(Config::new(shell, cwd, homedir))
147 }
148
149 pub fn home(&self) -> &Filesystem {
151 &self.home_path
152 }
153
154 pub fn git_path(&self) -> Filesystem {
156 self.home_path.join("git")
157 }
158
159 pub fn registry_index_path(&self) -> Filesystem {
161 self.home_path.join("registry").join("index")
162 }
163
164 pub fn registry_cache_path(&self) -> Filesystem {
166 self.home_path.join("registry").join("cache")
167 }
168
169 pub fn registry_source_path(&self) -> Filesystem {
171 self.home_path.join("registry").join("src")
172 }
173
174 pub fn default_registry(&self) -> CargoResult<Option<String>> {
176 Ok(match self.get_string("registry.default")? {
177 Some(registry) => Some(registry.val),
178 None => None,
179 })
180 }
181
182 pub fn shell(&self) -> RefMut<'_, Shell> {
184 self.shell.borrow_mut()
185 }
186
187 pub fn rustdoc(&self) -> CargoResult<&Path> {
189 self.rustdoc
190 .try_borrow_with(|| self.get_tool("rustdoc"))
191 .map(AsRef::as_ref)
192 }
193
194 pub fn rustc(&self, ws: Option<&Workspace<'_>>) -> CargoResult<Rustc> {
196 let cache_location = ws.map(|ws| {
197 ws.target_dir()
198 .join(".rustc_info.json")
199 .into_path_unlocked()
200 });
201 Rustc::new(
202 self.get_tool("rustc")?,
203 self.maybe_get_tool("rustc_wrapper")?,
204 &self
205 .home()
206 .join("bin")
207 .join("rustc")
208 .into_path_unlocked()
209 .with_extension(env::consts::EXE_EXTENSION),
210 if self.cache_rustc_info {
211 cache_location
212 } else {
213 None
214 },
215 )
216 }
217
218 pub fn cargo_exe(&self) -> CargoResult<&Path> {
220 self.cargo_exe
221 .try_borrow_with(|| {
222 fn from_current_exe() -> CargoResult<PathBuf> {
223 let exe = env::current_exe()?.canonicalize()?;
228 Ok(exe)
229 }
230
231 fn from_argv() -> CargoResult<PathBuf> {
232 let argv0 = env::args_os()
241 .map(PathBuf::from)
242 .next()
243 .ok_or_else(|| failure::format_err!("no argv[0]"))?;
244 paths::resolve_executable(&argv0)
245 }
246
247 let exe = from_current_exe()
248 .or_else(|_| from_argv())
249 .chain_err(|| "couldn't get the path to cargo executable")?;
250 Ok(exe)
251 })
252 .map(AsRef::as_ref)
253 }
254
255 pub fn profiles(&self) -> CargoResult<&ConfigProfiles> {
256 self.profiles.try_borrow_with(|| {
257 let ocp = self.get::<Option<ConfigProfiles>>("profile")?;
258 if let Some(config_profiles) = ocp {
259 if !self.cli_unstable().config_profile {
261 self.shell().warn(
262 "profiles in config files require `-Z config-profile` \
263 command-line option",
264 )?;
265 return Ok(ConfigProfiles::default());
266 }
267 Ok(config_profiles)
268 } else {
269 Ok(ConfigProfiles::default())
270 }
271 })
272 }
273
274 pub fn values(&self) -> CargoResult<&HashMap<String, ConfigValue>> {
275 self.values.try_borrow_with(|| self.load_values())
276 }
277
278 pub fn set_values(&self, values: HashMap<String, ConfigValue>) -> CargoResult<()> {
280 if self.values.borrow().is_some() {
281 failure::bail!("config values already found")
282 }
283 match self.values.fill(values) {
284 Ok(()) => Ok(()),
285 Err(_) => failure::bail!("could not fill values"),
286 }
287 }
288
289 pub fn reload_rooted_at_cargo_home(&mut self) -> CargoResult<()> {
290 let home = self.home_path.clone().into_path_unlocked();
291 let values = self.load_values_from(&home)?;
292 self.values.replace(values);
293 Ok(())
294 }
295
296 pub fn cwd(&self) -> &Path {
297 &self.cwd
298 }
299
300 pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
301 if let Some(ref dir) = self.target_dir {
302 Ok(Some(dir.clone()))
303 } else if let Some(dir) = env::var_os("CARGO_TARGET_DIR") {
304 Ok(Some(Filesystem::new(self.cwd.join(dir))))
305 } else if let Some(val) = self.get_path("build.target-dir")? {
306 let val = self.cwd.join(val.val);
307 Ok(Some(Filesystem::new(val)))
308 } else {
309 Ok(None)
310 }
311 }
312
313 fn get_cv(&self, key: &str) -> CargoResult<Option<ConfigValue>> {
314 let vals = self.values()?;
315 let mut parts = key.split('.').enumerate();
316 let mut val = match vals.get(parts.next().unwrap().1) {
317 Some(val) => val,
318 None => return Ok(None),
319 };
320 for (i, part) in parts {
321 match *val {
322 CV::Table(ref map, _) => {
323 val = match map.get(part) {
324 Some(val) => val,
325 None => return Ok(None),
326 }
327 }
328 CV::Integer(_, ref path)
329 | CV::String(_, ref path)
330 | CV::List(_, ref path)
331 | CV::Boolean(_, ref path) => {
332 let idx = key.split('.').take(i).fold(0, |n, s| n + s.len()) + i - 1;
333 let key_so_far = &key[..idx];
334 failure::bail!(
335 "expected table for configuration key `{}`, \
336 but found {} in {}",
337 key_so_far,
338 val.desc(),
339 path.display()
340 )
341 }
342 }
343 }
344 Ok(Some(val.clone()))
345 }
346
347 pub fn set_env(&mut self, env: HashMap<String, String>) {
349 self.env = env;
350 }
351
352 fn get_env<T>(&self, key: &ConfigKey) -> Result<OptValue<T>, ConfigError>
353 where
354 T: FromStr,
355 <T as FromStr>::Err: fmt::Display,
356 {
357 let key = key.to_env();
358 match self.env.get(&key) {
359 Some(value) => {
360 let definition = Definition::Environment(key);
361 Ok(Some(Value {
362 val: value
363 .parse()
364 .map_err(|e| ConfigError::new(format!("{}", e), definition.clone()))?,
365 definition,
366 }))
367 }
368 None => Ok(None),
369 }
370 }
371
372 fn has_key(&self, key: &ConfigKey) -> bool {
373 let env_key = key.to_env();
374 if self.env.get(&env_key).is_some() {
375 return true;
376 }
377 let env_pattern = format!("{}_", env_key);
378 if self.env.keys().any(|k| k.starts_with(&env_pattern)) {
379 return true;
380 }
381 if let Ok(o_cv) = self.get_cv(&key.to_config()) {
382 if o_cv.is_some() {
383 return true;
384 }
385 }
386 false
387 }
388
389 pub fn get_string(&self, key: &str) -> CargoResult<OptValue<String>> {
390 self.get_string_priv(&ConfigKey::from_str(key))
391 .map_err(|e| e.into())
392 }
393
394 fn get_string_priv(&self, key: &ConfigKey) -> Result<OptValue<String>, ConfigError> {
395 match self.get_env(key)? {
396 Some(v) => Ok(Some(v)),
397 None => {
398 let config_key = key.to_config();
399 let o_cv = self.get_cv(&config_key)?;
400 match o_cv {
401 Some(CV::String(s, path)) => Ok(Some(Value {
402 val: s,
403 definition: Definition::Path(path),
404 })),
405 Some(cv) => Err(ConfigError::expected(&config_key, "a string", &cv)),
406 None => Ok(None),
407 }
408 }
409 }
410 }
411
412 pub fn get_bool(&self, key: &str) -> CargoResult<OptValue<bool>> {
413 self.get_bool_priv(&ConfigKey::from_str(key))
414 .map_err(|e| e.into())
415 }
416
417 fn get_bool_priv(&self, key: &ConfigKey) -> Result<OptValue<bool>, ConfigError> {
418 match self.get_env(key)? {
419 Some(v) => Ok(Some(v)),
420 None => {
421 let config_key = key.to_config();
422 let o_cv = self.get_cv(&config_key)?;
423 match o_cv {
424 Some(CV::Boolean(b, path)) => Ok(Some(Value {
425 val: b,
426 definition: Definition::Path(path),
427 })),
428 Some(cv) => Err(ConfigError::expected(&config_key, "true/false", &cv)),
429 None => Ok(None),
430 }
431 }
432 }
433 }
434
435 fn string_to_path(&self, value: String, definition: &Definition) -> PathBuf {
436 let is_path = value.contains('/') || (cfg!(windows) && value.contains('\\'));
437 if is_path {
438 definition.root(self).join(value)
439 } else {
440 PathBuf::from(value)
442 }
443 }
444
445 pub fn get_path(&self, key: &str) -> CargoResult<OptValue<PathBuf>> {
446 if let Some(val) = self.get_string(key)? {
447 Ok(Some(Value {
448 val: self.string_to_path(val.val, &val.definition),
449 definition: val.definition,
450 }))
451 } else {
452 Ok(None)
453 }
454 }
455
456 pub fn get_path_and_args(&self, key: &str) -> CargoResult<OptValue<(PathBuf, Vec<String>)>> {
457 if let Some(mut val) = self.get_list_or_split_string(key)? {
458 if !val.val.is_empty() {
459 return Ok(Some(Value {
460 val: (
461 self.string_to_path(val.val.remove(0), &val.definition),
462 val.val,
463 ),
464 definition: val.definition,
465 }));
466 }
467 }
468 Ok(None)
469 }
470
471 pub fn get_list(&self, key: &str) -> CargoResult<OptValue<Vec<(String, PathBuf)>>> {
474 match self.get_cv(key)? {
475 Some(CV::List(i, path)) => Ok(Some(Value {
476 val: i,
477 definition: Definition::Path(path),
478 })),
479 Some(val) => self.expected("list", key, &val),
480 None => Ok(None),
481 }
482 }
483
484 pub fn get_list_or_split_string(&self, key: &str) -> CargoResult<OptValue<Vec<String>>> {
485 if let Some(value) = self.get_env::<String>(&ConfigKey::from_str(key))? {
486 return Ok(Some(Value {
487 val: value.val.split(' ').map(str::to_string).collect(),
488 definition: value.definition,
489 }));
490 }
491
492 match self.get_cv(key)? {
493 Some(CV::List(i, path)) => Ok(Some(Value {
494 val: i.into_iter().map(|(s, _)| s).collect(),
495 definition: Definition::Path(path),
496 })),
497 Some(CV::String(i, path)) => Ok(Some(Value {
498 val: i.split(' ').map(str::to_string).collect(),
499 definition: Definition::Path(path),
500 })),
501 Some(val) => self.expected("list or string", key, &val),
502 None => Ok(None),
503 }
504 }
505
506 pub fn get_table(&self, key: &str) -> CargoResult<OptValue<HashMap<String, CV>>> {
507 match self.get_cv(key)? {
508 Some(CV::Table(i, path)) => Ok(Some(Value {
509 val: i,
510 definition: Definition::Path(path),
511 })),
512 Some(val) => self.expected("table", key, &val),
513 None => Ok(None),
514 }
515 }
516
517 pub fn get_i64(&self, key: &str) -> CargoResult<OptValue<i64>> {
520 self.get_integer(&ConfigKey::from_str(key))
521 .map_err(|e| e.into())
522 }
523
524 fn get_integer(&self, key: &ConfigKey) -> Result<OptValue<i64>, ConfigError> {
525 let config_key = key.to_config();
526 match self.get_env::<i64>(key)? {
527 Some(v) => Ok(Some(v)),
528 None => match self.get_cv(&config_key)? {
529 Some(CV::Integer(i, path)) => Ok(Some(Value {
530 val: i,
531 definition: Definition::Path(path),
532 })),
533 Some(cv) => Err(ConfigError::expected(&config_key, "an integer", &cv)),
534 None => Ok(None),
535 },
536 }
537 }
538
539 fn expected<T>(&self, ty: &str, key: &str, val: &CV) -> CargoResult<T> {
540 val.expected(ty, key)
541 .map_err(|e| failure::format_err!("invalid configuration for key `{}`\n{}", key, e))
542 }
543
544 pub fn configure(
545 &mut self,
546 verbose: u32,
547 quiet: Option<bool>,
548 color: &Option<String>,
549 frozen: bool,
550 locked: bool,
551 target_dir: &Option<PathBuf>,
552 unstable_flags: &[String],
553 ) -> CargoResult<()> {
554 let extra_verbose = verbose >= 2;
555 let verbose = if verbose == 0 { None } else { Some(true) };
556
557 let cfg_verbose = self.get_bool("term.verbose").unwrap_or(None).map(|v| v.val);
559 let cfg_color = self.get_string("term.color").unwrap_or(None).map(|v| v.val);
560
561 let color = color.as_ref().or_else(|| cfg_color.as_ref());
562
563 let verbosity = match (verbose, cfg_verbose, quiet) {
564 (Some(true), _, None) | (None, Some(true), None) => Verbosity::Verbose,
565
566 (None, _, Some(true)) => Verbosity::Quiet,
569
570 (Some(true), _, Some(true)) => {
573 failure::bail!("cannot set both --verbose and --quiet");
574 }
575
576 (Some(false), _, _)
580 | (_, _, Some(false))
581 | (None, Some(false), None)
582 | (None, None, None) => Verbosity::Normal,
583 };
584
585 let cli_target_dir = match target_dir.as_ref() {
586 Some(dir) => Some(Filesystem::new(dir.clone())),
587 None => None,
588 };
589
590 self.shell().set_verbosity(verbosity);
591 self.shell().set_color_choice(color.map(|s| &s[..]))?;
592 self.extra_verbose = extra_verbose;
593 self.frozen = frozen;
594 self.locked = locked;
595 self.target_dir = cli_target_dir;
596 self.cli_flags.parse(unstable_flags)?;
597
598 Ok(())
599 }
600
601 pub fn cli_unstable(&self) -> &CliUnstable {
602 &self.cli_flags
603 }
604
605 pub fn extra_verbose(&self) -> bool {
606 self.extra_verbose
607 }
608
609 pub fn network_allowed(&self) -> bool {
610 !self.frozen() && !self.cli_unstable().offline
611 }
612
613 pub fn frozen(&self) -> bool {
614 self.frozen
615 }
616
617 pub fn lock_update_allowed(&self) -> bool {
618 !self.frozen && !self.locked
619 }
620
621 pub fn load_values(&self) -> CargoResult<HashMap<String, ConfigValue>> {
623 self.load_values_from(&self.cwd)
624 }
625
626 fn load_values_from(&self, path: &Path) -> CargoResult<HashMap<String, ConfigValue>> {
627 let mut cfg = CV::Table(HashMap::new(), PathBuf::from("."));
628 let home = self.home_path.clone().into_path_unlocked();
629
630 walk_tree(path, &home, |path| {
631 let mut contents = String::new();
632 let mut file = File::open(&path)?;
633 file.read_to_string(&mut contents)
634 .chain_err(|| format!("failed to read configuration file `{}`", path.display()))?;
635 let toml = cargo_toml::parse(&contents, path, self).chain_err(|| {
636 format!("could not parse TOML configuration in `{}`", path.display())
637 })?;
638 let value = CV::from_toml(path, toml).chain_err(|| {
639 format!(
640 "failed to load TOML configuration from `{}`",
641 path.display()
642 )
643 })?;
644 cfg.merge(value)
645 .chain_err(|| format!("failed to merge configuration at `{}`", path.display()))?;
646 Ok(())
647 })
648 .chain_err(|| "could not load Cargo configuration")?;
649
650 self.load_credentials(&mut cfg)?;
651 match cfg {
652 CV::Table(map, _) => Ok(map),
653 _ => unreachable!(),
654 }
655 }
656
657 pub fn get_registry_index(&self, registry: &str) -> CargoResult<Url> {
659 validate_package_name(registry, "registry name", "")?;
660 Ok(
661 match self.get_string(&format!("registries.{}.index", registry))? {
662 Some(index) => {
663 let url = index.val.to_url()?;
664 if url.password().is_some() {
665 failure::bail!("Registry URLs may not contain passwords");
666 }
667 url
668 }
669 None => failure::bail!("No index found for registry: `{}`", registry),
670 },
671 )
672 }
673
674 fn load_credentials(&self, cfg: &mut ConfigValue) -> CargoResult<()> {
676 let home_path = self.home_path.clone().into_path_unlocked();
677 let credentials = home_path.join("credentials");
678 if fs::metadata(&credentials).is_err() {
679 return Ok(());
680 }
681
682 let mut contents = String::new();
683 let mut file = File::open(&credentials)?;
684 file.read_to_string(&mut contents).chain_err(|| {
685 format!(
686 "failed to read configuration file `{}`",
687 credentials.display()
688 )
689 })?;
690
691 let toml = cargo_toml::parse(&contents, &credentials, self).chain_err(|| {
692 format!(
693 "could not parse TOML configuration in `{}`",
694 credentials.display()
695 )
696 })?;
697
698 let mut value = CV::from_toml(&credentials, toml).chain_err(|| {
699 format!(
700 "failed to load TOML configuration from `{}`",
701 credentials.display()
702 )
703 })?;
704
705 {
707 let value = match value {
708 CV::Table(ref mut value, _) => value,
709 _ => unreachable!(),
710 };
711
712 if let Some(token) = value.remove("token") {
713 if let Vacant(entry) = value.entry("registry".into()) {
714 let mut map = HashMap::new();
715 map.insert("token".into(), token);
716 let table = CV::Table(map, PathBuf::from("."));
717 entry.insert(table);
718 }
719 }
720 }
721
722 mem::swap(cfg, &mut value);
724 cfg.merge(value)?;
725
726 Ok(())
727 }
728
729 fn maybe_get_tool(&self, tool: &str) -> CargoResult<Option<PathBuf>> {
732 let var = tool
733 .chars()
734 .flat_map(|c| c.to_uppercase())
735 .collect::<String>();
736 if let Some(tool_path) = env::var_os(&var) {
737 let maybe_relative = match tool_path.to_str() {
738 Some(s) => s.contains('/') || s.contains('\\'),
739 None => false,
740 };
741 let path = if maybe_relative {
742 self.cwd.join(tool_path)
743 } else {
744 PathBuf::from(tool_path)
745 };
746 return Ok(Some(path));
747 }
748
749 let var = format!("build.{}", tool);
750 if let Some(tool_path) = self.get_path(&var)? {
751 return Ok(Some(tool_path.val));
752 }
753
754 Ok(None)
755 }
756
757 fn get_tool(&self, tool: &str) -> CargoResult<PathBuf> {
760 self.maybe_get_tool(tool)
761 .map(|t| t.unwrap_or_else(|| PathBuf::from(tool)))
762 }
763
764 pub fn jobserver_from_env(&self) -> Option<&jobserver::Client> {
765 self.jobserver.as_ref()
766 }
767
768 pub fn http(&self) -> CargoResult<&RefCell<Easy>> {
769 let http = self
770 .easy
771 .try_borrow_with(|| ops::http_handle(self).map(RefCell::new))?;
772 {
773 let mut http = http.borrow_mut();
774 http.reset();
775 let timeout = ops::configure_http_handle(self, &mut http)?;
776 timeout.configure(&mut http)?;
777 }
778 Ok(http)
779 }
780
781 pub fn crates_io_source_id<F>(&self, f: F) -> CargoResult<SourceId>
782 where
783 F: FnMut() -> CargoResult<SourceId>,
784 {
785 Ok(*(self.crates_io_source_id.try_borrow_with(f)?))
786 }
787
788 pub fn creation_time(&self) -> Instant {
789 self.creation_time
790 }
791
792 pub fn get<'de, T: de::Deserialize<'de>>(&self, key: &str) -> CargoResult<T> {
799 let d = Deserializer {
800 config: self,
801 key: ConfigKey::from_str(key),
802 };
803 T::deserialize(d).map_err(|e| e.into())
804 }
805}
806
807#[derive(Debug, Clone, Eq, PartialEq, Hash)]
812enum ConfigKeyPart {
813 Part(String),
815 CasePart(String),
817}
818
819impl ConfigKeyPart {
820 fn to_env(&self) -> String {
821 match self {
822 ConfigKeyPart::Part(s) => s.replace("-", "_").to_uppercase(),
823 ConfigKeyPart::CasePart(s) => s.clone(),
824 }
825 }
826
827 fn to_config(&self) -> String {
828 match self {
829 ConfigKeyPart::Part(s) => s.clone(),
830 ConfigKeyPart::CasePart(s) => s.clone(),
831 }
832 }
833}
834
835#[derive(Debug, Clone)]
837struct ConfigKey(Vec<ConfigKeyPart>);
838
839impl ConfigKey {
840 fn from_str(key: &str) -> ConfigKey {
841 ConfigKey(
842 key.split('.')
843 .map(|p| ConfigKeyPart::Part(p.to_string()))
844 .collect(),
845 )
846 }
847
848 fn join(&self, next: ConfigKeyPart) -> ConfigKey {
849 let mut res = self.clone();
850 res.0.push(next);
851 res
852 }
853
854 fn to_env(&self) -> String {
855 format!(
856 "CARGO_{}",
857 self.0
858 .iter()
859 .map(|p| p.to_env())
860 .collect::<Vec<_>>()
861 .join("_")
862 )
863 }
864
865 fn to_config(&self) -> String {
866 self.0
867 .iter()
868 .map(|p| p.to_config())
869 .collect::<Vec<_>>()
870 .join(".")
871 }
872
873 fn last(&self) -> &ConfigKeyPart {
874 self.0.last().unwrap()
875 }
876}
877
878impl fmt::Display for ConfigKey {
879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 self.to_config().fmt(f)
881 }
882}
883
884#[derive(Debug)]
886pub struct ConfigError {
887 error: failure::Error,
888 definition: Option<Definition>,
889}
890
891impl ConfigError {
892 fn new(message: String, definition: Definition) -> ConfigError {
893 ConfigError {
894 error: failure::err_msg(message),
895 definition: Some(definition),
896 }
897 }
898
899 fn expected(key: &str, expected: &str, found: &ConfigValue) -> ConfigError {
900 ConfigError {
901 error: failure::format_err!(
902 "`{}` expected {}, but found a {}",
903 key,
904 expected,
905 found.desc()
906 ),
907 definition: Some(Definition::Path(found.definition_path().to_path_buf())),
908 }
909 }
910
911 fn missing(key: &str) -> ConfigError {
912 ConfigError {
913 error: failure::format_err!("missing config key `{}`", key),
914 definition: None,
915 }
916 }
917
918 fn with_key_context(self, key: &str, definition: Definition) -> ConfigError {
919 ConfigError {
920 error: failure::format_err!("could not load config key `{}`: {}", key, self),
921 definition: Some(definition),
922 }
923 }
924}
925
926impl std::error::Error for ConfigError {
927 fn description(&self) -> &str {
929 "An error has occurred."
930 }
931}
932
933impl fmt::Display for ConfigError {
938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939 let message = self
940 .error
941 .iter_chain()
942 .map(|e| e.to_string())
943 .collect::<Vec<_>>()
944 .join("\nCaused by:\n ");
945 if let Some(ref definition) = self.definition {
946 write!(f, "error in {}: {}", definition, message)
947 } else {
948 message.fmt(f)
949 }
950 }
951}
952
953impl de::Error for ConfigError {
954 fn custom<T: fmt::Display>(msg: T) -> Self {
955 ConfigError {
956 error: failure::err_msg(msg.to_string()),
957 definition: None,
958 }
959 }
960}
961
962impl From<failure::Error> for ConfigError {
963 fn from(error: failure::Error) -> Self {
964 ConfigError {
965 error,
966 definition: None,
967 }
968 }
969}
970
971pub struct Deserializer<'config> {
974 config: &'config Config,
975 key: ConfigKey,
976}
977
978macro_rules! deserialize_method {
979 ($method:ident, $visit:ident, $getter:ident) => {
980 fn $method<V>(self, visitor: V) -> Result<V::Value, Self::Error>
981 where
982 V: de::Visitor<'de>,
983 {
984 let v = self.config.$getter(&self.key)?.ok_or_else(||
985 ConfigError::missing(&self.key.to_config()))?;
986 let Value{val, definition} = v;
987 let res: Result<V::Value, ConfigError> = visitor.$visit(val);
988 res.map_err(|e| e.with_key_context(&self.key.to_config(), definition))
989 }
990 }
991}
992
993impl<'de, 'config> de::Deserializer<'de> for Deserializer<'config> {
994 type Error = ConfigError;
995
996 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
997 where
998 V: de::Visitor<'de>,
999 {
1000 if let Some(v) = self.config.env.get(&self.key.to_env()) {
1004 let res: Result<V::Value, ConfigError> = if v == "true" || v == "false" {
1005 visitor.visit_bool(v.parse().unwrap())
1006 } else if let Ok(v) = v.parse::<i64>() {
1007 visitor.visit_i64(v)
1008 } else if self.config.cli_unstable().advanced_env
1009 && v.starts_with('[')
1010 && v.ends_with(']')
1011 {
1012 visitor.visit_seq(ConfigSeqAccess::new(self.config, &self.key)?)
1013 } else {
1014 visitor.visit_string(v.clone())
1015 };
1016 return res.map_err(|e| {
1017 e.with_key_context(
1018 &self.key.to_config(),
1019 Definition::Environment(self.key.to_env()),
1020 )
1021 });
1022 }
1023
1024 let o_cv = self.config.get_cv(&self.key.to_config())?;
1025 if let Some(cv) = o_cv {
1026 let res: (Result<V::Value, ConfigError>, PathBuf) = match cv {
1027 CV::Integer(i, path) => (visitor.visit_i64(i), path),
1028 CV::String(s, path) => (visitor.visit_string(s), path),
1029 CV::List(_, path) => (
1030 visitor.visit_seq(ConfigSeqAccess::new(self.config, &self.key)?),
1031 path,
1032 ),
1033 CV::Table(_, path) => (
1034 visitor.visit_map(ConfigMapAccess::new_map(self.config, self.key.clone())?),
1035 path,
1036 ),
1037 CV::Boolean(b, path) => (visitor.visit_bool(b), path),
1038 };
1039 let (res, path) = res;
1040 return res
1041 .map_err(|e| e.with_key_context(&self.key.to_config(), Definition::Path(path)));
1042 }
1043 Err(ConfigError::missing(&self.key.to_config()))
1044 }
1045
1046 deserialize_method!(deserialize_bool, visit_bool, get_bool_priv);
1047 deserialize_method!(deserialize_i8, visit_i64, get_integer);
1048 deserialize_method!(deserialize_i16, visit_i64, get_integer);
1049 deserialize_method!(deserialize_i32, visit_i64, get_integer);
1050 deserialize_method!(deserialize_i64, visit_i64, get_integer);
1051 deserialize_method!(deserialize_u8, visit_i64, get_integer);
1052 deserialize_method!(deserialize_u16, visit_i64, get_integer);
1053 deserialize_method!(deserialize_u32, visit_i64, get_integer);
1054 deserialize_method!(deserialize_u64, visit_i64, get_integer);
1055 deserialize_method!(deserialize_string, visit_string, get_string_priv);
1056
1057 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1058 where
1059 V: de::Visitor<'de>,
1060 {
1061 if self.config.has_key(&self.key) {
1062 visitor.visit_some(self)
1063 } else {
1064 visitor.visit_none()
1066 }
1067 }
1068
1069 fn deserialize_struct<V>(
1070 self,
1071 _name: &'static str,
1072 fields: &'static [&'static str],
1073 visitor: V,
1074 ) -> Result<V::Value, Self::Error>
1075 where
1076 V: de::Visitor<'de>,
1077 {
1078 visitor.visit_map(ConfigMapAccess::new_struct(self.config, self.key, fields)?)
1079 }
1080
1081 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1082 where
1083 V: de::Visitor<'de>,
1084 {
1085 visitor.visit_map(ConfigMapAccess::new_map(self.config, self.key)?)
1086 }
1087
1088 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1089 where
1090 V: de::Visitor<'de>,
1091 {
1092 visitor.visit_seq(ConfigSeqAccess::new(self.config, &self.key)?)
1093 }
1094
1095 fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1096 where
1097 V: de::Visitor<'de>,
1098 {
1099 visitor.visit_seq(ConfigSeqAccess::new(self.config, &self.key)?)
1100 }
1101
1102 fn deserialize_tuple_struct<V>(
1103 self,
1104 _name: &'static str,
1105 _len: usize,
1106 visitor: V,
1107 ) -> Result<V::Value, Self::Error>
1108 where
1109 V: de::Visitor<'de>,
1110 {
1111 visitor.visit_seq(ConfigSeqAccess::new(self.config, &self.key)?)
1112 }
1113
1114 fn deserialize_newtype_struct<V>(
1115 self,
1116 name: &'static str,
1117 visitor: V,
1118 ) -> Result<V::Value, Self::Error>
1119 where
1120 V: de::Visitor<'de>,
1121 {
1122 if name == "ConfigRelativePath" {
1123 match self.config.get_string_priv(&self.key)? {
1124 Some(v) => {
1125 let path = v
1126 .definition
1127 .root(self.config)
1128 .join(v.val)
1129 .display()
1130 .to_string();
1131 visitor.visit_newtype_struct(path.into_deserializer())
1132 }
1133 None => Err(ConfigError::missing(&self.key.to_config())),
1134 }
1135 } else {
1136 visitor.visit_newtype_struct(self)
1137 }
1138 }
1139
1140 serde::forward_to_deserialize_any! {
1142 f32 f64 char str bytes
1143 byte_buf unit unit_struct
1144 enum identifier ignored_any
1145 }
1146}
1147
1148struct ConfigMapAccess<'config> {
1149 config: &'config Config,
1150 key: ConfigKey,
1151 set_iter: <HashSet<ConfigKeyPart> as IntoIterator>::IntoIter,
1152 next: Option<ConfigKeyPart>,
1153}
1154
1155impl<'config> ConfigMapAccess<'config> {
1156 fn new_map(
1157 config: &'config Config,
1158 key: ConfigKey,
1159 ) -> Result<ConfigMapAccess<'config>, ConfigError> {
1160 let mut set = HashSet::new();
1161 if let Some(mut v) = config.get_table(&key.to_config())? {
1162 for (key, _value) in v.val.drain() {
1164 set.insert(ConfigKeyPart::CasePart(key));
1165 }
1166 }
1167 if config.cli_unstable().advanced_env {
1168 let env_pattern = format!("{}_", key.to_env());
1170 for env_key in config.env.keys() {
1171 if env_key.starts_with(&env_pattern) {
1172 let rest = &env_key[env_pattern.len()..];
1174 let part = rest.splitn(2, '_').next().unwrap();
1176 set.insert(ConfigKeyPart::CasePart(part.to_string()));
1178 }
1179 }
1180 }
1181 Ok(ConfigMapAccess {
1182 config,
1183 key,
1184 set_iter: set.into_iter(),
1185 next: None,
1186 })
1187 }
1188
1189 fn new_struct(
1190 config: &'config Config,
1191 key: ConfigKey,
1192 fields: &'static [&'static str],
1193 ) -> Result<ConfigMapAccess<'config>, ConfigError> {
1194 let mut set = HashSet::new();
1195 for field in fields {
1196 set.insert(ConfigKeyPart::Part(field.to_string()));
1197 }
1198 if let Some(mut v) = config.get_table(&key.to_config())? {
1199 for (t_key, value) in v.val.drain() {
1200 let part = ConfigKeyPart::Part(t_key);
1201 if !set.contains(&part) {
1202 config.shell().warn(format!(
1203 "unused key `{}` in config file `{}`",
1204 key.join(part).to_config(),
1205 value.definition_path().display()
1206 ))?;
1207 }
1208 }
1209 }
1210 Ok(ConfigMapAccess {
1211 config,
1212 key,
1213 set_iter: set.into_iter(),
1214 next: None,
1215 })
1216 }
1217}
1218
1219impl<'de, 'config> de::MapAccess<'de> for ConfigMapAccess<'config> {
1220 type Error = ConfigError;
1221
1222 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
1223 where
1224 K: de::DeserializeSeed<'de>,
1225 {
1226 match self.set_iter.next() {
1227 Some(key) => {
1228 let de_key = key.to_config();
1229 self.next = Some(key);
1230 seed.deserialize(de_key.into_deserializer()).map(Some)
1231 }
1232 None => Ok(None),
1233 }
1234 }
1235
1236 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
1237 where
1238 V: de::DeserializeSeed<'de>,
1239 {
1240 let next_key = self.next.take().expect("next field missing");
1241 let next_key = self.key.join(next_key);
1242 seed.deserialize(Deserializer {
1243 config: self.config,
1244 key: next_key,
1245 })
1246 }
1247}
1248
1249struct ConfigSeqAccess {
1250 list_iter: vec::IntoIter<(String, Definition)>,
1251}
1252
1253impl ConfigSeqAccess {
1254 fn new(config: &Config, key: &ConfigKey) -> Result<ConfigSeqAccess, ConfigError> {
1255 let mut res = Vec::new();
1256 if let Some(v) = config.get_list(&key.to_config())? {
1257 for (s, path) in v.val {
1258 res.push((s, Definition::Path(path)));
1259 }
1260 }
1261
1262 if config.cli_unstable().advanced_env {
1263 let env_key = key.to_env();
1265 let def = Definition::Environment(env_key.clone());
1266 if let Some(v) = config.env.get(&env_key) {
1267 if !(v.starts_with('[') && v.ends_with(']')) {
1268 return Err(ConfigError::new(
1269 format!("should have TOML list syntax, found `{}`", v),
1270 def,
1271 ));
1272 }
1273 let temp_key = key.last().to_env();
1274 let toml_s = format!("{}={}", temp_key, v);
1275 let toml_v: toml::Value = toml::de::from_str(&toml_s).map_err(|e| {
1276 ConfigError::new(format!("could not parse TOML list: {}", e), def.clone())
1277 })?;
1278 let values = toml_v
1279 .as_table()
1280 .unwrap()
1281 .get(&temp_key)
1282 .unwrap()
1283 .as_array()
1284 .expect("env var was not array");
1285 for value in values {
1286 let s = value.as_str().ok_or_else(|| {
1288 ConfigError::new(
1289 format!("expected string, found {}", value.type_str()),
1290 def.clone(),
1291 )
1292 })?;
1293 res.push((s.to_string(), def.clone()));
1294 }
1295 }
1296 }
1297 Ok(ConfigSeqAccess {
1298 list_iter: res.into_iter(),
1299 })
1300 }
1301}
1302
1303impl<'de> de::SeqAccess<'de> for ConfigSeqAccess {
1304 type Error = ConfigError;
1305
1306 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1307 where
1308 T: de::DeserializeSeed<'de>,
1309 {
1310 match self.list_iter.next() {
1311 Some((value, _def)) => seed.deserialize(value.into_deserializer()).map(Some),
1313 None => Ok(None),
1314 }
1315 }
1316}
1317
1318#[derive(Debug, Eq, PartialEq, Clone, Deserialize)]
1322pub struct ConfigRelativePath(PathBuf);
1323
1324impl ConfigRelativePath {
1325 pub fn path(self) -> PathBuf {
1326 self.0
1327 }
1328}
1329
1330#[derive(Eq, PartialEq, Clone)]
1331pub enum ConfigValue {
1332 Integer(i64, PathBuf),
1333 String(String, PathBuf),
1334 List(Vec<(String, PathBuf)>, PathBuf),
1335 Table(HashMap<String, ConfigValue>, PathBuf),
1336 Boolean(bool, PathBuf),
1337}
1338
1339pub struct Value<T> {
1340 pub val: T,
1341 pub definition: Definition,
1342}
1343
1344pub type OptValue<T> = Option<Value<T>>;
1345
1346#[derive(Clone, Debug)]
1347pub enum Definition {
1348 Path(PathBuf),
1349 Environment(String),
1350}
1351
1352impl fmt::Debug for ConfigValue {
1353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1354 match *self {
1355 CV::Integer(i, ref path) => write!(f, "{} (from {})", i, path.display()),
1356 CV::Boolean(b, ref path) => write!(f, "{} (from {})", b, path.display()),
1357 CV::String(ref s, ref path) => write!(f, "{} (from {})", s, path.display()),
1358 CV::List(ref list, ref path) => {
1359 write!(f, "[")?;
1360 for (i, &(ref s, ref path)) in list.iter().enumerate() {
1361 if i > 0 {
1362 write!(f, ", ")?;
1363 }
1364 write!(f, "{} (from {})", s, path.display())?;
1365 }
1366 write!(f, "] (from {})", path.display())
1367 }
1368 CV::Table(ref table, _) => write!(f, "{:?}", table),
1369 }
1370 }
1371}
1372
1373impl ConfigValue {
1374 fn from_toml(path: &Path, toml: toml::Value) -> CargoResult<ConfigValue> {
1375 match toml {
1376 toml::Value::String(val) => Ok(CV::String(val, path.to_path_buf())),
1377 toml::Value::Boolean(b) => Ok(CV::Boolean(b, path.to_path_buf())),
1378 toml::Value::Integer(i) => Ok(CV::Integer(i, path.to_path_buf())),
1379 toml::Value::Array(val) => Ok(CV::List(
1380 val.into_iter()
1381 .map(|toml| match toml {
1382 toml::Value::String(val) => Ok((val, path.to_path_buf())),
1383 v => failure::bail!("expected string but found {} in list", v.type_str()),
1384 })
1385 .collect::<CargoResult<_>>()?,
1386 path.to_path_buf(),
1387 )),
1388 toml::Value::Table(val) => Ok(CV::Table(
1389 val.into_iter()
1390 .map(|(key, value)| {
1391 let value = CV::from_toml(path, value)
1392 .chain_err(|| format!("failed to parse key `{}`", key))?;
1393 Ok((key, value))
1394 })
1395 .collect::<CargoResult<_>>()?,
1396 path.to_path_buf(),
1397 )),
1398 v => failure::bail!(
1399 "found TOML configuration value of unknown type `{}`",
1400 v.type_str()
1401 ),
1402 }
1403 }
1404
1405 fn into_toml(self) -> toml::Value {
1406 match self {
1407 CV::Boolean(s, _) => toml::Value::Boolean(s),
1408 CV::String(s, _) => toml::Value::String(s),
1409 CV::Integer(i, _) => toml::Value::Integer(i),
1410 CV::List(l, _) => {
1411 toml::Value::Array(l.into_iter().map(|(s, _)| toml::Value::String(s)).collect())
1412 }
1413 CV::Table(l, _) => {
1414 toml::Value::Table(l.into_iter().map(|(k, v)| (k, v.into_toml())).collect())
1415 }
1416 }
1417 }
1418
1419 fn merge(&mut self, from: ConfigValue) -> CargoResult<()> {
1420 match (self, from) {
1421 (&mut CV::List(ref mut old, _), CV::List(ref mut new, _)) => {
1422 let new = mem::replace(new, Vec::new());
1423 old.extend(new.into_iter());
1424 }
1425 (&mut CV::Table(ref mut old, _), CV::Table(ref mut new, _)) => {
1426 let new = mem::replace(new, HashMap::new());
1427 for (key, value) in new {
1428 match old.entry(key.clone()) {
1429 Occupied(mut entry) => {
1430 let path = value.definition_path().to_path_buf();
1431 let entry = entry.get_mut();
1432 entry.merge(value).chain_err(|| {
1433 format!(
1434 "failed to merge key `{}` between \
1435 files:\n \
1436 file 1: {}\n \
1437 file 2: {}",
1438 key,
1439 entry.definition_path().display(),
1440 path.display()
1441 )
1442 })?;
1443 }
1444 Vacant(entry) => {
1445 entry.insert(value);
1446 }
1447 };
1448 }
1449 }
1450 (expected @ &mut CV::List(_, _), found)
1452 | (expected @ &mut CV::Table(_, _), found)
1453 | (expected, found @ CV::List(_, _))
1454 | (expected, found @ CV::Table(_, _)) => {
1455 return Err(internal(format!(
1456 "expected {}, but found {}",
1457 expected.desc(),
1458 found.desc()
1459 )));
1460 }
1461 _ => {}
1462 }
1463
1464 Ok(())
1465 }
1466
1467 pub fn i64(&self, key: &str) -> CargoResult<(i64, &Path)> {
1468 match *self {
1469 CV::Integer(i, ref p) => Ok((i, p)),
1470 _ => self.expected("integer", key),
1471 }
1472 }
1473
1474 pub fn string(&self, key: &str) -> CargoResult<(&str, &Path)> {
1475 match *self {
1476 CV::String(ref s, ref p) => Ok((s, p)),
1477 _ => self.expected("string", key),
1478 }
1479 }
1480
1481 pub fn table(&self, key: &str) -> CargoResult<(&HashMap<String, ConfigValue>, &Path)> {
1482 match *self {
1483 CV::Table(ref table, ref p) => Ok((table, p)),
1484 _ => self.expected("table", key),
1485 }
1486 }
1487
1488 pub fn list(&self, key: &str) -> CargoResult<&[(String, PathBuf)]> {
1489 match *self {
1490 CV::List(ref list, _) => Ok(list),
1491 _ => self.expected("list", key),
1492 }
1493 }
1494
1495 pub fn boolean(&self, key: &str) -> CargoResult<(bool, &Path)> {
1496 match *self {
1497 CV::Boolean(b, ref p) => Ok((b, p)),
1498 _ => self.expected("bool", key),
1499 }
1500 }
1501
1502 pub fn desc(&self) -> &'static str {
1503 match *self {
1504 CV::Table(..) => "table",
1505 CV::List(..) => "array",
1506 CV::String(..) => "string",
1507 CV::Boolean(..) => "boolean",
1508 CV::Integer(..) => "integer",
1509 }
1510 }
1511
1512 pub fn definition_path(&self) -> &Path {
1513 match *self {
1514 CV::Boolean(_, ref p)
1515 | CV::Integer(_, ref p)
1516 | CV::String(_, ref p)
1517 | CV::List(_, ref p)
1518 | CV::Table(_, ref p) => p,
1519 }
1520 }
1521
1522 fn expected<T>(&self, wanted: &str, key: &str) -> CargoResult<T> {
1523 failure::bail!(
1524 "expected a {}, but found a {} for `{}` in {}",
1525 wanted,
1526 self.desc(),
1527 key,
1528 self.definition_path().display()
1529 )
1530 }
1531}
1532
1533impl Definition {
1534 pub fn root<'a>(&'a self, config: &'a Config) -> &'a Path {
1535 match *self {
1536 Definition::Path(ref p) => p.parent().unwrap().parent().unwrap(),
1537 Definition::Environment(_) => config.cwd(),
1538 }
1539 }
1540}
1541
1542impl fmt::Display for Definition {
1543 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1544 match *self {
1545 Definition::Path(ref p) => p.display().fmt(f),
1546 Definition::Environment(ref key) => write!(f, "environment variable `{}`", key),
1547 }
1548 }
1549}
1550
1551pub fn homedir(cwd: &Path) -> Option<PathBuf> {
1552 ::home::cargo_home_with_cwd(cwd).ok()
1553}
1554
1555fn walk_tree<F>(pwd: &Path, home: &Path, mut walk: F) -> CargoResult<()>
1556where
1557 F: FnMut(&Path) -> CargoResult<()>,
1558{
1559 let mut stash: HashSet<PathBuf> = HashSet::new();
1560
1561 for current in paths::ancestors(pwd) {
1562 let possible = current.join(".cargo").join("config");
1563 if fs::metadata(&possible).is_ok() {
1564 walk(&possible)?;
1565 stash.insert(possible);
1566 }
1567 }
1568
1569 let config = home.join("config");
1573 if !stash.contains(&config) && fs::metadata(&config).is_ok() {
1574 walk(&config)?;
1575 }
1576
1577 Ok(())
1578}
1579
1580pub fn save_credentials(cfg: &Config, token: String, registry: Option<String>) -> CargoResult<()> {
1581 let mut file = {
1582 cfg.home_path.create_dir()?;
1583 cfg.home_path
1584 .open_rw(Path::new("credentials"), cfg, "credentials' config file")?
1585 };
1586
1587 let (key, value) = {
1588 let key = "token".to_string();
1589 let value = ConfigValue::String(token, file.path().to_path_buf());
1590 let mut map = HashMap::new();
1591 map.insert(key, value);
1592 let table = CV::Table(map, file.path().to_path_buf());
1593
1594 if let Some(registry) = registry {
1595 let mut map = HashMap::new();
1596 map.insert(registry, table);
1597 (
1598 "registries".into(),
1599 CV::Table(map, file.path().to_path_buf()),
1600 )
1601 } else {
1602 ("registry".into(), table)
1603 }
1604 };
1605
1606 let mut contents = String::new();
1607 file.read_to_string(&mut contents).chain_err(|| {
1608 format!(
1609 "failed to read configuration file `{}`",
1610 file.path().display()
1611 )
1612 })?;
1613
1614 let mut toml = cargo_toml::parse(&contents, file.path(), cfg)?;
1615
1616 if let Some(token) = toml.as_table_mut().unwrap().remove("token") {
1618 let mut map = HashMap::new();
1619 map.insert("token".to_string(), token);
1620 toml.as_table_mut()
1621 .unwrap()
1622 .insert("registry".into(), map.into());
1623 }
1624
1625 toml.as_table_mut().unwrap().insert(key, value.into_toml());
1626
1627 let contents = toml.to_string();
1628 file.seek(SeekFrom::Start(0))?;
1629 file.write_all(contents.as_bytes())?;
1630 file.file().set_len(contents.len() as u64)?;
1631 set_permissions(file.file(), 0o600)?;
1632
1633 return Ok(());
1634
1635 #[cfg(unix)]
1636 fn set_permissions(file: &File, mode: u32) -> CargoResult<()> {
1637 use std::os::unix::fs::PermissionsExt;
1638
1639 let mut perms = file.metadata()?.permissions();
1640 perms.set_mode(mode);
1641 file.set_permissions(perms)?;
1642 Ok(())
1643 }
1644
1645 #[cfg(not(unix))]
1646 #[allow(unused)]
1647 fn set_permissions(file: &File, mode: u32) -> CargoResult<()> {
1648 Ok(())
1649 }
1650}