1use cargo_util::collections::HashMap;
7use std::collections::hash_map::Entry;
8use std::fmt;
9use std::mem;
10
11use anyhow::Context as _;
12use anyhow::Result;
13use anyhow::anyhow;
14use anyhow::bail;
15
16use super::key::KeyOrIdx;
17use super::{ConfigKey, Definition};
18
19use self::ConfigValue as CV;
20
21const NON_MERGEABLE_LISTS: &[&str] = &[
31 "credential-alias.*",
32 "doc.browser",
33 "host.runner",
34 "registries.*.credential-provider",
35 "registry.credential-provider",
36 "target.*.runner",
37];
38
39#[derive(Eq, PartialEq, Clone)]
41pub enum ConfigValue {
42 Integer(i64, Definition),
43 String(String, Definition),
44 List(Vec<ConfigValue>, Definition),
45 Table(HashMap<String, ConfigValue>, Definition),
46 Boolean(bool, Definition),
47}
48
49impl fmt::Debug for ConfigValue {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 match self {
52 CV::Integer(i, def) => write!(f, "{} (from {})", i, def),
53 CV::Boolean(b, def) => write!(f, "{} (from {})", b, def),
54 CV::String(s, def) => write!(f, "{} (from {})", s, def),
55 CV::List(list, def) => {
56 write!(f, "[")?;
57 for (i, item) in list.iter().enumerate() {
58 if i > 0 {
59 write!(f, ", ")?;
60 }
61 write!(f, "{item:?}")?;
62 }
63 write!(f, "] (from {})", def)
64 }
65 CV::Table(table, _) => write!(f, "{:?}", table),
66 }
67 }
68}
69
70impl ConfigValue {
71 pub fn from_toml(def: Definition, toml: toml::Value) -> Result<ConfigValue> {
72 use toml_writer::TomlWrite as _;
73
74 let mut error_path = Vec::new();
75 Self::from_toml_inner(def, toml, &mut error_path).with_context(|| {
76 let mut it = error_path.iter().rev().peekable();
77 let mut key_path = String::with_capacity(error_path.len() * 3);
78 while let Some(k) = it.next() {
79 match k {
80 KeyOrIdx::Key(s) => key_path.key(s).unwrap(),
81 KeyOrIdx::Idx(i) => key_path.push_str(&format!("[{i}]")),
82 }
83 if matches!(it.peek(), Some(KeyOrIdx::Key(_))) {
84 key_path.key_sep().unwrap();
85 }
86 }
87 format!("failed to parse config at `{key_path}`")
88 })
89 }
90
91 fn from_toml_inner(
92 def: Definition,
93 toml: toml::Value,
94 path: &mut Vec<KeyOrIdx>,
95 ) -> Result<ConfigValue> {
96 match toml {
97 toml::Value::String(val) => Ok(CV::String(val, def)),
98 toml::Value::Boolean(b) => Ok(CV::Boolean(b, def)),
99 toml::Value::Integer(i) => Ok(CV::Integer(i, def)),
100 toml::Value::Array(val) => Ok(CV::List(
101 val.into_iter()
102 .enumerate()
103 .map(|(i, toml)| {
104 CV::from_toml_inner(def.clone(), toml, path)
105 .inspect_err(|_| path.push(KeyOrIdx::Idx(i)))
106 })
107 .collect::<Result<_>>()?,
108 def,
109 )),
110 toml::Value::Table(val) => Ok(CV::Table(
111 val.into_iter()
112 .map(
113 |(key, value)| match CV::from_toml_inner(def.clone(), value, path) {
114 Ok(value) => Ok((key, value)),
115 Err(e) => {
116 path.push(KeyOrIdx::Key(key));
117 Err(e)
118 }
119 },
120 )
121 .collect::<Result<_>>()?,
122 def,
123 )),
124 v => bail!("unsupported TOML configuration type `{}`", v.type_str()),
125 }
126 }
127
128 pub fn into_toml(self) -> toml::Value {
129 match self {
130 CV::Boolean(s, _) => toml::Value::Boolean(s),
131 CV::String(s, _) => toml::Value::String(s),
132 CV::Integer(i, _) => toml::Value::Integer(i),
133 CV::List(l, _) => toml::Value::Array(l.into_iter().map(|cv| cv.into_toml()).collect()),
134 CV::Table(l, _) => {
135 toml::Value::Table(l.into_iter().map(|(k, v)| (k, v.into_toml())).collect())
136 }
137 }
138 }
139
140 pub fn merge(&mut self, from: ConfigValue) -> Result<()> {
150 self.merge_helper(from, &mut ConfigKey::new())
151 }
152
153 fn merge_helper(&mut self, from: ConfigValue, parts: &mut ConfigKey) -> Result<()> {
154 let is_higher_priority = from.definition().is_higher_priority(self.definition());
155 match (self, from) {
156 (&mut CV::List(ref mut old, ref mut old_def), CV::List(ref mut new, new_def)) => {
157 if is_nonmergeable_list(&parts) {
158 if is_higher_priority {
160 mem::swap(new, old);
161 *old_def = new_def;
162 }
163 } else {
164 new.append(old);
166 mem::swap(new, old);
167 }
168 old.sort_by(|a, b| a.definition().cmp(b.definition()));
169 }
170 (&mut CV::Table(ref mut old, _), CV::Table(ref mut new, _)) => {
171 for (key, value) in mem::take(new) {
172 match old.entry(key.clone()) {
173 Entry::Occupied(mut entry) => {
174 let new_def = value.definition().clone();
175 let entry = entry.get_mut();
176 parts.push(&key);
177 entry.merge_helper(value, parts).with_context(|| {
178 format!(
179 "failed to merge key `{}` between \
180 {} and {}",
181 key,
182 entry.definition(),
183 new_def,
184 )
185 })?;
186 }
187 Entry::Vacant(entry) => {
188 entry.insert(value);
189 }
190 };
191 }
192 }
193 (expected @ &mut CV::List(_, _), found)
195 | (expected @ &mut CV::Table(_, _), found)
196 | (expected, found @ CV::List(_, _))
197 | (expected, found @ CV::Table(_, _)) => {
198 return Err(anyhow!(
199 "failed to merge config value from `{}` into `{}`: expected {}, but found {}",
200 found.definition(),
201 expected.definition(),
202 expected.desc(),
203 found.desc()
204 ));
205 }
206 (old, mut new) => {
207 if is_higher_priority {
208 mem::swap(old, &mut new);
209 }
210 }
211 }
212
213 Ok(())
214 }
215
216 pub fn i64(&self, key: &str) -> Result<(i64, &Definition)> {
217 match self {
218 CV::Integer(i, def) => Ok((*i, def)),
219 _ => self.expected("integer", key),
220 }
221 }
222
223 pub fn string(&self, key: &str) -> Result<(&str, &Definition)> {
224 match self {
225 CV::String(s, def) => Ok((s, def)),
226 _ => self.expected("string", key),
227 }
228 }
229
230 pub fn table(&self, key: &str) -> Result<(&HashMap<String, ConfigValue>, &Definition)> {
231 match self {
232 CV::Table(table, def) => Ok((table, def)),
233 _ => self.expected("table", key),
234 }
235 }
236
237 pub fn table_mut(
238 &mut self,
239 key: &str,
240 ) -> Result<(&mut HashMap<String, ConfigValue>, &mut Definition)> {
241 match self {
242 CV::Table(table, def) => Ok((table, def)),
243 _ => self.expected("table", key),
244 }
245 }
246
247 pub fn is_table(&self) -> bool {
248 matches!(self, CV::Table(..))
249 }
250
251 pub fn string_list(&self, key: &str) -> Result<Vec<(String, Definition)>> {
252 match self {
253 CV::List(list, _) => list
254 .iter()
255 .map(|cv| match cv {
256 CV::String(s, def) => Ok((s.clone(), def.clone())),
257 _ => self.expected("string", key),
258 })
259 .collect::<Result<_>>(),
260 _ => self.expected("list", key),
261 }
262 }
263
264 pub fn boolean(&self, key: &str) -> Result<(bool, &Definition)> {
265 match self {
266 CV::Boolean(b, def) => Ok((*b, def)),
267 _ => self.expected("bool", key),
268 }
269 }
270
271 pub fn desc(&self) -> &'static str {
272 match *self {
273 CV::Table(..) => "table",
274 CV::List(..) => "array",
275 CV::String(..) => "string",
276 CV::Boolean(..) => "boolean",
277 CV::Integer(..) => "integer",
278 }
279 }
280
281 pub fn definition(&self) -> &Definition {
282 match self {
283 CV::Boolean(_, def)
284 | CV::Integer(_, def)
285 | CV::String(_, def)
286 | CV::List(_, def)
287 | CV::Table(_, def) => def,
288 }
289 }
290
291 pub(crate) fn expected<T>(&self, wanted: &str, key: &str) -> Result<T> {
292 bail!(
293 "expected a {}, but found a {} for `{}` in {}",
294 wanted,
295 self.desc(),
296 key,
297 self.definition()
298 )
299 }
300}
301
302pub(crate) fn is_nonmergeable_list(key: &ConfigKey) -> bool {
303 NON_MERGEABLE_LISTS.iter().any(|l| key.matches(l))
304}