use crate::catalog::{Chunk, Entry, Msg, hole_ranges};
use crate::linked::Broken;
use crate::plural::Plural;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum LinkError {
Missing,
Cycle,
Broken,
UnknownModifier,
Lazy,
}
impl fmt::Display for LinkError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
LinkError::Missing => "names no message",
LinkError::Cycle => "is a cycle",
LinkError::Broken => "links a message left as written",
LinkError::UnknownModifier => "has an unknown modifier",
LinkError::Lazy => "names no message read at build (its view has lazy files)",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum CheckItem {
MissingPage { locale: String, page: String },
MissingKey {
locale: String,
page: String,
key: String,
},
Placeholders {
locale: String,
page: String,
key: String,
expected: Vec<String>,
found: Vec<String>,
},
PluralForms {
locale: String,
page: String,
key: String,
forms: usize,
expected: Vec<usize>,
categories: Vec<String>,
},
PluralShape {
locale: String,
page: String,
key: String,
categories: Vec<String>,
},
BrokenLink {
locale: String,
page: String,
key: String,
link: String,
reason: LinkError,
},
}
impl fmt::Display for CheckItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CheckItem::MissingPage { locale, page } => {
write!(
f,
"{locale}: no file for page \"{page}\" (other locales have one)"
)
}
CheckItem::MissingKey { locale, page, key } => {
write!(
f,
"{locale}/{page}: \"{key}\" is missing (the default locale has it)"
)
}
CheckItem::Placeholders {
locale,
page,
key,
expected,
found,
} => write!(
f,
"{locale}/{page}: \"{key}\" has {{{}}}, the default locale {{{}}}",
found.join(", "),
expected.join(", ")
),
CheckItem::PluralForms {
locale,
page,
key,
forms,
expected,
categories,
} => {
let expected: Vec<String> = expected.iter().map(usize::to_string).collect();
write!(
f,
"{locale}/{page}: \"{key}\" has {forms} plural forms, expected {} (zero | {})",
expected.join(" or "),
categories.join(" | ")
)
}
CheckItem::PluralShape {
locale,
page,
key,
categories,
} => write!(
f,
"{locale}/{page}: \"{key}\" is read by index, not by category (zero | {}): \
the zero form has a `{{` or a form of several counts lacks {{count}}",
categories.join(" | ")
),
CheckItem::BrokenLink {
locale,
page,
key,
link,
reason,
} => write!(
f,
"{locale}/{page}: \"{key}\" left as written: {link} {reason}"
),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CheckReport {
pub items: Vec<CheckItem>,
}
impl CheckReport {
#[must_use]
pub fn is_clean(&self) -> bool {
self.items.is_empty()
}
}
impl fmt::Display for CheckReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.items.is_empty() {
return f.write_str("catalog check: clean");
}
write!(f, "catalog check: {} problem(s)", self.items.len())?;
for item in &self.items {
write!(f, "\n - {item}")?;
}
Ok(())
}
}
#[derive(Debug, Default)]
pub(crate) struct Facts {
pub(crate) reference: Option<Arc<str>>,
pub(crate) broken: std::sync::Mutex<Vec<Broken>>,
}
pub(crate) fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn page_name(page: Option<&Arc<str>>) -> String {
page.map_or_else(|| "index".to_owned(), |p| String::from(&**p))
}
fn holes(e: &Entry, plural: bool) -> Option<BTreeSet<&str>> {
let raw = match e {
Entry::Msg(_) => e.text()?,
_ => return None,
};
Some(
hole_ranges(raw)
.filter_map(|(s, e)| raw.get(s..e))
.filter(|name| !(plural && *name == "count"))
.collect(),
)
}
fn sorted(set: &BTreeSet<&str>) -> Vec<String> {
set.iter().map(|s| (*s).to_owned()).collect()
}
pub(crate) fn run<'a>(
chunks: impl Iterator<Item = (&'a Arc<str>, Option<&'a Arc<str>>, &'a Chunk)>,
facts: &Facts,
plural: impl Fn(&str) -> Option<&'static Plural>,
) -> CheckReport {
let chunks: BTreeMap<(&Arc<str>, Option<&Arc<str>>), &Chunk> = chunks
.filter(|(_, _, c)| !c.only_linked())
.map(|(l, p, c)| ((l, p), c))
.collect();
let locales: BTreeSet<&Arc<str>> = chunks.keys().map(|(l, _)| *l).collect();
let pages: BTreeSet<Option<&Arc<str>>> = chunks.keys().map(|(_, p)| *p).collect();
let mut items = Vec::new();
for page in &pages {
for locale in &locales {
if !chunks.contains_key(&(*locale, *page)) {
items.push(CheckItem::MissingPage {
locale: String::from(&***locale),
page: page_name(*page),
});
}
}
}
if let Some(reference) = facts.reference.as_ref() {
for ((_, page), base) in chunks.iter().filter(|((l, _), _)| *l == reference) {
for locale in locales.iter().filter(|l| **l != reference) {
let Some(other) = chunks.get(&(*locale, *page)) else {
continue;
};
for (key, e) in base.leaves() {
let mine = match other.get(key) {
Some(m) if other.has(key) => m,
_ => {
items.push(CheckItem::MissingKey {
locale: String::from(&***locale),
page: page_name(*page),
key: key.to_owned(),
});
continue;
}
};
let plural = [e, mine]
.iter()
.any(|x| matches!(x, Entry::Msg(Msg::Plural(_))));
if let (Some(want), Some(got)) = (holes(e, plural), holes(mine, plural))
&& want != got
{
items.push(CheckItem::Placeholders {
locale: String::from(&***locale),
page: page_name(*page),
key: key.to_owned(),
expected: sorted(&want),
found: sorted(&got),
});
}
}
}
}
}
for ((locale, page), chunk) in &chunks {
let rules = plural(locale);
for (key, e) in chunk.leaves() {
let Entry::Msg(Msg::Plural(p)) = e else {
continue;
};
let (forms, marked, shape) = p.layout();
let Some((expected, shape_only)) = shape.check(marked, rules) else {
continue;
};
let categories = rules
.map(|r| r.named_names().into_iter().map(str::to_owned).collect())
.unwrap_or_default();
let (locale, page, key) = (String::from(&***locale), page_name(*page), key.to_owned());
items.push(if shape_only {
CheckItem::PluralShape {
locale,
page,
key,
categories,
}
} else {
CheckItem::PluralForms {
locale,
page,
key,
forms,
expected,
categories,
}
});
}
}
for b in lock(&facts.broken).iter() {
if locales.contains(&b.locale) {
items.push(CheckItem::BrokenLink {
locale: String::from(&*b.locale),
page: page_name(b.page.as_ref()),
key: String::from(&*b.key),
link: String::from(&*b.link),
reason: b.reason,
});
}
}
items.sort();
items.dedup();
CheckReport { items }
}