1use crate::catalog::{Chunk, Entry, Msg, hole_ranges};
14use crate::linked::Broken;
15use crate::plural::Plural;
16use std::collections::{BTreeMap, BTreeSet};
17use std::fmt;
18use std::sync::Arc;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
22#[non_exhaustive]
23pub enum LinkError {
24 Missing,
26 Cycle,
28 Broken,
30 UnknownModifier,
32 Lazy,
35}
36
37impl fmt::Display for LinkError {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.write_str(match self {
40 LinkError::Missing => "names no message",
41 LinkError::Cycle => "is a cycle",
42 LinkError::Broken => "links a message left as written",
43 LinkError::UnknownModifier => "has an unknown modifier",
44 LinkError::Lazy => "names no message read at build (its view has lazy files)",
45 })
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
51#[non_exhaustive]
52pub enum CheckItem {
53 MissingPage { locale: String, page: String },
55 MissingKey {
57 locale: String,
58 page: String,
59 key: String,
60 },
61 Placeholders {
63 locale: String,
64 page: String,
65 key: String,
66 expected: Vec<String>,
68 found: Vec<String>,
70 },
71 PluralForms {
73 locale: String,
74 page: String,
75 key: String,
76 forms: usize,
77 expected: Vec<usize>,
80 categories: Vec<String>,
82 },
83 PluralShape {
86 locale: String,
87 page: String,
88 key: String,
89 categories: Vec<String>,
90 },
91 BrokenLink {
93 locale: String,
94 page: String,
95 key: String,
96 link: String,
98 reason: LinkError,
99 },
100}
101
102impl fmt::Display for CheckItem {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 match self {
105 CheckItem::MissingPage { locale, page } => {
106 write!(
107 f,
108 "{locale}: no file for page \"{page}\" (other locales have one)"
109 )
110 }
111 CheckItem::MissingKey { locale, page, key } => {
112 write!(
113 f,
114 "{locale}/{page}: \"{key}\" is missing (the default locale has it)"
115 )
116 }
117 CheckItem::Placeholders {
118 locale,
119 page,
120 key,
121 expected,
122 found,
123 } => write!(
124 f,
125 "{locale}/{page}: \"{key}\" has {{{}}}, the default locale {{{}}}",
126 found.join(", "),
127 expected.join(", ")
128 ),
129 CheckItem::PluralForms {
130 locale,
131 page,
132 key,
133 forms,
134 expected,
135 categories,
136 } => {
137 let expected: Vec<String> = expected.iter().map(usize::to_string).collect();
138 write!(
139 f,
140 "{locale}/{page}: \"{key}\" has {forms} plural forms, expected {} (zero | {})",
141 expected.join(" or "),
142 categories.join(" | ")
143 )
144 }
145 CheckItem::PluralShape {
146 locale,
147 page,
148 key,
149 categories,
150 } => write!(
151 f,
152 "{locale}/{page}: \"{key}\" is read by index, not by category (zero | {}): \
153 the zero form has a `{{` or a form of several counts lacks {{count}}",
154 categories.join(" | ")
155 ),
156 CheckItem::BrokenLink {
157 locale,
158 page,
159 key,
160 link,
161 reason,
162 } => write!(
163 f,
164 "{locale}/{page}: \"{key}\" left as written: {link} {reason}"
165 ),
166 }
167 }
168}
169
170#[derive(Debug, Clone, Default, PartialEq, Eq)]
191#[non_exhaustive]
192pub struct CheckReport {
193 pub items: Vec<CheckItem>,
195}
196
197impl CheckReport {
198 #[must_use]
200 pub fn is_clean(&self) -> bool {
201 self.items.is_empty()
202 }
203}
204
205impl fmt::Display for CheckReport {
206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207 if self.items.is_empty() {
208 return f.write_str("catalog check: clean");
209 }
210 write!(f, "catalog check: {} problem(s)", self.items.len())?;
211 for item in &self.items {
212 write!(f, "\n - {item}")?;
213 }
214 Ok(())
215 }
216}
217
218#[derive(Debug, Default)]
220pub(crate) struct Facts {
221 pub(crate) reference: Option<Arc<str>>,
223 pub(crate) broken: std::sync::Mutex<Vec<Broken>>,
225}
226
227pub(crate) fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
229 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
230}
231
232fn page_name(page: Option<&Arc<str>>) -> String {
233 page.map_or_else(|| "index".to_owned(), |p| String::from(&**p))
234}
235
236fn holes(e: &Entry, plural: bool) -> Option<BTreeSet<&str>> {
239 let raw = match e {
240 Entry::Msg(_) => e.text()?,
241 _ => return None,
242 };
243 Some(
244 hole_ranges(raw)
245 .filter_map(|(s, e)| raw.get(s..e))
246 .filter(|name| !(plural && *name == "count"))
247 .collect(),
248 )
249}
250
251fn sorted(set: &BTreeSet<&str>) -> Vec<String> {
252 set.iter().map(|s| (*s).to_owned()).collect()
253}
254
255pub(crate) fn run<'a>(
257 chunks: impl Iterator<Item = (&'a Arc<str>, Option<&'a Arc<str>>, &'a Chunk)>,
258 facts: &Facts,
259 plural: impl Fn(&str) -> Option<&'static Plural>,
260) -> CheckReport {
261 let chunks: BTreeMap<(&Arc<str>, Option<&Arc<str>>), &Chunk> = chunks
262 .filter(|(_, _, c)| !c.only_linked())
263 .map(|(l, p, c)| ((l, p), c))
264 .collect();
265 let locales: BTreeSet<&Arc<str>> = chunks.keys().map(|(l, _)| *l).collect();
266 let pages: BTreeSet<Option<&Arc<str>>> = chunks.keys().map(|(_, p)| *p).collect();
267 let mut items = Vec::new();
268
269 for page in &pages {
270 for locale in &locales {
271 if !chunks.contains_key(&(*locale, *page)) {
272 items.push(CheckItem::MissingPage {
273 locale: String::from(&***locale),
274 page: page_name(*page),
275 });
276 }
277 }
278 }
279
280 if let Some(reference) = facts.reference.as_ref() {
281 for ((_, page), base) in chunks.iter().filter(|((l, _), _)| *l == reference) {
282 for locale in locales.iter().filter(|l| **l != reference) {
283 let Some(other) = chunks.get(&(*locale, *page)) else {
284 continue;
285 };
286 for (key, e) in base.leaves() {
287 let mine = match other.get(key) {
288 Some(m) if other.has(key) => m,
289 _ => {
290 items.push(CheckItem::MissingKey {
291 locale: String::from(&***locale),
292 page: page_name(*page),
293 key: key.to_owned(),
294 });
295 continue;
296 }
297 };
298 let plural = [e, mine]
299 .iter()
300 .any(|x| matches!(x, Entry::Msg(Msg::Plural(_))));
301 if let (Some(want), Some(got)) = (holes(e, plural), holes(mine, plural))
302 && want != got
303 {
304 items.push(CheckItem::Placeholders {
305 locale: String::from(&***locale),
306 page: page_name(*page),
307 key: key.to_owned(),
308 expected: sorted(&want),
309 found: sorted(&got),
310 });
311 }
312 }
313 }
314 }
315 }
316
317 for ((locale, page), chunk) in &chunks {
318 let rules = plural(locale);
319 for (key, e) in chunk.leaves() {
320 let Entry::Msg(Msg::Plural(p)) = e else {
321 continue;
322 };
323 let (forms, marked, shape) = p.layout();
324 let Some((expected, shape_only)) = shape.check(marked, rules) else {
325 continue;
326 };
327 let categories = rules
328 .map(|r| r.named_names().into_iter().map(str::to_owned).collect())
329 .unwrap_or_default();
330 let (locale, page, key) = (String::from(&***locale), page_name(*page), key.to_owned());
331 items.push(if shape_only {
332 CheckItem::PluralShape {
333 locale,
334 page,
335 key,
336 categories,
337 }
338 } else {
339 CheckItem::PluralForms {
340 locale,
341 page,
342 key,
343 forms,
344 expected,
345 categories,
346 }
347 });
348 }
349 }
350
351 for b in lock(&facts.broken).iter() {
352 if locales.contains(&b.locale) {
353 items.push(CheckItem::BrokenLink {
354 locale: String::from(&*b.locale),
355 page: page_name(b.page.as_ref()),
356 key: String::from(&*b.key),
357 link: String::from(&*b.link),
358 reason: b.reason,
359 });
360 }
361 }
362
363 items.sort();
364 items.dedup();
365 CheckReport { items }
366}