Debian Codegraph @

lib/src/config.rs

raw
1 // Copyright 2022 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Configuration store helpers.
16
17 use std::borrow::Borrow;
18 use std::convert::Infallible;
19 use std::fmt;
20 use std::fmt::Display;
21 use std::fs;
22 use std::io;
23 use std::ops::Range;
24 use std::path::Path;
25 use std::path::PathBuf;
26 use std::slice;
27 use std::str::FromStr;
28 use std::sync::Arc;
29 use std::sync::LazyLock;
30
31 use itertools::Itertools as _;
32 use serde::Deserialize;
33 use serde::de::IntoDeserializer as _;
34 use thiserror::Error;
35 use toml_edit::Document;
36 use toml_edit::DocumentMut;
37
38 pub use crate::config_resolver::ConfigMigrateError;
39 pub use crate::config_resolver::ConfigMigrateLayerError;
40 pub use crate::config_resolver::ConfigMigrationRule;
41 pub use crate::config_resolver::ConfigResolutionContext;
42 pub use crate::config_resolver::migrate;
43 pub use crate::config_resolver::resolve;
44 use crate::file_util::IoResultExt as _;
45 use crate::file_util::PathError;
46
47 /// Config value or table node.
48 pub type ConfigItem = toml_edit::Item;
49 /// Non-inline table of config key and value pairs.
50 pub type ConfigTable = toml_edit::Table;
51 /// Non-inline or inline table of config key and value pairs.
52 pub type ConfigTableLike<'a> = dyn toml_edit::TableLike + 'a;
53 /// Generic config value.
54 pub type ConfigValue = toml_edit::Value;
55
56 /// Error that can occur when parsing or loading config variables.
57 #[derive(Debug, Error)]
58 pub enum ConfigLoadError {
59 /// Config file or directory cannot be read.
60 #[error("Failed to read configuration file")]
61 Read(#[source] PathError),
62 /// TOML file or text cannot be parsed.
63 #[error("Configuration cannot be parsed as TOML document")]
64 Parse {
65 /// Source error.
66 #[source]
67 error: Box<toml_edit::TomlError>,
68 /// Source file path.
69 source_path: Option<PathBuf>,
70 },
71 }
72
73 /// Error that can occur when saving config variables to file.
74 #[derive(Debug, Error)]
75 #[error("Failed to write configuration file")]
76 pub struct ConfigFileSaveError(#[source] pub PathError);
77
78 /// Error that can occur when looking up config variable.
79 #[derive(Debug, Error)]
80 pub enum ConfigGetError {
81 /// Config value is not set.
82 #[error("Value not found for {name}")]
83 NotFound {
84 /// Dotted config name path.
85 name: String,
86 },
87 /// Config value cannot be converted to the expected type.
88 #[error("Invalid type or value for {name}")]
89 Type {
90 /// Dotted config name path.
91 name: String,
92 /// Source error.
93 #[source]
94 error: Box<dyn std::error::Error + Send + Sync>,
95 /// Source file path where the value is defined.
96 source_path: Option<PathBuf>,
97 },
98 }
99
100 /// Error that can occur when updating config variable.
101 #[derive(Debug, Error)]
102 pub enum ConfigUpdateError {
103 /// Non-table value exists at parent path, which shouldn't be removed.
104 #[error("Would overwrite non-table value with parent table {name}")]
105 WouldOverwriteValue {
106 /// Dotted config name path.
107 name: String,
108 },
109 /// Non-inline table exists at the path, which shouldn't be overwritten by a
110 /// value.
111 #[error("Would overwrite entire table {name}")]
112 WouldOverwriteTable {
113 /// Dotted config name path.
114 name: String,
115 },
116 /// Non-inline table exists at the path, which shouldn't be deleted.
117 #[error("Would delete entire table {name}")]
118 WouldDeleteTable {
119 /// Dotted config name path.
120 name: String,
121 },
122 }
123
124 /// Extension methods for `Result<T, ConfigGetError>`.
125 pub trait ConfigGetResultExt<T> {
126 /// Converts `NotFound` error to `Ok(None)`, leaving other errors.
127 fn optional(self) -> Result<Option<T>, ConfigGetError>;
128 }
129
130 impl<T> ConfigGetResultExt<T> for Result<T, ConfigGetError> {
131 fn optional(self) -> Result<Option<T>, ConfigGetError> {
132 match self {
133 Ok(value) => Ok(Some(value)),
134 Err(ConfigGetError::NotFound { .. }) => Ok(None),
135 Err(err) => Err(err),
136 }
137 }
138 }
139
140 /// Dotted config name path.
141 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
142 pub struct ConfigNamePathBuf(Vec<toml_edit::Key>);
143
144 impl ConfigNamePathBuf {
145 /// Creates an empty path pointing to the root table.
146 ///
147 /// This isn't a valid TOML key expression, but provided for convenience.
148 pub fn root() -> Self {
149 Self(vec![])
150 }
151
152 /// Returns true if the path is empty (i.e. pointing to the root table.)
153 pub fn is_root(&self) -> bool {
154 self.0.is_empty()
155 }
156
157 /// Returns true if the `base` is a prefix of this path.
158 pub fn starts_with(&self, base: impl AsRef<[toml_edit::Key]>) -> bool {
159 self.0.starts_with(base.as_ref())
160 }
161
162 /// Returns iterator of path components (or keys.)
163 pub fn components(&self) -> slice::Iter<'_, toml_edit::Key> {
164 self.0.iter()
165 }
166
167 /// Appends the given `key` component.
168 pub fn push(&mut self, key: impl Into<toml_edit::Key>) {
169 self.0.push(key.into());
170 }
171 }
172
173 // Help obtain owned value from ToConfigNamePath::Output. If we add a slice
174 // type (like &Path for PathBuf), this will be From<&ConfigNamePath>.
175 impl From<&Self> for ConfigNamePathBuf {
176 fn from(value: &Self) -> Self {
177 value.clone()
178 }
179 }
180
181 impl<K: Into<toml_edit::Key>> FromIterator<K> for ConfigNamePathBuf {
182 fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
183 let keys = iter.into_iter().map(|k| k.into()).collect();
184 Self(keys)
185 }
186 }
187
188 impl FromStr for ConfigNamePathBuf {
189 type Err = toml_edit::TomlError;
190
191 fn from_str(s: &str) -> Result<Self, Self::Err> {
192 // TOML parser ensures that the returned vec is not empty.
193 toml_edit::Key::parse(s).map(ConfigNamePathBuf)
194 }
195 }
196
197 impl AsRef<[toml_edit::Key]> for ConfigNamePathBuf {
198 fn as_ref(&self) -> &[toml_edit::Key] {
199 &self.0
200 }
201 }
202
203 impl Display for ConfigNamePathBuf {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 let mut components = self.0.iter().fuse();
206 if let Some(key) = components.next() {
207 write!(f, "{key}")?;
208 }
209 components.try_for_each(|key| write!(f, ".{key}"))
210 }
211 }
212
213 /// Value that can be converted to a dotted config name path.
214 ///
215 /// This is an abstraction to specify a config name path in either a string or a
216 /// parsed form. It's similar to `Into<T>`, but the output type `T` is
217 /// constrained by the source type.
218 pub trait ToConfigNamePath: Sized {
219 /// Path type to be converted from `Self`.
220 type Output: Borrow<ConfigNamePathBuf> + Into<ConfigNamePathBuf>;
221
222 /// Converts this object into a dotted config name path.
223 fn into_name_path(self) -> Self::Output;
224 }
225
226 impl ToConfigNamePath for ConfigNamePathBuf {
227 type Output = Self;
228
229 fn into_name_path(self) -> Self::Output {
230 self
231 }
232 }
233
234 impl ToConfigNamePath for &ConfigNamePathBuf {
235 type Output = Self;
236
237 fn into_name_path(self) -> Self::Output {
238 self
239 }
240 }
241
242 impl ToConfigNamePath for &'static str {
243 // This can be changed to ConfigNamePathStr(str) if allocation cost matters.
244 type Output = ConfigNamePathBuf;
245
246 /// Parses this string into a dotted config name path.
247 ///
248 /// The string must be a valid TOML dotted key. A static str is required to
249 /// prevent API misuse.
250 fn into_name_path(self) -> Self::Output {
251 self.parse()
252 .expect("valid TOML dotted key must be provided")
253 }
254 }
255
256 impl<const N: usize> ToConfigNamePath for [&str; N] {
257 type Output = ConfigNamePathBuf;
258
259 fn into_name_path(self) -> Self::Output {
260 self.into_iter().collect()
261 }
262 }
263
264 impl<const N: usize> ToConfigNamePath for &[&str; N] {
265 type Output = ConfigNamePathBuf;
266
267 fn into_name_path(self) -> Self::Output {
268 self.as_slice().into_name_path()
269 }
270 }
271
272 impl ToConfigNamePath for &[&str] {
273 type Output = ConfigNamePathBuf;
274
275 fn into_name_path(self) -> Self::Output {
276 self.iter().copied().collect()
277 }
278 }
279
280 /// Source of configuration variables in order of precedence.
281 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
282 pub enum ConfigSource {
283 /// Default values (which has the lowest precedence.)
284 Default,
285 /// System configuration files.
286 System,
287 /// Base environment variables.
288 EnvBase,
289 /// User configuration files.
290 User,
291 /// Repo configuration files.
292 Repo,
293 /// Workspace configuration files.
294 Workspace,
295 /// Override environment variables.
296 EnvOverrides,
297 /// Command-line arguments (which has the highest precedence.)
298 CommandArg,
299 }
300
301 impl Display for ConfigSource {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 use ConfigSource::*;
304 let c = match self {
305 Default => "default",
306 System => "system",
307 User => "user",
308 Repo => "repo",
309 Workspace => "workspace",
310 CommandArg => "cli",
311 EnvBase | EnvOverrides => "env",
312 };
313 write!(f, "{c}")
314 }
315 }
316
317 /// Set of configuration variables with source information.
318 #[derive(Clone, Debug)]
319 pub struct ConfigLayer {
320 /// Source type of this layer.
321 pub source: ConfigSource,
322 /// Source file path of this layer if any.
323 pub path: Option<PathBuf>,
324 /// Configuration variables.
325 pub data: DocumentMut,
326 }
327
328 impl ConfigLayer {
329 /// Creates new layer with empty data.
330 pub fn empty(source: ConfigSource) -> Self {
331 Self::with_data(source, DocumentMut::new())
332 }
333
334 /// Creates new layer with the configuration variables `data`.
335 pub fn with_data(source: ConfigSource, data: DocumentMut) -> Self {
336 Self {
337 source,
338 path: None,
339 data,
340 }
341 }
342
343 /// Parses TOML document `text` into new layer.
344 pub fn parse(source: ConfigSource, text: &str) -> Result<Self, ConfigLoadError> {
345 let data = Document::parse(text).map_err(|error| ConfigLoadError::Parse {
346 error: Box::new(error),
347 source_path: None,
348 })?;
349 Ok(Self::with_data(source, data.into_mut()))
350 }
351
352 /// Loads TOML file from the specified `path`.
353 pub fn load_from_file(source: ConfigSource, path: PathBuf) -> Result<Self, ConfigLoadError> {
354 let text = fs::read_to_string(&path)
355 .context(&path)
356 .map_err(ConfigLoadError::Read)?;
357 let data = Document::parse(text).map_err(|error| ConfigLoadError::Parse {
358 error: Box::new(error),
359 source_path: Some(path.clone()),
360 })?;
361 Ok(Self {
362 source,
363 path: Some(path),
364 data: data.into_mut(),
365 })
366 }
367
368 fn load_from_dir(source: ConfigSource, path: &Path) -> Result<Vec<Self>, ConfigLoadError> {
369 // TODO: Walk the directory recursively?
370 let mut file_paths: Vec<_> = path
371 .read_dir()
372 .and_then(|dir_entries| {
373 dir_entries
374 .map(|entry| Ok(entry?.path()))
375 .filter_ok(|path| path.is_file() && path.extension() == Some("toml".as_ref()))
376 .try_collect()
377 })
378 .context(path)
379 .map_err(ConfigLoadError::Read)?;
380 file_paths.sort_unstable();
381 file_paths
382 .into_iter()
383 .map(|path| Self::load_from_file(source, path))
384 .try_collect()
385 }
386
387 /// Returns true if the table has no configuration variables.
388 pub fn is_empty(&self) -> bool {
389 self.data.is_empty()
390 }
391
392 // Add .get_value(name) if needed. look_up_*() are low-level API.
393
394 /// Looks up sub table by the `name` path. Returns `Some(table)` if a table
395 /// was found at the path. Returns `Err(item)` if middle or leaf node wasn't
396 /// a table.
397 pub fn look_up_table(
398 &self,
399 name: impl ToConfigNamePath,
400 ) -> Result<Option<&ConfigTableLike<'_>>, &ConfigItem> {
401 match self.look_up_item(name) {
402 Ok(Some(item)) => match item.as_table_like() {
403 Some(table) => Ok(Some(table)),
404 None => Err(item),
405 },
406 Ok(None) => Ok(None),
407 Err(item) => Err(item),
408 }
409 }
410
411 /// Looks up item by the `name` path. Returns `Some(item)` if an item
412 /// found at the path. Returns `Err(item)` if middle node wasn't a table.
413 pub fn look_up_item(
414 &self,
415 name: impl ToConfigNamePath,
416 ) -> Result<Option<&ConfigItem>, &ConfigItem> {
417 look_up_item(self.data.as_item(), name.into_name_path().borrow())
418 }
419
420 /// Sets `new_value` to the `name` path. Returns old value if any.
421 ///
422 /// This function errors out if attempted to overwrite a non-table middle
423 /// node or a leaf non-inline table. An inline table can be overwritten
424 /// because it's syntactically a value.
425 pub fn set_value(
426 &mut self,
427 name: impl ToConfigNamePath,
428 new_value: impl Into<ConfigValue>,
429 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
430 let would_overwrite_table = |name| ConfigUpdateError::WouldOverwriteValue { name };
431 let name = name.into_name_path();
432 let name = name.borrow();
433 let (leaf_key, table_keys) = name
434 .0
435 .split_last()
436 .ok_or_else(|| would_overwrite_table(name.to_string()))?;
437 let parent_table = ensure_table(self.data.as_table_mut(), table_keys)
438 .map_err(|keys| would_overwrite_table(keys.join(".")))?;
439 match parent_table.entry_format(leaf_key) {
440 toml_edit::Entry::Occupied(mut entry) => {
441 if !entry.get().is_value() {
442 return Err(ConfigUpdateError::WouldOverwriteTable {
443 name: name.to_string(),
444 });
445 }
446 let old_item = entry.insert(toml_edit::value(new_value));
447 Ok(Some(old_item.into_value().unwrap()))
448 }
449 toml_edit::Entry::Vacant(entry) => {
450 entry.insert(toml_edit::value(new_value));
451 // Reset whitespace formatting (i.e. insert space before '=')
452 let mut new_key = parent_table.key_mut(leaf_key).unwrap();
453 new_key.leaf_decor_mut().clear();
454 Ok(None)
455 }
456 }
457 }
458
459 /// Deletes value specified by the `name` path. Returns old value if any.
460 ///
461 /// Returns `Ok(None)` if middle node wasn't a table or a value wasn't
462 /// found. Returns `Err` if attempted to delete a non-inline table. An
463 /// inline table can be deleted because it's syntactically a value.
464 pub fn delete_value(
465 &mut self,
466 name: impl ToConfigNamePath,
467 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
468 let would_delete_table = |name| ConfigUpdateError::WouldDeleteTable { name };
469 let name = name.into_name_path();
470 let name = name.borrow();
471 let mut keys = name.components();
472 let leaf_key = keys
473 .next_back()
474 .ok_or_else(|| would_delete_table(name.to_string()))?;
475 let Some(parent_table) = keys.try_fold(
476 self.data.as_table_mut() as &mut ConfigTableLike,
477 |table, key| table.get_mut(key)?.as_table_like_mut(),
478 ) else {
479 return Ok(None);
480 };
481 match parent_table.entry(leaf_key) {
482 toml_edit::Entry::Occupied(entry) => {
483 if !entry.get().is_value() {
484 return Err(would_delete_table(name.to_string()));
485 }
486 let old_item = entry.remove();
487 Ok(Some(old_item.into_value().unwrap()))
488 }
489 toml_edit::Entry::Vacant(_) => Ok(None),
490 }
491 }
492
493 /// Inserts tables down to the `name` path. Returns mutable reference to the
494 /// leaf table.
495 ///
496 /// This function errors out if attempted to overwrite a non-table node. In
497 /// file-system analogy, this is equivalent to `std::fs::create_dir_all()`.
498 pub fn ensure_table(
499 &mut self,
500 name: impl ToConfigNamePath,
501 ) -> Result<&mut ConfigTableLike<'_>, ConfigUpdateError> {
502 let would_overwrite_table = |name| ConfigUpdateError::WouldOverwriteValue { name };
503 let name = name.into_name_path();
504 let name = name.borrow();
505 ensure_table(self.data.as_table_mut(), &name.0)
506 .map_err(|keys| would_overwrite_table(keys.join(".")))
507 }
508 }
509
510 /// Looks up item from the `root_item`. Returns `Some(item)` if an item found at
511 /// the path. Returns `Err(item)` if middle node wasn't a table.
512 fn look_up_item<'a>(
513 root_item: &'a ConfigItem,
514 name: &ConfigNamePathBuf,
515 ) -> Result<Option<&'a ConfigItem>, &'a ConfigItem> {
516 let mut cur_item = root_item;
517 for key in name.components() {
518 let Some(table) = cur_item.as_table_like() else {
519 return Err(cur_item);
520 };
521 cur_item = match table.get(key) {
522 Some(item) => item,
523 None => return Ok(None),
524 };
525 }
526 Ok(Some(cur_item))
527 }
528
529 /// Inserts tables recursively. Returns `Err(keys)` if middle node exists at the
530 /// prefix name `keys` and wasn't a table.
531 fn ensure_table<'a, 'b>(
532 root_table: &'a mut ConfigTableLike<'a>,
533 keys: &'b [toml_edit::Key],
534 ) -> Result<&'a mut ConfigTableLike<'a>, &'b [toml_edit::Key]> {
535 keys.iter()
536 .enumerate()
537 .try_fold(root_table, |table, (i, key)| {
538 let sub_item = table.entry_format(key).or_insert_with(new_implicit_table);
539 sub_item.as_table_like_mut().ok_or(&keys[..=i])
540 })
541 }
542
543 fn new_implicit_table() -> ConfigItem {
544 let mut table = ConfigTable::new();
545 table.set_implicit(true);
546 ConfigItem::Table(table)
547 }
548
549 /// Wrapper for file-based [`ConfigLayer`], providing convenient methods for
550 /// modification.
551 #[derive(Clone, Debug)]
552 pub struct ConfigFile {
553 layer: Arc<ConfigLayer>,
554 }
555
556 impl ConfigFile {
557 /// Loads TOML file from the specified `path` if exists. Returns an empty
558 /// object if the file doesn't exist.
559 pub fn load_or_empty(
560 source: ConfigSource,
561 path: impl Into<PathBuf>,
562 ) -> Result<Self, ConfigLoadError> {
563 let layer = match ConfigLayer::load_from_file(source, path.into()) {
564 Ok(layer) => Arc::new(layer),
565 Err(ConfigLoadError::Read(PathError {
566 path,
567 source: error,
568 })) if error.kind() == io::ErrorKind::NotFound => {
569 let mut data = DocumentMut::new();
570 data.decor_mut()
571 .set_prefix("#:schema https://docs.jj-vcs.dev/latest/config-schema.json\n\n");
572 let layer = ConfigLayer {
573 source,
574 path: Some(path),
575 data,
576 };
577 Arc::new(layer)
578 }
579 Err(err) => return Err(err),
580 };
581 Ok(Self { layer })
582 }
583
584 /// Wraps file-based [`ConfigLayer`] for modification. Returns `Err(layer)`
585 /// if the source `path` is unknown.
586 pub fn from_layer(layer: Arc<ConfigLayer>) -> Result<Self, Arc<ConfigLayer>> {
587 if layer.path.is_some() {
588 Ok(Self { layer })
589 } else {
590 Err(layer)
591 }
592 }
593
594 /// Writes serialized data to the source file.
595 pub fn save(&self) -> Result<(), ConfigFileSaveError> {
596 fs::write(self.path(), self.layer.data.to_string())
597 .context(self.path())
598 .map_err(ConfigFileSaveError)
599 }
600
601 /// Source file path.
602 pub fn path(&self) -> &Path {
603 self.layer.path.as_ref().expect("path must be known")
604 }
605
606 /// Returns the underlying config layer.
607 pub fn layer(&self) -> &Arc<ConfigLayer> {
608 &self.layer
609 }
610
611 // No layer_mut() is implemented because it would allow removing layer.path
612
613 /// Mutable reference to the underlying configuration variables.
614 pub fn data_mut(&mut self) -> &mut DocumentMut {
615 &mut Arc::make_mut(&mut self.layer).data
616 }
617
618 /// See [`ConfigLayer::set_value()`].
619 pub fn set_value(
620 &mut self,
621 name: impl ToConfigNamePath,
622 new_value: impl Into<ConfigValue>,
623 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
624 Arc::make_mut(&mut self.layer).set_value(name, new_value)
625 }
626
627 /// See [`ConfigLayer::delete_value()`].
628 pub fn delete_value(
629 &mut self,
630 name: impl ToConfigNamePath,
631 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
632 Arc::make_mut(&mut self.layer).delete_value(name)
633 }
634 }
635
636 /// Stack of configuration layers which can be merged as needed.
637 ///
638 /// A [`StackedConfig`] is something like a read-only `overlayfs`. Tables and
639 /// values are directories and files respectively, and tables are merged across
640 /// layers. Tables and values can be addressed by [dotted name
641 /// paths](ToConfigNamePath).
642 ///
643 /// There's no tombstone notation to remove items from the lower layers.
644 ///
645 /// Beware that arrays of tables are no different than inline arrays. They are
646 /// values, so are never merged. This might be confusing because they would be
647 /// merged if two TOML documents are concatenated literally. Avoid using array
648 /// of tables syntax.
649 #[derive(Clone, Debug)]
650 pub struct StackedConfig {
651 /// Layers sorted by `source` (the lowest precedence one first.)
652 layers: Vec<Arc<ConfigLayer>>,
653 }
654
655 impl StackedConfig {
656 /// Creates an empty stack of configuration layers.
657 pub fn empty() -> Self {
658 Self { layers: vec![] }
659 }
660
661 /// Creates a stack of configuration layers containing the default variables
662 /// referred to by `jj-lib`.
663 pub fn with_defaults() -> Self {
664 Self {
665 layers: DEFAULT_CONFIG_LAYERS.to_vec(),
666 }
667 }
668
669 /// Loads config file from the specified `path`, inserts it at the position
670 /// specified by `source`. The file should exist.
671 pub fn load_file(
672 &mut self,
673 source: ConfigSource,
674 path: impl Into<PathBuf>,
675 ) -> Result<(), ConfigLoadError> {
676 let layer = ConfigLayer::load_from_file(source, path.into())?;
677 self.add_layer(layer);
678 Ok(())
679 }
680
681 /// Loads config files from the specified directory `path`, inserts them at
682 /// the position specified by `source`. The directory should exist.
683 pub fn load_dir(
684 &mut self,
685 source: ConfigSource,
686 path: impl AsRef<Path>,
687 ) -> Result<(), ConfigLoadError> {
688 let layers = ConfigLayer::load_from_dir(source, path.as_ref())?;
689 self.extend_layers(layers);
690 Ok(())
691 }
692
693 /// Inserts new layer at the position specified by `layer.source`.
694 pub fn add_layer(&mut self, layer: impl Into<Arc<ConfigLayer>>) {
695 let layer = layer.into();
696 let index = self.insert_point(layer.source);
697 self.layers.insert(index, layer);
698 }
699
700 /// Inserts multiple layers at the positions specified by `layer.source`.
701 pub fn extend_layers<I>(&mut self, layers: I)
702 where
703 I: IntoIterator,
704 I::Item: Into<Arc<ConfigLayer>>,
705 {
706 let layers = layers.into_iter().map(Into::into);
707 for (source, chunk) in &layers.chunk_by(|layer| layer.source) {
708 let index = self.insert_point(source);
709 self.layers.splice(index..index, chunk);
710 }
711 }
712
713 /// Removes layers of the specified `source`.
714 pub fn remove_layers(&mut self, source: ConfigSource) {
715 self.layers.drain(self.layer_range(source));
716 }
717
718 fn layer_range(&self, source: ConfigSource) -> Range<usize> {
719 // Linear search since the size of Vec wouldn't be large.
720 let start = self
721 .layers
722 .iter()
723 .take_while(|layer| layer.source < source)
724 .count();
725 let count = self.layers[start..]
726 .iter()
727 .take_while(|layer| layer.source == source)
728 .count();
729 start..(start + count)
730 }
731
732 fn insert_point(&self, source: ConfigSource) -> usize {
733 // Search from end since layers are usually added in order, and the size
734 // of Vec wouldn't be large enough to do binary search.
735 let skip = self
736 .layers
737 .iter()
738 .rev()
739 .take_while(|layer| layer.source > source)
740 .count();
741 self.layers.len() - skip
742 }
743
744 /// Layers sorted by precedence.
745 pub fn layers(&self) -> &[Arc<ConfigLayer>] {
746 &self.layers
747 }
748
749 /// Mutable references to layers sorted by precedence.
750 pub fn layers_mut(&mut self) -> &mut [Arc<ConfigLayer>] {
751 &mut self.layers
752 }
753
754 /// Layers of the specified `source`.
755 pub fn layers_for(&self, source: ConfigSource) -> &[Arc<ConfigLayer>] {
756 &self.layers[self.layer_range(source)]
757 }
758
759 /// Looks up value of the specified type `T` from all layers, merges sub
760 /// fields as needed.
761 pub fn get<'de, T: Deserialize<'de>>(
762 &self,
763 name: impl ToConfigNamePath,
764 ) -> Result<T, ConfigGetError> {
765 self.get_value_with(name, |value| T::deserialize(value.into_deserializer()))
766 }
767
768 /// Looks up value from all layers, merges sub fields as needed.
769 pub fn get_value(&self, name: impl ToConfigNamePath) -> Result<ConfigValue, ConfigGetError> {
770 self.get_value_with::<_, Infallible>(name, Ok)
771 }
772
773 /// Looks up value from all layers, merges sub fields as needed, then
774 /// converts the value by using the given function.
775 pub fn get_value_with<T, E: Into<Box<dyn std::error::Error + Send + Sync>>>(
776 &self,
777 name: impl ToConfigNamePath,
778 convert: impl FnOnce(ConfigValue) -> Result<T, E>,
779 ) -> Result<T, ConfigGetError> {
780 self.get_item_with(name, |item| {
781 // Item variants other than Item::None can be converted to a Value,
782 // and Item::None is not a valid TOML type. See also the following
783 // thread: https://github.com/toml-rs/toml/issues/299
784 let value = item
785 .into_value()
786 .expect("Item::None should not exist in loaded tables");
787 convert(value)
788 })
789 }
790
791 /// Looks up sub table from all layers, merges fields as needed.
792 ///
793 /// Use `table_keys(prefix)` and `get([prefix, key])` instead if table
794 /// values have to be converted to non-generic value type.
795 pub fn get_table(&self, name: impl ToConfigNamePath) -> Result<ConfigTable, ConfigGetError> {
796 self.get_item_with(name, |item| {
797 item.into_table()
798 .map_err(|item| format!("Expected a table, but is {}", item.type_name()))
799 })
800 }
801
802 fn get_item_with<T, E: Into<Box<dyn std::error::Error + Send + Sync>>>(
803 &self,
804 name: impl ToConfigNamePath,
805 convert: impl FnOnce(ConfigItem) -> Result<T, E>,
806 ) -> Result<T, ConfigGetError> {
807 let name = name.into_name_path();
808 let name = name.borrow();
809 let (item, layer_index) =
810 get_merged_item(&self.layers, name).ok_or_else(|| ConfigGetError::NotFound {
811 name: name.to_string(),
812 })?;
813 // If the value is a table, the error might come from lower layers. We
814 // cannot report precise source information in that case. However,
815 // toml_edit captures dotted keys in the error object. If the keys field
816 // were public, we can look up the source information. This is probably
817 // simpler than reimplementing Deserializer.
818 convert(item).map_err(|err| ConfigGetError::Type {
819 name: name.to_string(),
820 error: err.into(),
821 source_path: self.layers[layer_index].path.clone(),
822 })
823 }
824
825 /// Returns iterator over sub table keys in order of layer precedence.
826 /// Duplicated keys are omitted.
827 pub fn table_keys(&self, name: impl ToConfigNamePath) -> impl Iterator<Item = &str> {
828 let name = name.into_name_path();
829 let name = name.borrow();
830 let to_merge = get_tables_to_merge(&self.layers, name);
831 to_merge
832 .into_iter()
833 .rev()
834 .flat_map(|table| table.iter().map(|(k, _)| k))
835 .unique()
836 }
837 }
838
839 /// Looks up item from `layers`, merges sub fields as needed. Returns a merged
840 /// item and the uppermost layer index where the item was found.
841 fn get_merged_item(
842 layers: &[Arc<ConfigLayer>],
843 name: &ConfigNamePathBuf,
844 ) -> Option<(ConfigItem, usize)> {
845 let mut to_merge = Vec::new();
846 for (index, layer) in layers.iter().enumerate().rev() {
847 let item = match layer.look_up_item(name) {
848 Ok(Some(item)) => item,
849 Ok(None) => continue, // parent is a table, but no value found
850 Err(_) => break, // parent is not a table, shadows lower layers
851 };
852 if item.is_table_like() {
853 to_merge.push((item, index));
854 } else if to_merge.is_empty() {
855 return Some((item.clone(), index)); // no need to allocate vec
856 } else {
857 break; // shadows lower layers
858 }
859 }
860
861 // Simply merge tables from the bottom layer. Upper items should override
862 // the lower items (including their children) no matter if the upper items
863 // are shadowed by the other upper items.
864 let (item, mut top_index) = to_merge.pop()?;
865 let mut merged = item.clone();
866 for (item, index) in to_merge.into_iter().rev() {
867 merge_items(&mut merged, item);
868 top_index = index;
869 }
870 Some((merged, top_index))
871 }
872
873 /// Looks up tables to be merged from `layers`, returns in reverse order.
874 fn get_tables_to_merge<'a>(
875 layers: &'a [Arc<ConfigLayer>],
876 name: &ConfigNamePathBuf,
877 ) -> Vec<&'a ConfigTableLike<'a>> {
878 let mut to_merge = Vec::new();
879 for layer in layers.iter().rev() {
880 match layer.look_up_table(name) {
881 Ok(Some(table)) => to_merge.push(table),
882 Ok(None) => {} // parent is a table, but no value found
883 Err(_) => break, // parent/leaf is not a table, shadows lower layers
884 }
885 }
886 to_merge
887 }
888
889 /// Merges `upper_item` fields into `lower_item` recursively.
890 fn merge_items(lower_item: &mut ConfigItem, upper_item: &ConfigItem) {
891 let (Some(lower_table), Some(upper_table)) =
892 (lower_item.as_table_like_mut(), upper_item.as_table_like())
893 else {
894 // Not a table, the upper item wins.
895 *lower_item = upper_item.clone();
896 return;
897 };
898 for (key, upper) in upper_table.iter() {
899 match lower_table.entry(key) {
900 toml_edit::Entry::Occupied(entry) => {
901 merge_items(entry.into_mut(), upper);
902 }
903 toml_edit::Entry::Vacant(entry) => {
904 entry.insert(upper.clone());
905 }
906 }
907 }
908 }
909
910 static DEFAULT_CONFIG_LAYERS: LazyLock<[Arc<ConfigLayer>; 1]> = LazyLock::new(|| {
911 let parse = |text: &str| Arc::new(ConfigLayer::parse(ConfigSource::Default, text).unwrap());
912 [parse(include_str!("config/misc.toml"))]
913 });
914
915 #[cfg(test)]
916 mod tests {
917 use assert_matches::assert_matches;
918 use indoc::indoc;
919 use pretty_assertions::assert_eq;
920
921 use super::*;
922 use crate::tests::TestResult;
923
924 #[test]
925 fn test_config_layer_set_value() -> TestResult {
926 let mut layer = ConfigLayer::empty(ConfigSource::User);
927 // Cannot overwrite the root table
928 assert_matches!(
929 layer.set_value(ConfigNamePathBuf::root(), 0),
930 Err(ConfigUpdateError::WouldOverwriteValue { name }) if name.is_empty()
931 );
932
933 // Insert some values
934 layer.set_value("foo", 1)?;
935 layer.set_value("bar.baz.blah", "2")?;
936 layer.set_value("bar.qux", ConfigValue::from_iter([("inline", "table")]))?;
937 layer.set_value("bar.to-update", ConfigValue::from_iter([("some", true)]))?;
938 insta::assert_snapshot!(layer.data, @r#"
939 foo = 1
940
941 [bar]
942 qux = { inline = "table" }
943 to-update = { some = true }
944
945 [bar.baz]
946 blah = "2"
947 "#);
948
949 // Can overwrite value
950 layer.set_value("foo", ConfigValue::from_iter(["new", "foo"]))?;
951 // Can overwrite inline table
952 layer.set_value("bar.qux", "new bar.qux")?;
953 // Can add value to inline table
954 layer.set_value(
955 "bar.to-update.new",
956 ConfigValue::from_iter([("table", "value")]),
957 )?;
958 // Cannot overwrite table
959 assert_matches!(
960 layer.set_value("bar", 0),
961 Err(ConfigUpdateError::WouldOverwriteTable { name }) if name == "bar"
962 );
963 // Cannot overwrite value by table
964 assert_matches!(
965 layer.set_value("bar.baz.blah.blah", 0),
966 Err(ConfigUpdateError::WouldOverwriteValue { name }) if name == "bar.baz.blah"
967 );
968 insta::assert_snapshot!(layer.data, @r#"
969 foo = ["new", "foo"]
970
971 [bar]
972 qux = "new bar.qux"
973 to-update = { some = true, new = { table = "value" } }
974
975 [bar.baz]
976 blah = "2"
977 "#);
978 Ok(())
979 }
980
981 #[test]
982 fn test_config_layer_set_value_formatting() -> TestResult {
983 let mut layer = ConfigLayer::empty(ConfigSource::User);
984 // Quoting style should be preserved on insertion
985 layer.set_value("'foo' . bar . 'baz'", ConfigValue::from_str("'value'")?)?;
986 insta::assert_snapshot!(layer.data, @"
987 ['foo' . bar]
988 'baz' = 'value'
989 ");
990
991 // Style of existing keys isn't updated
992 layer.set_value("foo.bar.baz", "new value")?;
993 layer.set_value("foo.'bar'.blah", 0)?;
994 insta::assert_snapshot!(layer.data, @r#"
995 ['foo' . bar]
996 'baz' = "new value"
997 blah = 0
998 "#);
999 Ok(())
1000 }
1001
1002 #[test]
1003 fn test_config_layer_set_value_inline_table() -> TestResult {
1004 let mut layer = ConfigLayer::empty(ConfigSource::User);
1005 layer.set_value("a", ConfigValue::from_iter([("b", "a.b")]))?;
1006 insta::assert_snapshot!(layer.data, @r#"a = { b = "a.b" }"#);
1007
1008 // Should create nested inline tables
1009 layer.set_value("a.c.d", "a.c.d")?;
1010 insta::assert_snapshot!(layer.data, @r#"a = { b = "a.b", c.d = "a.c.d" }"#);
1011 Ok(())
1012 }
1013
1014 #[test]
1015 fn test_config_layer_delete_value() -> TestResult {
1016 let mut layer = ConfigLayer::empty(ConfigSource::User);
1017 // Cannot delete the root table
1018 assert_matches!(
1019 layer.delete_value(ConfigNamePathBuf::root()),
1020 Err(ConfigUpdateError::WouldDeleteTable { name }) if name.is_empty()
1021 );
1022
1023 // Insert some values
1024 layer.set_value("foo", 1)?;
1025 layer.set_value("bar.baz.blah", "2")?;
1026 layer.set_value("bar.qux", ConfigValue::from_iter([("inline", "table")]))?;
1027 layer.set_value("bar.to-update", ConfigValue::from_iter([("some", true)]))?;
1028 insta::assert_snapshot!(layer.data, @r#"
1029 foo = 1
1030
1031 [bar]
1032 qux = { inline = "table" }
1033 to-update = { some = true }
1034
1035 [bar.baz]
1036 blah = "2"
1037 "#);
1038
1039 // Can delete value
1040 let old_value = layer.delete_value("foo")?;
1041 assert_eq!(old_value.and_then(|v| v.as_integer()), Some(1));
1042 // Can delete inline table
1043 let old_value = layer.delete_value("bar.qux")?;
1044 assert!(old_value.is_some_and(|v| v.is_inline_table()));
1045 // Can delete inner value from inline table
1046 let old_value = layer.delete_value("bar.to-update.some")?;
1047 assert_eq!(old_value.and_then(|v| v.as_bool()), Some(true));
1048 // Cannot delete table
1049 assert_matches!(
1050 layer.delete_value("bar"),
1051 Err(ConfigUpdateError::WouldDeleteTable { name }) if name == "bar"
1052 );
1053 // Deleting a non-table child isn't an error because the value doesn't
1054 // exist
1055 assert_matches!(layer.delete_value("bar.baz.blah.blah"), Ok(None));
1056 insta::assert_snapshot!(layer.data, @r#"
1057 [bar]
1058 to-update = {}
1059
1060 [bar.baz]
1061 blah = "2"
1062 "#);
1063 Ok(())
1064 }
1065
1066 #[test]
1067 fn test_stacked_config_layer_order() {
1068 let empty_data = || DocumentMut::new();
1069 let layer_sources = |config: &StackedConfig| {
1070 config
1071 .layers()
1072 .iter()
1073 .map(|layer| layer.source)
1074 .collect_vec()
1075 };
1076
1077 // Insert in reverse order
1078 let mut config = StackedConfig::empty();
1079 config.add_layer(ConfigLayer::with_data(ConfigSource::Repo, empty_data()));
1080 config.add_layer(ConfigLayer::with_data(ConfigSource::User, empty_data()));
1081 config.add_layer(ConfigLayer::with_data(ConfigSource::System, empty_data()));
1082 config.add_layer(ConfigLayer::with_data(ConfigSource::Default, empty_data()));
1083 assert_eq!(
1084 layer_sources(&config),
1085 vec![
1086 ConfigSource::Default,
1087 ConfigSource::System,
1088 ConfigSource::User,
1089 ConfigSource::Repo,
1090 ]
1091 );
1092
1093 // Insert some more
1094 config.add_layer(ConfigLayer::with_data(
1095 ConfigSource::CommandArg,
1096 empty_data(),
1097 ));
1098 config.add_layer(ConfigLayer::with_data(ConfigSource::EnvBase, empty_data()));
1099 config.add_layer(ConfigLayer::with_data(ConfigSource::User, empty_data()));
1100 assert_eq!(
1101 layer_sources(&config),
1102 vec![
1103 ConfigSource::Default,
1104 ConfigSource::System,
1105 ConfigSource::EnvBase,
1106 ConfigSource::User,
1107 ConfigSource::User,
1108 ConfigSource::Repo,
1109 ConfigSource::CommandArg,
1110 ]
1111 );
1112
1113 // Remove last, first, middle
1114 config.remove_layers(ConfigSource::CommandArg);
1115 config.remove_layers(ConfigSource::Default);
1116 config.remove_layers(ConfigSource::User);
1117 assert_eq!(
1118 layer_sources(&config),
1119 vec![
1120 ConfigSource::System,
1121 ConfigSource::EnvBase,
1122 ConfigSource::Repo,
1123 ]
1124 );
1125
1126 // Remove unknown
1127 config.remove_layers(ConfigSource::Default);
1128 config.remove_layers(ConfigSource::EnvOverrides);
1129 assert_eq!(
1130 layer_sources(&config),
1131 vec![
1132 ConfigSource::System,
1133 ConfigSource::EnvBase,
1134 ConfigSource::Repo,
1135 ]
1136 );
1137
1138 // Insert multiple
1139 config.extend_layers([
1140 ConfigLayer::with_data(ConfigSource::Repo, empty_data()),
1141 ConfigLayer::with_data(ConfigSource::Repo, empty_data()),
1142 ConfigLayer::with_data(ConfigSource::User, empty_data()),
1143 ]);
1144 assert_eq!(
1145 layer_sources(&config),
1146 vec![
1147 ConfigSource::System,
1148 ConfigSource::EnvBase,
1149 ConfigSource::User,
1150 ConfigSource::Repo,
1151 ConfigSource::Repo,
1152 ConfigSource::Repo,
1153 ]
1154 );
1155
1156 // Remove remainders
1157 config.remove_layers(ConfigSource::EnvBase);
1158 config.remove_layers(ConfigSource::System);
1159 config.remove_layers(ConfigSource::User);
1160 config.remove_layers(ConfigSource::Repo);
1161 assert_eq!(layer_sources(&config), vec![]);
1162 }
1163
1164 fn new_user_layer(text: &str) -> ConfigLayer {
1165 ConfigLayer::parse(ConfigSource::User, text).unwrap()
1166 }
1167
1168 #[test]
1169 fn test_stacked_config_get_simple_value() -> TestResult {
1170 let mut config = StackedConfig::empty();
1171 config.add_layer(new_user_layer(indoc! {"
1172 a.b.c = 'a.b.c #0'
1173 "}));
1174 config.add_layer(new_user_layer(indoc! {"
1175 a.d = ['a.d #1']
1176 "}));
1177
1178 assert_eq!(config.get::<String>("a.b.c")?, "a.b.c #0");
1179
1180 assert_eq!(config.get::<Vec<String>>("a.d")?, vec!["a.d #1".to_owned()]);
1181
1182 // Table "a.b" exists, but key doesn't
1183 assert_matches!(
1184 config.get::<String>("a.b.missing"),
1185 Err(ConfigGetError::NotFound { name }) if name == "a.b.missing"
1186 );
1187
1188 // Node "a.b.c" is not a table
1189 assert_matches!(
1190 config.get::<String>("a.b.c.d"),
1191 Err(ConfigGetError::NotFound { name }) if name == "a.b.c.d"
1192 );
1193
1194 // Type error
1195 assert_matches!(
1196 config.get::<String>("a.b"),
1197 Err(ConfigGetError::Type { name, .. }) if name == "a.b"
1198 );
1199 Ok(())
1200 }
1201
1202 #[test]
1203 fn test_stacked_config_get_table_as_value() -> TestResult {
1204 let mut config = StackedConfig::empty();
1205 config.add_layer(new_user_layer(indoc! {"
1206 a.b = { c = 'a.b.c #0' }
1207 "}));
1208 config.add_layer(new_user_layer(indoc! {"
1209 a.d = ['a.d #1']
1210 "}));
1211
1212 // Table can be converted to a value (so it can be deserialized to a
1213 // structured value.)
1214 insta::assert_snapshot!(
1215 config.get_value("a")?,
1216 @"{ b = { c = 'a.b.c #0' }, d = ['a.d #1'] }");
1217 Ok(())
1218 }
1219
1220 #[test]
1221 fn test_stacked_config_get_inline_table() -> TestResult {
1222 let mut config = StackedConfig::empty();
1223 config.add_layer(new_user_layer(indoc! {"
1224 a.b = { c = 'a.b.c #0' }
1225 "}));
1226 config.add_layer(new_user_layer(indoc! {"
1227 a.b = { d = 'a.b.d #1' }
1228 "}));
1229
1230 // Inline tables are merged
1231 insta::assert_snapshot!(
1232 config.get_value("a.b")?,
1233 @" { c = 'a.b.c #0' , d = 'a.b.d #1' }");
1234 Ok(())
1235 }
1236
1237 #[test]
1238 fn test_stacked_config_get_inline_non_inline_table() -> TestResult {
1239 let mut config = StackedConfig::empty();
1240 config.add_layer(new_user_layer(indoc! {"
1241 a.b = { c = 'a.b.c #0' }
1242 "}));
1243 config.add_layer(new_user_layer(indoc! {"
1244 a.b.d = 'a.b.d #1'
1245 "}));
1246
1247 insta::assert_snapshot!(
1248 config.get_value("a.b")?,
1249 @" { c = 'a.b.c #0' , d = 'a.b.d #1'}");
1250 insta::assert_snapshot!(
1251 config.get_table("a")?,
1252 @"b = { c = 'a.b.c #0' , d = 'a.b.d #1'}");
1253 Ok(())
1254 }
1255
1256 #[test]
1257 fn test_stacked_config_get_value_shadowing_table() -> TestResult {
1258 let mut config = StackedConfig::empty();
1259 config.add_layer(new_user_layer(indoc! {"
1260 a.b.c = 'a.b.c #0'
1261 "}));
1262 // a.b.c is shadowed by a.b
1263 config.add_layer(new_user_layer(indoc! {"
1264 a.b = 'a.b #1'
1265 "}));
1266
1267 assert_eq!(config.get::<String>("a.b")?, "a.b #1");
1268
1269 assert_matches!(
1270 config.get::<String>("a.b.c"),
1271 Err(ConfigGetError::NotFound { name }) if name == "a.b.c"
1272 );
1273 Ok(())
1274 }
1275
1276 #[test]
1277 fn test_stacked_config_get_table_shadowing_table() -> TestResult {
1278 let mut config = StackedConfig::empty();
1279 config.add_layer(new_user_layer(indoc! {"
1280 a.b = 'a.b #0'
1281 "}));
1282 // a.b is shadowed by a.b.c
1283 config.add_layer(new_user_layer(indoc! {"
1284 a.b.c = 'a.b.c #1'
1285 "}));
1286 insta::assert_snapshot!(config.get_table("a.b")?, @"c = 'a.b.c #1'");
1287 Ok(())
1288 }
1289
1290 #[test]
1291 fn test_stacked_config_get_merged_table() -> TestResult {
1292 let mut config = StackedConfig::empty();
1293 config.add_layer(new_user_layer(indoc! {"
1294 a.a.a = 'a.a.a #0'
1295 a.a.b = 'a.a.b #0'
1296 a.b = 'a.b #0'
1297 "}));
1298 config.add_layer(new_user_layer(indoc! {"
1299 a.a.b = 'a.a.b #1'
1300 a.a.c = 'a.a.c #1'
1301 a.c = 'a.c #1'
1302 "}));
1303 insta::assert_snapshot!(config.get_table("a")?, @"
1304 a.a = 'a.a.a #0'
1305 a.b = 'a.a.b #1'
1306 a.c = 'a.a.c #1'
1307 b = 'a.b #0'
1308 c = 'a.c #1'
1309 ");
1310 assert_eq!(config.table_keys("a").collect_vec(), vec!["a", "b", "c"]);
1311 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["a", "b", "c"]);
1312 assert_eq!(config.table_keys("a.b").collect_vec(), vec![""; 0]);
1313 assert_eq!(config.table_keys("a.missing").collect_vec(), vec![""; 0]);
1314 Ok(())
1315 }
1316
1317 #[test]
1318 fn test_stacked_config_get_merged_table_shadowed_top() -> TestResult {
1319 let mut config = StackedConfig::empty();
1320 config.add_layer(new_user_layer(indoc! {"
1321 a.a.a = 'a.a.a #0'
1322 a.b = 'a.b #0'
1323 "}));
1324 // a.a.a and a.b are shadowed by a
1325 config.add_layer(new_user_layer(indoc! {"
1326 a = 'a #1'
1327 "}));
1328 // a is shadowed by a.a.b
1329 config.add_layer(new_user_layer(indoc! {"
1330 a.a.b = 'a.a.b #2'
1331 "}));
1332 insta::assert_snapshot!(config.get_table("a")?, @"a.b = 'a.a.b #2'");
1333 assert_eq!(config.table_keys("a").collect_vec(), vec!["a"]);
1334 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["b"]);
1335 Ok(())
1336 }
1337
1338 #[test]
1339 fn test_stacked_config_get_merged_table_shadowed_child() -> TestResult {
1340 let mut config = StackedConfig::empty();
1341 config.add_layer(new_user_layer(indoc! {"
1342 a.a.a = 'a.a.a #0'
1343 a.b = 'a.b #0'
1344 "}));
1345 // a.a.a is shadowed by a.a
1346 config.add_layer(new_user_layer(indoc! {"
1347 a.a = 'a.a #1'
1348 "}));
1349 // a.a is shadowed by a.a.b
1350 config.add_layer(new_user_layer(indoc! {"
1351 a.a.b = 'a.a.b #2'
1352 "}));
1353 insta::assert_snapshot!(config.get_table("a")?, @"
1354 a.b = 'a.a.b #2'
1355 b = 'a.b #0'
1356 ");
1357 assert_eq!(config.table_keys("a").collect_vec(), vec!["a", "b"]);
1358 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["b"]);
1359 Ok(())
1360 }
1361
1362 #[test]
1363 fn test_stacked_config_get_merged_table_shadowed_parent() -> TestResult {
1364 let mut config = StackedConfig::empty();
1365 config.add_layer(new_user_layer(indoc! {"
1366 a.a.a = 'a.a.a #0'
1367 "}));
1368 // a.a.a is shadowed by a
1369 config.add_layer(new_user_layer(indoc! {"
1370 a = 'a #1'
1371 "}));
1372 // a is shadowed by a.a.b
1373 config.add_layer(new_user_layer(indoc! {"
1374 a.a.b = 'a.a.b #2'
1375 "}));
1376 // a is not under a.a, but it should still shadow lower layers
1377 insta::assert_snapshot!(config.get_table("a.a")?, @"b = 'a.a.b #2'");
1378 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["b"]);
1379 Ok(())
1380 }
1381 }