1use std::borrow::Cow;
2use std::fmt;
3
4use toml_writer::TomlWrite as _;
5
6#[derive(Debug, Clone)]
14pub struct ConfigKey {
15 env: String,
19 parts: Vec<(String, usize)>,
26}
27
28impl ConfigKey {
29 pub fn new() -> ConfigKey {
32 ConfigKey {
33 env: "CARGO".to_string(),
34 parts: Vec::new(),
35 }
36 }
37
38 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 pub fn push(&mut self, name: &str) {
58 let env = name.replace(['-', '.'], "_").to_uppercase();
59 self._push(&env, name);
60 }
61
62 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 pub fn pop(&mut self) {
79 let (_part, env) = self.parts.pop().unwrap();
80 self.env.truncate(env);
81 }
82
83 pub fn as_env_key(&self) -> &str {
86 &self.env
87 }
88
89 pub fn parts(&self) -> impl Iterator<Item = &str> {
91 self.parts.iter().map(|p| p.0.as_ref())
92 }
93
94 pub fn is_root(&self) -> bool {
96 self.parts.is_empty()
97 }
98
99 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 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#[derive(Debug, Clone)]
158pub struct ArrayItemKeyPath {
159 base: ConfigKey,
160 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 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}