1use std::borrow::Borrow;
18use std::convert::Infallible;
19use std::fmt;
20use std::fmt::Display;
21use std::fs;
22use std::io;
23use std::ops::Range;
24use std::path::Path;
25use std::path::PathBuf;
26use std::slice;
27use std::str::FromStr;
28use std::sync::Arc;
29use std::sync::LazyLock;
30
31use itertools::Itertools as _;
32use serde::Deserialize;
33use serde::de::IntoDeserializer as _;
34use thiserror::Error;
35use toml_edit::Document;
36use toml_edit::DocumentMut;
37
38pub use crate::config_resolver::ConfigMigrateError;
39pub use crate::config_resolver::ConfigMigrateLayerError;
40pub use crate::config_resolver::ConfigMigrationRule;
41pub use crate::config_resolver::ConfigResolutionContext;
42pub use crate::config_resolver::migrate;
43pub use crate::config_resolver::resolve;
44use crate::file_util::IoResultExt as _;
45use crate::file_util::PathError;
46
47pub type ConfigItem = toml_edit::Item;
49pub type ConfigTable = toml_edit::Table;
51pub type ConfigTableLike<'a> = dyn toml_edit::TableLike + 'a;
53pub type ConfigValue = toml_edit::Value;
55
56#[derive(Debug, Error)]
58pub enum ConfigLoadError {
59 #[error("Failed to read configuration file")]
61 Read(#[source] PathError),
62 #[error("Configuration cannot be parsed as TOML document")]
64 Parse {
65 #[source]
67 error: Box<toml_edit::TomlError>,
68 source_path: Option<PathBuf>,
70 },
71}
72
73#[derive(Debug, Error)]
75#[error("Failed to write configuration file")]
76pub struct ConfigFileSaveError(#[source] pub PathError);
77
78#[derive(Debug, Error)]
80pub enum ConfigGetError {
81 #[error("Value not found for {name}")]
83 NotFound {
84 name: String,
86 },
87 #[error("Invalid type or value for {name}")]
89 Type {
90 name: String,
92 #[source]
94 error: Box<dyn std::error::Error + Send + Sync>,
95 source_path: Option<PathBuf>,
97 },
98}
99
100#[derive(Debug, Error)]
102pub enum ConfigUpdateError {
103 #[error("Would overwrite non-table value with parent table {name}")]
105 WouldOverwriteValue {
106 name: String,
108 },
109 #[error("Would overwrite entire table {name}")]
112 WouldOverwriteTable {
113 name: String,
115 },
116 #[error("Would delete entire table {name}")]
118 WouldDeleteTable {
119 name: String,
121 },
122}
123
124pub trait ConfigGetResultExt<T> {
126 fn optional(self) -> Result<Option<T>, ConfigGetError>;
128}
129
130impl<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#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
142pub struct ConfigNamePathBuf(Vec<toml_edit::Key>);
143
144impl ConfigNamePathBuf {
145 pub fn root() -> Self {
149 Self(vec![])
150 }
151
152 pub fn is_root(&self) -> bool {
154 self.0.is_empty()
155 }
156
157 pub fn starts_with(&self, base: impl AsRef<[toml_edit::Key]>) -> bool {
159 self.0.starts_with(base.as_ref())
160 }
161
162 pub fn components(&self) -> slice::Iter<'_, toml_edit::Key> {
164 self.0.iter()
165 }
166
167 pub fn push(&mut self, key: impl Into<toml_edit::Key>) {
169 self.0.push(key.into());
170 }
171}
172
173impl From<&Self> for ConfigNamePathBuf {
176 fn from(value: &Self) -> Self {
177 value.clone()
178 }
179}
180
181impl<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
188impl FromStr for ConfigNamePathBuf {
189 type Err = toml_edit::TomlError;
190
191 fn from_str(s: &str) -> Result<Self, Self::Err> {
192 toml_edit::Key::parse(s).map(ConfigNamePathBuf)
194 }
195}
196
197impl AsRef<[toml_edit::Key]> for ConfigNamePathBuf {
198 fn as_ref(&self) -> &[toml_edit::Key] {
199 &self.0
200 }
201}
202
203impl 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
213pub trait ToConfigNamePath: Sized {
219 type Output: Borrow<ConfigNamePathBuf> + Into<ConfigNamePathBuf>;
221
222 fn into_name_path(self) -> Self::Output;
224}
225
226impl ToConfigNamePath for ConfigNamePathBuf {
227 type Output = Self;
228
229 fn into_name_path(self) -> Self::Output {
230 self
231 }
232}
233
234impl ToConfigNamePath for &ConfigNamePathBuf {
235 type Output = Self;
236
237 fn into_name_path(self) -> Self::Output {
238 self
239 }
240}
241
242impl ToConfigNamePath for &'static str {
243 type Output = ConfigNamePathBuf;
245
246 fn into_name_path(self) -> Self::Output {
251 self.parse()
252 .expect("valid TOML dotted key must be provided")
253 }
254}
255
256impl<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
264impl<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
272impl 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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
282pub enum ConfigSource {
283 Default,
285 EnvBase,
287 User,
289 Repo,
291 EnvOverrides,
293 CommandArg,
295}
296
297impl Display for ConfigSource {
298 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299 use ConfigSource::*;
300 let c = match self {
301 Default => "default",
302 User => "user",
303 Repo => "repo",
304 CommandArg => "cli",
305 EnvBase | EnvOverrides => "env",
306 };
307 write!(f, "{c}")
308 }
309}
310
311#[derive(Clone, Debug)]
313pub struct ConfigLayer {
314 pub source: ConfigSource,
316 pub path: Option<PathBuf>,
318 pub data: DocumentMut,
320}
321
322impl ConfigLayer {
323 pub fn empty(source: ConfigSource) -> Self {
325 Self::with_data(source, DocumentMut::new())
326 }
327
328 pub fn with_data(source: ConfigSource, data: DocumentMut) -> Self {
330 Self {
331 source,
332 path: None,
333 data,
334 }
335 }
336
337 pub fn parse(source: ConfigSource, text: &str) -> Result<Self, ConfigLoadError> {
339 let data = Document::parse(text).map_err(|error| ConfigLoadError::Parse {
340 error: Box::new(error),
341 source_path: None,
342 })?;
343 Ok(Self::with_data(source, data.into_mut()))
344 }
345
346 pub fn load_from_file(source: ConfigSource, path: PathBuf) -> Result<Self, ConfigLoadError> {
348 let text = fs::read_to_string(&path)
349 .context(&path)
350 .map_err(ConfigLoadError::Read)?;
351 let data = Document::parse(text).map_err(|error| ConfigLoadError::Parse {
352 error: Box::new(error),
353 source_path: Some(path.clone()),
354 })?;
355 Ok(Self {
356 source,
357 path: Some(path),
358 data: data.into_mut(),
359 })
360 }
361
362 fn load_from_dir(source: ConfigSource, path: &Path) -> Result<Vec<Self>, ConfigLoadError> {
363 let mut file_paths: Vec<_> = path
365 .read_dir()
366 .and_then(|dir_entries| {
367 dir_entries
368 .map(|entry| Ok(entry?.path()))
369 .filter_ok(|path| path.is_file() && path.extension() == Some("toml".as_ref()))
370 .try_collect()
371 })
372 .context(path)
373 .map_err(ConfigLoadError::Read)?;
374 file_paths.sort_unstable();
375 file_paths
376 .into_iter()
377 .map(|path| Self::load_from_file(source, path))
378 .try_collect()
379 }
380
381 pub fn is_empty(&self) -> bool {
383 self.data.is_empty()
384 }
385
386 pub fn look_up_table(
392 &self,
393 name: impl ToConfigNamePath,
394 ) -> Result<Option<&ConfigTableLike<'_>>, &ConfigItem> {
395 match self.look_up_item(name) {
396 Ok(Some(item)) => match item.as_table_like() {
397 Some(table) => Ok(Some(table)),
398 None => Err(item),
399 },
400 Ok(None) => Ok(None),
401 Err(item) => Err(item),
402 }
403 }
404
405 pub fn look_up_item(
408 &self,
409 name: impl ToConfigNamePath,
410 ) -> Result<Option<&ConfigItem>, &ConfigItem> {
411 look_up_item(self.data.as_item(), name.into_name_path().borrow())
412 }
413
414 pub fn set_value(
420 &mut self,
421 name: impl ToConfigNamePath,
422 new_value: impl Into<ConfigValue>,
423 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
424 let would_overwrite_table = |name| ConfigUpdateError::WouldOverwriteValue { name };
425 let name = name.into_name_path();
426 let name = name.borrow();
427 let (leaf_key, table_keys) = name
428 .0
429 .split_last()
430 .ok_or_else(|| would_overwrite_table(name.to_string()))?;
431 let parent_table = ensure_table(self.data.as_table_mut(), table_keys)
432 .map_err(|keys| would_overwrite_table(keys.join(".")))?;
433 match parent_table.entry_format(leaf_key) {
434 toml_edit::Entry::Occupied(mut entry) => {
435 if !entry.get().is_value() {
436 return Err(ConfigUpdateError::WouldOverwriteTable {
437 name: name.to_string(),
438 });
439 }
440 let old_item = entry.insert(toml_edit::value(new_value));
441 Ok(Some(old_item.into_value().unwrap()))
442 }
443 toml_edit::Entry::Vacant(entry) => {
444 entry.insert(toml_edit::value(new_value));
445 let mut new_key = parent_table.key_mut(leaf_key).unwrap();
447 new_key.leaf_decor_mut().clear();
448 Ok(None)
449 }
450 }
451 }
452
453 pub fn delete_value(
459 &mut self,
460 name: impl ToConfigNamePath,
461 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
462 let would_delete_table = |name| ConfigUpdateError::WouldDeleteTable { name };
463 let name = name.into_name_path();
464 let name = name.borrow();
465 let mut keys = name.components();
466 let leaf_key = keys
467 .next_back()
468 .ok_or_else(|| would_delete_table(name.to_string()))?;
469 let Some(parent_table) = keys.try_fold(
470 self.data.as_table_mut() as &mut ConfigTableLike,
471 |table, key| table.get_mut(key)?.as_table_like_mut(),
472 ) else {
473 return Ok(None);
474 };
475 match parent_table.entry(leaf_key) {
476 toml_edit::Entry::Occupied(entry) => {
477 if !entry.get().is_value() {
478 return Err(would_delete_table(name.to_string()));
479 }
480 let old_item = entry.remove();
481 Ok(Some(old_item.into_value().unwrap()))
482 }
483 toml_edit::Entry::Vacant(_) => Ok(None),
484 }
485 }
486
487 pub fn ensure_table(
493 &mut self,
494 name: impl ToConfigNamePath,
495 ) -> Result<&mut ConfigTableLike<'_>, ConfigUpdateError> {
496 let would_overwrite_table = |name| ConfigUpdateError::WouldOverwriteValue { name };
497 let name = name.into_name_path();
498 let name = name.borrow();
499 ensure_table(self.data.as_table_mut(), &name.0)
500 .map_err(|keys| would_overwrite_table(keys.join(".")))
501 }
502}
503
504fn look_up_item<'a>(
507 root_item: &'a ConfigItem,
508 name: &ConfigNamePathBuf,
509) -> Result<Option<&'a ConfigItem>, &'a ConfigItem> {
510 let mut cur_item = root_item;
511 for key in name.components() {
512 let Some(table) = cur_item.as_table_like() else {
513 return Err(cur_item);
514 };
515 cur_item = match table.get(key) {
516 Some(item) => item,
517 None => return Ok(None),
518 };
519 }
520 Ok(Some(cur_item))
521}
522
523fn ensure_table<'a, 'b>(
526 root_table: &'a mut ConfigTableLike<'a>,
527 keys: &'b [toml_edit::Key],
528) -> Result<&'a mut ConfigTableLike<'a>, &'b [toml_edit::Key]> {
529 keys.iter()
530 .enumerate()
531 .try_fold(root_table, |table, (i, key)| {
532 let sub_item = table.entry_format(key).or_insert_with(new_implicit_table);
533 sub_item.as_table_like_mut().ok_or(&keys[..=i])
534 })
535}
536
537fn new_implicit_table() -> ConfigItem {
538 let mut table = ConfigTable::new();
539 table.set_implicit(true);
540 ConfigItem::Table(table)
541}
542
543#[derive(Clone, Debug)]
546pub struct ConfigFile {
547 layer: Arc<ConfigLayer>,
548}
549
550impl ConfigFile {
551 pub fn load_or_empty(
554 source: ConfigSource,
555 path: impl Into<PathBuf>,
556 ) -> Result<Self, ConfigLoadError> {
557 let layer = match ConfigLayer::load_from_file(source, path.into()) {
558 Ok(layer) => Arc::new(layer),
559 Err(ConfigLoadError::Read(PathError {
560 path,
561 source: error,
562 })) if error.kind() == io::ErrorKind::NotFound => {
563 let mut data = DocumentMut::new();
564 data.decor_mut().set_prefix(
565 "#:schema https://jj-vcs.github.io/jj/latest/config-schema.json\n\n",
566 );
567 let layer = ConfigLayer {
568 source,
569 path: Some(path),
570 data,
571 };
572 Arc::new(layer)
573 }
574 Err(err) => return Err(err),
575 };
576 Ok(Self { layer })
577 }
578
579 pub fn from_layer(layer: Arc<ConfigLayer>) -> Result<Self, Arc<ConfigLayer>> {
582 if layer.path.is_some() {
583 Ok(Self { layer })
584 } else {
585 Err(layer)
586 }
587 }
588
589 pub fn save(&self) -> Result<(), ConfigFileSaveError> {
591 fs::write(self.path(), self.layer.data.to_string())
592 .context(self.path())
593 .map_err(ConfigFileSaveError)
594 }
595
596 pub fn path(&self) -> &Path {
598 self.layer.path.as_ref().expect("path must be known")
599 }
600
601 pub fn layer(&self) -> &Arc<ConfigLayer> {
603 &self.layer
604 }
605
606 pub fn set_value(
608 &mut self,
609 name: impl ToConfigNamePath,
610 new_value: impl Into<ConfigValue>,
611 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
612 Arc::make_mut(&mut self.layer).set_value(name, new_value)
613 }
614
615 pub fn delete_value(
617 &mut self,
618 name: impl ToConfigNamePath,
619 ) -> Result<Option<ConfigValue>, ConfigUpdateError> {
620 Arc::make_mut(&mut self.layer).delete_value(name)
621 }
622}
623
624#[derive(Clone, Debug)]
638pub struct StackedConfig {
639 layers: Vec<Arc<ConfigLayer>>,
641}
642
643impl StackedConfig {
644 pub fn empty() -> Self {
646 Self { layers: vec![] }
647 }
648
649 pub fn with_defaults() -> Self {
652 Self {
653 layers: DEFAULT_CONFIG_LAYERS.to_vec(),
654 }
655 }
656
657 pub fn load_file(
660 &mut self,
661 source: ConfigSource,
662 path: impl Into<PathBuf>,
663 ) -> Result<(), ConfigLoadError> {
664 let layer = ConfigLayer::load_from_file(source, path.into())?;
665 self.add_layer(layer);
666 Ok(())
667 }
668
669 pub fn load_dir(
672 &mut self,
673 source: ConfigSource,
674 path: impl AsRef<Path>,
675 ) -> Result<(), ConfigLoadError> {
676 let layers = ConfigLayer::load_from_dir(source, path.as_ref())?;
677 self.extend_layers(layers);
678 Ok(())
679 }
680
681 pub fn add_layer(&mut self, layer: impl Into<Arc<ConfigLayer>>) {
683 let layer = layer.into();
684 let index = self.insert_point(layer.source);
685 self.layers.insert(index, layer);
686 }
687
688 pub fn extend_layers<I>(&mut self, layers: I)
690 where
691 I: IntoIterator,
692 I::Item: Into<Arc<ConfigLayer>>,
693 {
694 let layers = layers.into_iter().map(Into::into);
695 for (source, chunk) in &layers.chunk_by(|layer| layer.source) {
696 let index = self.insert_point(source);
697 self.layers.splice(index..index, chunk);
698 }
699 }
700
701 pub fn remove_layers(&mut self, source: ConfigSource) {
703 self.layers.drain(self.layer_range(source));
704 }
705
706 fn layer_range(&self, source: ConfigSource) -> Range<usize> {
707 let start = self
709 .layers
710 .iter()
711 .take_while(|layer| layer.source < source)
712 .count();
713 let count = self.layers[start..]
714 .iter()
715 .take_while(|layer| layer.source == source)
716 .count();
717 start..(start + count)
718 }
719
720 fn insert_point(&self, source: ConfigSource) -> usize {
721 let skip = self
724 .layers
725 .iter()
726 .rev()
727 .take_while(|layer| layer.source > source)
728 .count();
729 self.layers.len() - skip
730 }
731
732 pub fn layers(&self) -> &[Arc<ConfigLayer>] {
734 &self.layers
735 }
736
737 pub fn layers_mut(&mut self) -> &mut [Arc<ConfigLayer>] {
739 &mut self.layers
740 }
741
742 pub fn layers_for(&self, source: ConfigSource) -> &[Arc<ConfigLayer>] {
744 &self.layers[self.layer_range(source)]
745 }
746
747 pub fn get<'de, T: Deserialize<'de>>(
750 &self,
751 name: impl ToConfigNamePath,
752 ) -> Result<T, ConfigGetError> {
753 self.get_value_with(name, |value| T::deserialize(value.into_deserializer()))
754 }
755
756 pub fn get_value(&self, name: impl ToConfigNamePath) -> Result<ConfigValue, ConfigGetError> {
758 self.get_value_with::<_, Infallible>(name, Ok)
759 }
760
761 pub fn get_value_with<T, E: Into<Box<dyn std::error::Error + Send + Sync>>>(
764 &self,
765 name: impl ToConfigNamePath,
766 convert: impl FnOnce(ConfigValue) -> Result<T, E>,
767 ) -> Result<T, ConfigGetError> {
768 self.get_item_with(name, |item| {
769 let value = item
773 .into_value()
774 .expect("Item::None should not exist in loaded tables");
775 convert(value)
776 })
777 }
778
779 pub fn get_table(&self, name: impl ToConfigNamePath) -> Result<ConfigTable, ConfigGetError> {
784 self.get_item_with(name, |item| {
785 item.into_table()
786 .map_err(|item| format!("Expected a table, but is {}", item.type_name()))
787 })
788 }
789
790 fn get_item_with<T, E: Into<Box<dyn std::error::Error + Send + Sync>>>(
791 &self,
792 name: impl ToConfigNamePath,
793 convert: impl FnOnce(ConfigItem) -> Result<T, E>,
794 ) -> Result<T, ConfigGetError> {
795 let name = name.into_name_path();
796 let name = name.borrow();
797 let (item, layer_index) =
798 get_merged_item(&self.layers, name).ok_or_else(|| ConfigGetError::NotFound {
799 name: name.to_string(),
800 })?;
801 convert(item).map_err(|err| ConfigGetError::Type {
807 name: name.to_string(),
808 error: err.into(),
809 source_path: self.layers[layer_index].path.clone(),
810 })
811 }
812
813 pub fn table_keys(&self, name: impl ToConfigNamePath) -> impl Iterator<Item = &str> {
816 let name = name.into_name_path();
817 let name = name.borrow();
818 let to_merge = get_tables_to_merge(&self.layers, name);
819 to_merge
820 .into_iter()
821 .rev()
822 .flat_map(|table| table.iter().map(|(k, _)| k))
823 .unique()
824 }
825}
826
827fn get_merged_item(
830 layers: &[Arc<ConfigLayer>],
831 name: &ConfigNamePathBuf,
832) -> Option<(ConfigItem, usize)> {
833 let mut to_merge = Vec::new();
834 for (index, layer) in layers.iter().enumerate().rev() {
835 let item = match layer.look_up_item(name) {
836 Ok(Some(item)) => item,
837 Ok(None) => continue, Err(_) => break, };
840 if item.is_table_like() {
841 to_merge.push((item, index));
842 } else if to_merge.is_empty() {
843 return Some((item.clone(), index)); } else {
845 break; }
847 }
848
849 let (item, mut top_index) = to_merge.pop()?;
853 let mut merged = item.clone();
854 for (item, index) in to_merge.into_iter().rev() {
855 merge_items(&mut merged, item);
856 top_index = index;
857 }
858 Some((merged, top_index))
859}
860
861fn get_tables_to_merge<'a>(
863 layers: &'a [Arc<ConfigLayer>],
864 name: &ConfigNamePathBuf,
865) -> Vec<&'a ConfigTableLike<'a>> {
866 let mut to_merge = Vec::new();
867 for layer in layers.iter().rev() {
868 match layer.look_up_table(name) {
869 Ok(Some(table)) => to_merge.push(table),
870 Ok(None) => {} Err(_) => break, }
873 }
874 to_merge
875}
876
877fn merge_items(lower_item: &mut ConfigItem, upper_item: &ConfigItem) {
879 let (Some(lower_table), Some(upper_table)) =
880 (lower_item.as_table_like_mut(), upper_item.as_table_like())
881 else {
882 *lower_item = upper_item.clone();
884 return;
885 };
886 for (key, upper) in upper_table.iter() {
887 match lower_table.entry(key) {
888 toml_edit::Entry::Occupied(entry) => {
889 merge_items(entry.into_mut(), upper);
890 }
891 toml_edit::Entry::Vacant(entry) => {
892 entry.insert(upper.clone());
893 }
894 };
895 }
896}
897
898static DEFAULT_CONFIG_LAYERS: LazyLock<[Arc<ConfigLayer>; 1]> = LazyLock::new(|| {
899 let parse = |text: &str| Arc::new(ConfigLayer::parse(ConfigSource::Default, text).unwrap());
900 [parse(include_str!("config/misc.toml"))]
901});
902
903#[cfg(test)]
904mod tests {
905 use assert_matches::assert_matches;
906 use indoc::indoc;
907 use pretty_assertions::assert_eq;
908
909 use super::*;
910
911 #[test]
912 fn test_config_layer_set_value() {
913 let mut layer = ConfigLayer::empty(ConfigSource::User);
914 assert_matches!(
916 layer.set_value(ConfigNamePathBuf::root(), 0),
917 Err(ConfigUpdateError::WouldOverwriteValue { name }) if name.is_empty()
918 );
919
920 layer.set_value("foo", 1).unwrap();
922 layer.set_value("bar.baz.blah", "2").unwrap();
923 layer
924 .set_value("bar.qux", ConfigValue::from_iter([("inline", "table")]))
925 .unwrap();
926 layer
927 .set_value("bar.to-update", ConfigValue::from_iter([("some", true)]))
928 .unwrap();
929 insta::assert_snapshot!(layer.data, @r#"
930 foo = 1
931
932 [bar]
933 qux = { inline = "table" }
934 to-update = { some = true }
935
936 [bar.baz]
937 blah = "2"
938 "#);
939
940 layer
942 .set_value("foo", ConfigValue::from_iter(["new", "foo"]))
943 .unwrap();
944 layer.set_value("bar.qux", "new bar.qux").unwrap();
946 layer
948 .set_value(
949 "bar.to-update.new",
950 ConfigValue::from_iter([("table", "value")]),
951 )
952 .unwrap();
953 assert_matches!(
955 layer.set_value("bar", 0),
956 Err(ConfigUpdateError::WouldOverwriteTable { name }) if name == "bar"
957 );
958 assert_matches!(
960 layer.set_value("bar.baz.blah.blah", 0),
961 Err(ConfigUpdateError::WouldOverwriteValue { name }) if name == "bar.baz.blah"
962 );
963 insta::assert_snapshot!(layer.data, @r#"
964 foo = ["new", "foo"]
965
966 [bar]
967 qux = "new bar.qux"
968 to-update = { some = true, new = { table = "value" } }
969
970 [bar.baz]
971 blah = "2"
972 "#);
973 }
974
975 #[test]
976 fn test_config_layer_set_value_formatting() {
977 let mut layer = ConfigLayer::empty(ConfigSource::User);
978 layer
980 .set_value(
981 "'foo' . bar . 'baz'",
982 ConfigValue::from_str("'value'").unwrap(),
983 )
984 .unwrap();
985 insta::assert_snapshot!(layer.data, @r"
986 ['foo' . bar]
987 'baz' = 'value'
988 ");
989
990 layer.set_value("foo.bar.baz", "new value").unwrap();
992 layer.set_value("foo.'bar'.blah", 0).unwrap();
993 insta::assert_snapshot!(layer.data, @r#"
994 ['foo' . bar]
995 'baz' = "new value"
996 blah = 0
997 "#);
998 }
999
1000 #[test]
1001 fn test_config_layer_set_value_inline_table() {
1002 let mut layer = ConfigLayer::empty(ConfigSource::User);
1003 layer
1004 .set_value("a", ConfigValue::from_iter([("b", "a.b")]))
1005 .unwrap();
1006 insta::assert_snapshot!(layer.data, @r#"a = { b = "a.b" }"#);
1007
1008 layer.set_value("a.c.d", "a.c.d").unwrap();
1010 insta::assert_snapshot!(layer.data, @r#"a = { b = "a.b", c.d = "a.c.d" }"#);
1011 }
1012
1013 #[test]
1014 fn test_config_layer_delete_value() {
1015 let mut layer = ConfigLayer::empty(ConfigSource::User);
1016 assert_matches!(
1018 layer.delete_value(ConfigNamePathBuf::root()),
1019 Err(ConfigUpdateError::WouldDeleteTable { name }) if name.is_empty()
1020 );
1021
1022 layer.set_value("foo", 1).unwrap();
1024 layer.set_value("bar.baz.blah", "2").unwrap();
1025 layer
1026 .set_value("bar.qux", ConfigValue::from_iter([("inline", "table")]))
1027 .unwrap();
1028 layer
1029 .set_value("bar.to-update", ConfigValue::from_iter([("some", true)]))
1030 .unwrap();
1031 insta::assert_snapshot!(layer.data, @r#"
1032 foo = 1
1033
1034 [bar]
1035 qux = { inline = "table" }
1036 to-update = { some = true }
1037
1038 [bar.baz]
1039 blah = "2"
1040 "#);
1041
1042 let old_value = layer.delete_value("foo").unwrap();
1044 assert_eq!(old_value.and_then(|v| v.as_integer()), Some(1));
1045 let old_value = layer.delete_value("bar.qux").unwrap();
1047 assert!(old_value.is_some_and(|v| v.is_inline_table()));
1048 let old_value = layer.delete_value("bar.to-update.some").unwrap();
1050 assert_eq!(old_value.and_then(|v| v.as_bool()), Some(true));
1051 assert_matches!(
1053 layer.delete_value("bar"),
1054 Err(ConfigUpdateError::WouldDeleteTable { name }) if name == "bar"
1055 );
1056 assert_matches!(layer.delete_value("bar.baz.blah.blah"), Ok(None));
1059 insta::assert_snapshot!(layer.data, @r#"
1060 [bar]
1061 to-update = {}
1062
1063 [bar.baz]
1064 blah = "2"
1065 "#);
1066 }
1067
1068 #[test]
1069 fn test_stacked_config_layer_order() {
1070 let empty_data = || DocumentMut::new();
1071 let layer_sources = |config: &StackedConfig| {
1072 config
1073 .layers()
1074 .iter()
1075 .map(|layer| layer.source)
1076 .collect_vec()
1077 };
1078
1079 let mut config = StackedConfig::empty();
1081 config.add_layer(ConfigLayer::with_data(ConfigSource::Repo, empty_data()));
1082 config.add_layer(ConfigLayer::with_data(ConfigSource::User, empty_data()));
1083 config.add_layer(ConfigLayer::with_data(ConfigSource::Default, empty_data()));
1084 assert_eq!(
1085 layer_sources(&config),
1086 vec![
1087 ConfigSource::Default,
1088 ConfigSource::User,
1089 ConfigSource::Repo,
1090 ]
1091 );
1092
1093 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::EnvBase,
1105 ConfigSource::User,
1106 ConfigSource::User,
1107 ConfigSource::Repo,
1108 ConfigSource::CommandArg,
1109 ]
1110 );
1111
1112 config.remove_layers(ConfigSource::CommandArg);
1114 config.remove_layers(ConfigSource::Default);
1115 config.remove_layers(ConfigSource::User);
1116 assert_eq!(
1117 layer_sources(&config),
1118 vec![ConfigSource::EnvBase, ConfigSource::Repo]
1119 );
1120
1121 config.remove_layers(ConfigSource::Default);
1123 config.remove_layers(ConfigSource::EnvOverrides);
1124 assert_eq!(
1125 layer_sources(&config),
1126 vec![ConfigSource::EnvBase, ConfigSource::Repo]
1127 );
1128
1129 config.extend_layers([
1131 ConfigLayer::with_data(ConfigSource::Repo, empty_data()),
1132 ConfigLayer::with_data(ConfigSource::Repo, empty_data()),
1133 ConfigLayer::with_data(ConfigSource::User, empty_data()),
1134 ]);
1135 assert_eq!(
1136 layer_sources(&config),
1137 vec![
1138 ConfigSource::EnvBase,
1139 ConfigSource::User,
1140 ConfigSource::Repo,
1141 ConfigSource::Repo,
1142 ConfigSource::Repo,
1143 ]
1144 );
1145
1146 config.remove_layers(ConfigSource::EnvBase);
1148 config.remove_layers(ConfigSource::User);
1149 config.remove_layers(ConfigSource::Repo);
1150 assert_eq!(layer_sources(&config), vec![]);
1151 }
1152
1153 fn new_user_layer(text: &str) -> ConfigLayer {
1154 ConfigLayer::parse(ConfigSource::User, text).unwrap()
1155 }
1156
1157 #[test]
1158 fn test_stacked_config_get_simple_value() {
1159 let mut config = StackedConfig::empty();
1160 config.add_layer(new_user_layer(indoc! {"
1161 a.b.c = 'a.b.c #0'
1162 "}));
1163 config.add_layer(new_user_layer(indoc! {"
1164 a.d = ['a.d #1']
1165 "}));
1166
1167 assert_eq!(config.get::<String>("a.b.c").unwrap(), "a.b.c #0");
1168
1169 assert_eq!(
1170 config.get::<Vec<String>>("a.d").unwrap(),
1171 vec!["a.d #1".to_owned()]
1172 );
1173
1174 assert_matches!(
1176 config.get::<String>("a.b.missing"),
1177 Err(ConfigGetError::NotFound { name }) if name == "a.b.missing"
1178 );
1179
1180 assert_matches!(
1182 config.get::<String>("a.b.c.d"),
1183 Err(ConfigGetError::NotFound { name }) if name == "a.b.c.d"
1184 );
1185
1186 assert_matches!(
1188 config.get::<String>("a.b"),
1189 Err(ConfigGetError::Type { name, .. }) if name == "a.b"
1190 );
1191 }
1192
1193 #[test]
1194 fn test_stacked_config_get_table_as_value() {
1195 let mut config = StackedConfig::empty();
1196 config.add_layer(new_user_layer(indoc! {"
1197 a.b = { c = 'a.b.c #0' }
1198 "}));
1199 config.add_layer(new_user_layer(indoc! {"
1200 a.d = ['a.d #1']
1201 "}));
1202
1203 insta::assert_snapshot!(
1206 config.get_value("a").unwrap(),
1207 @"{ b = { c = 'a.b.c #0' }, d = ['a.d #1'] }");
1208 }
1209
1210 #[test]
1211 fn test_stacked_config_get_inline_table() {
1212 let mut config = StackedConfig::empty();
1213 config.add_layer(new_user_layer(indoc! {"
1214 a.b = { c = 'a.b.c #0' }
1215 "}));
1216 config.add_layer(new_user_layer(indoc! {"
1217 a.b = { d = 'a.b.d #1' }
1218 "}));
1219
1220 insta::assert_snapshot!(
1222 config.get_value("a.b").unwrap(),
1223 @" { c = 'a.b.c #0' , d = 'a.b.d #1' }");
1224 }
1225
1226 #[test]
1227 fn test_stacked_config_get_inline_non_inline_table() {
1228 let mut config = StackedConfig::empty();
1229 config.add_layer(new_user_layer(indoc! {"
1230 a.b = { c = 'a.b.c #0' }
1231 "}));
1232 config.add_layer(new_user_layer(indoc! {"
1233 a.b.d = 'a.b.d #1'
1234 "}));
1235
1236 insta::assert_snapshot!(
1237 config.get_value("a.b").unwrap(),
1238 @" { c = 'a.b.c #0' , d = 'a.b.d #1'}");
1239 insta::assert_snapshot!(
1240 config.get_table("a").unwrap(),
1241 @"b = { c = 'a.b.c #0' , d = 'a.b.d #1'}");
1242 }
1243
1244 #[test]
1245 fn test_stacked_config_get_value_shadowing_table() {
1246 let mut config = StackedConfig::empty();
1247 config.add_layer(new_user_layer(indoc! {"
1248 a.b.c = 'a.b.c #0'
1249 "}));
1250 config.add_layer(new_user_layer(indoc! {"
1252 a.b = 'a.b #1'
1253 "}));
1254
1255 assert_eq!(config.get::<String>("a.b").unwrap(), "a.b #1");
1256
1257 assert_matches!(
1258 config.get::<String>("a.b.c"),
1259 Err(ConfigGetError::NotFound { name }) if name == "a.b.c"
1260 );
1261 }
1262
1263 #[test]
1264 fn test_stacked_config_get_table_shadowing_table() {
1265 let mut config = StackedConfig::empty();
1266 config.add_layer(new_user_layer(indoc! {"
1267 a.b = 'a.b #0'
1268 "}));
1269 config.add_layer(new_user_layer(indoc! {"
1271 a.b.c = 'a.b.c #1'
1272 "}));
1273 insta::assert_snapshot!(config.get_table("a.b").unwrap(), @"c = 'a.b.c #1'");
1274 }
1275
1276 #[test]
1277 fn test_stacked_config_get_merged_table() {
1278 let mut config = StackedConfig::empty();
1279 config.add_layer(new_user_layer(indoc! {"
1280 a.a.a = 'a.a.a #0'
1281 a.a.b = 'a.a.b #0'
1282 a.b = 'a.b #0'
1283 "}));
1284 config.add_layer(new_user_layer(indoc! {"
1285 a.a.b = 'a.a.b #1'
1286 a.a.c = 'a.a.c #1'
1287 a.c = 'a.c #1'
1288 "}));
1289 insta::assert_snapshot!(config.get_table("a").unwrap(), @r"
1290 a.a = 'a.a.a #0'
1291 a.b = 'a.a.b #1'
1292 a.c = 'a.a.c #1'
1293 b = 'a.b #0'
1294 c = 'a.c #1'
1295 ");
1296 assert_eq!(config.table_keys("a").collect_vec(), vec!["a", "b", "c"]);
1297 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["a", "b", "c"]);
1298 assert_eq!(config.table_keys("a.b").collect_vec(), vec![""; 0]);
1299 assert_eq!(config.table_keys("a.missing").collect_vec(), vec![""; 0]);
1300 }
1301
1302 #[test]
1303 fn test_stacked_config_get_merged_table_shadowed_top() {
1304 let mut config = StackedConfig::empty();
1305 config.add_layer(new_user_layer(indoc! {"
1306 a.a.a = 'a.a.a #0'
1307 a.b = 'a.b #0'
1308 "}));
1309 config.add_layer(new_user_layer(indoc! {"
1311 a = 'a #1'
1312 "}));
1313 config.add_layer(new_user_layer(indoc! {"
1315 a.a.b = 'a.a.b #2'
1316 "}));
1317 insta::assert_snapshot!(config.get_table("a").unwrap(), @"a.b = 'a.a.b #2'");
1318 assert_eq!(config.table_keys("a").collect_vec(), vec!["a"]);
1319 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["b"]);
1320 }
1321
1322 #[test]
1323 fn test_stacked_config_get_merged_table_shadowed_child() {
1324 let mut config = StackedConfig::empty();
1325 config.add_layer(new_user_layer(indoc! {"
1326 a.a.a = 'a.a.a #0'
1327 a.b = 'a.b #0'
1328 "}));
1329 config.add_layer(new_user_layer(indoc! {"
1331 a.a = 'a.a #1'
1332 "}));
1333 config.add_layer(new_user_layer(indoc! {"
1335 a.a.b = 'a.a.b #2'
1336 "}));
1337 insta::assert_snapshot!(config.get_table("a").unwrap(), @r"
1338 a.b = 'a.a.b #2'
1339 b = 'a.b #0'
1340 ");
1341 assert_eq!(config.table_keys("a").collect_vec(), vec!["a", "b"]);
1342 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["b"]);
1343 }
1344
1345 #[test]
1346 fn test_stacked_config_get_merged_table_shadowed_parent() {
1347 let mut config = StackedConfig::empty();
1348 config.add_layer(new_user_layer(indoc! {"
1349 a.a.a = 'a.a.a #0'
1350 "}));
1351 config.add_layer(new_user_layer(indoc! {"
1353 a = 'a #1'
1354 "}));
1355 config.add_layer(new_user_layer(indoc! {"
1357 a.a.b = 'a.a.b #2'
1358 "}));
1359 insta::assert_snapshot!(config.get_table("a.a").unwrap(), @"b = 'a.a.b #2'");
1361 assert_eq!(config.table_keys("a.a").collect_vec(), vec!["b"]);
1362 }
1363}