Debian Codegraph @

src/value.rs

raw
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 // Based on https://github.com/rust-lang/cargo/blob/0.80.0/src/cargo/util/context/value.rs.
4
5 use alloc::{
6 borrow::{Cow, ToOwned as _},
7 collections::BTreeMap,
8 string::String,
9 vec::Vec,
10 };
11 use core::{fmt, mem, str::FromStr};
12 use std::path::{Path, PathBuf};
13
14 use serde_derive::{Deserialize, Serialize};
15
16 use crate::error::Result;
17
18 #[allow(clippy::exhaustive_structs)]
19 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20 #[serde(transparent)]
21 pub struct Value<T> {
22 /// The inner value that was deserialized.
23 pub val: T,
24 /// The location where `val` was defined in configuration (e.g. file it was
25 /// defined in, env var etc).
26 #[serde(skip)]
27 pub definition: Option<Definition>,
28 }
29
30 impl Value<String> {
31 pub(crate) fn parse<T: FromStr>(self) -> Result<Value<T>, T::Err> {
32 Ok(Value { val: self.val.parse()?, definition: self.definition })
33 }
34 // https://doc.rust-lang.org/nightly/cargo/reference/config.html#config-relative-paths
35 pub(crate) fn resolve_as_program_path(&self, current_dir: &Path) -> Cow<'_, Path> {
36 match &self.definition {
37 Some(def) if !Path::new(&self.val).is_absolute() && self.val.contains(['/', '\\']) => {
38 def.root(current_dir).join(&self.val).into()
39 }
40 _ => Path::new(&self.val).into(),
41 }
42 }
43 pub(crate) fn resolve_as_path(&self, current_dir: &Path) -> Cow<'_, Path> {
44 match &self.definition {
45 Some(def) if !Path::new(&self.val).is_absolute() => {
46 def.root(current_dir).join(&self.val).into()
47 }
48 _ => Path::new(&self.val).into(),
49 }
50 }
51 }
52
53 /// Location where a config value is defined.
54 #[derive(Clone, Debug)]
55 #[non_exhaustive]
56 pub enum Definition {
57 /// Defined in a `.cargo/config`, includes the path to the file.
58 Path(PathBuf),
59 /// Defined in an environment variable, includes the environment key.
60 Environment(Cow<'static, str>),
61 /// Passed in on the command line.
62 /// A path is attached when the config value is a path to a config file.
63 Cli(Option<PathBuf>),
64 }
65
66 impl Definition {
67 /// Root directory where this is defined.
68 ///
69 /// If from a file, it is the directory above `.cargo/config`.
70 /// CLI and env are the current working directory.
71 pub(crate) fn root<'a>(&'a self, current_dir: &'a Path) -> &'a Path {
72 match self {
73 Definition::Path(p) | Definition::Cli(Some(p)) => p.parent().unwrap().parent().unwrap(),
74 Definition::Environment(_) | Definition::Cli(None) => current_dir,
75 }
76 }
77 pub(crate) fn root_opt<'a>(&'a self, current_dir: Option<&'a Path>) -> Option<&'a Path> {
78 match self {
79 Definition::Path(p) | Definition::Cli(Some(p)) => {
80 Some(p.parent().unwrap().parent().unwrap())
81 }
82 Definition::Environment(_) | Definition::Cli(None) => current_dir,
83 }
84 }
85
86 // /// Returns `true` if self is a higher priority to other.
87 // ///
88 // /// CLI is preferred over environment, which is preferred over files.
89 // pub(crate) fn is_higher_priority(&self, other: &Definition) -> bool {
90 // matches!(
91 // (self, other),
92 // (Definition::Cli(_), Definition::Environment(_) | Definition::Path(_))
93 // | (Definition::Environment(_), Definition::Path(_))
94 // )
95 // }
96 }
97
98 impl fmt::Display for Definition {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 match self {
101 Definition::Path(p) | Definition::Cli(Some(p)) => p.display().fmt(f),
102 Definition::Environment(key) => write!(f, "environment variable `{key}`"),
103 Definition::Cli(None) => f.write_str("--config cli option"),
104 }
105 }
106 }
107
108 impl PartialEq for Definition {
109 fn eq(&self, other: &Definition) -> bool {
110 // configuration values are equivalent no matter where they're defined,
111 // but they need to be defined in the same location. For example if
112 // they're defined in the environment that's different than being
113 // defined in a file due to path interpretations.
114 mem::discriminant(self) == mem::discriminant(other)
115 }
116 }
117
118 pub(crate) trait SetPath {
119 fn set_path(&mut self, path: &Path);
120 }
121 impl<T: SetPath> SetPath for Option<T> {
122 fn set_path(&mut self, path: &Path) {
123 if let Some(v) = self {
124 v.set_path(path);
125 }
126 }
127 }
128 impl<T: SetPath> SetPath for Vec<T> {
129 fn set_path(&mut self, path: &Path) {
130 for v in self {
131 v.set_path(path);
132 }
133 }
134 }
135 impl<T: SetPath> SetPath for BTreeMap<String, T> {
136 fn set_path(&mut self, path: &Path) {
137 for v in self.values_mut() {
138 v.set_path(path);
139 }
140 }
141 }
142 impl<T> SetPath for Value<T> {
143 fn set_path(&mut self, path: &Path) {
144 self.definition = Some(Definition::Path(path.to_owned()));
145 }
146 }