Skip to main content

cargo_util_config/
key.rs

1use std::borrow::Cow;
2use std::fmt;
3
4use toml_writer::TomlWrite as _;
5
6/// Key for a configuration variable.
7///
8/// This type represents a configuration variable that we're looking up in
9/// Cargo's configuration. This structure simultaneously keeps track of a
10/// corresponding environment variable name as well as a TOML config name. The
11/// intention here is that this is built up and torn down over time efficiently,
12/// avoiding clones and such as possible.
13#[derive(Debug, Clone)]
14pub struct ConfigKey {
15    // The current environment variable this configuration key maps to. This is
16    // updated with `push` methods and looks like `CARGO_FOO_BAR` for pushing
17    // `foo` and then `bar`.
18    env: String,
19    // This is used to keep track of how many sub-keys have been pushed on
20    // this `ConfigKey`. Each element of this vector is a new sub-key pushed
21    // onto this `ConfigKey`. Each element is a pair where the first item is
22    // the key part as a string, and the second item is an index into `env`.
23    // The `env` index is used on `pop` to truncate `env` to rewind back to
24    // the previous `ConfigKey` state before a `push`.
25    parts: Vec<(String, usize)>,
26}
27
28impl ConfigKey {
29    /// Creates a new blank configuration key which is ready to get built up by
30    /// using `push` and `push_sensitive`.
31    pub fn new() -> ConfigKey {
32        ConfigKey {
33            env: "CARGO".to_string(),
34            parts: Vec::new(),
35        }
36    }
37
38    /// Creates a `ConfigKey` from the `key` specified.
39    ///
40    /// The `key` specified is expected to be a period-separated toml
41    /// configuration key.
42    pub fn from_parts(parts: impl IntoIterator<Item = impl AsRef<str>>) -> ConfigKey {
43        let mut cfg = ConfigKey::new();
44        for part in parts {
45            cfg.push(part.as_ref());
46        }
47        cfg
48    }
49
50    /// Pushes a new sub-key on this `ConfigKey`. This sub-key should be
51    /// equivalent to accessing a sub-table in TOML.
52    ///
53    /// Note that this considers `name` to be case-insensitive, meaning that the
54    /// corresponding toml key is appended with this `name` as-is and the
55    /// corresponding env key is appended with `name` after transforming it to
56    /// uppercase characters.
57    pub fn push(&mut self, name: &str) {
58        let env = name.replace(['-', '.'], "_").to_uppercase();
59        self._push(&env, name);
60    }
61
62    /// Performs the same function as `push` except that the corresponding
63    /// environment variable does not get the uppercase letters of `name` but
64    /// instead `name` is pushed raw onto the corresponding environment
65    /// variable.
66    pub fn push_sensitive(&mut self, name: &str) {
67        self._push(name, name);
68    }
69
70    fn _push(&mut self, env: &str, config: &str) {
71        self.parts.push((config.to_string(), self.env.len()));
72        self.env.push('_');
73        self.env.push_str(env);
74    }
75
76    /// Rewinds this `ConfigKey` back to the state it was at before the last
77    /// `push` method being called.
78    pub fn pop(&mut self) {
79        let (_part, env) = self.parts.pop().unwrap();
80        self.env.truncate(env);
81    }
82
83    /// Returns the corresponding environment variable key for this
84    /// configuration value.
85    pub fn as_env_key(&self) -> &str {
86        &self.env
87    }
88
89    /// Returns an iterator of the key parts as strings.
90    pub fn parts(&self) -> impl Iterator<Item = &str> {
91        self.parts.iter().map(|p| p.0.as_ref())
92    }
93
94    /// Returns whether or not this is a key for the root table.
95    pub fn is_root(&self) -> bool {
96        self.parts.is_empty()
97    }
98
99    /// Returns whether or not the given key string matches this key.
100    /// Use * to match any key part.
101    pub fn matches(&self, pattern: &str) -> bool {
102        let mut parts = self.parts();
103        pattern
104            .split('.')
105            .all(|pat| parts.next() == Some(pat) || pat == "*")
106            && parts.next().is_none()
107    }
108}
109
110impl std::str::FromStr for ConfigKey {
111    type Err = anyhow::Error;
112
113    /// Parse a `ConfigKey` as a TOML key
114    fn from_str(key: &str) -> Result<Self, Self::Err> {
115        use toml_parser::parser::{EventKind, parse_key};
116
117        let source = toml_parser::Source::new(key);
118        let tokens = source.lex().into_vec();
119        let mut events = Vec::new();
120        let mut error = None;
121        parse_key(&tokens, &mut events, &mut error);
122
123        let mut result = Self::new();
124        for event in events {
125            if event.kind() == EventKind::SimpleKey {
126                let mut part = Cow::Borrowed("");
127                source.get(event).unwrap().decode_key(&mut part, &mut error);
128                result.push(&part);
129            }
130        }
131        if let Some(error) = error {
132            anyhow::bail!("invalid config key `{key}`: {}", error.description());
133        }
134        Ok(result)
135    }
136}
137
138impl fmt::Display for ConfigKey {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        for (i, part) in self.parts().enumerate() {
141            if i != 0 {
142                f.key_sep()?;
143            }
144            f.key(part)?;
145        }
146        Ok(())
147    }
148}
149
150#[derive(Debug, Clone)]
151pub enum KeyOrIdx {
152    Key(String),
153    Idx(usize),
154}
155
156/// Tracks the key path to an item in an array for detailed error context.
157#[derive(Debug, Clone)]
158pub struct ArrayItemKeyPath {
159    base: ConfigKey,
160    /// This is stored in reverse, and is pushed only when erroring out.
161    /// The first element is the innermost key.
162    path: Vec<KeyOrIdx>,
163}
164
165impl ArrayItemKeyPath {
166    pub fn new(base: ConfigKey) -> Self {
167        Self {
168            base,
169            path: Vec::new(),
170        }
171    }
172
173    pub fn push_key(&mut self, k: String) {
174        self.path.push(KeyOrIdx::Key(k))
175    }
176
177    pub fn push_index(&mut self, i: usize) {
178        self.path.push(KeyOrIdx::Idx(i))
179    }
180}
181
182impl fmt::Display for ArrayItemKeyPath {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        write!(f, "{}", self.base)?;
185        for k in self.path.iter().rev() {
186            match k {
187                KeyOrIdx::Key(s) => {
188                    f.key_sep()?;
189                    f.key(s)?;
190                }
191                KeyOrIdx::Idx(i) => {
192                    write!(f, "[{i}]")?;
193                }
194            }
195        }
196        Ok(())
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use snapbox::assert_data_eq;
203    use snapbox::str;
204
205    use super::*;
206
207    #[test]
208    fn parse_quoted_key_parts() {
209        let key = r#"target . 'a.b' . "c\u002Ed" . ''"#.parse::<ConfigKey>().unwrap();
210        assert_eq!(
211            key.parts().collect::<Vec<_>>(),
212            ["target", "a.b", "c.d", ""]
213        );
214    }
215
216    #[test]
217    fn reject_invalid_keys() {
218        use snapbox::IntoData as _;
219
220        for (key, expected) in [
221            (
222                "",
223                str!["invalid config key ``: unquoted keys cannot be empty"],
224            ),
225            (
226                ".a",
227                str!["invalid config key `.a`: unquoted keys cannot be empty"],
228            ),
229            (
230                "a.",
231                str!["invalid config key `a.`: unquoted keys cannot be empty"],
232            ),
233            (
234                "a..b",
235                str!["invalid config key `a..b`: unquoted keys cannot be empty"],
236            ),
237            ("a b", str!["invalid config key `a b`: unexpected content"]),
238            ("a=b", str!["invalid config key `a=b`: unexpected content"]),
239            (
240                "'unclosed",
241                str!["invalid config key `'unclosed`: invalid literal string"],
242            ),
243            (
244                r#""bad\q""#,
245                str![[r#"invalid config key `"bad\q"`: missing escaped value"#]],
246            ),
247        ] {
248            assert_data_eq!(
249                key.parse::<ConfigKey>().unwrap_err().to_string(),
250                expected.raw()
251            );
252        }
253    }
254
255    #[test]
256    fn array_item_key_path_display() {
257        let base = "array".parse::<ConfigKey>().unwrap();
258        let mut key_path = ArrayItemKeyPath::new(base);
259        // These are pushed in reverse order.
260        key_path.push_index(1);
261        key_path.push_key("rustflags".into());
262        key_path.push_key("thumbv8m.base-none-eabi".into());
263        key_path.push_index(2);
264        key_path.push_index(3);
265
266        assert_data_eq!(
267            key_path.to_string(),
268            str![[r#"array[3][2]."thumbv8m.base-none-eabi".rustflags[1]"#]]
269        );
270    }
271}