cargo_util_config/
config_store.rs1use std::fs;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context as _, Result, bail};
5
6use super::{ConfigKey, ConfigValue, Definition, Scope};
7use cargo_util::collections::{BuildHasher, HashMap};
8
9use ConfigValue as CV;
10
11#[derive(Default, Debug)]
12pub struct ConfigStore {
13 values: HashMap<String, ConfigValue>,
15 def: Definition,
16}
17
18impl ConfigStore {
19 pub const fn new() -> Self {
20 Self {
21 values: HashMap::with_hasher(BuildHasher),
22 def: Definition::builtin(),
23 }
24 }
25
26 pub fn from_values(values: HashMap<String, ConfigValue>) -> Self {
27 Self {
28 values,
29 def: Definition::builtin(),
30 }
31 }
32
33 pub fn from_table_value(value: ConfigValue) -> Option<Self> {
34 match value {
35 CV::Table(values, def) => Some(Self { values, def }),
36 _ => None,
37 }
38 }
39
40 pub fn from_layers(layers: impl IntoIterator<Item = Self>) -> Result<Self> {
44 let layers: Vec<_> = layers.into_iter().collect();
45 let mut merged = Self::default();
46 for mut layer in layers.into_iter().rev() {
48 layer.values.remove("include");
49 merged.merge(layer)?;
50 }
51 Ok(merged)
52 }
53
54 pub fn read_layer(path: &Path, scope: Scope) -> Result<Self> {
56 tracing::debug!(?path, ?scope, "load config from file");
57
58 let contents = fs::read_to_string(path)
59 .with_context(|| format!("failed to read configuration file `{}`", path.display()))?;
60 let toml = contents.parse::<toml::Table>().with_context(|| {
61 format!("could not parse TOML configuration in `{}`", path.display())
62 })?;
63 let def = match scope {
64 Scope::Cli => Definition::cli(Some(path.into())),
65 Scope::Path => Definition::path(path.into()),
66 Scope::BuiltIn => Definition::builtin(),
67 Scope::Environment => {
68 unimplemented!("Environment defiinitions are not supported")
69 }
70 };
71 let value = CV::from_toml(def, toml::Value::Table(toml)).with_context(|| {
72 format!(
73 "failed to load TOML configuration from `{}`",
74 path.display()
75 )
76 })?;
77 Ok(Self::from_table_value(value).unwrap())
78 }
79
80 pub fn parse_cli_key_value(arg: &str) -> Result<Self> {
82 let doc = arg.parse::<toml::Table>().with_context(|| {
83 format!(
84 "failed to parse value from --config argument `{arg}` as a dotted key expression"
85 )
86 })?;
87 validate_cli_key_value(arg)?;
88
89 if doc
90 .get("registry")
91 .and_then(|v| v.as_table())
92 .and_then(|t| t.get("token"))
93 .is_some()
94 {
95 bail!("registry.token cannot be set through --config for security reasons");
96 } else if let Some((k, _)) = doc
97 .get("registries")
98 .and_then(|v| v.as_table())
99 .and_then(|t| t.iter().find(|(_, v)| v.get("token").is_some()))
100 {
101 bail!(
102 "registries.{}.token cannot be set through --config for security reasons",
103 k
104 );
105 }
106
107 let table = CV::from_toml(Definition::cli(None), toml::Value::Table(doc))
108 .with_context(|| format!("failed to convert --config argument `{arg}`"))?;
109 Ok(Self::from_table_value(table).unwrap())
110 }
111
112 pub fn into_value(self) -> ConfigValue {
113 let Self { values, def } = self;
114 CV::Table(values, def)
115 }
116
117 pub fn definition(&self) -> &Definition {
118 &self.def
119 }
120
121 pub fn merge(&mut self, from: Self) -> Result<()> {
125 let mut root_cv = std::mem::take(self).into_value();
126 let from = from.into_value();
127 root_cv.merge(from)?;
128 *self = Self::from_table_value(root_cv).unwrap();
129
130 Ok(())
131 }
132
133 pub fn values(&self) -> &HashMap<String, ConfigValue> {
134 &self.values
135 }
136
137 pub fn values_mut(&mut self) -> &mut HashMap<String, ConfigValue> {
138 &mut self.values
139 }
140
141 pub fn get_cv(&self, key: &ConfigKey) -> Result<Option<ConfigValue>> {
146 let vals = self.values();
147 tracing::trace!("get cv {:?}", key);
148 if key.is_root() {
149 return Ok(Some(CV::Table(
152 vals.clone(),
153 Definition::path(PathBuf::new()),
154 )));
155 }
156 let mut parts = key.parts().enumerate();
157 let Some(mut val) = vals.get(parts.next().unwrap().1) else {
158 return Ok(None);
159 };
160 for (i, part) in parts {
161 match val {
162 CV::Table(map, _) => {
163 val = match map.get(part) {
164 Some(val) => val,
165 None => return Ok(None),
166 }
167 }
168 CV::Integer(_, def)
169 | CV::String(_, def)
170 | CV::List(_, def)
171 | CV::Boolean(_, def) => {
172 let key_so_far = ConfigKey::from_parts(key.parts().take(i));
173 bail!(
174 "expected table for configuration key `{}`, \
175 but found {} in {}",
176 key_so_far,
177 val.desc(),
178 def
179 )
180 }
181 }
182 }
183 Ok(Some(val.clone()))
184 }
185}
186
187fn validate_cli_key_value(arg: &str) -> Result<()> {
192 use toml_parser::parser::EventKind;
193
194 let invalid_expression = || {
195 anyhow::anyhow!(
196 "--config argument `{arg}` was not a TOML dotted key expression (such as `build.jobs = 2`)"
197 )
198 };
199 let decoration =
200 || anyhow::anyhow!("--config argument `{arg}` includes non-whitespace decoration");
201
202 let tokens = toml_parser::Source::new(arg).lex().into_vec();
203 let mut events = Vec::new();
204 toml_parser::parser::parse_document(&tokens, &mut events, &mut ());
205 let mut events = events
206 .into_iter()
207 .map(|token| token.kind())
208 .filter(|kind| !matches!(*kind, EventKind::Whitespace | EventKind::Newline))
209 .peekable();
210
211 if events.next_if_eq(&EventKind::Comment).is_some() {
212 return Err(decoration());
213 }
214
215 if !events
216 .next_if(|token| matches!(token, EventKind::SimpleKey))
217 .is_some()
218 {
219 return Err(invalid_expression());
220 }
221 while events
222 .next_if(|token| matches!(token, EventKind::KeySep | EventKind::SimpleKey))
223 .is_some()
224 {}
225
226 if !events.next_if_eq(&EventKind::KeyValSep).is_some() {
227 return Err(invalid_expression());
228 }
229
230 let mut array_depth = None::<usize>;
231 while let Some(token) = events.next() {
232 match token {
233 EventKind::StdTableOpen | EventKind::ArrayTableOpen => {
234 return Err(invalid_expression());
235 }
236 EventKind::SimpleKey if array_depth.unwrap_or(0) == 0 => {
237 return Err(invalid_expression());
239 }
240 EventKind::InlineTableOpen if !array_depth.is_some() => {
241 bail!(
242 "--config argument `{arg}` sets a value to an inline table, which is not accepted"
243 );
244 }
245 EventKind::ArrayOpen => *array_depth.get_or_insert_default() += 1,
246 EventKind::ArrayClose => *array_depth.get_or_insert_default() -= 1,
247 EventKind::Comment => return Err(decoration()),
248 _ => {}
249 }
250 }
251
252 Ok(())
253}