use crate::ini_merge;
use crate::yaml;
use crate::yaml_merge::{mapping_subset, merge_yaml, root_mapping};
use eyre::{Result, bail, eyre};
use indexmap::IndexMap;
use jsonc_parser::ParseOptions;
use jsonc_parser::cst::{CstInputValue, CstObject, CstObjectProp, CstRootNode};
use serde_json::value::RawValue;
use serde_json::{Map, Value};
use std::path::Path;
use std::str::FromStr;
use toml_edit::{DocumentMut, Item, TableLike};
#[derive(Debug, Clone, Copy, Eq, PartialEq, strum::EnumIter)]
pub enum Format {
Json,
Jsonc,
Toml,
Yaml,
Ini,
}
impl Format {
pub fn from_path(path: &Path) -> Option<Self> {
match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
"json" => Some(Self::Json),
"jsonc" => Some(Self::Jsonc),
"toml" => Some(Self::Toml),
"yaml" | "yml" => Some(Self::Yaml),
"ini" => Some(Self::Ini),
_ => None,
}
}
pub fn from_name(name: &str) -> Option<Self> {
match name.to_ascii_lowercase().as_str() {
"json" => Some(Self::Json),
"jsonc" => Some(Self::Jsonc),
"toml" => Some(Self::Toml),
"yaml" | "yml" => Some(Self::Yaml),
"ini" => Some(Self::Ini),
_ => None,
}
}
fn name(self) -> &'static str {
match self {
Self::Json => "JSON",
Self::Jsonc => "JSONC",
Self::Toml => "TOML",
Self::Yaml => "YAML",
Self::Ini => "INI",
}
}
}
enum Doc {
Json(Value),
Toml(toml::Table),
YamlTree(Option<YamlTree>),
YamlValues(yaml::Mapping),
}
struct YamlTree {
file: yaml_edit::YamlFile,
root: yaml_edit::Mapping,
}
pub fn contains(format: Format, target: &str, source: &str) -> Result<bool> {
if format == Format::Ini {
return ini_merge::contains(target, source);
}
Ok(
match parse_pair(format, (target, "target"), (source, "source"))? {
(Doc::Json(target), Doc::Json(source)) => json_subset(&source, &target),
(Doc::Toml(target), Doc::Toml(source)) => toml_subset(&source, &target),
(Doc::YamlTree(target), Doc::YamlTree(source)) => match (source, target) {
(None, _) => true,
(Some(_), None) => false,
(Some(source), Some(target)) => yaml_subset(&source.root, &target.root),
},
(Doc::YamlValues(target), Doc::YamlValues(source)) => mapping_subset(&source, &target),
_ => unreachable!("both sides are parsed as the same format"),
},
)
}
pub fn merge(format: Format, target: &str, source: &str) -> Result<String> {
if contains(format, target, source)? {
return Ok(target.to_string());
}
match format {
Format::Json => merge_json(target, source),
Format::Jsonc => merge_jsonc(target, source),
Format::Toml => merge_toml(target, source),
Format::Yaml => merge_yaml(target, source),
Format::Ini => ini_merge::merge(target, source),
}
}
pub fn missing(format: Format, target: &str, source: &str) -> Result<Option<String>> {
if format == Format::Ini {
return ini_merge::missing(target, source);
}
Ok(
match parse_pair(format, (target, "target"), (source, "source"))? {
(Doc::Json(Value::Object(target)), Doc::Json(Value::Object(source))) => {
let missing = json_missing(&source, &target);
(!missing.is_empty())
.then(|| serde_json::to_string(&Value::Object(missing)))
.transpose()?
}
(Doc::Toml(target), Doc::Toml(source)) => {
let missing = toml_missing(&source, &target);
(!missing.is_empty())
.then(|| toml::to_string(&missing))
.transpose()?
}
(Doc::YamlTree(target), Doc::YamlTree(source)) => match (source, target) {
(None, _) => None,
(Some(source), None) => Some(source.file.to_string()),
(Some(source), Some(target)) => {
yaml_remove_present(&source.root, &target.root);
(!source.root.is_empty()).then(|| source.file.to_string())
}
},
(Doc::YamlValues(target), Doc::YamlValues(source)) => {
let missing = yaml_values_missing(&source, &target);
(!missing.is_empty())
.then(|| yaml::to_string(&missing))
.transpose()?
}
_ => unreachable!("both sides are parsed as the same format"),
},
)
}
pub fn fill_missing(format: Format, target: &str, source: &str) -> Result<String> {
match missing(format, target, source)? {
Some(missing) => merge(format, target, &missing),
None => Ok(target.to_string()),
}
}
fn json_missing(source: &Map<String, Value>, target: &Map<String, Value>) -> Map<String, Value> {
let mut out = Map::new();
for (key, sv) in source {
match (sv, target.get(key)) {
(_, None) => {
out.insert(key.clone(), sv.clone());
}
(Value::Object(s), Some(Value::Object(t))) => {
let inner = json_missing(s, t);
if !inner.is_empty() {
out.insert(key.clone(), Value::Object(inner));
}
}
_ => {}
}
}
out
}
fn toml_missing(source: &toml::Table, target: &toml::Table) -> toml::Table {
let mut out = toml::Table::new();
for (key, sv) in source {
match (sv, target.get(key)) {
(_, None) => {
out.insert(key.clone(), sv.clone());
}
(toml::Value::Table(s), Some(toml::Value::Table(t))) => {
let inner = toml_missing(s, t);
if !inner.is_empty() {
out.insert(key.clone(), toml::Value::Table(inner));
}
}
_ => {}
}
}
out
}
fn yaml_remove_present(source: &yaml_edit::Mapping, target: &yaml_edit::Mapping) {
let keys: Vec<_> = source.keys().collect();
for key in keys {
let (Some(sv), Some(tv)) = (source.get(&key), target.get(&key)) else {
continue;
};
match (sv.as_mapping(), tv.as_mapping()) {
(Some(s), Some(t)) => {
yaml_remove_present(s, t);
if s.is_empty() {
source.remove(&key);
}
}
_ => {
source.remove(&key);
}
}
}
}
fn yaml_values_missing(source: &yaml::Mapping, target: &yaml::Mapping) -> yaml::Mapping {
let mut out = yaml::Mapping::new();
for (key, sv) in source {
match (sv, target.get(key)) {
(_, None) => {
out.insert(key.clone(), sv.clone());
}
(yaml::Value::Mapping(s), Some(yaml::Value::Mapping(t))) => {
let inner = yaml_values_missing(s, t);
if !inner.is_empty() {
out.insert(key.clone(), yaml::Value::Mapping(inner));
}
}
_ => {}
}
}
out
}
fn yaml_subset(source: &yaml_edit::Mapping, target: &yaml_edit::Mapping) -> bool {
source.iter().all(|(key, sv)| match target.get(&key) {
None => false,
Some(tv) => match (sv.as_mapping(), tv.as_mapping()) {
(Some(s), Some(t)) => yaml_subset(s, t),
_ => sv.yaml_eq(&tv),
},
})
}
fn parse_pair(format: Format, a: (&str, &str), b: (&str, &str)) -> Result<(Doc, Doc)> {
if format != Format::Yaml {
return Ok((
parse(format, a.0, a.1, false)?,
parse(format, b.0, b.1, false)?,
));
}
let (a_tags, a_aliases) = yaml_features(a.0);
let (b_tags, b_aliases) = yaml_features(b.0);
let values = a_aliases || b_aliases;
if values && (a_tags || b_tags) {
bail!(
"YAML that uses both tags and anchors or aliases cannot be merged; \
expand the aliases in the {} or the {}",
a.1,
b.1
);
}
Ok((
parse(format, a.0, a.1, values)?,
parse(format, b.0, b.1, values)?,
))
}
fn yaml_features(text: &str) -> (bool, bool) {
use yaml_edit::SyntaxKind;
let tokens = yaml_edit::lex(text);
let has = |kinds: &[SyntaxKind]| tokens.iter().any(|(kind, _)| kinds.contains(kind));
(
has(&[SyntaxKind::TAG]),
has(&[
SyntaxKind::ANCHOR,
SyntaxKind::REFERENCE,
SyntaxKind::MERGE_KEY,
]),
)
}
fn parse(format: Format, text: &str, what: &str, yaml_values: bool) -> Result<Doc> {
let blank = text.trim().is_empty()
|| (matches!(format, Format::Toml | Format::Yaml) && is_comments_only(text));
let fail =
|e: &dyn std::fmt::Display| eyre!("failed to parse the {} {what}: {e}", format.name());
let not_a_table = || {
eyre!(
"the {} {what} must hold a table at the top level",
format.name()
)
};
Ok(match format {
Format::Json if blank => Doc::Json(Value::Object(Map::new())),
Format::Json => match serde_json::from_str(text).map_err(|e| fail(&e))? {
value @ Value::Object(_) => Doc::Json(value),
_ => return Err(not_a_table()),
},
Format::Jsonc if blank => Doc::Json(Value::Object(Map::new())),
Format::Jsonc => match parse_jsonc(text).map_err(|e| fail(&e))?.value() {
None => Doc::Json(Value::Object(Map::new())),
Some(node) => match node.to_serde_value() {
Some(value @ Value::Object(_)) => Doc::Json(value),
_ => return Err(not_a_table()),
},
},
Format::Toml if blank => Doc::Toml(toml::Table::new()),
Format::Toml => Doc::Toml(toml::from_str(text).map_err(|e| fail(&e))?),
Format::Yaml if blank && yaml_values => Doc::YamlValues(yaml::Mapping::new()),
Format::Yaml if blank => Doc::YamlTree(None),
Format::Yaml => {
let yaml::Value::Mapping(map) = yaml::from_str(text).map_err(|e| fail(&e))? else {
return Err(not_a_table());
};
if yaml_values {
Doc::YamlValues(map)
} else {
let file = yaml_edit::YamlFile::from_str(text).map_err(|e| fail(&e))?;
let root = root_mapping(&file, what, false)?.ok_or_else(not_a_table)?;
Doc::YamlTree(Some(YamlTree { file, root }))
}
}
Format::Ini => unreachable!("INI is read by ini_merge"),
})
}
pub fn conflicts(format: Format, a: &str, b: &str) -> Result<Vec<String>> {
if format == Format::Ini {
return ini_merge::conflicts(a, b);
}
let mut paths = vec![];
match parse_pair(format, (a, "source"), (b, "source"))? {
(Doc::Json(a), Doc::Json(b)) => json_conflicts(&a, &b, "", &mut paths),
(Doc::Toml(a), Doc::Toml(b)) => toml_conflicts(&a, &b, "", &mut paths),
(Doc::YamlTree(Some(a)), Doc::YamlTree(Some(b))) => {
yaml_conflicts(&a.root, &b.root, "", &mut paths)
}
(Doc::YamlTree(_), Doc::YamlTree(_)) => {}
(Doc::YamlValues(a), Doc::YamlValues(b)) => yaml_values_conflicts(&a, &b, "", &mut paths),
_ => unreachable!("both sides are parsed as the same format"),
}
Ok(paths)
}
fn child_path(prefix: &str, key: &str) -> String {
if prefix.is_empty() {
key.to_string()
} else {
format!("{prefix}.{key}")
}
}
fn json_conflicts(a: &Value, b: &Value, prefix: &str, paths: &mut Vec<String>) {
let (Value::Object(a), Value::Object(b)) = (a, b) else {
return;
};
for (key, av) in a {
let Some(bv) = b.get(key) else { continue };
let path = child_path(prefix, key);
if av.is_object() && bv.is_object() {
json_conflicts(av, bv, &path, paths);
} else if av != bv {
paths.push(path);
}
}
}
fn toml_conflicts(a: &toml::Table, b: &toml::Table, prefix: &str, paths: &mut Vec<String>) {
for (key, av) in a {
let Some(bv) = b.get(key) else { continue };
let path = child_path(prefix, key);
match (av, bv) {
(toml::Value::Table(av), toml::Value::Table(bv)) => {
toml_conflicts(av, bv, &path, paths);
}
_ if av != bv => paths.push(path),
_ => {}
}
}
}
fn yaml_conflicts(
a: &yaml_edit::Mapping,
b: &yaml_edit::Mapping,
prefix: &str,
paths: &mut Vec<String>,
) {
for (key, av) in a.iter() {
let Some(bv) = b.get(&key) else { continue };
let name = match key.as_scalar() {
Some(scalar) => scalar.as_string(),
None => key.to_string().trim().to_string(),
};
let path = child_path(prefix, &name);
match (av.as_mapping(), bv.as_mapping()) {
(Some(av), Some(bv)) => yaml_conflicts(av, bv, &path, paths),
_ if !av.yaml_eq(&bv) => paths.push(path),
_ => {}
}
}
}
fn yaml_values_conflicts(
a: &yaml::Mapping,
b: &yaml::Mapping,
prefix: &str,
paths: &mut Vec<String>,
) {
for (key, av) in a {
let Some(bv) = b.get(key) else { continue };
let name = match key {
yaml::Value::String(name) => name.clone(),
other => yaml::to_string(other)
.unwrap_or_default()
.trim()
.to_string(),
};
let path = child_path(prefix, &name);
match (av, bv) {
(yaml::Value::Mapping(av), yaml::Value::Mapping(bv)) => {
yaml_values_conflicts(av, bv, &path, paths);
}
_ if av != bv => paths.push(path),
_ => {}
}
}
}
fn is_comments_only(text: &str) -> bool {
text.lines()
.all(|l| l.trim().is_empty() || l.trim_start().starts_with('#'))
}
fn json_subset(source: &Value, target: &Value) -> bool {
match (source, target) {
(Value::Object(s), Value::Object(t)) => s
.iter()
.all(|(k, sv)| t.get(k).is_some_and(|tv| json_subset(sv, tv))),
_ => source == target,
}
}
fn toml_subset(source: &toml::Table, target: &toml::Table) -> bool {
source.iter().all(|(key, sv)| match (sv, target.get(key)) {
(toml::Value::Table(s), Some(toml::Value::Table(t))) => toml_subset(s, t),
(sv, Some(tv)) => sv == tv,
(_, None) => false,
})
}
fn merge_json(target: &str, source: &str) -> Result<String> {
let Doc::Json(Value::Object(source)) = parse(Format::Json, source, "source", false)? else {
unreachable!("parsed as a JSON object");
};
let existing: IndexMap<String, Box<RawValue>> = if target.trim().is_empty() {
IndexMap::new()
} else {
serde_json::from_str(target).map_err(|e| eyre!("failed to parse the JSON target: {e}"))?
};
let merged = merge_json_objects(existing, source);
let indent = json_indent(target);
let mut out = String::new();
print_json_object(&merged, 0, &indent, &mut out)?;
if target.is_empty() || target.ends_with('\n') {
out.push('\n');
}
Ok(out)
}
fn jsonc_options() -> ParseOptions {
ParseOptions {
allow_comments: true,
allow_trailing_commas: true,
allow_loose_object_property_names: false,
allow_missing_commas: false,
allow_single_quoted_strings: false,
allow_hexadecimal_numbers: false,
allow_unary_plus_numbers: false,
allow_bare_decimal_point_numbers: false,
allow_non_finite_numbers: false,
allow_extended_string_escapes: false,
}
}
pub fn from_jsonc_str<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
Ok(jsonc_parser::parse_to_serde_value(text, &jsonc_options())?)
}
pub fn from_json_with_comments_str<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
if let Some(c) = non_json_whitespace(text) {
bail!("invalid whitespace {c:?}: JSON allows only space, tab, CR and LF");
}
let options = ParseOptions {
allow_trailing_commas: false,
..jsonc_options()
};
Ok(jsonc_parser::parse_to_serde_value(text, &options)?)
}
fn non_json_whitespace(text: &str) -> Option<char> {
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' => {
while let Some(c) = chars.next() {
match c {
'\\' => {
chars.next();
}
'"' => break,
_ => {}
}
}
}
'/' if chars.peek() == Some(&'/') => {
for c in chars.by_ref() {
if c == '\n' {
break;
}
}
}
'/' if chars.peek() == Some(&'*') => {
chars.next();
while let Some(c) = chars.next() {
if c == '*' && chars.peek() == Some(&'/') {
chars.next();
break;
}
}
}
' ' | '\t' | '\n' | '\r' => {}
c if c.is_whitespace() => return Some(c),
_ => {}
}
}
None
}
fn parse_jsonc(text: &str) -> Result<CstRootNode> {
Ok(CstRootNode::parse(text, &jsonc_options())?)
}
fn merge_jsonc(target: &str, source: &str) -> Result<String> {
let Doc::Json(Value::Object(source)) = parse(Format::Jsonc, source, "source", false)? else {
unreachable!("parsed as a JSON object");
};
let blank = target.trim().is_empty();
let root = parse_jsonc(if blank { "{}" } else { target })
.map_err(|e| eyre!("failed to parse the JSONC target: {e}"))?;
merge_jsonc_object(&root.object_value_or_set(), source);
let mut out = root.to_string();
if blank {
out.push('\n');
}
Ok(out)
}
fn effective_jsonc_prop(object: &CstObject, key: &str) -> Option<CstObjectProp> {
object
.properties()
.into_iter()
.rev()
.find(|prop| prop.decoded_name().as_deref() == Some(key))
}
fn merge_jsonc_object(target: &CstObject, source: Map<String, Value>) {
for (key, value) in source {
let Some(prop) = effective_jsonc_prop(target, &key) else {
target.append(&key, jsonc_input(value));
continue;
};
let existing = prop.value();
match (value, existing.as_ref().and_then(|node| node.as_object())) {
(Value::Object(source_child), Some(target_child)) => {
merge_jsonc_object(&target_child, source_child);
}
(value, _)
if existing.and_then(|node| node.to_serde_value()).as_ref() == Some(&value) => {}
(value, _) => prop.set_value(jsonc_input(value)),
}
}
}
fn jsonc_input(value: Value) -> CstInputValue {
match value {
Value::Null => CstInputValue::Null,
Value::Bool(b) => CstInputValue::Bool(b),
Value::Number(n) => CstInputValue::Number(n.to_string()),
Value::String(s) => CstInputValue::String(s),
Value::Array(items) => CstInputValue::Array(items.into_iter().map(jsonc_input).collect()),
Value::Object(map) => CstInputValue::Object(
map.into_iter()
.map(|(key, value)| (key, jsonc_input(value)))
.collect(),
),
}
}
enum JsonNode {
Raw(Box<RawValue>),
Object(IndexMap<String, JsonNode>),
Value(Value),
}
fn merge_json_objects(
target: IndexMap<String, Box<RawValue>>,
source: Map<String, Value>,
) -> IndexMap<String, JsonNode> {
let mut merged: IndexMap<String, JsonNode> = target
.into_iter()
.map(|(key, raw)| (key, JsonNode::Raw(raw)))
.collect();
for (key, value) in source {
match (merged.get_mut(&key), value) {
(Some(node), Value::Object(source_child)) => {
let existing = match node {
JsonNode::Raw(raw) => serde_json::from_str(raw.get()).ok(),
_ => None,
};
*node = match existing {
Some(existing) => JsonNode::Object(merge_json_objects(existing, source_child)),
None => JsonNode::Value(Value::Object(source_child)),
};
}
(Some(node), value) => *node = JsonNode::Value(value),
(None, value) => {
merged.insert(key, JsonNode::Value(value));
}
}
}
merged
}
fn print_json_object(
map: &IndexMap<String, JsonNode>,
depth: usize,
indent: &str,
out: &mut String,
) -> Result<()> {
if map.is_empty() {
out.push_str("{}");
return Ok(());
}
out.push_str("{\n");
for (i, (key, node)) in map.iter().enumerate() {
if i > 0 {
out.push_str(",\n");
}
out.push_str(&indent.repeat(depth + 1));
out.push_str(&serde_json::to_string(key)?);
out.push_str(": ");
match node {
JsonNode::Raw(raw) => out.push_str(raw.get()),
JsonNode::Object(child) => print_json_object(child, depth + 1, indent, out)?,
JsonNode::Value(value) => {
let mut buf = Vec::new();
let formatter = serde_json::ser::PrettyFormatter::with_indent(indent.as_bytes());
serde::Serialize::serialize(
value,
&mut serde_json::Serializer::with_formatter(&mut buf, formatter),
)?;
let nested = String::from_utf8(buf)?
.replace('\n', &format!("\n{}", indent.repeat(depth + 1)));
out.push_str(&nested);
}
}
}
out.push('\n');
out.push_str(&indent.repeat(depth));
out.push('}');
Ok(())
}
fn json_indent(text: &str) -> String {
text.lines()
.find_map(|l| {
let indent: String = l.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
(!indent.is_empty() && indent.len() < l.len()).then_some(indent)
})
.unwrap_or_else(|| " ".to_string())
}
fn merge_toml(target: &str, source: &str) -> Result<String> {
let mut doc = target
.parse::<DocumentMut>()
.map_err(|e| eyre!("failed to parse the TOML target: {e}"))?;
let source = source
.parse::<DocumentMut>()
.map_err(|e| eyre!("failed to parse the TOML source: {e}"))?;
merge_toml_tables(doc.as_table_mut(), source.as_table());
Ok(doc.to_string())
}
fn merge_toml_tables(target: &mut dyn TableLike, source: &dyn TableLike) {
for (key, source_item) in source.iter() {
let Some(target_item) = target.get_mut(key) else {
target.insert(key, source_item.clone());
continue;
};
if let (Some(t), Some(s)) = (target_item.as_table_like_mut(), source_item.as_table_like()) {
merge_toml_tables(t, s);
} else if !same_toml_item(target_item, source_item) {
let mut replacement = source_item.clone();
if let (Some(old), Some(new)) = (target_item.as_value(), replacement.as_value_mut()) {
*new.decor_mut() = old.decor().clone();
}
*target_item = replacement;
}
}
}
fn same_toml_item(a: &Item, b: &Item) -> bool {
match (toml_value(a), toml_value(b)) {
(Some(a), Some(b)) => a == b,
_ => false,
}
}
fn toml_value(item: &Item) -> Option<toml::Value> {
let mut doc = DocumentMut::new();
doc.insert("v", item.clone());
toml::from_str::<toml::Table>(&doc.to_string())
.ok()?
.remove("v")
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn formats_come_from_extensions() {
for (path, format) in [
("a.json", Some(Format::Json)),
("a.TOML", Some(Format::Toml)),
("a.yaml", Some(Format::Yaml)),
("a.yml", Some(Format::Yaml)),
("a.jsonc", Some(Format::Jsonc)),
("a.INI", Some(Format::Ini)),
("a.cfg", None),
("a", None),
] {
assert_eq!(Format::from_path(Path::new(path)), format, "{path}");
}
}
#[test]
fn json_keeps_unowned_keys_in_order_and_the_indent() {
let target = "{\n \"z\": 1,\n \"model\": \"old\",\n \"a\": {\"x\": 1}\n}\n";
let source = r#"{"model": "new", "a": {"y": 2}, "n": [1, 2]}"#;
assert_eq!(
merge(Format::Json, target, source).unwrap(),
"{\n \"z\": 1,\n \"model\": \"new\",\n \"a\": {\n \"x\": 1,\n \"y\": 2\n },\n \"n\": [\n 1,\n 2\n ]\n}\n"
);
}
#[test]
fn jsonc_keeps_comments_and_trailing_commas() {
let target = "{\n // editor\n \"editor.fontSize\": 14, // px\n \"files.exclude\": {\n \"a\": true, /* x */\n },\n \"keep\": [1, 2,],\n}\n";
let source = r#"{"editor.fontSize": 16, "files.exclude": {"b": true}, "new": {"k": [1]}}"#;
assert_eq!(
merge(Format::Jsonc, target, source).unwrap(),
"{\n // editor\n \"editor.fontSize\": 16, // px\n \"files.exclude\": {\n \"a\": true, /* x */\n \"b\": true,\n },\n \"keep\": [1, 2,],\n \"new\": {\n \"k\": [1],\n },\n}\n"
);
}
#[test]
fn jsonc_repeated_target_key_merges_into_the_effective_value() {
let merged = merge(Format::Jsonc, r#"{"a": 1, "a": 2}"#, r#"{"a": 1}"#).unwrap();
assert!(
contains(Format::Jsonc, &merged, r#"{"a": 1}"#).unwrap(),
"{merged}"
);
}
#[test]
fn jsonc_satisfied_target_comes_back_untouched() {
let target = "{\n // c\n \"a\": 1, \"b\": 2,\n}";
assert_eq!(merge(Format::Jsonc, target, r#"{"a": 1}"#).unwrap(), target);
assert!(contains(Format::Jsonc, target, "// s\n{\"a\": 1,}").unwrap());
assert!(!contains(Format::Jsonc, target, r#"{"a": 2}"#).unwrap());
}
#[test]
fn jsonc_creates_or_fills_an_empty_target() {
assert_eq!(
merge(Format::Jsonc, "", r#"{"a": 1}"#).unwrap(),
"{\n \"a\": 1\n}\n"
);
assert_eq!(
merge(Format::Jsonc, "// only a comment\n", r#"{"a": 1}"#).unwrap(),
"// only a comment\n{\n \"a\": 1\n}\n"
);
}
#[test]
fn jsonc_fill_missing_keeps_existing_values() {
let merged = fill_missing(
Format::Jsonc,
"{\n // mine\n \"a\": 1,\n}\n",
r#"{"a": 2, "b": 3}"#,
)
.unwrap();
assert_eq!(merged, "{\n // mine\n \"a\": 1,\n \"b\": 3,\n}\n");
}
#[test]
fn jsonc_rejects_what_is_not_jsonc() {
for text in [
"{'a': 1}",
"{a: 1}",
"{\"a\": 0x1}",
"{\"a\": 1 \"b\": 2}",
"[1]",
] {
assert!(merge(Format::Jsonc, text, "{}").is_err(), "{text}");
assert!(merge(Format::Jsonc, "{}", text).is_err(), "{text}");
}
}
#[test]
fn formats_come_from_names() {
assert_eq!(Format::from_name("JSONC"), Some(Format::Jsonc));
assert_eq!(Format::from_name("yml"), Some(Format::Yaml));
assert_eq!(Format::from_name("ini"), Some(Format::Ini));
assert_eq!(Format::from_name("xml"), None);
}
#[test]
fn json_arrays_are_replaced() {
let merged = merge(Format::Json, r#"{"l": [1, 2, 3]}"#, r#"{"l": [9]}"#).unwrap();
assert_eq!(merged, "{\n \"l\": [\n 9\n ]\n}");
}
#[test]
fn toml_edits_in_place() {
let target = "\
# written by the desktop app
notify = [\"a\"]
[desktop]
theme = \"dark\" # app choice
[plugins.foo]
path = \"/Applications/X.app\"
";
let source = "model = \"gpt\"\n\n[desktop]\ntheme = \"light\"\nsize = 3\n";
assert_eq!(
merge(Format::Toml, target, source).unwrap(),
"\
# written by the desktop app
notify = [\"a\"]
model = \"gpt\"
[desktop]
theme = \"light\" # app choice
size = 3
[plugins.foo]
path = \"/Applications/X.app\"
"
);
}
#[test]
fn toml_merges_inline_tables_and_replaces_arrays() {
let merged = merge(
Format::Toml,
"t = { a = 1, b = 2 }\nl = [1, 2]\n",
"t = { b = 3 }\nl = [9]\n",
)
.unwrap();
assert_eq!(merged, "t = { a = 1, b = 3 }\nl = [9]\n");
}
#[test]
fn toml_creates_a_missing_file() {
assert_eq!(
merge(Format::Toml, "", "[a]\nb = 1\n").unwrap(),
"[a]\nb = 1\n"
);
}
#[test]
fn yaml_goes_through_the_yaml_merge_helper() {
assert_eq!(
merge(Format::Yaml, "# c\na: 1\nb: 2\n", "a: 5\n").unwrap(),
"# c\na: 5\nb: 2\n"
);
}
#[test]
fn fill_missing_keeps_existing_values_and_adds_absent_keys() {
let target = "# app\nmodel = \"mine\"\n\n[tui]\ntheme = \"dark\"\n";
let source =
"model = \"default\"\neffort = \"high\"\n\n[tui]\ntheme = \"light\"\nsize = 3\n";
assert_eq!(
fill_missing(Format::Toml, target, source).unwrap(),
"# app\nmodel = \"mine\"\neffort = \"high\"\n\n[tui]\ntheme = \"dark\"\nsize = 3\n"
);
let json = fill_missing(
Format::Json,
r#"{"model": "mine"}"#,
r#"{"model": "d", "e": 1}"#,
)
.unwrap();
assert_eq!(json, "{\n \"model\": \"mine\",\n \"e\": 1\n}");
assert_eq!(
fill_missing(Format::Yaml, "a: 1\n", "a: 2\nb: 3\n").unwrap(),
"a: 1\nb: 3\n"
);
}
#[test]
fn nothing_is_missing_when_every_key_has_a_value() {
for (format, target, source) in [
(
Format::Json,
r#"{"a": {"b": 2}, "c": 1}"#,
r#"{"a": {"b": 1}, "c": {"d": 1}}"#,
),
(Format::Toml, "a = 1\n", "a = 2\n"),
(Format::Yaml, "a: 1\n", "a: {b: 1}\n"),
] {
assert_eq!(missing(format, target, source).unwrap(), None, "{format:?}");
assert_eq!(fill_missing(format, target, source).unwrap(), target);
}
}
#[test]
fn a_satisfied_target_comes_back_untouched() {
for (format, target, source) in [
(Format::Json, "{\"a\":1, \"b\":2}", r#"{"a": 1}"#),
(Format::Toml, "a = 1 # x\nb = 2\n", "a = 1\n"),
(Format::Yaml, "a: 1 # x\nb: 2\n", "a: 1\n"),
] {
assert_eq!(merge(format, target, source).unwrap(), target);
assert!(contains(format, target, source).unwrap());
}
}
#[test]
fn contains_only_looks_at_owned_keys() {
let source = "a = 1\n[t]\nx = 2\n";
assert!(
contains(
Format::Toml,
"extra = 9\na = 1\n[t]\nx = 2\ny = 3\n",
source
)
.unwrap()
);
assert!(!contains(Format::Toml, "a = 1\n[t]\nx = 3\n", source).unwrap());
assert!(!contains(Format::Toml, "a = 1\n", source).unwrap());
assert!(!contains(Format::Json, r#"{"l":[1,2]}"#, r#"{"l":[1]}"#).unwrap());
}
#[test]
fn an_equal_toml_array_keeps_its_spacing_and_comments() {
let target = "list = [\n 1, # one\n 2,\n] # keep\nmode = \"old\"\n";
let merged = merge(Format::Toml, target, "list = [1, 2]\nmode = \"new\"\n").unwrap();
assert_eq!(merged, target.replace("\"old\"", "\"new\""));
}
#[test]
fn an_equal_toml_array_of_tables_keeps_its_formatting() {
let target = "mode = \"old\"\n\n[[bin]] # first\nname = \"a\"\n\n[[bin]]\nname = \"b\"\n";
let merged = merge(
Format::Toml,
target,
"mode = \"new\"\n[[bin]]\nname = \"a\"\n[[bin]]\nname = \"b\"\n",
)
.unwrap();
assert_eq!(merged, target.replace("\"old\"", "\"new\""));
}
#[test]
fn untouched_json_values_keep_their_exact_text() {
let target = "{\n \"big\": 18446744073709551617,\n \"sci\": 1e3,\n \"esc\": \"\\u00e9\",\n \"model\": \"old\"\n}\n";
let merged = merge(Format::Json, target, r#"{"model": "new"}"#).unwrap();
assert_eq!(merged, target.replace("\"old\"", "\"new\""));
}
#[test]
fn values_json_cannot_hold_are_compared_as_themselves() {
assert!(
!contains(
Format::Toml,
"when = \"2026-01-02T03:04:05Z\"\n",
"when = 2026-01-02T03:04:05Z\n"
)
.unwrap()
);
let merged = merge(Format::Toml, "big = inf\nx = 1\n", "x = 2\n").unwrap();
assert_eq!(merged, "big = inf\nx = 2\n");
let target = "# keep\n1: one\nenv:\n 2: two\nname: old\n";
assert_eq!(
merge(Format::Yaml, target, "name: new\n").unwrap(),
target.replace("old", "new")
);
assert!(!contains(Format::Yaml, target, "env:\n 2: three\n").unwrap());
}
#[test]
fn sources_conflict_only_on_different_values_for_one_key() {
let conflicts = |a, b| conflicts(Format::Toml, a, b).unwrap();
assert_eq!(
conflicts("m = 1\n[t]\nx = 1\ny = 2\n", "m = 2\n[t]\nx = 9\ny = 2\n"),
vec!["m".to_string(), "t.x".to_string()]
);
assert!(conflicts("m = 1\n[t]\nx = 1\n", "m = 1\n[t]\ny = 2\n").is_empty());
assert_eq!(conflicts("t = 1\n", "[t]\nx = 1\n"), vec!["t".to_string()]);
}
#[test]
fn conflicts_are_found_in_every_format() {
assert_eq!(
conflicts(Format::Json, r#"{"a": {"b": 1}}"#, r#"{"a": {"b": 2}}"#).unwrap(),
vec!["a.b".to_string()]
);
assert_eq!(
conflicts(Format::Yaml, "a:\n b: 1\n1: x\n", "a:\n b: 2\n1: y\n").unwrap(),
vec!["a.b".to_string(), "1".to_string()]
);
}
#[test]
fn yaml_tags_are_part_of_the_value() {
let target = "path: !include settings.yaml\n";
assert!(!contains(Format::Yaml, target, "path: settings.yaml\n").unwrap());
assert_eq!(
merge(Format::Yaml, target, "path: settings.yaml\n").unwrap(),
"path: settings.yaml\n"
);
assert_eq!(
fill_missing(Format::Yaml, "a: 1\n", "a: 2\nkey: !secret api_key\n").unwrap(),
"a: 1\nkey: !secret api_key\n"
);
assert_eq!(
conflicts(Format::Yaml, "a: !secret x\n", "a: x\n").unwrap(),
vec!["a".to_string()]
);
}
#[test]
fn yaml_punctuation_in_text_is_not_a_tag_or_anchor() {
let text = "a: 'x!y'\nb: hi!\nc: \"&x *y\"\nd: a&b # !c &d *e\n";
assert_eq!(yaml_features(text), (false, false));
assert_eq!(yaml_features("a: !t x\n"), (true, false));
assert_eq!(yaml_features("a: &x 1\nb: *x\n"), (false, true));
}
#[test]
fn yaml_aliases_resolve_against_their_anchors() {
let source = "a: &v default\nb: *v\n";
assert_eq!(
fill_missing(Format::Yaml, "a: mine\n", source).unwrap(),
"a: mine\nb: default\n"
);
assert!(contains(Format::Yaml, "a: default\nb: default\n", source).unwrap());
let merged = "base: &b {x: 1}\nkid:\n <<: *b\n";
assert!(contains(Format::Yaml, "base: {x: 1}\nkid: {x: 1}\n", merged).unwrap());
assert!(
fill_missing(Format::Yaml, "a: 1\n", "a: &v !secret x\nb: *v\n")
.unwrap_err()
.to_string()
.contains("both tags and anchors")
);
}
#[test]
fn merging_twice_changes_nothing() {
for (format, target, source) in [
(Format::Json, "{\"x\": 1}\n", "{\"a\": {\"b\": [1]}}"),
(Format::Toml, "x = 1\n", "[a]\nb = [1]\n"),
(Format::Yaml, "x: 1\n", "a:\n b: [1]\n"),
] {
let once = merge(format, target, source).unwrap();
assert_eq!(merge(format, &once, source).unwrap(), once);
}
}
#[test]
fn unparseable_or_non_table_input_is_an_error() {
assert!(merge(Format::Json, "{// c\n}", "{}").is_err());
assert!(merge(Format::Json, "[1]", "{}").is_err());
assert!(merge(Format::Toml, "a = ", "a = 1").is_err());
assert!(merge(Format::Yaml, "- a\n", "a: 1\n").is_err());
assert!(merge(Format::Json, "{}", "[1]").is_err());
}
}