use std::collections::{BTreeMap, btree_map::Entry};
use tramlines_core::grammar::BrokenFormat;
use super::formats::{formats_path, layer_of, line_message};
use crate::{
Error, RepoPath, Result, Spanned, Yaml,
grammar::{FormatRegistry, FormatSource, Grammar, PackLayer, RegexCache},
};
pub(super) fn settled_types(
docs: &mut [(RepoPath, Spanned)],
repo: Option<(&RepoPath, &Spanned)>,
below: &FormatRegistry,
grammar: &Grammar,
regexes: &RegexCache,
) -> Result<Option<(FormatRegistry, Vec<BrokenFormat>)>> {
let Some((repo_path, repo_doc)) = repo else {
return Ok(None);
};
let mut count: BTreeMap<String, usize> = BTreeMap::new();
for (_, doc) in docs.iter() {
for (name, _) in doc
.get("types")
.and_then(Spanned::as_map)
.unwrap_or_default()
{
*count.entry(name.value.clone()).or_default() += 1;
}
}
let declared = |name: &str| repo_doc.get("types").and_then(|t| t.get(name)).is_some();
let names: Vec<String> = count
.into_iter()
.filter(|(name, n)| *n > 1 && declared(name))
.map(|(name, _)| name)
.collect();
if names.is_empty() {
return Ok(None);
}
for (_, doc) in docs.iter_mut() {
if let Some(Yaml::Map(types)) = map_mut(doc, "types") {
types.retain(|(name, _)| !names.contains(&name.value));
}
}
let kept = repo_doc
.get("types")
.and_then(Spanned::as_map)
.unwrap_or_default()
.iter()
.filter(|(name, _)| names.contains(&name.value))
.cloned()
.collect();
let only = Spanned::new(
Yaml::Map(vec![(
Spanned::new("types".to_string(), repo_doc.line),
Spanned::new(Yaml::Map(kept), repo_doc.line),
)]),
repo_doc.line,
);
let none = Spanned::new(Yaml::Map(Vec::new()), 1);
let types = layer_of(
repo_path,
&only,
&none,
FormatSource::Repo,
grammar,
regexes,
below,
)?
.types;
let settled = FormatRegistry {
types,
..FormatRegistry::default()
};
let (mut out, broken) = below.layered(&settled);
for b in &broken {
if let Some(entry) = below.entries.get(&b.name) {
out.entries.insert(b.name.clone(), entry.clone());
}
}
Ok(Some((out, broken)))
}
pub(super) fn unsettled(broken: &[BrokenFormat], repo: &FormatRegistry) -> Result<()> {
let path = formats_path();
let findings: Vec<crate::Finding> = broken
.iter()
.filter(|b| !repo.entries.contains_key(&b.name))
.flat_map(|b| b.findings(&path, None))
.collect();
refuse(&findings)
}
pub(super) fn folder_files(
docs: &[(RepoPath, Spanned)],
below: &FormatRegistry,
grammar: &Grammar,
regexes: &RegexCache,
) -> Result<Vec<(RepoPath, FormatRegistry)>> {
let mut shared = below.clone();
for (path, doc) in docs.iter().rev() {
let none = Spanned::new(Yaml::Map(Vec::new()), 1);
let types = layer_of(path, doc, &none, source_of(path), grammar, regexes, below)?;
shared.types = shared.types.layered(&types.types);
}
let mut files = Vec::new();
for (path, doc) in docs {
let registry = doc
.get("registry")
.ok_or_else(|| Error::formats(path.clone(), "The file has no `registry` map."))?;
let file = layer_of(
path,
doc,
registry,
source_of(path),
grammar,
regexes,
&shared,
)?;
files.push((path.clone(), file));
}
Ok(files)
}
pub(super) fn refuse_findings(folder: &PackLayer, repo: &FormatRegistry) -> Result<FormatRegistry> {
let (registry, findings) = folder.with_host(repo, &formats_path());
refuse(&findings)?;
Ok(registry)
}
fn refuse(findings: &[crate::Finding]) -> Result<()> {
if let Some(first) = findings.first() {
let messages: Vec<String> = findings
.iter()
.map(|f| match &f.path {
p if *p == first.path => line_message(f),
p => format!("{p}: {}", line_message(f)),
})
.collect();
return Err(Error::formats(first.path.clone(), messages.join("; ")));
}
Ok(())
}
const MAPS: [(&str, &str); 2] = [("format", "registry"), ("type", "types")];
pub(super) fn without_alike(docs: &mut [(RepoPath, Spanned)], below: &FormatRegistry) {
let mut first: BTreeMap<(&str, String), Spanned> = BTreeMap::new();
for (_, doc) in docs {
for (what, map) in MAPS {
let Some(Yaml::Map(entries)) = map_mut(doc, map) else {
continue;
};
entries.retain(
|(name, value)| match first.entry((map, name.value.clone())) {
Entry::Occupied(earlier) => {
let base = below
.get(&name.value)
.filter(|_| what == "format")
.map(|f| &f.raw);
!alike(earlier.get(), value, base)
}
Entry::Vacant(slot) => {
slot.insert(value.clone());
true
}
},
);
}
}
}
pub(crate) fn is_patch(value: &Spanned) -> bool {
value.get("patch").and_then(Spanned::as_bool) == Some(true)
}
fn map_mut<'a>(doc: &'a mut Spanned, key: &str) -> Option<&'a mut Yaml> {
let Yaml::Map(entries) = &mut doc.value else {
return None;
};
entries
.iter_mut()
.find(|(k, _)| k.value == key)
.map(|(_, v)| &mut v.value)
}
fn alike(a: &Spanned, b: &Spanned, base: Option<&Spanned>) -> bool {
let below = base
.and_then(|e| e.get("variants"))
.filter(|v| v.as_map().is_some() && is_patch(a));
let counts = |name: &str, value: &Spanned| match below {
Some(held) => held.get(name).is_none() && !matches!(value.value, Yaml::Null),
None => true,
};
let order = |d: &Spanned| -> Option<Vec<String>> {
let variants = d.get("variants")?.as_map()?;
Some(
variants
.iter()
.filter(|(k, v)| counts(&k.value, v))
.map(|(k, _)| k.value.clone())
.collect(),
)
};
same_value(a, b) && order(a) == order(b)
}
fn same_value(a: &Spanned, b: &Spanned) -> bool {
match (&a.value, &b.value) {
(Yaml::Seq(x), Yaml::Seq(y)) => {
x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_value(p, q))
}
(Yaml::Map(x), Yaml::Map(y)) => {
x.len() == y.len()
&& x.iter().all(|(k, v)| {
y.iter()
.find(|(l, _)| l.value == k.value)
.is_some_and(|(_, w)| same_value(v, w))
})
}
(Yaml::Float(x), Yaml::Float(y)) => x.total_cmp(y).is_eq(),
(x, y) => x == y,
}
}
pub(super) fn check_clashes(docs: &[(RepoPath, Spanned)], repo: Option<&Spanned>) -> Result<()> {
let names = |doc: &'_ Spanned, map: &str| -> Vec<String> {
doc.get(map)
.and_then(Spanned::as_map)
.unwrap_or_default()
.iter()
.map(|(k, _)| k.value.clone())
.collect()
};
let decided = |map: &str, name: &str| {
repo.and_then(|r| r.get(map))
.and_then(Spanned::as_map)
.unwrap_or_default()
.iter()
.find(|(k, _)| k.value == name)
.is_some_and(|(_, v)| !is_patch(v))
};
let mut clashes: Vec<(&RepoPath, String)> = Vec::new();
for (what, map) in MAPS {
let mut first: BTreeMap<String, &RepoPath> = BTreeMap::new();
for (path, doc) in docs {
for name in names(doc, map) {
match first.get(&name) {
Some(earlier) if !decided(map, &name) => {
clashes.push((path, clash(what, &name, earlier, path)));
}
Some(_) => {}
None => {
first.insert(name, path);
}
}
}
}
}
clashes.sort_by(|a, b| a.0.cmp(b.0));
match clashes.first() {
None => Ok(()),
Some((path, _)) => Err(Error::formats(
(*path).clone(),
clashes
.iter()
.map(|(_, m)| m.as_str())
.collect::<Vec<_>>()
.join("; "),
)),
}
}
fn clash(what: &str, name: &str, first: &RepoPath, later: &RepoPath) -> String {
format!(
"{what} `{name}` is declared differently in `{first}` and `{later}` of \
/.sokf/formats.d/, and no file of the folder takes precedence; declare \
it in full in `{}` to choose one",
formats_path()
)
}
fn source_of(path: &RepoPath) -> FormatSource {
FormatSource::File(path.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::yaml;
fn value(text: &str) -> Spanned {
yaml::parse(text, 1).unwrap()
}
#[test]
fn alike_compares_parsed_values_and_the_order_of_the_variants() {
let entry = "template: '${:colour} line.'\nexample: Red line.\n";
for other in [
entry,
"# A comment.\nexample: \"Red line.\"\ntemplate: \"${:colour} line.\"\n",
"{ example: Red line., template: '${:colour} line.' }\n",
] {
assert!(alike(&value(entry), &value(other), None), "{other:?}");
}
for other in [
"template: '${:colour} line.'\nexample: Blue line.\n",
"template: '${:colour} line.'\nexample: Red line.\nkey: colour\n",
"template: '${:colour} line.'\n",
] {
assert!(!alike(&value(entry), &value(other), None), "{other:?}");
}
assert!(!alike(&value("['1']"), &value("[1]"), None));
assert!(alike(&value("[.nan]"), &value("[.NaN]"), None));
assert!(!alike(&value("[a, b]"), &value("[b, a]"), None));
let variants = |a: &str, b: &str| {
value(&format!(
"variants:\n {a}:\n text: {a}\n example: {a}\n {b}:\n example: {b}\n text: {b}\n"
))
};
assert!(alike(
&variants("one", "two"),
&variants("one", "two"),
None
));
assert!(!alike(
&variants("one", "two"),
&variants("two", "one"),
None
));
let patch = |a: &str, b: &str| {
value(&format!(
"patch: true\nvariants:\n {a}:\n example: {a}\n {b}:\n example: {b}\n"
))
};
let base = variants("one", "two");
assert!(alike(
&patch("one", "two"),
&patch("two", "one"),
Some(&base)
));
assert!(!alike(&patch("one", "new"), &patch("new", "one"), None));
let null = |first: bool| {
let (x, y) = (" x: ~\n", " y:\n example: y\n");
let (a, b) = if first { (x, y) } else { (y, x) };
value(&format!("patch: true\nvariants:\n{a}{b}"))
};
let single = value("pattern: '.*'\nexample: x\n");
assert!(!alike(&null(true), &null(false), Some(&single)));
assert!(alike(&null(true), &null(false), Some(&base)));
let other = variants("three", "four");
assert!(!alike(
&patch("one", "two"),
&patch("two", "one"),
Some(&other)
));
}
}