tw-cli 0.1.0

One command for a Markdoc corpus
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! `tw` -- one command for a Markdoc corpus.
mod dotenv;

/// Held by a test that changes `PATH` and by every test that runs a program
/// found on it (git): cargo runs tests on several threads.
#[cfg(test)]
pub(crate) static PATH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
mod extension;
mod external;
mod forge;
mod setup;
mod tools;

use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use markdoc_lint::{Corpus, Diagnostic, Severity, corpus, lint_document};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

#[derive(Parser)]
#[command(name = "tw", version, about = "One command for a Markdoc corpus")]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Lint the structure and the prose, and report both together.
    Check {
        /// The content root. Defaults to the corpus root: the nearest
        /// directory at or above the working directory that has .tooling/,
        /// when one has; else the nearest with tw.toml or markdoc-lint.toml;
        /// else the working directory. Paths given are read from the
        /// working directory.
        #[arg(long, value_name = "DIR")]
        root: Option<PathBuf>,

        /// One JSON object on stdout, for CI and for an editor.
        #[arg(long)]
        json: bool,

        /// Structure only: skip the prose pass.
        ///
        /// Measured on this corpus, the structural rules cost 0.15 s for one
        /// file and 0.32 s for all four thousand, while one file through the
        /// prose engine costs 1.5 s. A pre-commit hook wants the first and
        /// cannot afford the second, which is why the tiers are a flag and
        /// not a guess about how many files were staged.
        #[arg(long)]
        no_prose: bool,

        /// Threads for the prose pass. Capped by markdoc-prose itself.
        #[arg(long, value_name = "N")]
        jobs: Option<usize>,

        /// Only what git has staged. What the pre-commit hook runs.
        #[arg(long, conflicts_with = "paths")]
        staged: bool,

        /// Print the rules and what this corpus has done with them, and
        /// check nothing.
        ///
        /// Every convention rule is off until the corpus configures it, so
        /// a corpus with a typo in `markdoc-lint.toml` and a corpus with
        /// nothing to report both print a clean run. This is what tells
        /// them apart.
        #[arg(long, conflicts_with_all = ["staged", "paths"])]
        list_rules: bool,

        /// Files or directories. The whole corpus when none are given.
        #[arg(value_name = "PATH")]
        paths: Vec<PathBuf>,
    },

    /// Install the hooks, fetch the pinned tools, and say what else to do.
    Setup {
        #[arg(long, default_value = ".", value_name = "DIR")]
        root: PathBuf,
        /// Do not download anything.
        #[arg(long)]
        no_tools: bool,
    },

    /// Replace this binary with the newest release, then re-pin the tools.
    Update {
        #[arg(long, default_value = ".", value_name = "DIR")]
        root: PathBuf,
        /// Where releases of `tw` itself come from.
        #[arg(long, default_value = "markdoc-rs/tw", value_name = "OWNER/REPO")]
        repo: String,
    },

    /// Print a completion script for a shell.
    ///
    /// bash  : tw completions bash > /etc/bash_completion.d/tw
    /// zsh   : tw completions zsh > "${fpath[1]}/_tw"
    /// fish  : tw completions fish > ~/.config/fish/completions/tw.fish
    /// pwsh  : tw completions powershell >> $PROFILE
    #[command(verbatim_doc_comment)]
    Completions {
        #[arg(value_name = "SHELL")]
        shell: Shell,
    },

    /// Format the tags. Runs the pinned markdoc-ls.
    Fmt {
        #[arg(long, default_value = ".", value_name = "DIR")]
        root: PathBuf,
        /// Passed through to `markdoc-ls --format`.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Run the language server. Runs the pinned markdoc-ls.
    Lsp {
        #[arg(long, default_value = ".", value_name = "DIR")]
        root: PathBuf,
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Build and serve the site locally. Runs the site generator tw.toml
    /// names under [preview].
    Preview {
        /// Defaults to the corpus root, as for `tw check`.
        #[arg(long, value_name = "DIR")]
        root: Option<PathBuf>,
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Render the manuals. Runs the pinned markdoc-pdf.
    Build {
        #[arg(long, default_value = ".", value_name = "DIR")]
        root: PathBuf,
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Anything else: `tw foo` runs `tw-foo` from PATH, as git runs
    /// `git-foo`.
    ///
    /// Last, and that is the point: clap matches every built-in above
    /// before it reaches here, so an extension cannot shadow a command a
    /// hook depends on by being first on PATH. See `extension.rs`.
    #[command(external_subcommand)]
    External(Vec<String>),
}

/// Hand the terminal to another tool and do not come back.
///
/// On Unix this replaces the process, so the child owns the terminal outright
/// -- which matters for `tw preview`, a long-running server a writer stops
/// with Ctrl-C, and for `tw lsp`, where an editor is speaking JSON-RPC over
/// the pipes and a relay in the middle is a place for it to go wrong.
fn launch(path: &Path, root: &Path, args: &[String]) -> Result<ExitCode, String> {
    let mut command = std::process::Command::new(path);
    command.arg("--root").arg(root).args(args);
    hand_over(command, path)
}

/// `launch` for a command line that takes no `--root`: run as written, from
/// the corpus root.
fn launch_in(path: &Path, root: &Path, args: &[String]) -> Result<ExitCode, String> {
    let mut command = std::process::Command::new(path);
    command.args(args).current_dir(root);
    hand_over(command, path)
}

fn hand_over(mut command: std::process::Command, path: &Path) -> Result<ExitCode, String> {
    dotenv::apply(&mut command);

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        // Only returns on failure.
        let error = command.exec();
        Err(format!("{}: {error}", path.display()))
    }

    // On Windows `path` may be a `.cmd` -- `npm.cmd` for `run = ["npm", ...]`,
    // found through PATHEXT by `tools::which`. Rust's std starts a `.cmd` or
    // `.bat` through cmd.exe and escapes every argument for it; an argument
    // it cannot escape safely makes `status` fail with an error rather than
    // reach cmd.exe altered.
    #[cfg(not(unix))]
    {
        let status = command
            .status()
            .map_err(|e| format!("{}: {e}", path.display()))?;
        Ok(ExitCode::from(status.code().unwrap_or(1) as u8))
    }
}

/// What `git` says is staged, filtered to Markdown.
fn staged_markdown(root: &Path) -> Result<Vec<PathBuf>, String> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["diff", "--cached", "--name-only", "--diff-filter=ACM"])
        .output()
        .map_err(|e| format!("git: {e}"))?;
    if !out.status.success() {
        return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
    }
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter(|l| l.ends_with(".md"))
        .map(|l| root.join(l))
        .filter(|p| p.is_file())
        .collect())
}

fn main() -> ExitCode {
    // Listing PATH costs a read_dir per entry, and `tw check --staged` is
    // in pre-commit. So the only run that pays for discovery is the one
    // that asked a question discovery answers.
    let argv: Vec<String> = std::env::args().collect();
    if argv.len() == 2 && matches!(argv[1].as_str(), "help" | "--help" | "-h") {
        return help();
    }

    let cli = Cli::parse();
    // The corpus's `.env` (dotenv.rs), loaded before anything reads a token
    // or starts a program, from the root the command works on.
    let start = match &cli.command {
        Command::Check { root, .. } | Command::Preview { root, .. } => root.clone(),
        Command::Setup { root, .. }
        | Command::Update { root, .. }
        | Command::Fmt { root, .. }
        | Command::Lsp { root, .. }
        | Command::Build { root, .. } => Some(root.clone()),
        Command::Completions { .. } | Command::External(_) => None,
    };
    if !matches!(cli.command, Command::Completions { .. }) {
        let at = start
            .and_then(|r| r.canonicalize().ok())
            .or_else(|| std::env::current_dir().ok())
            .unwrap_or_else(|| PathBuf::from("."));
        // At the corpus root by the one rule `TW_ROOT` and `tw check` use
        // (`tools::corpus_root`), and only when it has `.tooling/`: outside a
        // corpus there is no `.env` to read -- the working directory's
        // belongs to some other project (`dotenv::for_run`).
        if let Err(e) = dotenv::init(&at) {
            eprintln!("tw: {e}");
            return ExitCode::from(2);
        }
    }

    match cli.command {
        Command::Check {
            root,
            json,
            no_prose,
            jobs,
            staged,
            list_rules,
            paths,
        } => {
            let root = corpus_root(root);
            if list_rules {
                report(rules(&root, json))
            } else {
                report(check_staged(&root, json, no_prose, jobs, staged, &paths))
            }
        }

        Command::Setup { root, no_tools } => {
            report(setup::run(&root, no_tools).map(|()| ExitCode::SUCCESS))
        }

        Command::Update { root, repo } => {
            report(setup::update(&root, &repo).map(|()| ExitCode::SUCCESS))
        }

        Command::Completions { shell } => {
            let mut command = Cli::command();
            let name = command.get_name().to_string();
            clap_complete::generate(shell, &mut command, name, &mut std::io::stdout());
            ExitCode::SUCCESS
        }

        Command::Fmt { root, args } => {
            report(launched(&tools::MARKDOC_LS, &root, "--format", &args))
        }
        Command::Lsp { root, args } => report(launched(&tools::MARKDOC_LS, &root, "", &args)),
        Command::Preview { root, args } => report(preview(&corpus_root(root), &args)),
        Command::Build { root, args } => report(launched(&tools::MARKDOC_PDF, &root, "", &args)),

        Command::External(args) => {
            let (root, config) = corpus();
            report(extension::run(&args, &root, &config))
        }
    }
}

/// `tw help`: clap's own, plus whatever is on PATH.
///
/// A list that stopped at the built-ins would be wrong in exactly the way
/// `--list-rules` exists to prevent one level down -- `tw xlate` works and
/// `tw help` not mentioning it is how a writer concludes it does not.
fn help() -> ExitCode {
    let mut command = Cli::command();
    let (root, config) = corpus();
    let found = extension::discover(&extension::pinned_dirs(&root, &config));
    if !found.is_empty() {
        let builtins: Vec<String> = command
            .get_subcommands()
            .map(|s| s.get_name().to_string())
            .collect();
        command = command.after_long_help(extension::help_section(&found, &builtins));
    }
    let _ = command.print_long_help();
    println!();
    ExitCode::SUCCESS
}

/// Where we are, and what the corpus said about extensions.
///
/// A malformed `tw.toml` is reported and then stepped over, which is the
/// opposite of what `tw check` does with one -- and right here. `tw help`
/// has to work on a corpus somebody is halfway through configuring, and
/// `tw xlate` failing with a config error about a file the extension never
/// reads would be a confusing way to say "that command is not installed".
fn corpus() -> (PathBuf, external::Config) {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let root = tools::corpus(&cwd);
    let config = external::Config::load(&root).unwrap_or_else(|e| {
        eprintln!("tw: {e}");
        external::Config::default()
    });
    (root, config)
}

/// `--root` as given, or else the corpus root (`tools::corpus_root`, the
/// one rule `TW_ROOT` and the `.env` follow too), so `tw check` and
/// `tw preview` work from anywhere inside the corpus.
///
/// The commands with a `--root` that defaults to `.` differ on purpose and
/// use it as given. `tw fmt`, `tw lsp` and `tw build` hand it to the tool
/// they run, which reads its own configuration from there, as an editor
/// that starts `tw lsp` in a folder expects. `tw setup` installs the hooks
/// in it (`core.hooksPath` is the work tree's). In all of them the pins,
/// `tw.toml` and the `.env` are still found at the corpus root above it by
/// this one rule.
fn corpus_root(root: Option<PathBuf>) -> PathBuf {
    root.unwrap_or_else(|| {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        tools::corpus(&cwd)
    })
}

/// 2 for misuse, 1 for findings. A caller that cannot tell a broken config
/// from a corpus with errors in it will treat the first as the second and
/// commit anyway.
fn report(result: Result<ExitCode, String>) -> ExitCode {
    match result {
        Ok(code) => code,
        Err(message) => {
            eprintln!("tw: {message}");
            ExitCode::from(2)
        }
    }
}

/// `tw preview`: whatever the corpus says builds its site.
///
/// A site generator is the corpus's choice, not `tw`'s, so `tw` names none:
/// `[preview] run` in `tw.toml` does, and `[tools]` pins it the way `tw`
/// pins its own. Read from the corpus root -- the directory that holds
/// `.tooling/` -- so `tw preview` works from anywhere inside the corpus.
fn preview(root: &Path, args: &[String]) -> Result<ExitCode, String> {
    let root = root
        .canonicalize()
        .map_err(|e| format!("{}: {e}", root.display()))?;
    let root = tools::corpus(&root);
    let config = external::Config::load(&root)?;
    let run = config.preview.run.clone().ok_or_else(|| {
        format!(
            "this corpus names no site generator for `tw preview`. Say which \
             program builds and serves it in {} at its root:\n  \
             [preview]\n  run = \"<program>\"      # run as <program> --root <root>\n  \
             run = [\"<program>\", \"<arg>\"]   # or a command line, run as written\n  \
             and pin it with a [tools.<program>] entry, or put it on PATH.",
            external::CONFIG_FILENAME
        )
    })?;
    match run {
        external::PreviewRun::Program(program) => {
            let path = external::resolve(&program, &root, &config)?;
            launch(&path, &root, args)
        }
        external::PreviewRun::Command(words) => {
            let Some((program, lead)) = words.split_first() else {
                return Err(format!(
                    "[preview] run in {} is an empty list: name the command that builds \
                     and serves the site.",
                    external::CONFIG_FILENAME
                ));
            };
            let path = external::resolve(program, &root, &config)?;
            let mut all = lead.to_vec();
            all.extend_from_slice(args);
            launch_in(&path, &root, &all)
        }
    }
}

fn launched(
    tool: &tools::Launched,
    root: &Path,
    lead: &str,
    args: &[String],
) -> Result<ExitCode, String> {
    let root = root
        .canonicalize()
        .map_err(|e| format!("{}: {e}", root.display()))?;
    let path = tool.resolve(&root)?;
    let mut all: Vec<String> = Vec::new();
    if !lead.is_empty() {
        all.push(lead.to_string());
    }
    all.extend_from_slice(args);
    launch(&path, &root, &all)
}

/// The rule set as this corpus has it.
///
/// `tw` names no rule here and knows none of them: the set, each rule's
/// summary, the ids it can emit and the configuration that turns it on all
/// come from `markdoc_lint::rules`, so a rule added there — or, later, one
/// loaded from somewhere else — appears without this function changing.
fn rules(root: &Path, json: bool) -> Result<ExitCode, String> {
    let root = root
        .canonicalize()
        .map_err(|e| format!("{}: {e}", root.display()))?;
    let config = markdoc_lint::Config::load(&root).map_err(|e| e.to_string())?;
    let status = markdoc_lint::rules::status(&config);
    let tw_config = external::Config::load(&root)?;

    if json {
        let externals: Vec<_> = tw_config
            .check
            .external
            .iter()
            .map(|e| {
                serde_json::json!({
                    "run": e.run,
                    "active": e.is_enabled(),
                    "severity_override": e.severity.map(|s| s.label()),
                })
            })
            .collect();
        let out = serde_json::json!({ "rules": status, "external": externals });
        println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());
        return Ok(ExitCode::SUCCESS);
    }

    for rule in &status {
        let state = if rule.disabled {
            "off, switched off"
        } else if !rule.configured {
            "off, not configured"
        } else {
            "on"
        };
        let severity = match rule.severity_override {
            Some(s) => format!(
                "{} (the rule says {})",
                s.label(),
                rule.info.default_severity.label()
            ),
            None => rule.info.default_severity.label().to_string(),
        };
        // Wide enough for the longest rule name there is, rather than for
        // the longest there was: a name that overflows pushes its whole row
        // out of line and the column stops being one.
        let width = status.iter().map(|r| r.info.name.len()).max().unwrap_or(0);
        println!("{:<width$} {state:<21} {severity}", rule.info.name);
        println!("    {}", rule.info.summary);
        // Which advice is useful depends on *why* it is off: a rule the
        // corpus switched off is changed in `[rules.…]`, not in the rule's
        // own section, and saying both at once helps nobody.
        if rule.disabled {
            println!(
                "    switched off by [rules.{}] enabled = false",
                rule.info.name
            );
        } else if let Some(by) = rule.info.configured_by
            && !rule.configured
        {
            println!("    turn it on with: {by}");
        }
        println!("    emits: {}", rule.info.diagnostics.join(", "));
        println!();
    }

    // A check that runs is a check this list has to show, whoever
    // implements it. `tw` cannot say what these emit -- the tool that owns
    // the format knows that and this one does not -- so it says what it
    // does know: the command, and whether it will run.
    if !tw_config.check.external.is_empty() {
        println!("asked as well, over --check --json (tw.toml):");
        for entry in &tw_config.check.external {
            let state = if entry.is_enabled() {
                "on"
            } else {
                "off, switched off"
            };
            println!("    {:<40} {state}", entry.command_line());
            if let Some(s) = entry.severity {
                println!("        every finding re-levelled to {}", s.label());
            }
        }
        println!();
    }

    // Said rather than implied. The prose pass is a second engine with a
    // second vocabulary, and a list that silently covered half of what
    // `tw check` reports would be worse than no list.
    eprintln!(
        "{} rule(s), {} active, {} external check(s). Prose findings come from \
         markdoc-prose, which is configured separately in markdoc-prose.toml.",
        status.len(),
        status.iter().filter(|r| r.active).count(),
        tw_config.active().count(),
    );
    Ok(ExitCode::SUCCESS)
}

/// `--staged` is `paths` that git chose. Nothing to check is success, not a
/// scan of the whole corpus: a commit touching no Markdown must not pay for
/// one, and a hook that silently widened its scope would be worse than slow.
fn check_staged(
    root: &Path,
    json: bool,
    no_prose: bool,
    jobs: Option<usize>,
    staged: bool,
    paths: &[PathBuf],
) -> Result<ExitCode, String> {
    if !staged {
        return check(root, json, no_prose, jobs, paths);
    }
    let files = staged_markdown(root)?;
    if files.is_empty() {
        return Ok(ExitCode::SUCCESS);
    }
    check(root, json, no_prose, jobs, &files)
}

/// Markdown under `root`, or under each path given, with the corpus's own
/// skip list applied.
///
/// The skip list is `markdoc-lint.toml`'s and not this command's. A second
/// idea about which files belong to the toolchain is the kind of thing that
/// drifts quietly -- it is why `translations/` is excluded here without `tw`
/// knowing which translation tool writes there.
///
/// A path named that is not there is an error, not nothing to check: a
/// typo'd file name in a hook or a script would otherwise pass as a clean
/// run of zero files.
fn targets(root: &Path, paths: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
    let is_markdown = |p: &Path| p.extension().and_then(|s| s.to_str()) == Some("md");

    if paths.is_empty() {
        return Ok(corpus::find_files(root, &is_markdown));
    }

    let mut out = Vec::new();
    for path in paths {
        let p = path.canonicalize().map_err(|e| {
            format!(
                "{}: {}",
                path.display(),
                if e.kind() == std::io::ErrorKind::NotFound {
                    "no such file or directory".to_string()
                } else {
                    e.to_string()
                }
            )
        })?;
        if p.is_dir() {
            out.extend(corpus::find_files(&p, &is_markdown));
        } else {
            out.push(p);
        }
    }
    Ok(out)
}

/// Corpus-relative, forward slashes, so a finding reads the same on every
/// machine and in CI.
fn rel_of(root: &Path, file: &Path) -> Option<String> {
    let rel = file.strip_prefix(root).ok()?;
    Some(rel.to_string_lossy().replace('\\', "/"))
}

fn default_jobs() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
}

fn check(
    root: &Path,
    json: bool,
    no_prose: bool,
    jobs: Option<usize>,
    paths: &[PathBuf],
) -> Result<ExitCode, String> {
    let root = root
        .canonicalize()
        .map_err(|e| format!("{}: {e}", root.display()))?;

    // A malformed config is fatal rather than ignored, in both passes.
    // Falling back to the defaults would turn a typo into "the linter
    // stopped finding things", which is the failure hardest to notice.
    let lint_config = markdoc_lint::Config::load(&root).map_err(|e| e.to_string())?;
    // Read even when the pass is skipped: a typo in markdoc-prose.toml
    // should fail the fast tier too, rather than wait for the slow one.
    let prose_config = markdoc_prose::Config::load(&root)?;
    // And the same for tw.toml, whose checks only run over a whole corpus:
    // a hook that checks one file should still refuse a broken config.
    let tw_config = external::Config::load(&root)?;

    let index = Corpus::load_with(&root, lint_config);

    // Read once, lint twice. Both passes want the same bytes, and reading a
    // four-thousand-file corpus twice is the easiest waste to avoid.
    let mut sources: Vec<(String, String)> = Vec::new();
    for file in targets(&root, paths)? {
        let Some(rel) = rel_of(&root, &file) else {
            continue;
        };
        if index.config.is_skipped(&rel) {
            continue;
        }
        let Ok(source) = std::fs::read_to_string(&file) else {
            continue;
        };
        sources.push((rel, source));
    }

    // Rules about the corpus's shape rather than about a document, once,
    // and only when the whole corpus was asked about. A pre-commit hook
    // runs over what is staged, and a finding about an empty directory is
    // not about the change somebody is making.
    let mut all: Vec<Diagnostic> = if paths.is_empty() {
        let mut corpus_wide = markdoc_lint::lint_corpus(&index);
        // Asked for the same reason and under the same condition: a nav
        // file names pages across a whole manual, so the question is not
        // about the file somebody staged either. Failures are fatal -- see
        // `external::run`.
        for entry in tw_config.active() {
            corpus_wide.extend(external::run(entry, &root, &tw_config)?);
        }
        corpus_wide
    } else {
        Vec::new()
    };
    // Every document on its own, on every core, in the order read.
    let linted = markdoc_lint::corpus::in_parallel(&sources, |(rel, source)| {
        lint_document(rel, source, &index).diagnostics
    });
    all.extend(linted.into_iter().flatten());

    // The prose pass is optional: a corpus with no markdoc-prose.toml gets
    // the structural rules and nothing else, rather than an error about a
    // file it never said it had.
    if prose_config.engine.enabled && !no_prose {
        let mut prose = markdoc_prose::Prose::new(&prose_config, &root)?;
        let jobs = jobs.unwrap_or_else(default_jobs);
        for diagnostics in prose
            .lint_many(&sources, jobs, |source| Some(source.clone()))
            .into_iter()
            .flatten()
        {
            all.extend(diagnostics);
        }
    }

    // Stable, and in the order a reader walks a file. `sort_by_key` is a
    // stable sort, so two findings on one line keep the order the passes
    // produced them in -- structure before prose, which is the order they
    // are worth reading in.
    all.sort_by_key(|d| {
        (
            d.file.clone(),
            d.span.map(|s| s.start_line).unwrap_or(0),
            d.span.map(|s| s.start_char).unwrap_or(0),
        )
    });

    let errors = all.iter().filter(|d| d.severity == Severity::Error).count();
    let warnings = all
        .iter()
        .filter(|d| d.severity == Severity::Warning)
        .count();

    if json {
        // One object, not a stream: a caller that wants to count has to read
        // the whole thing anyway, and a half-written stream after a crash
        // looks exactly like a clean run.
        let out = serde_json::json!({
            "files": sources.len(),
            "prose": !no_prose && prose_config.engine.enabled,
            "indexed": index.files,
            "errors": errors,
            "warnings": warnings,
            "diagnostics": all,
        });
        println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());
    } else {
        for d in &all {
            println!("{}", d.to_text());
        }
        eprintln!(
            "\n{} file(s) checked against an index of {}; {errors} error(s), {warnings} warning(s).",
            sources.len(),
            index.files
        );
    }

    Ok(if errors > 0 {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    })
}

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

    #[test]
    fn a_path_that_is_not_there_is_an_error_naming_it() {
        let d = std::env::temp_dir().join(format!("tw-targets-{}", std::process::id()));
        std::fs::create_dir_all(d.join("docs")).unwrap();
        std::fs::write(d.join("docs").join("a.md"), "# A\n").unwrap();
        let missing = d.join("does-not-exist.md");
        let err = targets(&d, &[d.join("docs").join("a.md"), missing.clone()]).unwrap_err();
        assert!(
            err.contains(&missing.display().to_string()) && err.contains("no such file"),
            "{err}"
        );
        // What is there is still found, file or directory.
        let found = targets(&d, &[d.join("docs")]).unwrap();
        assert_eq!(found.len(), 1);
        let _ = std::fs::remove_dir_all(&d);
    }
}