makeover 5.13.0

Shared theme loading for the make-family apps: TOML theme files parsed into intent-based color tokens, with perceptual derivations and WCAG contrast.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! Checking every web file under a repo, by exclusion.
//!
//! A [`Tree`] reads every sheet, page, image and script under its root except
//! the ones its build names as generated and the ones `look-exempt` excuses with
//! a reason, so a file added after the gate was written is checked the day it
//! appears. `look-ceilings.toml` holds a count per rule that the tree may not
//! exceed; a count below its ceiling is reported so the ceiling comes down.
//! `look-tree.toml` says what the build writes and joins, so every reader of a
//! tree, its own build and a linter outside it, checks the same files.

use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

use crate::look::{Context, Finding, Rule, css, markup, script};

/// The file at a tree's root listing what the gate does not read, one path per
/// line followed by the reason.
pub const EXEMPT_FILE: &str = "look-exempt";

/// The file at a tree's root holding each rule's ceiling.
pub const CEILINGS_FILE: &str = "look-ceilings.toml";

/// The file at a tree's root describing it to [`Tree::load`].
pub const TREE_FILE: &str = "look-tree.toml";

/// Directories no tree walks into.
const NEVER_WALKED: &[&str] = &["target", "node_modules", "vendor", "dist", "renders"];

/// A repo's web files, read by exclusion.
#[derive(Debug, Clone)]
pub struct Tree {
    root: PathBuf,
    generated: Vec<String>,
    joined: Vec<String>,
    runtime: Vec<String>,
    skipped: Vec<String>,
    intents: bool,
}

/// `look-tree.toml` could not be read as a tree's description.
#[derive(Debug)]
pub struct TreeFileError {
    pub path: PathBuf,
    pub why: String,
}

impl fmt::Display for TreeFileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.path.display(), self.why)
    }
}

impl std::error::Error for TreeFileError {}

/// Why a tree could not be checked.
#[derive(Debug)]
pub enum TreeError {
    /// A path named as generated is not on disk, so the tokens it defines
    /// would read as undefined.
    MissingGenerated(PathBuf),
    /// A `look-exempt` line with no reason after its path.
    ExemptWithoutReason { line: usize, path: String },
    /// `look-ceilings.toml` names a rule that does not exist or is not TOML.
    Ceilings(String),
    /// A file could not be read.
    Io(PathBuf, std::io::Error),
}

impl fmt::Display for TreeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingGenerated(p) => write!(
                f,
                "{} is named as generated and is not on disk; build it first",
                p.display()
            ),
            Self::ExemptWithoutReason { line, path } => {
                write!(f, "{EXEMPT_FILE} line {line}: `{path}` has no reason")
            }
            Self::Ceilings(why) => write!(f, "{CEILINGS_FILE}: {why}"),
            Self::Io(p, e) => write!(f, "{}: {e}", p.display()),
        }
    }
}

impl std::error::Error for TreeError {}

/// What a check of a tree found.
#[derive(Debug, Clone, Default)]
pub struct Report {
    /// Every finding, with the file it is in relative to the root.
    pub findings: Vec<(PathBuf, Finding)>,
    /// Each rule's ceiling; a rule absent here has a ceiling of zero.
    pub ceilings: BTreeMap<Rule, usize>,
    /// Every file read, for a build script to watch.
    pub read: Vec<PathBuf>,
}

impl Report {
    /// The number of findings for `rule`.
    #[must_use]
    pub fn count(&self, rule: Rule) -> usize {
        self.findings.iter().filter(|(_, f)| f.rule == rule).count()
    }

    fn ceiling(&self, rule: Rule) -> usize {
        self.ceilings.get(&rule).copied().unwrap_or(0)
    }

    /// Each rule whose count is above its ceiling, as `(rule, count, ceiling)`.
    #[must_use]
    pub fn over(&self) -> Vec<(Rule, usize, usize)> {
        Rule::ALL
            .iter()
            .map(|&r| (r, self.count(r), self.ceiling(r)))
            .filter(|(_, n, c)| n > c)
            .collect()
    }

    /// Each rule whose count is below its ceiling, which should come down.
    #[must_use]
    pub fn stale(&self) -> Vec<(Rule, usize, usize)> {
        Rule::ALL
            .iter()
            .map(|&r| (r, self.count(r), self.ceiling(r)))
            .filter(|(_, n, c)| n < c)
            .collect()
    }

    /// The ceilings file that would hold this tree at its present counts.
    #[must_use]
    pub fn measured_ceilings(&self) -> String {
        let lines: Vec<String> = Rule::ALL
            .iter()
            .map(|&r| (r, self.count(r)))
            .filter(|(_, n)| *n > 0)
            .map(|(r, n)| format!("{} = {n}", r.id()))
            .collect();
        format!("[ceiling]\n{}\n", lines.join("\n"))
    }
}

impl Tree {
    /// The web files under `root`.
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            generated: Vec::new(),
            joined: Vec::new(),
            runtime: Vec::new(),
            skipped: Vec::new(),
            intents: false,
        }
    }

    /// The web files under `root`, as its `look-tree.toml` describes them, or
    /// with nothing generated when it has none. The file's keys are the
    /// builder's: `generated`, `joined`, `skip` and `set_at_runtime` are lists
    /// of strings and `intents` is a bool.
    ///
    /// # Errors
    /// The file exists and cannot be read, is not TOML, or has a key this does
    /// not know.
    pub fn load(root: impl Into<PathBuf>) -> Result<Self, TreeFileError> {
        #[derive(serde::Deserialize, Default)]
        #[serde(deny_unknown_fields)]
        struct File {
            #[serde(default)]
            generated: Vec<String>,
            #[serde(default)]
            joined: Vec<String>,
            #[serde(default)]
            skip: Vec<String>,
            #[serde(default)]
            set_at_runtime: Vec<String>,
            #[serde(default)]
            intents: bool,
        }
        let tree = Self::new(root);
        let path = tree.root.join(TREE_FILE);
        let file: File = match std::fs::read_to_string(&path) {
            Ok(text) => toml::from_str(&text).map_err(|e| TreeFileError {
                path: path.clone(),
                why: e.to_string(),
            })?,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => File::default(),
            Err(e) => {
                return Err(TreeFileError {
                    path,
                    why: e.to_string(),
                });
            }
        };
        fn strs(v: &[String]) -> Vec<&str> {
            v.iter().map(String::as_str).collect()
        }
        let mut tree = tree
            .generated(&strs(&file.generated))
            .joined(&strs(&file.joined))
            .skip(&strs(&file.skip))
            .set_at_runtime(&strs(&file.set_at_runtime));
        tree.intents = file.intents;
        Ok(tree)
    }

    /// The theme's intents reach the page at runtime rather than from a sheet
    /// on disk, so the names they define are read from makeover's own themes.
    /// Every theme defines the same names.
    #[must_use]
    pub fn intents(mut self) -> Self {
        self.intents = true;
        self
    }

    /// Paths under the root, relative to it, that a build writes. They are not
    /// checked, and the custom properties their sheets define are what the
    /// tree's own sheets may read. A path with a `*` is a pattern within one
    /// segment, matching what is on disk; it may match nothing.
    #[must_use]
    pub fn generated(mut self, paths: &[&str]) -> Self {
        self.generated
            .extend(paths.iter().map(|p| p.trim_start_matches("./").to_string()));
        self
    }

    /// Paths under the root that a build writes by joining this tree's own
    /// files. They are not checked, since their parts are, and they define
    /// nothing a part could restate: a join's tokens are its parts' tokens.
    #[must_use]
    pub fn joined(mut self, paths: &[&str]) -> Self {
        self.joined
            .extend(paths.iter().map(|p| p.trim_start_matches("./").to_string()));
        self
    }

    /// Custom properties set where no sheet can see them, by the renderer on
    /// an element's `style` or from a script.
    #[must_use]
    pub fn set_at_runtime(mut self, names: &[&str]) -> Self {
        self.runtime.extend(names.iter().map(|n| (*n).to_string()));
        self
    }

    /// Directories under the root, relative to it, that are not this tree's:
    /// another crate's web files, a fixture.
    #[must_use]
    pub fn skip(mut self, dirs: &[&str]) -> Self {
        self.skipped.extend(
            dirs.iter()
                .map(|d| d.trim_start_matches("./").trim_end_matches('/').to_string()),
        );
        self
    }

    /// Reads the tree and reports what it found against its ceilings.
    ///
    /// # Errors
    /// A generated path is missing, `look-exempt` has a line with no reason,
    /// `look-ceilings.toml` does not parse or names an unknown rule, or a file
    /// cannot be read.
    pub fn check(&self) -> Result<Report, TreeError> {
        let exempt = self.exempt()?;
        let ceilings = self.ceilings()?;
        let mut report = Report {
            ceilings,
            ..Report::default()
        };

        let mut files = Vec::new();
        self.walk(&self.root, &mut files)?;

        let mut generated_css = Vec::new();
        for g in &self.generated {
            let paths: Vec<PathBuf> = if g.contains('*') {
                files
                    .iter()
                    .filter(|rel| matches(g, &slash(rel)))
                    .map(|rel| self.root.join(rel))
                    .collect()
            } else {
                let path = self.root.join(g);
                if !path.exists() {
                    return Err(TreeError::MissingGenerated(path));
                }
                vec![path]
            };
            for path in paths {
                if path.extension().is_some_and(|e| e == "css") {
                    generated_css.push(read(&path)?);
                }
            }
        }
        if self.intents {
            generated_css.push(intent_names_sheet());
        }
        let refs: Vec<&str> = generated_css.iter().map(String::as_str).collect();
        let mut ctx = Context::generated(&refs);
        ctx.set_at_runtime(self.runtime.iter().map(String::as_str));

        files.retain(|rel| {
            let s = slash(rel);
            !self.generated.iter().any(|g| matches(g, &s))
                && !self.joined.contains(&s)
                && !exempt.iter().any(|e| matches(e, &s))
        });
        files.sort();

        let mut texts = Vec::with_capacity(files.len());
        for rel in &files {
            texts.push(read(&self.root.join(rel))?);
        }
        for (rel, text) in files.iter().zip(&texts) {
            if kind(rel) == Some(Kind::Sheet) {
                ctx.link(text);
            }
        }
        for (rel, text) in files.iter().zip(&texts) {
            let found = match kind(rel) {
                Some(Kind::Sheet) => css(text, &ctx),
                Some(Kind::Markup) => markup(text),
                Some(Kind::Script) => script(text),
                Some(Kind::Manifest) => manifest(text),
                None => continue,
            };
            report
                .findings
                .extend(found.into_iter().map(|f| (rel.clone(), f)));
        }
        report.read = files;
        Ok(report)
    }

    /// The gate for a build script: checks the tree, prints every finding as a
    /// warning, watches what it read, and fails the build when a rule is over
    /// its ceiling or the tree cannot be checked.
    ///
    /// # Panics
    /// When a rule is over its ceiling or [`Tree::check`] fails.
    pub fn gate(&self) {
        println!(
            "cargo::rerun-if-changed={}",
            self.root.join(EXEMPT_FILE).display()
        );
        println!(
            "cargo::rerun-if-changed={}",
            self.root.join(CEILINGS_FILE).display()
        );
        println!(
            "cargo::rerun-if-changed={}",
            self.root.join(TREE_FILE).display()
        );
        let report = self.check().unwrap_or_else(|e| panic!("look gate: {e}"));
        for rel in &report.read {
            println!("cargo::rerun-if-changed={}", self.root.join(rel).display());
        }
        for (rule, n, c) in report.stale() {
            println!(
                "cargo::warning=look gate: {rule} is at {n}, under its ceiling of {c}; lower it in {CEILINGS_FILE}"
            );
        }
        let over = report.over();
        if over.is_empty() {
            return;
        }
        let lines: Vec<String> = over
            .iter()
            .flat_map(|(rule, n, c)| {
                std::iter::once(format!("  {rule}: {n} found, ceiling {c}")).chain(
                    report
                        .findings
                        .iter()
                        .filter(move |(_, f)| f.rule == *rule)
                        .map(|(rel, f)| {
                            format!("    {}:{}: {}", slash(rel), f.line, f.declaration)
                        }),
                )
            })
            .collect();
        panic!(
            "look gate: over the ceiling\n{}\nTake the value from a token, or name the file in look-exempt with a reason.",
            lines.join("\n")
        );
    }

    fn walk(&self, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), TreeError> {
        let entries = std::fs::read_dir(dir).map_err(|e| TreeError::Io(dir.to_path_buf(), e))?;
        for entry in entries {
            let entry = entry.map_err(|e| TreeError::Io(dir.to_path_buf(), e))?;
            let path = entry.path();
            let name = entry.file_name();
            let name = name.to_string_lossy();
            let rel = path.strip_prefix(&self.root).unwrap_or(&path).to_path_buf();
            if path.is_dir() {
                let skip = name.starts_with('.')
                    || NEVER_WALKED.contains(&name.as_ref())
                    || self.skipped.iter().any(|s| *s == slash(&rel));
                if !skip {
                    self.walk(&path, out)?;
                }
            } else if kind(&rel).is_some() {
                out.push(rel);
            }
        }
        Ok(())
    }

    fn exempt(&self) -> Result<Vec<String>, TreeError> {
        let path = self.root.join(EXEMPT_FILE);
        let Ok(text) = std::fs::read_to_string(&path) else {
            return Ok(Vec::new());
        };
        let mut out = Vec::new();
        for (i, line) in text.lines().enumerate() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let (entry, reason) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
            if reason.trim().is_empty() {
                return Err(TreeError::ExemptWithoutReason {
                    line: i + 1,
                    path: entry.to_string(),
                });
            }
            out.push(entry.trim_start_matches("./").to_string());
        }
        Ok(out)
    }

    fn ceilings(&self) -> Result<BTreeMap<Rule, usize>, TreeError> {
        #[derive(serde::Deserialize)]
        struct File {
            #[serde(default)]
            ceiling: BTreeMap<String, usize>,
        }
        let path = self.root.join(CEILINGS_FILE);
        let Ok(text) = std::fs::read_to_string(&path) else {
            return Ok(BTreeMap::new());
        };
        let file: File = toml::from_str(&text).map_err(|e| TreeError::Ceilings(e.to_string()))?;
        file.ceiling
            .into_iter()
            .map(|(id, n)| {
                Rule::from_id(&id)
                    .map(|r| (r, n))
                    .ok_or_else(|| TreeError::Ceilings(format!("no rule `{id}`")))
            })
            .collect()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    Sheet,
    Markup,
    Script,
    Manifest,
}

fn kind(rel: &Path) -> Option<Kind> {
    let name = rel.file_name()?.to_string_lossy().to_ascii_lowercase();
    if name == "manifest.json" || name.ends_with(".webmanifest") {
        return Some(Kind::Manifest);
    }
    if name.ends_with(".min.js") || name.ends_with(".d.ts") {
        return None;
    }
    match rel
        .extension()?
        .to_string_lossy()
        .to_ascii_lowercase()
        .as_str()
    {
        "css" => Some(Kind::Sheet),
        "html" | "htm" | "svg" => Some(Kind::Markup),
        "js" | "mjs" | "ts" | "tsx" => Some(Kind::Script),
        _ => None,
    }
}

/// The colour a web manifest writes for the browser's chrome.
fn manifest(text: &str) -> Vec<Finding> {
    let mut out = Vec::new();
    for (i, line) in text.lines().enumerate() {
        let Some((key, value)) = line.split_once(':') else {
            continue;
        };
        if key.trim().trim_matches('"').ends_with("_color") && value.contains('#') {
            out.push(Finding {
                rule: Rule::Colour,
                line: i + 1,
                declaration: line.trim().trim_end_matches(',').to_string(),
            });
        }
    }
    out
}

/// One embedded theme's intents as a sheet, for the names it defines.
fn intent_names_sheet() -> String {
    crate::embedded_themes()
        .find_map(|(name, toml)| {
            let id = crate::ThemeId::new(name).ok()?;
            crate::parse_theme_str(&id, toml, false).ok()
        })
        .map(|theme| crate::intent_css_vars(&crate::resolve(&theme)))
        .unwrap_or_default()
}

fn read(path: &Path) -> Result<String, TreeError> {
    std::fs::read_to_string(path).map_err(|e| TreeError::Io(path.to_path_buf(), e))
}

fn slash(rel: &Path) -> String {
    rel.to_string_lossy().replace('\\', "/")
}

/// Whether exempt entry `pattern` covers `path`: a directory with a trailing
/// `/` covers everything under it, and `*` stands for any run of characters
/// within one path segment.
fn matches(pattern: &str, path: &str) -> bool {
    if let Some(dir) = pattern.strip_suffix('/') {
        return path.starts_with(&format!("{dir}/"));
    }
    let p: Vec<&str> = pattern.split('/').collect();
    let s: Vec<&str> = path.split('/').collect();
    p.len() == s.len() && p.iter().zip(&s).all(|(p, s)| glob(p, s))
}

fn glob(pattern: &str, text: &str) -> bool {
    match pattern.split_once('*') {
        None => pattern == text,
        Some((head, tail)) => {
            text.starts_with(head)
                && (0..=text.len() - head.len()).any(|i| {
                    let rest = &text[head.len() + i..];
                    glob(tail, rest)
                })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tree_with(files: &[(&str, &str)]) -> (tempfile::TempDir, Tree) {
        let dir = tempfile::TempDir::new().unwrap();
        for (rel, text) in files {
            let path = dir.path().join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        }
        let tree = Tree::new(dir.path());
        (dir, tree)
    }

    /// A file added after the gate was written is read, because nothing lists
    /// what to read; only what not to.
    #[test]
    fn every_web_file_is_read_but_the_generated_and_the_exempt() {
        let (_d, tree) = tree_with(&[
            ("static/geometry.css", ":root { --gap: 1rem; }"),
            (
                "css/new-page.css",
                ".a { color: #fff; padding: var(--gap); }",
            ),
            ("templates/page.html", "<p style=\"color: red\">x</p>"),
            ("frontend/src/player.ts", "el.style.width = '3px';"),
            (
                "static/manifest.json",
                "{\n  \"theme_color\": \"#070605\"\n}",
            ),
            ("static/favicon.svg", "<svg><path fill=\"#1B365D\"/></svg>"),
            ("node_modules/x/y.css", ".b { color: red; }"),
            (
                "look-exempt",
                "static/favicon.svg the brand mark keeps its own colours\n",
            ),
        ]);
        let report = tree.generated(&["static/geometry.css"]).check().unwrap();
        let mut seen: Vec<(String, Rule)> = report
            .findings
            .iter()
            .map(|(p, f)| (slash(p), f.rule))
            .collect();
        seen.sort();
        assert_eq!(
            seen,
            vec![
                ("css/new-page.css".into(), Rule::Colour),
                ("frontend/src/player.ts".into(), Rule::ScriptStyle),
                ("static/manifest.json".into(), Rule::Colour),
                ("templates/page.html".into(), Rule::InlineStyle),
            ]
        );
    }

    #[test]
    fn a_missing_generated_sheet_refuses_the_check() {
        let (_d, tree) = tree_with(&[("css/a.css", ".a { color: var(--content); }")]);
        let err = tree.generated(&["static/palette.css"]).check().unwrap_err();
        assert!(matches!(err, TreeError::MissingGenerated(_)), "{err}");
    }

    #[test]
    fn an_exemption_needs_a_reason() {
        let (_d, tree) = tree_with(&[("look-exempt", "static/favicon.svg\n")]);
        assert!(matches!(
            tree.check().unwrap_err(),
            TreeError::ExemptWithoutReason { line: 1, .. }
        ));
    }

    /// Over the ceiling fails, under it is reported, and an unknown rule in the
    /// ceilings file is refused rather than ignored.
    #[test]
    fn ceilings_hold_the_count_and_only_move_down() {
        let (_d, tree) = tree_with(&[
            (
                "a.css",
                ".a { color: #fff; } .b { color: #000; } .c { padding: 2px; }",
            ),
            ("look-ceilings.toml", "[ceiling]\ncolour = 1\nlength = 3\n"),
        ]);
        let report = tree.check().unwrap();
        assert_eq!(report.over(), vec![(Rule::Colour, 2, 1)]);
        assert_eq!(report.stale(), vec![(Rule::Length, 1, 3)]);
        assert_eq!(
            report.measured_ceilings(),
            "[ceiling]\ncolour = 2\nlength = 1\n"
        );

        let (_d, bad) = tree_with(&[("look-ceilings.toml", "[ceiling]\ncolor = 1\n")]);
        assert!(matches!(bad.check().unwrap_err(), TreeError::Ceilings(_)));
    }

    /// A token one hand sheet defines and another reads is defined; one only a
    /// skipped directory defines is not.
    #[test]
    fn sheets_of_one_tree_read_each_others_tokens() {
        let (_d, tree) = tree_with(&[
            ("css/00-tokens.css", ":root { --track-gutter: 4rem; }"),
            (
                "css/10-day.css",
                ".day { padding-inline-start: var(--track-gutter); }",
            ),
            ("other/x.css", ":root { --elsewhere: 1rem; }"),
            ("css/20-x.css", ".x { margin: var(--elsewhere); }"),
        ]);
        let report = tree.skip(&["other"]).check().unwrap();
        let undefined: Vec<String> = report
            .findings
            .iter()
            .filter(|(_, f)| f.rule == Rule::UndefinedVar)
            .map(|(p, _)| slash(p))
            .collect();
        assert_eq!(undefined, vec!["css/20-x.css"]);
    }

    /// A sheet joined from the tree's own parts is not read, and the tokens its
    /// parts define are not generated tokens the parts restate.
    #[test]
    fn a_join_of_the_trees_own_parts_is_neither_checked_nor_generated() {
        let (_d, tree) = tree_with(&[
            (
                "css/05-core.css",
                ":root { --z-nav: 10; }\n.a { z-index: var(--z-nav); }",
            ),
            (
                "static/style.css",
                ":root { --z-nav: 10; }\n.a { z-index: var(--z-nav); color: #fff; }",
            ),
        ]);
        let report = tree.joined(&["static/style.css"]).check().unwrap();
        assert_eq!(report.findings, vec![]);
    }

    /// The tree's own description is what a build and a linter outside it
    /// both read, so they check the same files against the same tokens.
    #[test]
    fn look_tree_toml_describes_the_tree() {
        let (d, _) = tree_with(&[
            ("static/geometry.css", ":root { --gap: 1rem; }"),
            ("static/quasi-a1b2.js", "el.style.width = '3px';"),
            ("static/style.css", ".a { color: #fff; }"),
            (
                "css/a.css",
                ".a { padding: var(--gap); color: var(--content); margin: var(--x); }",
            ),
            ("crates/x/page.html", "<p style=\"color: red\">x</p>"),
            (
                "look-tree.toml",
                "generated = [\"static/geometry.css\", \"static/quasi-*.js\", \"static/none-*.js\"]\njoined = [\"static/style.css\"]\nskip = [\"crates\"]\nset_at_runtime = [\"--x\"]\nintents = true\n",
            ),
        ]);
        let report = Tree::load(d.path()).unwrap().check().unwrap();
        assert_eq!(report.findings, vec![]);
        assert_eq!(report.read, vec![PathBuf::from("css/a.css")]);
    }

    #[test]
    fn a_tree_with_no_description_generates_nothing() {
        let (d, _) = tree_with(&[("a.css", ".a { margin: var(--gap); }")]);
        let report = Tree::load(d.path()).unwrap().check().unwrap();
        assert_eq!(report.count(Rule::UndefinedVar), 1);
    }

    #[test]
    fn an_unknown_key_in_look_tree_toml_is_refused() {
        let (d, _) = tree_with(&[("look-tree.toml", "generate = [\"a.css\"]\n")]);
        assert!(Tree::load(d.path()).is_err());
    }

    #[test]
    fn an_exempt_pattern_matches_within_one_segment() {
        assert!(matches("static/patterns/*.svg", "static/patterns/dots.svg"));
        assert!(!matches(
            "static/patterns/*.svg",
            "static/patterns/deep/dots.svg"
        ));
        assert!(matches("mockups/", "mockups/weekly-review.html"));
        assert!(matches("media/logo-go*.svg", "media/logo-go-mark.svg"));
        assert!(!matches("media/logo-go*.svg", "media/logo.svg"));
    }
}