Skip to main content

htl_cli/
lib.rs

1//! htl CLI. Also built as `cargo-htl` so `cargo htl <verb>` works.
2//!
3//! - `htl check <paths...>`   type-check files or directories
4//! - `htl gen <file.tl>`      emit readable Lua (escape hatch)
5//! - `htl run <file.tl|.hb>`  type-check then execute (strict: type errors abort)
6//! - `htl build <dir>`        compile a tree of `.tl` into one stripped-bytecode bundle
7//! - `htl bundle info <.hb>`  print what a bundle records, without running it
8
9use htl::cache;
10mod junit;
11mod report;
12mod scaffold;
13
14/// Output format of every command that has `--format`. One enum, so its help must be
15/// true of all of them: `check` / `test` / `fix` put their text form on stderr (README,
16/// "Machine-readable output" says why), `cache status` / `bundle info` / `resolve` are
17/// reports and put it on stdout. Which stream is the README's to say, not this help's.
18#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
19enum Format {
20    /// Human-readable lines
21    Text,
22    /// One JSON document on stdout (README, "Machine-readable output":
23    /// https://github.com/ynishi/htl#machine-readable-output)
24    Json,
25}
26
27/// How `htl check` grains its cache. Separate from whether it caches at all, which is
28/// `--no-cache`.
29#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
30enum CacheModeArg {
31    /// One entry per module: an edit costs that module and what depends on it
32    PerModule,
33    /// One entry per run: any edit re-checks everything, a run with no edits reads one file
34    WholeRun,
35}
36
37#[derive(Subcommand)]
38enum TypesCmd {
39    /// Copy a library's declarations from teal-types into `types/`, and record which
40    /// commit they came from
41    Add {
42        /// The library as teal-types names it (`luasocket`, `lpeg`, …)
43        library: String,
44        /// Take them from a checkout of teal-types already on disk instead of fetching
45        #[arg(long)]
46        from: Option<PathBuf>,
47        /// Replace declarations that are already in `types/`
48        #[arg(long)]
49        force: bool,
50    },
51}
52
53#[derive(Subcommand)]
54enum PkgCmd {
55    /// Fetch every dependency `mlua-pkg.toml` declares and write `mlua-pkg.lock`
56    Install,
57    /// Write a dependency into `mlua-pkg.toml`; `install` is what fetches it
58    Add {
59        /// The name `require()` will use for it
60        name: String,
61        /// Remote git URL
62        git: String,
63        /// Pin to a tag: exact (`v1.0.0`), or a prefix that follows its patches (`v1.0`)
64        #[arg(long)]
65        tag: Option<String>,
66        /// Pin to a commit
67        #[arg(long)]
68        rev: Option<String>,
69        /// Track a branch (a build from it is not reproducible)
70        #[arg(long)]
71        branch: Option<String>,
72        /// The subdirectory `require()` resolves through, when it is not the one the
73        /// package declares
74        #[arg(long)]
75        entry: Option<PathBuf>,
76        /// Copy the package into this directory instead of linking it (manifest-relative,
77        /// rewritten by every install)
78        #[arg(long)]
79        target_dir: Option<PathBuf>,
80    },
81    /// Refresh dependencies, bump the pins that follow releases, then install
82    Update {
83        /// One dependency; every one when omitted
84        name: Option<String>,
85        /// Print the plan and write nothing
86        #[arg(long)]
87        dry_run: bool,
88        /// Bump exact tag pins too, to the highest release the remote has
89        #[arg(long)]
90        force: bool,
91    },
92    /// Remove cached packages the lockfile no longer refers to
93    Clean {
94        /// Remove the whole cache rather than the unreferenced entries
95        #[arg(long)]
96        all: bool,
97    },
98    /// Take a dependency's source into `patches/<dep>/`: a copy the project owns, edits
99    /// and commits, which install resolves the dependency from
100    Patch {
101        /// The dependency as `mlua-pkg.toml` names it
102        dep: String,
103        /// Refresh the copy even when it has uncommitted changes (they are discarded)
104        #[arg(long)]
105        force: bool,
106    },
107}
108
109#[derive(Subcommand)]
110enum CacheCmd {
111    /// Delete this project's stored check results
112    Clear {
113        /// A path inside the project; the store is found beside its htl.toml
114        path: Option<PathBuf>,
115    },
116    /// Report what the store holds
117    Status {
118        /// A path inside the project; the store is found beside its htl.toml
119        path: Option<PathBuf>,
120        /// Output format
121        #[arg(long, value_enum, default_value_t = Format::Text)]
122        format: Format,
123        /// List every entry rather than counting them by kind
124        #[arg(long)]
125        entries: bool,
126    },
127}
128
129#[derive(Subcommand)]
130enum BundleCmd {
131    /// Print what a bundle records: format, the htl that built it, payload kind, the Lua
132    /// its bytecode was compiled for, entry, modules, host-provided names
133    Info {
134        /// The `.hb` file
135        file: PathBuf,
136        /// Output format
137        #[arg(long, value_enum, default_value_t = Format::Text)]
138        format: Format,
139    },
140}
141
142impl From<CacheModeArg> for cache::Mode {
143    fn from(m: CacheModeArg) -> Self {
144        match m {
145            CacheModeArg::PerModule => cache::Mode::PerModule,
146            CacheModeArg::WholeRun => cache::Mode::WholeRun,
147        }
148    }
149}
150
151use anyhow::{Context, Result, bail};
152use clap::{Parser, Subcommand};
153use htl::BuildTarget;
154use htl::Htl;
155use htl::bundle::Bundle;
156// The project layer: which files a check walks, what it replays from the run cache and
157// what it keeps there, and which of a run's findings are said. Shared with `include_tl!`,
158// which asks the same of the same store.
159use htl::project;
160use std::fs;
161use std::path::{Path, PathBuf};
162use std::process::ExitCode;
163
164#[derive(Parser)]
165#[command(
166    name = "htl",
167    version,
168    about = "Teal, hidden: run / check / build .tl on mlua",
169    long_about = "\
170Teal, hidden: run / check / build .tl on mlua.
171
172htl is a toolchain for Teal, and a way to embed one. It type-checks `.tl` sources with \
173Teal's own checker, runs and tests them on an embedded mlua state, formats them, and \
174links them into a single stripped-bytecode bundle. A Rust host embeds the same engine, \
175so the scripts it ships are checked when the host is built rather than when its user \
176first runs one.
177
178The guide, with every command and what a project looks like:
179  https://github.com/ynishi/htl
180
181The API a Rust host holds — `include_tl!`, `#[host_module]`, the run cache:
182  https://docs.rs/htl"
183)]
184struct Cli {
185    #[command(subcommand)]
186    cmd: Cmd,
187}
188
189#[derive(Subcommand)]
190enum Cmd {
191    /// Type-check .tl files or directories (htl lints are reported as `lint:`)
192    ///
193    /// A module reached through `require` is checked with the file that required it, and
194    /// what has not changed is replayed from `.htl/`. README, "Lints":
195    /// https://github.com/ynishi/htl#lints-htl-check-include_tl
196    #[command(after_long_help = "\
197Examples:
198  htl check src                  every .tl under src/
199  htl check src --strict         every warn counts as deny: warnings and lints fail
200  htl check src --lint nil-index=deny,no-any=warn
201                                 one rule fails the run, another is advice
202  htl check src --lint -tl:hint  a warning kind of the Teal compiler silenced
203  htl check --list-lints         every rule with its default level, then exit
204
205Caching: https://github.com/ynishi/htl#caching
206")]
207    Check {
208        paths: Vec<PathBuf>,
209        /// Treat every `warn` as `deny`: warnings and lints fail the run
210        #[arg(long)]
211        strict: bool,
212        /// Rule levels over the defaults, e.g. `nil-index=deny,no-any=warn` (`-rule` =
213        /// allow, `+rule` = warn)
214        // A spec that silences a rule starts with `-`, and without this clap reads
215        // `--lint -contract` as a cluster of short flags and answers `unexpected argument
216        // '-c'`: the documented way to turn one rule off never reached the spec parser.
217        #[arg(long, allow_hyphen_values = true)]
218        lint: Option<String>,
219        /// List every lint rule with its default level and exit
220        #[arg(long)]
221        list_lints: bool,
222        /// Output format
223        #[arg(long, value_enum, default_value_t = Format::Text)]
224        format: Format,
225        /// Check even if an identical run is cached, and do not store this one
226        #[arg(long)]
227        no_cache: bool,
228        /// How the cache is grained; overrides `[cache] mode` in htl.toml
229        #[arg(long, value_enum)]
230        cache_mode: Option<CacheModeArg>,
231        /// Say why the cache was not used, and what this run did with it
232        #[arg(long)]
233        explain_cache: bool,
234    },
235    /// Run tests: `*_test.tl` and `tests/**/*.tl`, one isolated state per file
236    ///
237    /// README, "Tests": https://github.com/ynishi/htl#tests
238    #[command(after_long_help = "\
239Examples:
240  htl test                       every *_test.tl and tests/**/*.tl
241  htl test tests --filter parser only tests whose \"suite > name\" contains it
242  htl test --coverage --coverage-lines
243                                 which lines of each module the suite never reached
244  htl test --junit report.xml    also write the run as a JUnit report, for a CI
245")]
246    Test {
247        paths: Vec<PathBuf>,
248        /// Only run tests whose "suite > name" contains this substring
249        #[arg(long)]
250        filter: Option<String>,
251        /// Assertion library module consulted for the verdict (must expose `run(filter)`)
252        #[arg(long, default_value = htl::testing::DEFAULT_LIB)]
253        lib: String,
254        /// Lint rules on top of the defaults, e.g. `+no-any`
255        #[arg(long, allow_hyphen_values = true)]
256        lint: Option<String>,
257        /// Stop at the first failure (within a file, and across files)
258        #[arg(long)]
259        fail_fast: bool,
260        /// Print every test with its time (default: only failures and files)
261        #[arg(short, long)]
262        verbose: bool,
263        /// Only failures (with details), errors, and the summary line; no per-file `ok` lines
264        #[arg(short, long, conflicts_with = "verbose")]
265        quiet: bool,
266        /// Also print tests slower than this many milliseconds
267        #[arg(long, value_name = "MS")]
268        slow: Option<f64>,
269        /// Rewrite snapshots (`to_match_snapshot`) that differ instead of failing
270        #[arg(long)]
271        update: bool,
272        /// Report executed statements per `.tl` module the tests reached (slower: a line hook)
273        #[arg(long)]
274        coverage: bool,
275        /// With --coverage, also list the unexecuted line ranges of each module
276        #[arg(long, requires = "coverage")]
277        coverage_lines: bool,
278        /// Also write the coverage as an lcov tracefile here (implies --coverage)
279        #[arg(long, value_name = "FILE")]
280        lcov: Option<PathBuf>,
281        /// Also write the run as a JUnit XML report here, for a CI that reads test results
282        #[arg(long, value_name = "FILE")]
283        junit: Option<PathBuf>,
284        /// Seed the random stream tests draw from; printed every run, so a failure repeats
285        #[arg(long)]
286        seed: Option<u64>,
287        /// Output format
288        #[arg(long, value_enum, default_value_t = Format::Text)]
289        format: Format,
290        /// Check and generate every file even if a cached form is available, and store none
291        #[arg(long)]
292        no_cache: bool,
293        /// Say why the cache was not used, and what this run did with it
294        #[arg(long)]
295        explain_cache: bool,
296    },
297    /// Apply the fixes diagnostics carry (safe ones by default)
298    ///
299    /// README, "Fixing": https://github.com/ynishi/htl#fixing-htl-fix
300    #[command(after_long_help = "\
301Examples:
302  htl fix src                    apply the safe fixes to every .tl under src/
303  htl fix src --diff --dry-run   what would change, as a unified diff per file
304  htl fix src --rule forward-ref only that rule's fixes
305  htl fix src --unsafe           also the fixes that may change what the program does
306")]
307    Fix {
308        paths: Vec<PathBuf>,
309        /// Only fixes of these rules: any rule `htl check --list-lints` names, or
310        /// `forward-ref` / `tl:error`, the classes an error's fix is filed under
311        #[arg(long, value_delimiter = ',')]
312        rule: Vec<String>,
313        /// Also apply `unsafe` fixes (may change what the program does)
314        #[arg(long = "unsafe")]
315        unsafe_fixes: bool,
316        /// Compute and report, write nothing
317        #[arg(long)]
318        dry_run: bool,
319        /// Like --dry-run, and print a unified diff per file that would change
320        #[arg(long)]
321        diff: bool,
322        /// Fix files that git reports as modified or staged
323        #[arg(long)]
324        allow_dirty: bool,
325        /// Fix files that are not inside a git repository
326        #[arg(long)]
327        allow_no_vcs: bool,
328        /// Exit 1 when any file was changed (for CI)
329        #[arg(long)]
330        exit_non_zero_on_fix: bool,
331        /// Output format
332        #[arg(long, value_enum, default_value_t = Format::Text)]
333        format: Format,
334    },
335    /// Write the `.d.tl` files this project declares: those `#[host_module(dts = ..)]` /
336    /// `#[teal(dts = ..)]` ask for in a Rust crate, without building it, and the module
337    /// each `---@contract` type is declared in (check / run / test / build do both)
338    ///
339    /// Each declaration is reported as `wrote`, `unchanged`, or `not written`. The exit
340    /// code is about that last one and nothing else: non-zero when a declaration this
341    /// command was asked to write could not be written. A file already under `types/`
342    /// that no dependency ships any more is reported as `left in place` — nothing was
343    /// asked for, nothing is deleted, and the exit code does not move.
344    Dts {
345        /// Crate root or any path inside it (default: current directory)
346        dir: Option<PathBuf>,
347    },
348    /// Create a new Teal project directory
349    ///
350    /// README, "Layout of a project": https://github.com/ynishi/htl#layout-of-a-project-htl-new
351    #[command(after_long_help = "\
352Examples:
353  htl new hello                    src/main.tl, a module, tests/, mlua-pkg.toml
354  htl new hello --lib              a library: no entry script
355  htl new hello --embed            the same, plus a Rust host (--target bin)
356  htl new hello --target cdylib --lib
357                                   a library behind a C ABI, for a caller that is not Rust
358  htl new hello --embed --htl main
359                                   built against the unreleased htl (a git pin on main)
360  htl new hello --embed --htl path:../htl
361                                   built against a local checkout of this repository
362  htl new hello --no-x             without the htlx dependency the manifest gets by default
363
364Build targets: https://github.com/ynishi/htl#build-targets---target-name
365The cdylib target: https://github.com/ynishi/htl#the-cdylib-target---target-cdylib
366")]
367    New {
368        name: String,
369        /// Library only (no src/main.tl)
370        #[arg(long)]
371        lib: bool,
372        /// Also emit a Rust host: shorthand for --target bin
373        #[arg(long)]
374        embed: bool,
375        /// What will run this project's output: a target writes Cargo.toml + src/lib.rs
376        /// (the #[host_module], the embedded module, preload) and, when there is an entry
377        /// script, a thin src/main.rs
378        #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
379        target: Option<String>,
380        /// The htl the project depends on: `main`, or `path:<checkout>`. Without it, the
381        /// htl this binary was built with — its version on crates.io, or the checkout it
382        /// was built in
383        #[arg(long, value_name = "REQ")]
384        htl: Option<String>,
385        /// Leave the htlx (htl-x collections) dependency out of mlua-pkg.toml
386        #[arg(long)]
387        no_x: bool,
388    },
389    /// Fill in the scaffold files that are missing in an existing directory
390    Init {
391        dir: Option<PathBuf>,
392        #[arg(long)]
393        lib: bool,
394        /// Shorthand for --target bin
395        #[arg(long)]
396        embed: bool,
397        /// Fill in this target's files, and report the ones that were already there
398        #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
399        target: Option<String>,
400        /// The htl the project depends on: `main`, or `path:<checkout>`. Without it, the
401        /// htl this binary was built with — its version on crates.io, or the checkout it
402        /// was built in
403        #[arg(long, value_name = "REQ")]
404        htl: Option<String>,
405        /// Leave the htlx (htl-x collections) dependency out of mlua-pkg.toml
406        #[arg(long)]
407        no_x: bool,
408    },
409    /// Package management at the nearest `mlua-pkg.toml` project root: install / add /
410    /// update / clean / patch, through mlua-pkg's library rather than its binary
411    Pkg {
412        #[command(subcommand)]
413        cmd: PkgCmd,
414    },
415    /// Bring declarations for a library into `types/`
416    Types {
417        #[command(subcommand)]
418        cmd: TypesCmd,
419    },
420    /// Manage the check cache
421    ///
422    /// README, "Caching": https://github.com/ynishi/htl#caching
423    Cache {
424        #[command(subcommand)]
425        cmd: CacheCmd,
426    },
427    /// Format .tl files in place (indentation / blank lines / trailing whitespace)
428    Fmt {
429        paths: Vec<PathBuf>,
430        /// Do not write; exit 1 if any file would change
431        #[arg(long)]
432        check: bool,
433        /// Indent width in spaces (default: `[fmt] indent` in htl.toml, else 3)
434        #[arg(long)]
435        indent: Option<usize>,
436    },
437    /// Emit readable Lua for one .tl file (escape hatch)
438    Gen {
439        file: PathBuf,
440        #[arg(short, long)]
441        out: Option<PathBuf>,
442    },
443    /// Run a .tl script or a .hb bundle
444    Run {
445        file: PathBuf,
446        #[arg(trailing_var_arg = true)]
447        args: Vec<String>,
448    },
449    /// Compile a directory of .tl into a stripped-bytecode bundle
450    ///
451    /// A bundle is the `hb` target, so this refuses a project whose `[build] target` is
452    /// another one — a `bin` or a `cdylib` is built with `cargo build`.
453    ///
454    /// README, "Bundles": https://github.com/ynishi/htl#bundles-htl-build
455    #[command(after_long_help = "\
456Examples:
457  htl build src/main.tl -o app.hb
458                                 the entry's require closure, as one bundle
459  htl build src/main.tl -o app.hb --debug
460                                 keep line numbers and local names in the bytecode
461  htl build src/main.tl -o app.hb --host mymod
462                                 leave a module the host provides out of the bundle
463  htl run app.hb                 run what was built
464
465Caching: https://github.com/ynishi/htl#caching
466")]
467    Build {
468        /// Entry `.tl` file: it and everything it requires are bundled, replaying from
469        /// the run cache what still holds (a directory bundles every `.tl` under it, the
470        /// older snapshot form, which is not cached)
471        entry: PathBuf,
472        #[arg(short, long, default_value = "app.hb")]
473        out: PathBuf,
474        /// Entry module name when `entry` is a directory
475        #[arg(short, long, default_value = "main")]
476        main: String,
477        /// Keep debug info (line numbers, local names) in the bytecode
478        #[arg(long)]
479        debug: bool,
480        /// Store generated Lua source instead of bytecode: for a big-endian target, a Lua
481        /// with non-default number types, or a bundle that must outlive a Lua upgrade
482        #[arg(long)]
483        source: bool,
484        /// Modules to bundle that only a dynamic require reaches (also `[build] extra`)
485        #[arg(long, value_delimiter = ',')]
486        extra: Vec<String>,
487        /// Modules the host provides (also `[build] host`; `.d.tl`-only modules are implied)
488        #[arg(long, value_delimiter = ',')]
489        host: Vec<String>,
490        /// Generate every module even if its cached form still holds, and do not store
491        /// (the directory form is never cached)
492        #[arg(long)]
493        no_cache: bool,
494        /// Say why the cache was not used, and what this run did with it
495        #[arg(long)]
496        explain_cache: bool,
497    },
498    /// Report what no entry's `require` closure reaches: modules, and `mlua-pkg.toml`
499    /// dependencies
500    ///
501    /// README, "Unused": https://github.com/ynishi/htl#unused-htl-unused
502    #[command(after_long_help = "\
503Examples:
504  htl unused                     modules and dependencies no entry reaches
505  htl unused --exit-non-zero-on-unused
506                                 the same report, and a non-zero exit for a CI
507  htl unused --format json       the same report as one JSON document
508")]
509    Unused {
510        /// What to report on (default: the working directory). The walk is the project's
511        /// either way: a module reached only from `tests/` is reached
512        paths: Vec<PathBuf>,
513        /// Output format
514        #[arg(long, value_enum, default_value_t = Format::Text)]
515        format: Format,
516        /// Exit 1 when anything is reported (for CI)
517        #[arg(long)]
518        exit_non_zero_on_unused: bool,
519        /// Build the graph from a fresh check even if a cached one is available, and
520        /// store none
521        #[arg(long)]
522        no_cache: bool,
523        /// Say why the cache was not used, and what this run did with it
524        #[arg(long)]
525        explain_cache: bool,
526    },
527    /// Which file `require("<module>")` resolves to, and what that hides
528    ///
529    /// The whole chain in search order: what is read, what is reachable and not read, and
530    /// which crate or dependency each one came from. An override on the search path is the
531    /// mechanism working, and this is how to see it. README, "Which file a name resolves
532    /// to": https://github.com/ynishi/htl#which-file-a-name-resolves-to-htl-resolve
533    #[command(after_long_help = "\
534Examples:
535  htl resolve mq                 the chain for require(\"mq\")
536  htl resolve socket.http        a name with dots, as a require spells it
537  htl resolve mq --format json   the same rows as one JSON document
538
539Exits 1 when the name resolves to nothing, so a script can ask.
540
541`htl.test` is not on a project's search path: `htl test` preloads it into the state it
542runs, and the declarations behind it come from the binary rather than the project.
543")]
544    Resolve {
545        /// The module name a `require` would spell (`mq`, `socket.http`)
546        module: String,
547        /// A path inside the project (default: the working directory)
548        path: Option<PathBuf>,
549        /// Output format
550        #[arg(long, value_enum, default_value_t = Format::Text)]
551        format: Format,
552    },
553    /// Read a `.hb` bundle without running it
554    ///
555    /// README, "Bundles": https://github.com/ynishi/htl#bundles-htl-build
556    Bundle {
557        #[command(subcommand)]
558        cmd: BundleCmd,
559    },
560}
561
562/// The command line as clap holds it, before any argument is parsed.
563///
564/// The help is documentation, and the tests that keep it from rotting read it from here
565/// rather than from a copy kept beside them: they walk this tree and ask each command,
566/// argument and value for the strings it would print.
567pub fn command() -> clap::Command {
568    <Cli as clap::CommandFactory>::command()
569}
570
571pub fn run() -> ExitCode {
572    // Invoked as `cargo htl ...` -> argv = ["cargo-htl", "htl", ...]; drop the "htl".
573    let mut argv: Vec<String> = std::env::args().collect();
574    let is_cargo = Path::new(&argv[0])
575        .file_stem()
576        .and_then(|s| s.to_str())
577        .map(|s| s == "cargo-htl")
578        .unwrap_or(false);
579    if is_cargo && argv.get(1).map(String::as_str) == Some("htl") {
580        argv.remove(1);
581    }
582    match real_main(Cli::parse_from(argv)) {
583        Ok(code) => code,
584        Err(e) => {
585            eprintln!("htl: {e:#}");
586            ExitCode::from(2)
587        }
588    }
589}
590
591fn real_main(cli: Cli) -> Result<ExitCode> {
592    match cli.cmd {
593        Cmd::Check {
594            paths,
595            strict,
596            lint,
597            list_lints,
598            format,
599            no_cache,
600            cache_mode,
601            explain_cache,
602        } => cmd_check(
603            &paths,
604            lint.as_deref(),
605            CheckFlags {
606                strict,
607                list_lints,
608                json: format == Format::Json,
609                use_cache: !no_cache,
610                cache_mode: cache_mode.map(Into::into),
611                explain: explain_cache,
612            },
613        ),
614        Cmd::Fmt {
615            paths,
616            check,
617            indent,
618        } => cmd_fmt(&paths, check, indent),
619        Cmd::Test {
620            paths,
621            filter,
622            lib,
623            lint,
624            fail_fast,
625            verbose,
626            quiet,
627            slow,
628            update,
629            coverage,
630            coverage_lines,
631            lcov,
632            junit,
633            seed,
634            format,
635            no_cache,
636            explain_cache,
637        } => cmd_test(
638            &paths,
639            filter.as_deref(),
640            &lib,
641            lint.as_deref(),
642            TestFlags {
643                fail_fast,
644                verbose,
645                quiet,
646                slow,
647                update,
648                coverage: coverage || lcov.is_some(),
649                coverage_lines,
650                lcov,
651                junit,
652                json: format == Format::Json,
653                no_cache,
654                explain: explain_cache,
655                seed,
656            },
657        ),
658        Cmd::Pkg { cmd } => match cmd {
659            PkgCmd::Install => cmd_pkg_install(),
660            PkgCmd::Add {
661                name,
662                git,
663                tag,
664                rev,
665                branch,
666                entry,
667                target_dir,
668            } => cmd_pkg_add(htl::pkg::mlua_pkg::ops::AddSpec {
669                name,
670                git,
671                tag,
672                rev,
673                branch,
674                entry,
675                target_dir,
676            }),
677            PkgCmd::Update {
678                name,
679                dry_run,
680                force,
681            } => cmd_pkg_update(htl::pkg::mlua_pkg::ops::UpdateOpts {
682                name,
683                dry_run,
684                force,
685            }),
686            PkgCmd::Clean { all } => cmd_pkg_clean(all),
687            PkgCmd::Patch { dep, force } => cmd_pkg_patch(&dep, force),
688        },
689        Cmd::Types { cmd } => match cmd {
690            TypesCmd::Add {
691                library,
692                from,
693                force,
694            } => cmd_types_add(&library, from.as_deref(), force),
695        },
696        Cmd::Cache { cmd } => match cmd {
697            CacheCmd::Clear { path } => cmd_cache_clear(path.as_deref()),
698            CacheCmd::Status {
699                path,
700                format,
701                entries,
702            } => cmd_cache_status(path.as_deref(), format == Format::Json, entries),
703        },
704        Cmd::Dts { dir } => cmd_dts(dir.as_deref()),
705        Cmd::New {
706            name,
707            lib,
708            embed,
709            target,
710            htl,
711            no_x,
712        } => cmd_new(&name, lib, embed, target.as_deref(), htl.as_deref(), no_x),
713        Cmd::Init {
714            dir,
715            lib,
716            embed,
717            target,
718            htl,
719            no_x,
720        } => cmd_init(
721            dir.as_deref(),
722            lib,
723            embed,
724            target.as_deref(),
725            htl.as_deref(),
726            no_x,
727        ),
728        Cmd::Gen { file, out } => cmd_gen(&file, out.as_deref()),
729        Cmd::Run { file, args } => cmd_run(&file, &args),
730        Cmd::Fix {
731            paths,
732            rule,
733            unsafe_fixes,
734            dry_run,
735            diff,
736            allow_dirty,
737            allow_no_vcs,
738            exit_non_zero_on_fix,
739            format,
740        } => cmd_fix(
741            &paths,
742            FixFlags {
743                rule,
744                unsafe_fixes,
745                dry_run: dry_run || diff,
746                diff,
747                allow_dirty,
748                allow_no_vcs,
749                exit_non_zero_on_fix,
750                json: format == Format::Json,
751            },
752        ),
753        Cmd::Build {
754            entry,
755            out,
756            main,
757            debug,
758            source,
759            extra,
760            host,
761            no_cache,
762            explain_cache,
763        } => cmd_build(
764            &entry,
765            &out,
766            &main,
767            htl::link::LinkOptions {
768                debug,
769                source,
770                extra,
771                host,
772            },
773            BuildCache {
774                use_cache: !no_cache,
775                explain: explain_cache,
776            },
777        ),
778        Cmd::Unused {
779            paths,
780            format,
781            exit_non_zero_on_unused,
782            no_cache,
783            explain_cache,
784        } => cmd_unused(
785            &paths,
786            UnusedFlags {
787                json: format == Format::Json,
788                fail_on_unused: exit_non_zero_on_unused,
789                use_cache: !no_cache,
790                explain: explain_cache,
791            },
792        ),
793        Cmd::Resolve {
794            module,
795            path,
796            format,
797        } => cmd_resolve(&module, path.as_deref(), format == Format::Json),
798        Cmd::Bundle { cmd } => match cmd {
799            BundleCmd::Info { file, format } => cmd_bundle_info(&file, format == Format::Json),
800        },
801    }
802}
803
804/// The reporting layer, for the commands that report without a `--format` of their own.
805///
806/// `htl check` and `htl test` hand their findings to a [`project::Sink`] over a
807/// [`report::Out`]; `gen` / `run` / `build` used to loop `eprintln!` over the three
808/// vectors themselves, so the same finding read differently depending on which verb was
809/// typed. They come through here instead, and there is one renderer again.
810///
811/// One sink per command run, not per file: what the layer decides once per run — a
812/// dependency's error said once, and never on behalf of a file the run checks itself —
813/// is then once per *command*, which is what `htl build` over a closure of modules wants.
814fn text_sink() -> project::Sink<report::Out> {
815    project::Sink::new(report::Out::new(false))
816}
817
818/// (Re)generate the `.d.tl` files this project declares: the ones a Rust crate's
819/// `#[host_module]` / `#[derive(TealRecord)]` ask for, so the checker sees Rust-side
820/// modules before any `cargo build`, and the module each `---@contract` type is declared
821/// in, which is what an outside author writes their modules against. Quiet unless
822/// something was written.
823///
824/// A contract that could not be published is said here, on every command that generates:
825/// `htl check` reports it again as a lint (which `strict` makes fatal) and `htl dts`
826/// exits non-zero on it, but `run` / `test` / `build` have neither, and a declaration
827/// that is quietly not written is one an outside author finds missing later.
828fn auto_dts(start: &Path) -> Result<()> {
829    let mut project = None;
830    if let Some((root, _, cfg)) = load_config(start)? {
831        let (contracts, _) = htl::contract::resolve(&root, &cfg);
832        let (results, problems) = htl::contract::publish(&root, &contracts);
833        announce_dts(&results, &root);
834        for p in &problems {
835            eprintln!("dts: {p}");
836        }
837        project = Some(root);
838    }
839    let Some(root) = htl::dts::find_cargo_package_root(start) else {
840        return Ok(());
841    };
842    let results = htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("htl dts: {e}"))?;
843    announce_dts(&results, &root);
844    let types_root = project.unwrap_or_else(|| root.clone());
845    let report = dep_dts(&root, &types_root);
846    announce_dts(&report.written, &types_root);
847    announce_dep_report(&report, "dts: ");
848    Ok(())
849}
850
851/// What `htl dts` has to say about the declarations its dependencies ship. Three kinds,
852/// kept apart because they mean three different things to the reader and to the exit code
853/// — which is the distinction the single `[htl <rule>]` suffix they all used to carry was
854/// hiding. None of them is a lint: no rule name, nothing to configure or silence, and
855/// nothing that reaches the `Sink`, so `htl check` neither counts one nor carries one in
856/// `--format json` — it prints them, prefixed `dts:`, exactly as this command does.
857#[derive(Default)]
858struct DepReport {
859    /// `(target, written)` pairs, in the shape the rest of the report prints.
860    written: Vec<(PathBuf, bool)>,
861    /// Asked for and not written. This, and only this, is what `htl dts` exits non-zero on.
862    not_written: Vec<String>,
863    /// Under `types/` and no longer shipped by anything. Reported, never deleted, and it
864    /// fails nothing: what the file is for is the project's to say.
865    left_in_place: Vec<String>,
866    /// The crate graph would not resolve, so nothing was asked for — cargo could not be
867    /// run, or the project's lockfile does not cover its manifest and the graph is read
868    /// with `--locked`. Either way the committed declarations stand and the check that
869    /// follows names the module if one is missing, which is why this fails nothing.
870    unresolved: Option<String>,
871}
872
873/// Materialise the declarations this project's dependencies ship, under
874/// `<types_root>/types/<crate>/`, and report on what happened to each.
875///
876/// The graph comes from `cargo metadata`, so this costs a subprocess on every command that
877/// generates. Nothing is built, and nothing is downloaded for dependencies already fetched.
878fn dep_dts(cargo_root: &Path, types_root: &Path) -> DepReport {
879    let decls = match htl::dep_dts::resolve(cargo_root) {
880        Ok(d) => d,
881        Err(e) => {
882            return DepReport {
883                unresolved: Some(e),
884                ..DepReport::default()
885            };
886        }
887    };
888    // Orphans before materialising: the note beside a crate's declarations is what says
889    // which crate they came from, and the write below rewrites it.
890    let left_in_place = htl::dep_dts::orphans(types_root, &decls);
891    let (written, not_written) = htl::dep_dts::materialise(types_root, &decls);
892    DepReport {
893        written,
894        not_written,
895        left_in_place,
896        unresolved: None,
897    }
898}
899
900/// The three report lists, each said as what it is. `wrote` / `unchanged` name what
901/// happened to a declaration, and so do these: a reader who has never heard the words
902/// `shipped-declaration` or `orphaned-declaration` can still tell which line failed the
903/// command and which one is a file sitting there to decide about.
904fn announce_dep_report(report: &DepReport, prefix: &str) {
905    for p in &report.not_written {
906        eprintln!("{prefix}not written: {p}");
907    }
908    for p in &report.left_in_place {
909        eprintln!("{prefix}left in place: {p}");
910    }
911    if let Some(e) = &report.unresolved {
912        eprintln!("{prefix}{e}");
913    }
914}
915
916fn announce_dts(results: &[(PathBuf, bool)], root: &Path) {
917    for (target, written) in results {
918        if *written {
919            eprintln!(
920                "dts: wrote {}",
921                target.strip_prefix(root).unwrap_or(target).display()
922            );
923        }
924    }
925}
926
927fn cmd_dts(dir: Option<&Path>) -> Result<ExitCode> {
928    let start = match dir {
929        Some(d) => d.to_path_buf(),
930        None => std::env::current_dir()?,
931    };
932    // The contract types first: a project may publish one without having a Rust host at
933    // all, and the `bail!` below would then be wrong about there being nothing to do.
934    let mut results = Vec::new();
935    let mut failed = false;
936    let mut project = None;
937    if let Some((croot, _, cfg)) = load_config(&start)? {
938        let (contracts, _) = htl::contract::resolve(&croot, &cfg);
939        let (published, problems) = htl::contract::publish(&croot, &contracts);
940        for p in &problems {
941            eprintln!("  {p}");
942        }
943        // Asked to generate and did not: the command says so in its exit code, or a CI
944        // step that regenerates declarations would pass having written nothing.
945        failed = !problems.is_empty();
946        results.extend(published);
947        project = Some(croot);
948    }
949    let code = |failed: bool| {
950        if failed {
951            ExitCode::FAILURE
952        } else {
953            ExitCode::SUCCESS
954        }
955    };
956    let Some(root) = htl::dts::find_cargo_package_root(&start) else {
957        if results.is_empty() && !failed {
958            bail!(
959                "no Cargo.toml with a [package] section, and no ---@contract type to publish, \
960                 at or above {}",
961                start.display()
962            );
963        }
964        report_dts(&results, &start);
965        return Ok(code(failed));
966    };
967    results.extend(htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("{e}"))?);
968    let types_root = project.unwrap_or_else(|| root.clone());
969    let report = dep_dts(&root, &types_root);
970    announce_dep_report(&report, "  ");
971    // An orphan, and a graph that would not resolve, are reports. A declaration asked for
972    // and not written is a failure, the same as a contract that could not be published.
973    failed = failed || !report.not_written.is_empty();
974    results.extend(report.written);
975    report_dts(&results, &root);
976    Ok(code(failed))
977}
978
979fn report_dts(results: &[(PathBuf, bool)], root: &Path) {
980    let mut written = 0usize;
981    for (target, w) in results {
982        let rel = target.strip_prefix(root).unwrap_or(target).display();
983        eprintln!("  {} {}", if *w { "wrote    " } else { "unchanged" }, rel);
984        written += usize::from(*w);
985    }
986    eprintln!(
987        "htl dts: {} declaration(s) from {}, {} written",
988        results.len(),
989        root.display(),
990        written
991    );
992}
993
994/// If `start` is inside an `mlua-pkg.toml` project, expose its vendored deps to the
995/// checker / strict searcher. Returns the project when found.
996fn apply_project(h: &Htl, start: &Path) -> Result<Option<htl::pkg::Project>> {
997    let Some(p) = htl::pkg::Project::find(start) else {
998        return Ok(None);
999    };
1000    h.apply_project(&p)?;
1001    Ok(Some(p))
1002}
1003
1004/// What the run wrote, and — when a target was asked for by name — what it left alone. The
1005/// kept list is what makes `htl init --target bin` on an older project say which of that
1006/// target's files were already there instead of skipping them in silence.
1007fn report_scaffold(dir: &Path, written: &[PathBuf], kept: &[PathBuf]) {
1008    let rel = |p: &PathBuf| p.strip_prefix(dir).unwrap_or(p).display().to_string();
1009    for p in written {
1010        eprintln!("  created {}", rel(p));
1011    }
1012    for p in kept {
1013        eprintln!("  kept    {} (already there)", rel(p));
1014    }
1015    if kept.is_empty() {
1016        eprintln!(
1017            "htl: {} file(s) written under {}",
1018            written.len(),
1019            dir.display()
1020        );
1021    } else {
1022        eprintln!(
1023            "htl: {} file(s) written, {} kept under {}",
1024            written.len(),
1025            kept.len(),
1026            dir.display()
1027        );
1028    }
1029}
1030
1031fn cmd_new(
1032    name: &str,
1033    lib: bool,
1034    embed: bool,
1035    target: Option<&str>,
1036    htl: Option<&str>,
1037    no_x: bool,
1038) -> Result<ExitCode> {
1039    let dir = PathBuf::from(name);
1040    let pkg_name = dir
1041        .file_name()
1042        .and_then(|s| s.to_str())
1043        .ok_or_else(|| anyhow::anyhow!("invalid project name: {name}"))?
1044        .to_string();
1045    // Before the directory is touched: an unknown target, or one that disagrees with
1046    // --lib, fails here and leaves nothing behind. So does an htl this scaffold does not
1047    // write for — a release by number — so it is settled first too.
1048    let target = scaffold::resolve_target(target, embed, lib)?;
1049    let htl = scaffold::HtlPin::parse(htl)?;
1050    let opts = scaffold::Options {
1051        lib,
1052        target,
1053        htl,
1054        no_x,
1055    };
1056    let done = scaffold::scaffold(&dir, &pkg_name, &opts, true)?;
1057    report_scaffold(&dir, &done.written, &[]);
1058    // The manifest names a dependency: the fetch comes before the first test, or the
1059    // first test is a `module not found`.
1060    let fetch = if opts.writes_htlx() {
1061        "htl pkg install && "
1062    } else {
1063        ""
1064    };
1065    // The window target's first build needs two files nothing has written yet: `htl check`
1066    // materialises the dependency's declaration as `types/htl-mq/mq.d.tl` (from its
1067    // `[package.metadata.htl] dts`) and writes `src/fx.d.tl` from the host module, and
1068    // `cargo build` reads the first of them when `include_bundle!` links `mq`. So the
1069    // check comes before the run rather than after it.
1070    let then = match opts.target.map(|t| t.target) {
1071        Some(BuildTarget::Window) => "htl check . && cargo run",
1072        _ => "htl test",
1073    };
1074    eprintln!("next: cd {} && {fetch}{then}", dir.display());
1075    Ok(ExitCode::SUCCESS)
1076}
1077
1078fn cmd_init(
1079    dir: Option<&Path>,
1080    lib: bool,
1081    embed: bool,
1082    target: Option<&str>,
1083    htl: Option<&str>,
1084    no_x: bool,
1085) -> Result<ExitCode> {
1086    let dir = match dir {
1087        Some(d) => d.to_path_buf(),
1088        None => std::env::current_dir()?,
1089    };
1090    let abs = std::fs::canonicalize(&dir).unwrap_or(dir.clone());
1091    let name = abs
1092        .file_name()
1093        .and_then(|s| s.to_str())
1094        .ok_or_else(|| anyhow::anyhow!("cannot derive a project name from {}", abs.display()))?
1095        .to_string();
1096    let asked_for_a_target = target.is_some() || embed;
1097    let target = scaffold::resolve_target(target, embed, lib)?;
1098    let htl = scaffold::HtlPin::parse(htl)?;
1099    let opts = scaffold::Options {
1100        lib,
1101        target,
1102        htl,
1103        no_x,
1104    };
1105    let done = scaffold::scaffold(&dir, &name, &opts, false)?;
1106    // A target was named: say what it would have written and found already there. Without
1107    // one the old one-liner stands, so a plain re-run does not list the whole tree.
1108    let kept: &[PathBuf] = if asked_for_a_target { &done.kept } else { &[] };
1109    if done.written.is_empty() && kept.is_empty() {
1110        eprintln!("htl init: nothing to do, all scaffold files already exist");
1111    } else {
1112        report_scaffold(&dir, &done.written, kept);
1113    }
1114    Ok(ExitCode::SUCCESS)
1115}
1116
1117/// The project `htl pkg` acts on: the nearest one above the working directory.
1118///
1119/// mlua-pkg reports a missing manifest as an I/O error that does not name the file, and the
1120/// path htl looked for is the whole of the answer, so it is checked here.
1121fn pkg_project() -> Result<htl::pkg::Project> {
1122    let cwd = std::env::current_dir()?;
1123    htl::pkg::Project::find(&cwd).with_context(|| {
1124        format!(
1125            "no {} above {}: `htl pkg` runs in a project",
1126            htl::pkg::MANIFEST_NAME,
1127            cwd.display()
1128        )
1129    })
1130}
1131
1132/// `htl pkg install`: fetch what the manifest declares, then bring in what the deps publish.
1133fn cmd_pkg_install() -> Result<ExitCode> {
1134    let project = pkg_project()?;
1135    let report = project.install()?;
1136    report_install(&report, &project);
1137    // Re-read the project: install wrote the lockfile the two reports below are read from.
1138    // A dep publishes its declarations at `types/` in its package root, which is not where
1139    // `require` looks, so they are copied in for the checker to see.
1140    let project = htl::pkg::Project::at(&project.root);
1141    report_types_sync(&project.sync_types()?, &project.root);
1142    report_patch_drift(&project);
1143    Ok(ExitCode::SUCCESS)
1144}
1145
1146/// What install did, in the shape the other reports use. The library prints nothing.
1147fn report_install(report: &htl::pkg::mlua_pkg::ops::InstallReport, project: &htl::pkg::Project) {
1148    use htl::pkg::mlua_pkg::ops::Placement;
1149    for w in &report.warnings {
1150        // A patch that was not used is reported below in htl's own verbs, where both ways
1151        // out are named. The library's line points at `mlua-pkg patch --force`, which
1152        // rebuilds the copy without asking git whether what is in it was committed.
1153        if w.contains("patch_dir") && w.contains("not used") {
1154            continue;
1155        }
1156        eprintln!("warning: {w}");
1157    }
1158    let rel = |p: &Path| {
1159        p.strip_prefix(&project.root)
1160            .unwrap_or(p)
1161            .display()
1162            .to_string()
1163    };
1164    for p in &report.packages {
1165        let sha: String = p.sha.chars().take(7).collect();
1166        let where_it_is = match (&p.placement, p.patched) {
1167            (_, true) => format!("from {}", rel(p.root())),
1168            (Placement::Copied(dest), _) => format!("copied to {}", rel(dest)),
1169            (Placement::Symlink(_), _) => p.entry.display().to_string(),
1170        };
1171        eprintln!("  install {} {sha} ({where_it_is})", p.name);
1172    }
1173    let n = report.packages.len();
1174    if report.transitive > 0 {
1175        eprintln!(
1176            "htl pkg install: {n} package(s), {} of them transitive",
1177            report.transitive
1178        );
1179    } else {
1180        eprintln!("htl pkg install: {n} package(s)");
1181    }
1182}
1183
1184/// `htl pkg add <name> <git>`: the manifest entry, without fetching anything.
1185///
1186/// This is the one verb that may run outside a project: mlua-pkg writes a manifest when
1187/// there is none, and the directory it writes it in is the working one.
1188fn cmd_pkg_add(spec: htl::pkg::mlua_pkg::ops::AddSpec) -> Result<ExitCode> {
1189    use htl::pkg::mlua_pkg::ops::AddOutcome;
1190    let cwd = std::env::current_dir()?;
1191    let project = htl::pkg::Project::find(&cwd).unwrap_or_else(|| htl::pkg::Project::at(&cwd));
1192    let name = spec.name.clone();
1193    let done = project.add(spec)?;
1194    let manifest = project
1195        .manifest
1196        .strip_prefix(&project.root)
1197        .unwrap_or(&project.manifest)
1198        .display();
1199    if done.report.manifest_created {
1200        eprintln!("  created {manifest}");
1201    }
1202    let verb = match done.report.outcome {
1203        AddOutcome::Added => "added",
1204        AddOutcome::Replaced => "updated",
1205    };
1206    eprintln!("  {verb}   {name} in {manifest}");
1207    if let Some(dir) = &done.kept_patch_dir {
1208        // `add` rewrites the entry, and its spec has no room for a patch. Putting the key
1209        // back is the difference between the project resolving that dependency from its own
1210        // copy and resolving it from upstream with the copy left unread in the tree.
1211        eprintln!(
1212            "  kept    patch_dir = {} ({name} is patched)",
1213            dir.display()
1214        );
1215    }
1216    eprintln!("htl pkg add: run `htl pkg install` to fetch it");
1217    Ok(ExitCode::SUCCESS)
1218}
1219
1220/// `htl pkg update [name]`: what each pin does next, then the install that follows.
1221fn cmd_pkg_update(opts: htl::pkg::mlua_pkg::ops::UpdateOpts) -> Result<ExitCode> {
1222    use htl::pkg::mlua_pkg::ops::UpdateOutcome;
1223    let project = pkg_project()?;
1224    let dry_run = opts.dry_run;
1225    let report = project.update(opts)?;
1226    if report.entries.is_empty() {
1227        eprintln!("htl pkg update: no dependency selected");
1228        return Ok(ExitCode::SUCCESS);
1229    }
1230    for (name, outcome) in &report.entries {
1231        match outcome {
1232            UpdateOutcome::TagBumped { old, new } => {
1233                eprintln!("  update  {name}: tag {old} -> {new}")
1234            }
1235            UpdateOutcome::PrefixResolved { pin, resolved } => eprintln!(
1236                "  update  {name}: prefix '{pin}' is {resolved} (the manifest keeps the prefix)"
1237            ),
1238            UpdateOutcome::Refresh => eprintln!("  update  {name}: refresh (branch or unpinned)"),
1239            UpdateOutcome::Skipped(why) => eprintln!("  skip    {name}: {why}"),
1240        }
1241    }
1242    if dry_run {
1243        eprintln!("htl pkg update: dry run; nothing was written");
1244        return Ok(ExitCode::SUCCESS);
1245    }
1246    if let Some(install) = &report.install {
1247        report_install(install, &project);
1248        let project = htl::pkg::Project::at(&project.root);
1249        report_types_sync(&project.sync_types()?, &project.root);
1250        report_patch_drift(&project);
1251    }
1252    Ok(ExitCode::SUCCESS)
1253}
1254
1255/// `htl pkg clean`: the cache, which is machine-local and rebuilt by the next install.
1256fn cmd_pkg_clean(all: bool) -> Result<ExitCode> {
1257    use htl::pkg::mlua_pkg::ops::CleanReport;
1258    let project = pkg_project()?;
1259    match project.clean(all)? {
1260        CleanReport::CacheRemoved => eprintln!("htl pkg clean: removed every cached package"),
1261        CleanReport::NoLockfile => {
1262            eprintln!("htl pkg clean: no lockfile, so nothing was ever cached")
1263        }
1264        CleanReport::StaleRemoved { removed: 0 } => eprintln!("htl pkg clean: nothing to remove"),
1265        CleanReport::StaleRemoved { removed } => eprintln!(
1266            "htl pkg clean: removed {removed} cache entr{} the lockfile no longer refers to",
1267            if removed == 1 { "y" } else { "ies" }
1268        ),
1269    }
1270    Ok(ExitCode::SUCCESS)
1271}
1272
1273/// A patched copy the dependency is no longer resolved from, said after every install
1274/// until it is refreshed or removed.
1275///
1276/// A patch is bound to the revision it was taken from, and an upgrade moves the pin off it.
1277/// Install does not fail over that — the project builds against the new upstream — so the
1278/// only thing that keeps the copy from being forgotten in the tree is being told about it
1279/// each time. Both ways out are named, in htl's verbs: mlua-pkg's own warning points at
1280/// `mlua-pkg patch --force`, which skips the question htl asks git before overwriting.
1281fn report_patch_drift(project: &htl::pkg::Project) {
1282    let short = |s: &str| s.chars().take(7).collect::<String>();
1283    for s in project.patch_status() {
1284        if s.in_use {
1285            continue;
1286        }
1287        let rel = s
1288            .dir
1289            .strip_prefix(&project.root)
1290            .unwrap_or(&s.dir)
1291            .display();
1292        let why = match (&s.base, &s.locked) {
1293            _ if !s.dir.is_dir() => "the copy is not there".to_string(),
1294            (None, _) => "the lockfile records no revision it was taken from".to_string(),
1295            (Some(b), Some(l)) => {
1296                format!("taken from {}, {} is now at {}", short(b), s.name, short(l))
1297            }
1298            (Some(b), None) => format!("taken from {}, and nothing is locked", short(b)),
1299        };
1300        eprintln!("  patch   {rel} is not in use ({why})");
1301        eprintln!(
1302            "          carry the change forward: commit it, then `htl pkg patch {}`",
1303            s.name
1304        );
1305        eprintln!("          drop it: remove patch_dir from mlua-pkg.toml and delete {rel}");
1306    }
1307}
1308
1309/// `htl pkg patch <dep>`: the dependency's source, taken into `patches/<dep>/` where the
1310/// project owns it. Not a passthrough — htl decides the directory, writes `patch_dir` into
1311/// the manifest and answers the "may this be overwritten" question against git; the copy
1312/// and the `patch_base` bookkeeping are mlua-pkg's. See `Project::patch`.
1313fn cmd_pkg_patch(dep: &str, force: bool) -> Result<ExitCode> {
1314    let cwd = std::env::current_dir()?;
1315    let project = htl::pkg::Project::find(&cwd).context(
1316        "no mlua-pkg.toml above the current directory: a patch belongs to a project, so this runs in one",
1317    )?;
1318    let done = project.patch(dep, force)?;
1319    let report = &done.report;
1320    let rel = report
1321        .patch_dir
1322        .strip_prefix(&project.root)
1323        .unwrap_or(&report.patch_dir);
1324    let verb = if report.created { "patched" } else { "rebuilt" };
1325    let base: String = report.base.chars().take(7).collect();
1326    eprintln!("  {verb} {} ({dep} at {base})", rel.display());
1327    // Only when there was something to drop: on a dependency whose repository holds
1328    // nothing but the package this line would be noise, and the reader would learn the
1329    // rule from a line that says nothing happened.
1330    if !done.dropped.is_empty() {
1331        eprintln!(
1332            "  dropped {} (the repository's, not the package's)",
1333            done.dropped.join(", ")
1334        );
1335    }
1336    eprintln!("htl: it is the project's code now — edit it, commit it, then `htl pkg install`.");
1337    Ok(ExitCode::SUCCESS)
1338}
1339
1340/// What the deps published, in the shape `htl init` reports its scaffold. A name that was
1341/// already taken is said out loud: nothing was overwritten, and the project is the one
1342/// that decides which declaration it wants.
1343fn report_types_sync(sync: &htl::pkg::TypesSync, root: &Path) {
1344    let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).display().to_string();
1345    for (path, dep) in &sync.written {
1346        eprintln!("  types   {} (from {dep})", rel(path));
1347    }
1348    for (path, dep) in &sync.taken {
1349        eprintln!("  kept    {} ({dep} publishes one too)", rel(path));
1350    }
1351}
1352
1353/// `htl types add <library>`: the declarations a library did not ship, from the collection
1354/// that has them. The revision is recorded because nothing else in that ecosystem does —
1355/// see `Project::add_types`.
1356fn cmd_types_add(library: &str, from: Option<&Path>, force: bool) -> Result<ExitCode> {
1357    let cwd = std::env::current_dir()?;
1358    let project = htl::pkg::Project::find(&cwd).context(
1359        "no mlua-pkg.toml above the current directory: `types/` is a project's, so this runs in one",
1360    )?;
1361    let sync = match from {
1362        Some(dir) => project.add_types_from(dir, library, "local", force)?,
1363        None => project.add_types(library, force)?,
1364    };
1365    report_types_sync(&sync, &project.root);
1366    if sync.written.is_empty() && !sync.taken.is_empty() {
1367        eprintln!("htl: nothing written; --force replaces what is already there");
1368    }
1369    Ok(ExitCode::SUCCESS)
1370}
1371
1372/// What `htl unused` was asked for, beyond the paths.
1373struct UnusedFlags {
1374    json: bool,
1375    /// Exit 1 when anything was reported. Off by default: "unused" is a question about
1376    /// intent, so CI opts in rather than out.
1377    fail_on_unused: bool,
1378    use_cache: bool,
1379    explain: bool,
1380}
1381
1382/// What `htl check` was asked for, beyond the paths and the lint selection.
1383struct CheckFlags {
1384    strict: bool,
1385    list_lints: bool,
1386    json: bool,
1387    use_cache: bool,
1388    cache_mode: Option<cache::Mode>,
1389    explain: bool,
1390}
1391
1392struct TestFlags {
1393    fail_fast: bool,
1394    verbose: bool,
1395    quiet: bool,
1396    slow: Option<f64>,
1397    update: bool,
1398    coverage: bool,
1399    coverage_lines: bool,
1400    /// Where to write the lcov tracefile, if asked for.
1401    lcov: Option<PathBuf>,
1402    /// Where to write the JUnit XML report, if asked for.
1403    junit: Option<PathBuf>,
1404    json: bool,
1405    no_cache: bool,
1406    explain: bool,
1407    seed: Option<u64>,
1408}
1409
1410fn print_coverage(cov: &report::CoverageReport, with_lines: bool) {
1411    let width = cov
1412        .modules
1413        .iter()
1414        .map(|m| m.path.len())
1415        .max()
1416        .unwrap_or(4)
1417        .max(5);
1418    for m in &cov.modules {
1419        eprintln!(
1420            "coverage: {:<width$}  {:>5}/{:<5} {:5.1}%",
1421            m.path,
1422            m.executed,
1423            m.total,
1424            100.0 * m.executed as f64 / m.total as f64
1425        );
1426        if !m.never_ran.is_empty() {
1427            let names: Vec<String> = m
1428                .never_ran
1429                .iter()
1430                .map(|f| format!("{} ({})", f.name, f.line))
1431                .collect();
1432            eprintln!("          never ran: {}", names.join(", "));
1433        }
1434        if with_lines && !m.unexecuted.is_empty() {
1435            let spans: Vec<String> = m
1436                .unexecuted
1437                .iter()
1438                .map(|(a, b)| {
1439                    if a == b {
1440                        a.to_string()
1441                    } else {
1442                        format!("{a}-{b}")
1443                    }
1444                })
1445                .collect();
1446            eprintln!("          unexecuted: {}", spans.join(", "));
1447        }
1448    }
1449    if cov.total > 0 {
1450        eprintln!(
1451            "coverage: {:<width$}  {:>5}/{:<5} {:5.1}%  (statements; code run inside coroutines is not seen)",
1452            "total",
1453            cov.executed,
1454            cov.total,
1455            100.0 * cov.executed as f64 / cov.total as f64
1456        );
1457    } else {
1458        eprintln!("coverage: no .tl module reached");
1459    }
1460}
1461
1462/// One file's report as a JUnit suite.
1463///
1464/// The assertion library reports a failure as `"<suite > test>: <message>"` and its tests
1465/// by the same composed name, so a failing case takes back the message printed under the
1466/// file by matching that prefix — including the traceback a runtime error carries, which
1467/// belongs in the report for the same reason it belongs on the terminal: it is the part
1468/// that says where.
1469fn junit_suite(rep: &htl::testing::FileReport) -> junit::Suite {
1470    let mut left: Vec<&str> = rep.failures.iter().map(String::as_str).collect();
1471    let cases = rep
1472        .tests
1473        .iter()
1474        .map(|t| {
1475            let failure = (!t.ok)
1476                .then(|| {
1477                    let head = format!("{}: ", t.name);
1478                    let at = left.iter().position(|m| m.starts_with(&head))?;
1479                    Some(left.remove(at)[head.len()..].to_string())
1480                })
1481                .flatten();
1482            junit::Case {
1483                name: t.name.clone(),
1484                ms: t.ms,
1485                // A failing test whose message could not be matched still failed: say so
1486                // rather than reporting it as passed.
1487                failure: failure.or_else(|| (!t.ok).then(|| "failed".to_string())),
1488            }
1489        })
1490        .collect();
1491    let error = if !rep.check.ok() {
1492        Some(junit::Error {
1493            message: "type check failed".to_string(),
1494            kind: "check",
1495            body: rep.check.errors.join("\n"),
1496        })
1497    } else {
1498        rep.error.as_ref().map(|e| junit::Error {
1499            message: e.clone(),
1500            kind: "error",
1501            body: e.clone(),
1502        })
1503    };
1504    junit::Suite {
1505        file: rep.path.display().to_string(),
1506        duration_ms: rep.duration_ms,
1507        error,
1508        cases,
1509    }
1510}
1511
1512fn cmd_test(
1513    paths: &[PathBuf],
1514    filter: Option<&str>,
1515    lib: &str,
1516    lint: Option<&str>,
1517    flags: TestFlags,
1518) -> Result<ExitCode> {
1519    let paths = if paths.is_empty() {
1520        vec![PathBuf::from(".")]
1521    } else {
1522        paths.to_vec()
1523    };
1524    if let Some(first) = paths.first() {
1525        auto_dts(first)?;
1526    }
1527    // A patched dependency's `*_test.tl` are its suite, not this project's: `htl pkg patch`
1528    // takes the whole package root, tests included, and running them here would report a
1529    // library's own failures as the project's.
1530    let files = htl::testing::discover_tests_skipping(&paths, &project::patched(&paths))?;
1531    if files.is_empty() {
1532        eprintln!("htl test: no test files found (looked for *_test.tl and tests/**/*.tl)");
1533        return Ok(ExitCode::FAILURE);
1534    }
1535    let cfg = load_config(&paths[0])?;
1536    let opts = project::TestOptions {
1537        config: &cfg,
1538        lint,
1539        lib,
1540        filter,
1541        run: htl::testing::RunOptions {
1542            fail_fast: flags.fail_fast,
1543            update_snapshots: flags.update,
1544            coverage: flags.coverage,
1545            // Given, or drawn for the run and printed below, so that it can be given back.
1546            seed: flags.seed,
1547        },
1548        cache: project::cache_options(
1549            !flags.no_cache,
1550            Some(cache::Mode::PerModule),
1551            &cfg,
1552            flags.explain,
1553        ),
1554    };
1555
1556    let mut sink = project::Sink::new(report::Out::new(flags.json));
1557    let mut json_files: Vec<report::TestFile> = Vec::new();
1558    let mut junit_suites: Vec<junit::Suite> = Vec::new();
1559    // What is left of the run here: how a file reads on a terminal, and what the document
1560    // says about it. Which files run, in what isolation, from what store — and what they
1561    // draw — is `project::test`'s.
1562    let rep = project::test(&mut sink, &files, &opts, &mut |rep, sink| {
1563        if flags.json {
1564            json_files.push(report::TestFile::from_report(rep, sink.out().take()));
1565        }
1566        if flags.junit.is_some() {
1567            junit_suites.push(junit_suite(rep));
1568        }
1569        let f = &rep.path;
1570        let tag = if rep.ok() { "ok  " } else { "FAIL" };
1571        let detail = if !rep.check.ok() {
1572            "type check failed".to_string()
1573        } else if let Some(e) = &rep.error {
1574            // The cause on the file's own line, its frames under it: a traceback inside
1575            // the parenthesised summary would push `12 ms` past a screen of stack.
1576            format!("error: {}", e.lines().next().unwrap_or_default())
1577        } else if rep.file_level {
1578            "ran to completion (no test library used)".to_string()
1579        } else {
1580            format!("{} passed, {} failed", rep.passed, rep.failed)
1581        };
1582        // Quiet: a passing file is silence; failures, errors and slow tests still show.
1583        // JSON: nothing on stderr, the document carries it all.
1584        let show_file = !flags.json && (!flags.quiet || !rep.ok());
1585        if show_file {
1586            eprintln!(
1587                "{tag} {}  ({detail}, {:.0} ms)",
1588                f.display(),
1589                rep.duration_ms
1590            );
1591            if let Some(e) = &rep.error {
1592                for line in e.lines().skip(1) {
1593                    eprintln!("      {line}");
1594                }
1595            }
1596        }
1597        for tr in &rep.tests {
1598            let slow = flags.slow.is_some_and(|ms| tr.ms >= ms);
1599            if !flags.json && (flags.verbose || slow) {
1600                if flags.quiet && !show_file {
1601                    // The file line was skipped: name the file with the slow test.
1602                    eprintln!("slow {}  {}  ({:.1} ms)", f.display(), tr.name, tr.ms);
1603                    continue;
1604                }
1605                let mark = if tr.ok { "ok  " } else { "FAIL" };
1606                let note = if slow && !flags.verbose {
1607                    "  [slow]"
1608                } else {
1609                    ""
1610                };
1611                eprintln!("      {mark} {}  ({:.1} ms){note}", tr.name, tr.ms);
1612            }
1613        }
1614        if !flags.json {
1615            for m in &rep.failures {
1616                eprintln!("      - {m}");
1617            }
1618            // A snapshot written or rewritten is a change on disk: always say so, even in -q.
1619            for p in &rep.snapshots_written {
1620                eprintln!("snapshot written: {p}");
1621            }
1622            for p in &rep.snapshots_updated {
1623                eprintln!("snapshot updated: {p}");
1624            }
1625        }
1626    })?;
1627
1628    if let Some(out) = &flags.junit {
1629        // The run's own total, not the sum of the files: it is the number the summary
1630        // line prints, and the report is there to agree with the summary line.
1631        std::fs::write(out, junit::document(&junit_suites, rep.duration_ms))
1632            .with_context(|| format!("writing {}", out.display()))?;
1633    }
1634    if let (Some(out), Some(cov)) = (&flags.lcov, &rep.coverage) {
1635        // Against the project root rather than the working directory: a tracefile is
1636        // uploaded from wherever CI ran the command and resolved against the repository.
1637        let root = match &cfg {
1638            Some((dir, _, _)) => dir.clone(),
1639            None => std::env::current_dir()?,
1640        };
1641        let root = std::fs::canonicalize(&root).unwrap_or(root);
1642        std::fs::write(out, cov.lcov(&root))
1643            .with_context(|| format!("writing {}", out.display()))?;
1644    }
1645    let ok = rep.ok();
1646    if flags.json {
1647        let summary = report::TestSummary {
1648            files: rep.files.len(),
1649            files_run: rep.ran,
1650            passed: rep.passed,
1651            failed: rep.failed,
1652            files_with_errors: rep.files_with_errors,
1653            replayed: rep.replayed,
1654            duration_ms: rep.duration_ms,
1655            ok,
1656            seed: rep.seed,
1657        };
1658        report::emit(&report::TestReport {
1659            files: json_files,
1660            summary,
1661            coverage: rep.coverage,
1662        })?;
1663    } else {
1664        if let Some(cov) = &rep.coverage {
1665            print_coverage(cov, flags.coverage_lines);
1666            if let Some(out) = &flags.lcov {
1667                eprintln!("coverage: lcov written to {}", out.display());
1668            }
1669        }
1670        eprintln!(
1671            "htl test: {} file(s), {} passed, {} failed, {} file(s) with errors{}{} ({:.0} ms)",
1672            rep.ran,
1673            rep.passed,
1674            rep.failed,
1675            rep.files_with_errors,
1676            if rep.skipped() > 0 {
1677                format!(", {} file(s) not run (--fail-fast)", rep.skipped())
1678            } else {
1679                String::new()
1680            },
1681            // Says the checking was reused, not the run: every one of these files ran.
1682            if rep.replayed > 0 {
1683                format!(", {} checked from cache", rep.replayed)
1684            } else {
1685                String::new()
1686            },
1687            rep.duration_ms
1688        );
1689        // Always, not only on failure: the seed of a run that passed is what reproduces
1690        // the run that passes, and a failure two commits later is compared against it.
1691        eprintln!(
1692            "htl test: seed {} (repeat with --seed {})",
1693            rep.seed, rep.seed
1694        );
1695    }
1696    Ok(if ok {
1697        ExitCode::SUCCESS
1698    } else {
1699        ExitCode::FAILURE
1700    })
1701}
1702
1703/// Name the patched dependencies this walk enters, in the shape the other reports use.
1704///
1705/// Only the ones actually below a given root: `htl check src` walks the project's own
1706/// sources and nothing under `patches/`, and saying otherwise would be a claim about files
1707/// that were not read.
1708fn report_patched(paths: &[PathBuf]) {
1709    let roots: Vec<PathBuf> = paths
1710        .iter()
1711        .filter_map(|p| std::fs::canonicalize(p).ok())
1712        .collect();
1713    let cwd = std::env::current_dir().unwrap_or_default();
1714    let Some(project) = paths.first().and_then(|p| htl::pkg::Project::find(p)) else {
1715        return;
1716    };
1717    for p in &project.patches {
1718        let canon = std::fs::canonicalize(&p.dir).unwrap_or_else(|_| p.dir.clone());
1719        if !roots.iter().any(|r| canon.starts_with(r)) {
1720            continue;
1721        }
1722        let shown = p.dir.strip_prefix(&cwd).unwrap_or(&p.dir);
1723        eprintln!("  patched {} ({})", shown.display(), p.name);
1724    }
1725}
1726
1727/// Nearest `htl.toml` above the first path: `(dir holding it, path, config)`.
1728///
1729/// Where `[toolchain] htl` is answered, and the only place: every command that reads the
1730/// config comes through here, and the pin has to be settled before the command reads a
1731/// source file — which is a property of this function, not something each command could
1732/// be trusted to repeat. `htl new` / `htl init` do not call it, so a mismatch never stops
1733/// anyone from creating a project.
1734///
1735/// The version compared is this binary's, which is the one the pin is about. The `htl`
1736/// crate a Rust host builds against is Cargo's, pinned in `Cargo.toml` — a separate
1737/// question, and the one [`warn_cargo_htl_mismatch`] answers.
1738fn load_config(first: &Path) -> Result<project::Config> {
1739    let cfg = project::config_of(first)?;
1740    if let Some((_, path, c)) = &cfg {
1741        htl::config::check_toolchain(c, path, env!("CARGO_PKG_VERSION"))?;
1742    }
1743    Ok(cfg)
1744}
1745
1746/// Say so, once, when the `Cargo.toml` around this project asks for an `htl` crate this
1747/// command is not.
1748///
1749/// The two halves of htl are released together and a project uses both: the crate the host
1750/// links, and the command that checks the Teal beside it. A project left at `htl = "0.5.1"`
1751/// while the installed CLI had moved to 0.6.0 was checked by one and built against the
1752/// other, and nothing in either output mentioned the other one — which is the whole of the
1753/// failure, since either version alone was fine.
1754///
1755/// **A warning, not an error, and not one of the summary's `warning(s)`** — that count is
1756/// the checker's, and this is not about the sources. A project goes to a hard error over a
1757/// version skew for one of two reasons, and htl has neither: the format between the halves
1758/// is unstable, so a mismatched pair miscompiles rather than failing (wasm-bindgen refuses
1759/// a JS glue built by another version); or the diagnostic downstream is opaque, so the
1760/// person would otherwise read a type error from deep inside a dependency (cargo's
1761/// `rust-version`). Here both halves worked — the run that produced this report is the
1762/// evidence — and the line is worth printing only because the person has no other way to
1763/// notice. npm's `engines` is the same shape and warns by default; Prisma says nothing at
1764/// all, and its silence is filed as a bug.
1765///
1766/// Read from the `Cargo.toml` of the crate the project sits in, `[dependencies] htl` only:
1767/// a string, or a table with `version`. A table without one — `path`, `git`, or a
1768/// `workspace = true` inheritance — states no requirement here and is passed over without
1769/// a word, which is exactly what a scaffold written by a checkout-built CLI produces. No
1770/// `Cargo.toml`, no `[dependencies]`, no `htl` key, or a requirement cargo itself would
1771/// reject: nothing is printed, because there is nothing this can be surer about than cargo.
1772fn warn_cargo_htl_mismatch(first: &Path) {
1773    let Some(root) = htl::dts::find_cargo_package_root(first) else {
1774        return;
1775    };
1776    let Ok(text) = fs::read_to_string(root.join("Cargo.toml")) else {
1777        return;
1778    };
1779    let Ok(manifest) = text.parse::<toml::Table>() else {
1780        return;
1781    };
1782    let Some(dep) = manifest.get("dependencies").and_then(|d| d.get("htl")) else {
1783        return;
1784    };
1785    let req_text = match dep {
1786        toml::Value::String(s) => s.as_str(),
1787        toml::Value::Table(t) => match t.get("version").and_then(toml::Value::as_str) {
1788            Some(s) => s,
1789            None => return,
1790        },
1791        _ => return,
1792    };
1793    let running = env!("CARGO_PKG_VERSION");
1794    let (Ok(req), Ok(version)) = (
1795        semver::VersionReq::parse(req_text),
1796        semver::Version::parse(running),
1797    ) else {
1798        return;
1799    };
1800    if req.matches(&version) {
1801        return;
1802    }
1803    // Both ways out are named because either is the right one: the project may be the
1804    // thing that is current, in which case the command is what moves.
1805    eprintln!(
1806        "htl {running}; Cargo.toml asks for htl {req_text} — the crate and the CLI are \
1807         meant to move together (cargo install htl-cli --version {req_text}, or bump the \
1808         dependency)"
1809    );
1810}
1811
1812fn cmd_fmt(paths: &[PathBuf], check: bool, indent: Option<usize>) -> Result<ExitCode> {
1813    let paths = if paths.is_empty() {
1814        vec![PathBuf::from(".")]
1815    } else {
1816        paths.to_vec()
1817    };
1818    let cfg = load_config(&paths[0])?;
1819    let indent = indent
1820        .or_else(|| cfg.as_ref().and_then(|(_, _, c)| c.fmt.indent))
1821        .unwrap_or(3);
1822    let h = Htl::new()?;
1823    // Not a patched dependency: formatting the copy would turn every one of its files into
1824    // a diff against the revision it was taken from, and bury the project's own change
1825    // somewhere inside that.
1826    let files = htl::collect_tl_skipping(&paths, &project::patched(&paths))?;
1827    let (mut changed, mut failed) = (0usize, 0usize);
1828    for f in &files {
1829        let before = fs::read_to_string(f).with_context(|| format!("reading {}", f.display()))?;
1830        let after = match h.format_file(f, indent) {
1831            Ok(s) => s,
1832            Err(e) => {
1833                eprintln!("error: {e}");
1834                failed += 1;
1835                continue;
1836            }
1837        };
1838        if after != before {
1839            changed += 1;
1840            if check {
1841                eprintln!("would reformat: {}", f.display());
1842            } else {
1843                fs::write(f, after).with_context(|| format!("writing {}", f.display()))?;
1844                eprintln!("reformatted: {}", f.display());
1845            }
1846        }
1847    }
1848    eprintln!(
1849        "htl fmt: {} file(s), {} {}, {} failed",
1850        files.len(),
1851        changed,
1852        if check { "would change" } else { "reformatted" },
1853        failed
1854    );
1855    let fail = failed > 0 || (check && changed > 0);
1856    Ok(if fail {
1857        ExitCode::FAILURE
1858    } else {
1859        ExitCode::SUCCESS
1860    })
1861}
1862
1863struct FixFlags {
1864    rule: Vec<String>,
1865    unsafe_fixes: bool,
1866    dry_run: bool,
1867    diff: bool,
1868    allow_dirty: bool,
1869    allow_no_vcs: bool,
1870    exit_non_zero_on_fix: bool,
1871    json: bool,
1872}
1873
1874fn cmd_fix(paths: &[PathBuf], flags: FixFlags) -> Result<ExitCode> {
1875    use htl::fix::{FixOptions, fix_file, git_dirty, unified_diff};
1876    let paths = if paths.is_empty() {
1877        vec![PathBuf::from(".")]
1878    } else {
1879        paths.to_vec()
1880    };
1881    let h = Htl::new()?;
1882    let cfg = load_config(&paths[0])?;
1883    let file_spec = cfg
1884        .as_ref()
1885        .map(|(_, _, c)| c.lint_spec())
1886        .unwrap_or_default();
1887    if !file_spec.is_empty() {
1888        h.configure_lints(&file_spec)?;
1889    }
1890    if let Some(first) = paths.first() {
1891        auto_dts(first)?;
1892        apply_project(&h, first)?;
1893    }
1894    if let Some((root, _, c)) = &cfg {
1895        h.apply_config(root, c)?;
1896    }
1897    h.install_test_lib()?;
1898    h.install_std()?;
1899    let opts = FixOptions {
1900        unsafe_fixes: flags.unsafe_fixes,
1901        promoted: cfg
1902            .as_ref()
1903            .map(|(_, _, c)| c.fix.unsafe_.clone())
1904            .unwrap_or_default(),
1905        disabled: cfg
1906            .as_ref()
1907            .map(|(_, _, c)| c.fix.disable.clone())
1908            .unwrap_or_default(),
1909        only: flags.rule.clone(),
1910        dry_run: flags.dry_run,
1911    };
1912    // Here as well as inside `fix_file`, so a misspelt rule is answered even when the
1913    // paths hold no `.tl` at all — the request is wrong either way.
1914    opts.validate()?;
1915    let files = htl::collect_tl(&paths)?;
1916
1917    // The working tree is the undo: refuse to rewrite what git could not give back.
1918    if !flags.dry_run {
1919        let mut dirty = Vec::new();
1920        let mut no_vcs = Vec::new();
1921        for f in &files {
1922            match git_dirty(f)? {
1923                Some(true) => dirty.push(f.clone()),
1924                Some(false) => {}
1925                None => no_vcs.push(f.clone()),
1926            }
1927        }
1928        if !dirty.is_empty() && !flags.allow_dirty {
1929            bail!(
1930                "htl fix rewrites files in place and relies on git to undo it; these have uncommitted changes:\n  {}\ncommit or stash them, or pass --allow-dirty",
1931                dirty
1932                    .iter()
1933                    .map(|p| p.display().to_string())
1934                    .collect::<Vec<_>>()
1935                    .join("\n  ")
1936            );
1937        }
1938        if !no_vcs.is_empty() && !flags.allow_no_vcs {
1939            bail!(
1940                "htl fix rewrites files in place and relies on git to undo it; these are not in a git repository:\n  {}\npass --allow-no-vcs to proceed without that safety net",
1941                no_vcs
1942                    .iter()
1943                    .map(|p| p.display().to_string())
1944                    .collect::<Vec<_>>()
1945                    .join("\n  ")
1946            );
1947        }
1948    }
1949
1950    let mut sink = project::Sink::new(report::Out::new(flags.json));
1951    // Dependencies are reported as `htl check` reports them and never rewritten: a fix
1952    // under `.htl/` goes at the next install, one under `[check] paths` is not this
1953    // project's. `fix_file` only ever writes the file it was given.
1954    let fix_root = cfg
1955        .as_ref()
1956        .map(|(r, _, _)| r.clone())
1957        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
1958    let contracts = match &cfg {
1959        Some((r, _, c)) => htl::contract::resolve(r, c).0,
1960        None => Vec::new(),
1961    };
1962    let origins = project::Origins::new(&paths[0], &fix_root, &cfg, &contracts);
1963    sink.walking(&files);
1964    let (mut applied, mut skipped, mut json_files) = (Vec::new(), Vec::new(), Vec::new());
1965    let (mut changed, mut deferred, mut reverted, mut errors_remaining) =
1966        (0usize, 0usize, 0usize, 0usize);
1967    for f in &files {
1968        h.add_layout_paths(f)?;
1969        let before = if flags.diff {
1970            std::fs::read_to_string(f).ok()
1971        } else {
1972            None
1973        };
1974        let out = fix_file(&h, f, &opts)?;
1975        if out.contents.is_some() {
1976            changed += 1;
1977        }
1978        deferred += out.deferred;
1979        if out.reverted.is_some() {
1980            reverted += 1;
1981        }
1982        errors_remaining += out.check.errors.len();
1983        if !flags.json {
1984            for a in &out.applied {
1985                eprintln!(
1986                    "fixed: {}:{}: {} ({}{})",
1987                    f.display(),
1988                    a.line,
1989                    a.rule,
1990                    a.applicability.as_str(),
1991                    if flags.dry_run { ", not written" } else { "" }
1992                );
1993            }
1994            for s in &out.skipped {
1995                eprintln!(
1996                    "skipped: {}:{}: {} — {}",
1997                    f.display(),
1998                    s.line,
1999                    s.rule,
2000                    s.reason
2001                );
2002            }
2003            if let Some(r) = &out.reverted {
2004                eprintln!("reverted: {}: {r}", f.display());
2005            }
2006            if let Some(o) = &out.oscillation {
2007                eprintln!("stopped: {}: fixes of {o} undo each other", f.display());
2008            }
2009            if out.deferred > 0 {
2010                eprintln!(
2011                    "deferred: {}: {} edit(s) overlapped applied ones; run htl fix again",
2012                    f.display(),
2013                    out.deferred
2014                );
2015            }
2016            if flags.diff
2017                && let (Some(b), Some(a)) = (&before, &out.contents)
2018            {
2019                print!("{}", unified_diff(&f.display().to_string(), b, a));
2020            }
2021            // A suggestion is never written, so the diff is the only place it is shown.
2022            // Against what was applied, when something was: the two are one edit session.
2023            if flags.diff
2024                && let (Some(b), Some(s)) = (
2025                    out.contents.as_ref().or(before.as_ref()),
2026                    out.suggested.as_ref(),
2027                )
2028            {
2029                print!(
2030                    "{}",
2031                    unified_diff(&format!("{} (suggested)", f.display()), b, s)
2032                );
2033            }
2034        }
2035        sink.checkinfo(&out.check);
2036        sink.dependency_errors(&out.check, &|p| origins.of(p));
2037        if flags.json {
2038            applied.extend(out.applied.iter().map(|a| report::FixApplied {
2039                file: f.display().to_string(),
2040                line: a.line,
2041                rule: a.rule.clone(),
2042                applicability: a.applicability.as_str(),
2043                pass: a.pass,
2044            }));
2045            skipped.extend(out.skipped.iter().map(|s| report::FixSkipped {
2046                file: f.display().to_string(),
2047                line: s.line,
2048                rule: s.rule.clone(),
2049                reason: s.reason.clone(),
2050            }));
2051            json_files.push(report::FixFile {
2052                path: f.display().to_string(),
2053                changed: out.contents.is_some(),
2054                deferred: out.deferred,
2055                reverted: out.reverted.clone(),
2056                oscillation: out.oscillation.clone(),
2057                diagnostics: sink.out().take(),
2058            });
2059        }
2060    }
2061    // A broken dependency is an error `htl fix` cannot remove; it remains, as `htl check`
2062    // would count it, so the two exit the same way on the same tree.
2063    errors_remaining += sink.dependency_error_count();
2064    let n_applied = if flags.json { applied.len() } else { 0 };
2065    let fail = errors_remaining > 0 || (flags.exit_non_zero_on_fix && changed > 0);
2066    if flags.json {
2067        let n_skipped = skipped.len();
2068        report::emit(&report::FixReport {
2069            dry_run: flags.dry_run,
2070            applied,
2071            skipped,
2072            files: json_files,
2073            summary: report::FixSummary {
2074                files: files.len(),
2075                files_changed: changed,
2076                applied: n_applied,
2077                skipped: n_skipped,
2078                deferred,
2079                reverted,
2080                errors_remaining,
2081                ok: !fail,
2082            },
2083        })?;
2084    } else {
2085        eprintln!(
2086            "htl fix: {} file(s), {} changed{}, {} error(s) remaining{}",
2087            files.len(),
2088            changed,
2089            if flags.dry_run {
2090                " (dry run, nothing written)"
2091            } else {
2092                ""
2093            },
2094            errors_remaining,
2095            if deferred > 0 {
2096                format!(", {deferred} deferred")
2097            } else {
2098                String::new()
2099            }
2100        );
2101    }
2102    Ok(if fail {
2103        ExitCode::FAILURE
2104    } else {
2105        ExitCode::SUCCESS
2106    })
2107}
2108
2109/// Type-check a tree, replaying the modules whose inputs have not moved.
2110///
2111/// The order here is load-bearing. Generating `.d.tl` and collecting the file list come
2112/// first, because both produce inputs the keys are built from. Every module is looked up
2113/// before any is checked, so that a run where nothing moved never builds a checker at all —
2114/// that costs about 13.5 ms (`crates/htl-core/benches/check.rs`), which is most of what a
2115/// fully replayed run has to save on a small project.
2116///
2117/// A module that misses re-checks its dependencies as part of its own check, since the
2118/// checker's store starts empty. So an edit costs the edited module, whatever depends on
2119/// it, and whatever those pull in — less than the project, more than the minimum.
2120fn cmd_check(paths: &[PathBuf], lint: Option<&str>, flags: CheckFlags) -> Result<ExitCode> {
2121    let CheckFlags {
2122        list_lints,
2123        json,
2124        use_cache,
2125        cache_mode,
2126        explain,
2127        ..
2128    } = flags;
2129    let mut sink = project::Sink::new(report::Out::new(json));
2130    let paths = if paths.is_empty() {
2131        vec![PathBuf::from(".")]
2132    } else {
2133        paths.to_vec()
2134    };
2135    // Listing the rules reports nothing about the project and shares nothing with a run —
2136    // and now not even a Lua state: the registry is Rust (`htl_core::lint::RULES`), which
2137    // is what lets the rules the project layer reports under be listed beside the ones
2138    // `lint.lua` implements.
2139    if list_lints {
2140        // The name and the level a project that says nothing gets. Two columns rather than
2141        // one because the default is a level now, and the three rules at `allow` are
2142        // otherwise invisible: a reader would have to turn one on to find out it was off.
2143        // Still one rule per line, name first, so it reads and greps as it always did.
2144        let width = htl::lint::rule_names()
2145            .iter()
2146            .map(|r| r.len())
2147            .max()
2148            .unwrap_or(0);
2149        for (name, level) in htl::lint::rule_defaults() {
2150            println!("{name:width$}  {level}");
2151        }
2152        return Ok(ExitCode::SUCCESS);
2153    }
2154    // htl.toml first, then --lint, so the flag wins; `strict` from the file unless flagged.
2155    let cfg = load_config(&paths[0])?;
2156    warn_cargo_htl_mismatch(&paths[0]);
2157    let strict = flags.strict
2158        || cfg
2159            .as_ref()
2160            .and_then(|(_, _, c)| c.lint.strict)
2161            .unwrap_or(false);
2162    // `.d.tl` written from Rust source is an input to the check, so it is regenerated
2163    // before anything hashes the tree: a hit computed over stale declarations would be a
2164    // hit on a different question from the one being asked.
2165    if let Some(first) = paths.first() {
2166        auto_dts(first)?;
2167    }
2168    // A patched dependency is walked with the project's own sources — it is the project's
2169    // code, and its errors are the project's to fix. Which dependency each directory
2170    // stands in for is said here, so that an error under it is read as that dependency's
2171    // without the reader having to know the manifest.
2172    let files = htl::collect_tl(&paths)?;
2173    if !json {
2174        report_patched(&paths);
2175    }
2176
2177    // The walk, the store and every decision about them are the library's: `include_tl!`
2178    // asks the same questions of the same store, and the two answering them separately is
2179    // what let them disagree. What is left here is the flags, the summary and the exit code.
2180    let rep = project::check(
2181        &mut sink,
2182        &files,
2183        &project::Options {
2184            paths: &paths,
2185            config: &cfg,
2186            lint,
2187            cache: project::cache_options(use_cache, cache_mode, &cfg, explain),
2188        },
2189    )?;
2190    let fail = report_check(
2191        sink.out(),
2192        json,
2193        &rep,
2194        strict,
2195        patched_files(&paths, &rep.files),
2196    )?;
2197    Ok(if fail {
2198        ExitCode::FAILURE
2199    } else {
2200        ExitCode::SUCCESS
2201    })
2202}
2203
2204/// Report what no entry's `require` closure reaches.
2205///
2206/// The graph is the check's — `htl check` resolves every `require` already, and the
2207/// `require-cycle` lint reads the same edges — so this is that walk plus the entries the
2208/// project declares (`htl::unused`). What is left here is the flags, the printing and the
2209/// exit code.
2210fn cmd_unused(paths: &[PathBuf], flags: UnusedFlags) -> Result<ExitCode> {
2211    let UnusedFlags {
2212        json,
2213        fail_on_unused,
2214        use_cache,
2215        explain,
2216    } = flags;
2217    let paths = if paths.is_empty() {
2218        vec![PathBuf::from(".")]
2219    } else {
2220        paths.to_vec()
2221    };
2222    let cfg = load_config(&paths[0])?;
2223    // A `.d.tl` written from Rust source is an input to the check the graph comes from,
2224    // exactly as it is for `htl check`.
2225    auto_dts(&paths[0])?;
2226    let rep = htl::unused::unused(&htl::unused::Options {
2227        paths: &paths,
2228        config: &cfg,
2229        cache: project::cache_options(use_cache, None, &cfg, explain),
2230    })?;
2231    let s = &rep.summary;
2232    if json {
2233        report::emit(&rep)?;
2234    } else if s.no_entry {
2235        eprintln!(
2236            "htl unused: nothing to start from, so nothing is reported. An entry is \
2237             src/main.tl, a test file, a module under a [[contract]] directory, or a name \
2238             in [build] extra / host"
2239        );
2240    } else {
2241        if s.check_errors > 0 {
2242            eprintln!(
2243                "htl unused: {} error(s) in the check this graph comes from — what those \
2244                 files require is missing from it (htl check)",
2245                s.check_errors
2246            );
2247        }
2248        for m in &rep.modules {
2249            match &m.module {
2250                Some(n) => eprintln!("module: {} ({n})", m.path),
2251                None => eprintln!("module: {}", m.path),
2252            }
2253        }
2254        for d in &rep.dependencies {
2255            eprintln!("dependency: {}", d.name);
2256        }
2257        eprintln!(
2258            "htl unused: {}, {} [{} considered, {} reached, {}]",
2259            count(s.modules, "module", "modules"),
2260            count(s.dependencies, "dependency", "dependencies"),
2261            s.considered,
2262            s.reached,
2263            count(s.entries, "entry", "entries"),
2264        );
2265    }
2266    Ok(if fail_on_unused && !s.ok {
2267        ExitCode::FAILURE
2268    } else {
2269        ExitCode::SUCCESS
2270    })
2271}
2272
2273/// Say which file a module name resolves to, and what that hides.
2274///
2275/// The chain comes from the library ([`htl::resolve`]), over a checker set up exactly as a
2276/// check of this project sets one up — the installed deps, then the config's search paths,
2277/// in that order, because `add_path` prepends and the order is the whole answer. Asking
2278/// any other way would report a path nothing else uses.
2279///
2280/// A report, so both forms go to stdout (README, "Machine-readable output").
2281fn cmd_resolve(module: &str, path: Option<&Path>, json: bool) -> Result<ExitCode> {
2282    let start = path.unwrap_or(Path::new("."));
2283    let cfg = load_config(start)?;
2284    // The declarations a check generates before it reads anything are inputs to the
2285    // answer — `types/<crate>/` is written by `htl dts` — and a report without them would
2286    // describe a project nobody checks.
2287    auto_dts(start)?;
2288    let h = Htl::new()?;
2289    // First, so that the project's own directories go in front of it as they do under
2290    // `htl run`: `add_path` prepends, and the report prints the order it searched.
2291    h.install_std()?;
2292    let project = apply_project(&h, start)?;
2293    if let Some((root, _, c)) = &cfg {
2294        h.apply_config(root, c)?;
2295    }
2296    let rep = htl::resolve::resolve(
2297        &h,
2298        module,
2299        cfg.as_ref().map(|(r, _, _)| r.as_path()),
2300        project.as_ref(),
2301    )?;
2302    if json {
2303        report::emit(&rep)?;
2304    } else {
2305        print_resolution(&rep);
2306    }
2307    Ok(if rep.summary.ok {
2308        ExitCode::SUCCESS
2309    } else {
2310        ExitCode::FAILURE
2311    })
2312}
2313
2314/// The text form of a resolution: a table in search order, then the directories that were
2315/// consulted. The order column is the reason one row is read and the others are not, which
2316/// is why it is printed rather than left to be looked up.
2317fn print_resolution(r: &htl::resolve::Resolution) {
2318    match &r.read {
2319        Some(read) => println!("htl resolve {}: {read}", r.module),
2320        None => println!(
2321            "htl resolve {}: nothing on the search path answers require(\"{}\")",
2322            r.module, r.module
2323        ),
2324    }
2325    if !r.candidates.is_empty() {
2326        let w = |f: fn(&htl::resolve::Candidate) -> usize, head: usize| {
2327            r.candidates.iter().map(f).max().unwrap_or(0).max(head)
2328        };
2329        let file = w(|c| c.path.len(), 4);
2330        let kind = w(|c| c.kind.as_str().len(), 4);
2331        let read_at = r
2332            .candidates
2333            .iter()
2334            .find(|c| c.status == htl::resolve::Status::Read)
2335            .map(|c| c.order);
2336        println!();
2337        println!("  order  {:file$}  {:kind$}  status", "file", "kind");
2338        for c in &r.candidates {
2339            let status = match (c.status, c.shadowed_by, read_at) {
2340                (htl::resolve::Status::Shadowed, Some(by), _) => format!("shadowed by {by}"),
2341                // Not hidden by the row that is read: typed by it, and loaded by the run.
2342                (htl::resolve::Status::Runtime, _, Some(by)) => format!("runtime, typed by {by}"),
2343                (s, _, _) => s.as_str().to_string(),
2344            };
2345            let origin = match &c.origin {
2346                Some(o) => format!("  ({})", o.describe()),
2347                None => String::new(),
2348            };
2349            println!(
2350                "  {:<5}  {:file$}  {:kind$}  {status}{origin}",
2351                c.order,
2352                c.path,
2353                c.kind.as_str()
2354            );
2355        }
2356    }
2357    println!();
2358    println!("  searched, in order: {}", r.searched.join(", "));
2359}
2360
2361/// `1 module` / `2 modules`: a count whose noun agrees with it, for a line short enough
2362/// that `module(s)` would be the loudest thing on it.
2363fn count(n: usize, one: &str, many: &str) -> String {
2364    format!("{n} {}", if n == 1 { one } else { many })
2365}
2366
2367/// Delete this project's cache store.
2368///
2369/// The store sits beside `htl.toml`, which is not necessarily where anyone is standing:
2370/// `htl check src` run from anywhere in a repo writes to the project root. That is the
2371/// reason this exists rather than leaving people to work out which directory to remove.
2372///
2373/// Only `.htl/cache` goes. `.htl/` itself is left in place for whatever else may come to
2374/// live there, and the path is built here rather than taken from an argument, so there is
2375/// no spelling of the command that removes anything else.
2376fn cmd_cache_clear(path: Option<&Path>) -> Result<ExitCode> {
2377    let start = path.unwrap_or(Path::new("."));
2378    let root = load_config(start)?
2379        .map(|(r, _, _)| r)
2380        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
2381    let dir = root.join(".htl").join("cache");
2382    if !dir.is_dir() {
2383        eprintln!("htl cache: nothing stored at {}", dir.display());
2384        return Ok(ExitCode::SUCCESS);
2385    }
2386    let n = fs::read_dir(&dir)
2387        .map(|rd| {
2388            rd.flatten()
2389                .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
2390                .count()
2391        })
2392        .unwrap_or(0);
2393    fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
2394    eprintln!(
2395        "htl cache: removed {n} {} from {}",
2396        if n == 1 { "entry" } else { "entries" },
2397        dir.display()
2398    );
2399    Ok(ExitCode::SUCCESS)
2400}
2401
2402/// The project root a cache command works on: beside `htl.toml`, or the working directory.
2403fn cache_root(path: Option<&Path>) -> Result<PathBuf> {
2404    let start = path.unwrap_or(Path::new("."));
2405    Ok(cache::root_for(start)
2406        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))))
2407}
2408
2409/// Say what the store holds.
2410///
2411/// Answers "what is stored", not "what would be reused": an entry listed here can still miss
2412/// on the next run because a file it recorded has changed. The two are different questions
2413/// and conflating them would make this command lie in the more dangerous direction.
2414fn cmd_cache_status(path: Option<&Path>, json: bool, list_entries: bool) -> Result<ExitCode> {
2415    let c = cache::describe(&cache_root(path)?);
2416    if json {
2417        report::emit(&c)?;
2418        return Ok(ExitCode::SUCCESS);
2419    }
2420
2421    if c.entries.is_empty() {
2422        println!("htl cache: empty ({})", c.dir);
2423        return Ok(ExitCode::SUCCESS);
2424    }
2425    let mut by_kind: std::collections::BTreeMap<&str, (usize, u64)> = Default::default();
2426    for e in &c.entries {
2427        let slot = by_kind.entry(e.kind.as_str()).or_default();
2428        slot.0 += 1;
2429        slot.1 += e.bytes;
2430    }
2431    println!(
2432        "htl cache: {} entries, {} at {}",
2433        c.entries.len(),
2434        human_bytes(c.bytes),
2435        c.dir
2436    );
2437    for (kind, (n, bytes)) in &by_kind {
2438        let what = match *kind {
2439            cache::CHECK => "checked modules",
2440            cache::GEN => "checked and generated test files (htl test)",
2441            cache::MODULE => "generated modules (htl test / build, include_bundle!)",
2442            cache::RUN => "whole runs",
2443            _ => "entries this build cannot read",
2444        };
2445        println!("  {n:>5} {what} ({})", human_bytes(*bytes));
2446    }
2447    if let (Some(min), Some(max)) = (
2448        c.entries.iter().map(|e| e.age_secs).min(),
2449        c.entries.iter().map(|e| e.age_secs).max(),
2450    ) {
2451        println!(
2452            "  last used between {} and {} ago",
2453            human_age(min),
2454            human_age(max)
2455        );
2456    }
2457    if list_entries {
2458        println!();
2459        for e in &c.entries {
2460            println!(
2461                "  {:<6} {:>8}  {}",
2462                e.kind,
2463                human_bytes(e.bytes),
2464                e.subjects.join(", ")
2465            );
2466        }
2467    }
2468    Ok(ExitCode::SUCCESS)
2469}
2470
2471fn human_bytes(n: u64) -> String {
2472    if n >= 1 << 20 {
2473        format!("{:.1} MB", n as f64 / (1u64 << 20) as f64)
2474    } else if n >= 1 << 10 {
2475        format!("{:.0} KB", n as f64 / (1u64 << 10) as f64)
2476    } else {
2477        format!("{n} B")
2478    }
2479}
2480
2481fn human_age(secs: u64) -> String {
2482    match secs {
2483        s if s < 90 => format!("{s}s"),
2484        s if s < 5400 => format!("{}m", s / 60),
2485        s if s < 172_800 => format!("{}h", s / 3600),
2486        s => format!("{}d", s / 86_400),
2487    }
2488}
2489
2490/// How many of the files a walk visited came out of a patched dependency.
2491///
2492/// The prefix test a diagnostic's `origin` is decided by, asked of the file list instead,
2493/// and canonicalised on both sides for the same reason it is there: the walk spells a file
2494/// the way the command line spelled the root it started from (`htl check .` gives
2495/// `./patches/mathx/src/mathx.tl`), while the `patch_dir` the manifest declares is
2496/// absolute. Zero for a project with no patch, which is what keeps the summary line below
2497/// unchanged for everyone who has never run `htl pkg patch`.
2498fn patched_files(paths: &[PathBuf], files: &[PathBuf]) -> usize {
2499    let dirs: Vec<PathBuf> = project::patched(paths)
2500        .into_iter()
2501        .map(|d| fs::canonicalize(&d).unwrap_or(d))
2502        .collect();
2503    if dirs.is_empty() {
2504        return 0;
2505    }
2506    files
2507        .iter()
2508        .filter(|f| {
2509            let f = fs::canonicalize(f).unwrap_or_else(|_| (*f).to_path_buf());
2510            dirs.iter().any(|d| f.starts_with(d))
2511        })
2512        .count()
2513}
2514
2515/// The one place a check reports its totals, so a replayed module and a checked one cannot
2516/// drift apart in how they are summarized. Returns whether the run counts as a failure.
2517///
2518/// `patched` is how many of those files are a patched dependency's ([`patched_files`]),
2519/// split out of the count rather than added to it. One `htl pkg patch` turned a project's
2520/// `15 file(s)` into `25 file(s)` with nothing said, and a file count that moves for a
2521/// reason the line does not give is a file count a reader cannot use: the dependency's
2522/// `tests/` are now in the walk, they are not the project's, and the line has to say so.
2523fn report_check(
2524    out: &mut report::Out,
2525    json: bool,
2526    rep: &project::Report,
2527    strict: bool,
2528    patched: usize,
2529) -> Result<bool> {
2530    let (files, replayed) = (rep.files.len(), rep.replayed);
2531    let (errors, warnings, lints) = (rep.errors, rep.warnings, rep.lints);
2532    let fail = rep.failed(strict);
2533    let all_cached = rep.all_cached();
2534    if json {
2535        report::emit(&report::CheckReport {
2536            files,
2537            patched,
2538            diagnostics: out.take(),
2539            summary: report::CheckSummary {
2540                errors,
2541                warnings,
2542                lints,
2543                denied: rep.denied,
2544                strict,
2545                ok: !fail,
2546                cached: all_cached,
2547                replayed,
2548            },
2549        })?;
2550    } else {
2551        // Say nothing when nothing was replayed; say how much when it was only some.
2552        let cached = if all_cached {
2553            " [cached]".to_string()
2554        } else if replayed > 0 {
2555            format!(" [{replayed}/{files} cached]")
2556        } else {
2557            String::new()
2558        };
2559        // The three counts say what kinds of thing the run said; `at deny` says how much
2560        // of that it failed on, and is left out when it is none of it — its being there at
2561        // all is the news. A run with two warnings and one denied lint reads as
2562        // `0 error(s), 2 warning(s), 1 lint(s), 1 at deny`.
2563        let denied = match rep.denied {
2564            0 => String::new(),
2565            n => format!(", {n} at deny"),
2566        };
2567        // A project with no patch reads exactly as it read before the split existed: the
2568        // second number appears only when there is something on the other side of it, and
2569        // the two always add up to the one number that was there.
2570        let counted = match patched {
2571            0 => format!("{files} file(s)"),
2572            n => format!("{} file(s) + {n} in patched dependencies", files - n),
2573        };
2574        eprintln!(
2575            "htl check: {counted}, {errors} error(s), {warnings} warning(s), {lints} lint(s){denied}{}{cached}",
2576            if strict { " [strict]" } else { "" }
2577        );
2578    }
2579    Ok(fail)
2580}
2581
2582fn cmd_gen(file: &Path, out: Option<&Path>) -> Result<ExitCode> {
2583    let h = Htl::new()?;
2584    h.add_layout_paths(file)?;
2585    auto_dts(file)?;
2586    apply_project(&h, file)?;
2587    h.install_std()?;
2588    let (code, c) = h.gen_lua(file)?;
2589    text_sink().checkinfo(&c);
2590    let Some(mut code) = code else {
2591        return Ok(ExitCode::FAILURE);
2592    };
2593    if !code.ends_with('\n') {
2594        code.push('\n');
2595    }
2596    match out {
2597        Some(p) => fs::write(p, code).with_context(|| format!("writing {}", p.display()))?,
2598        None => print!("{code}"),
2599    }
2600    Ok(ExitCode::SUCCESS)
2601}
2602
2603fn cmd_run(file: &Path, args: &[String]) -> Result<ExitCode> {
2604    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
2605    let h = Htl::new()?;
2606    auto_dts(file)?;
2607    apply_project(&h, file)?;
2608    h.install_test_lib()?;
2609    h.install_std()?;
2610    if Bundle::is_bundle(&bytes) {
2611        let b = Bundle::decode(&bytes)?;
2612        return Ok(match h.run_bundle(&b, args) {
2613            Ok(()) => ExitCode::SUCCESS,
2614            Err(e) => {
2615                // A bundle's frames are as good as its payload: stripped bytecode has no
2616                // lines to show, and `htl build --debug` is what keeps them.
2617                eprintln!("{}", htl::developer_message(&e));
2618                ExitCode::FAILURE
2619            }
2620        });
2621    }
2622    // Check first so lints/warnings are visible before the script runs.
2623    h.add_layout_paths(file)?;
2624    h.install_searcher()?;
2625    h.set_arg(&file.to_string_lossy(), args)?;
2626    let (code, c) = h.gen_lua(file)?;
2627    text_sink().checkinfo(&c);
2628    let Some(code) = code else {
2629        return Ok(ExitCode::FAILURE);
2630    };
2631    match h.exec(&code, &format!("@{}", file.display()), args) {
2632        Ok(()) => Ok(ExitCode::SUCCESS),
2633        Err(e) => {
2634            // Innermost cause and the frames that reached it. `htl run` is a development
2635            // command, so the frames are the default; `htl::user_message` is what an
2636            // embedding host shows people who did not write the Teal.
2637            eprintln!("{}", htl::developer_message(&e));
2638            Ok(ExitCode::FAILURE)
2639        }
2640    }
2641}
2642
2643/// The run cache as `htl build` was asked to use it: `--no-cache` and `--explain-cache`,
2644/// the two switches that mean something for one closure. There is no `--cache-mode`: a
2645/// build's entries are per module, as `htl test`'s are, since a build is many modules and
2646/// an edit to one should cost that one and its dependents rather than the closure.
2647struct BuildCache {
2648    use_cache: bool,
2649    explain: bool,
2650}
2651
2652fn cmd_build(
2653    entry: &Path,
2654    out: &Path,
2655    main: &str,
2656    mut opts: htl::link::LinkOptions,
2657    cache_flags: BuildCache,
2658) -> Result<ExitCode> {
2659    let h = Htl::new()?;
2660    auto_dts(entry)?;
2661    apply_project(&h, entry)?;
2662    // `std.*` resolves to its declaration and nothing else, so the linker files it under
2663    // the host's modules — which is what it is: the binary that runs the bundle preloads
2664    // it, as `htl run` does before `run_bundle`.
2665    h.install_std()?;
2666    let cfg = load_config(entry)?;
2667    if let Some((root, _, cfg)) = &cfg {
2668        h.apply_config(root, cfg)?;
2669        opts.extra.extend(cfg.build.extra.iter().cloned());
2670        opts.host.extend(cfg.build.host.iter().cloned());
2671        // The one thing `[build] target` changes: this command produces the `hb` target and
2672        // nothing else, so a project that records another is told which command does build
2673        // it rather than handed a bundle nothing in it was going to load. Here rather than
2674        // further down because both forms of `htl build` pass through — the directory form
2675        // returns a few lines below — and because nothing has been written yet.
2676        if let Some(t) = cfg.build.target.filter(|t| *t != BuildTarget::Hb) {
2677            eprintln!(
2678                "htl build: this project's target is `{}` — what runs its output is {} — and `htl build` writes a `.hb` bundle, which is the `hb` target. Build it with `cargo build`; to bundle its scripts anyway, drop `[build] target` from htl.toml.",
2679                t.name(),
2680                t.runs_it()
2681            );
2682            return Ok(ExitCode::FAILURE);
2683        }
2684    }
2685    if entry.is_dir() {
2686        if cache_flags.explain {
2687            eprintln!("htl cache: the directory form of `htl build` is not cached");
2688        }
2689        return cmd_build_dir(&h, entry, out, main, &opts);
2690    }
2691    h.add_layout_paths(entry)?;
2692    // The store: `module` entries keyed the way `htl test` and the macros key them — the
2693    // file the module is and the lint selection `htl.toml` puts in force — so a module any
2694    // of them generated is one the build replays, and the reverse. Nothing is swept here:
2695    // a build sees one closure, and only `htl check`, which sees the project, bounds the
2696    // store (`cache.rs`).
2697    let root = cache::root_for(entry)
2698        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
2699    let spec = cfg
2700        .as_ref()
2701        .map(|(_, _, c)| c.lint_spec())
2702        .unwrap_or_default();
2703    let lint = (!spec.is_empty()).then_some(spec.as_str());
2704    let cache_opts = project::cache_options(
2705        cache_flags.use_cache,
2706        Some(cache::Mode::PerModule),
2707        &cfg,
2708        cache_flags.explain,
2709    );
2710    let store = project::store(&root, cache_opts, None, "htl build");
2711    let link_store = store.as_ref().map(|c| htl::link::LinkStore {
2712        cache: c,
2713        lint,
2714        root: &root,
2715        config: cfg.as_ref().map(|(_, p, c)| (p.as_path(), c)),
2716    });
2717    let linked = htl::link::link_with(&h, entry, &opts, link_store)?;
2718    project::explain_cache(store.as_ref(), cache_opts);
2719    // One sink for the whole closure: a build is many modules, and what the layer says
2720    // once per run is said once for the build rather than once per module.
2721    let mut sink = text_sink();
2722    for (_, c) in &linked.checks {
2723        sink.checkinfo(c);
2724    }
2725    let n_err = linked.errors.len();
2726    for e in linked
2727        .errors
2728        .iter()
2729        .filter(|e| e.contains("is not on the search path"))
2730    {
2731        eprintln!("error: {e}");
2732    }
2733    if n_err > 0 {
2734        eprintln!("htl build: {n_err} error(s), bundle not written");
2735        return Ok(ExitCode::FAILURE);
2736    }
2737    let buf = linked.bundle()?.encode();
2738    fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
2739    let typed = linked.modules.iter().filter(|m| m.typed).count();
2740    // The same suffix `htl check` prints: everything from the store, some of it, or
2741    // nothing said when none was.
2742    let cached = if typed > 0 && linked.cached == typed {
2743        " [cached]".to_string()
2744    } else if linked.cached > 0 {
2745        format!(" [{}/{typed} cached]", linked.cached)
2746    } else {
2747        String::new()
2748    };
2749    eprintln!(
2750        "htl build: {} module(s) ({typed} typed, {} lua) -> {} ({} bytes{}{}){cached}",
2751        linked.modules.len(),
2752        linked.modules.len() - typed,
2753        out.display(),
2754        buf.len(),
2755        if opts.source {
2756            ", source"
2757        } else {
2758            ", bytecode"
2759        },
2760        if opts.debug { " with debug info" } else { "" }
2761    );
2762    if !linked.host_modules.is_empty() {
2763        eprintln!(
2764            "htl build: host must provide: {}",
2765            linked.host_modules.join(", ")
2766        );
2767    }
2768    Ok(ExitCode::SUCCESS)
2769}
2770
2771/// The older form: every `.tl` under a directory, module names from their paths.
2772fn cmd_build_dir(
2773    h: &Htl,
2774    dir: &Path,
2775    out: &Path,
2776    entry: &str,
2777    opts: &htl::link::LinkOptions,
2778) -> Result<ExitCode> {
2779    h.add_path(dir)?;
2780    let files = htl::collect_tl(&[dir.to_path_buf()])?;
2781    let mut b = Bundle {
2782        entry: entry.to_string(),
2783        htl_version: env!("CARGO_PKG_VERSION").into(),
2784        ..Default::default()
2785    };
2786    let mut n_err = 0usize;
2787    let mut sink = text_sink();
2788    for f in &files {
2789        let name = htl::module_name(dir, f)?;
2790        let (code, c) = h.gen_lua(f)?;
2791        sink.checkinfo(&c);
2792        n_err += c.errors.len();
2793        let Some(code) = code else { continue };
2794        let (kind, payload) = if opts.source {
2795            (htl::bundle::Kind::Source, code.into_bytes())
2796        } else {
2797            (
2798                htl::bundle::Kind::Bytecode,
2799                h.compile_with(&name, &code, !opts.debug)?,
2800            )
2801        };
2802        b.modules.push(htl::bundle::Module {
2803            name,
2804            kind,
2805            payload,
2806        });
2807    }
2808    if n_err > 0 {
2809        eprintln!("htl build: {n_err} error(s), bundle not written");
2810        return Ok(ExitCode::FAILURE);
2811    }
2812    if b.module(entry).is_none() {
2813        bail!(
2814            "entry module '{entry}' not found among {} module(s)",
2815            b.modules.len()
2816        );
2817    }
2818    if !opts.source {
2819        b.fingerprint = h.fingerprint()?;
2820    }
2821    let buf = b.encode();
2822    fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
2823    eprintln!(
2824        "htl build: {} module(s) -> {} ({} bytes)",
2825        b.modules.len(),
2826        out.display(),
2827        buf.len()
2828    );
2829    Ok(ExitCode::SUCCESS)
2830}
2831
2832/// What `htl bundle info` reports: everything the file records and nothing it does not
2833/// (no Lua state is created, nothing is loaded). `lua` is the header the bytecode was
2834/// compiled for, in the fields the mismatch message names; `None` when the bundle
2835/// carries no fingerprint, which `payload` explains (`source`) or `format` does (`1`).
2836#[derive(serde::Serialize)]
2837struct BundleInfo {
2838    file: String,
2839    format: u8,
2840    htl_version: Option<String>,
2841    /// `bytecode`, `source`, or `mixed` when modules disagree.
2842    payload: &'static str,
2843    lua: Option<htl::bundle::LuaHeader>,
2844    entry: String,
2845    modules: Vec<BundleModuleInfo>,
2846    host_modules: Vec<String>,
2847}
2848
2849#[derive(serde::Serialize)]
2850struct BundleModuleInfo {
2851    name: String,
2852    kind: &'static str,
2853    bytes: usize,
2854}
2855
2856fn cmd_bundle_info(file: &Path, json: bool) -> Result<ExitCode> {
2857    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
2858    let Some(format) = htl::bundle::format_version(&bytes) else {
2859        bail!("{} is not an htl bundle (bad magic)", file.display());
2860    };
2861    let b = Bundle::decode(&bytes)?;
2862    let kind_name = |k: htl::bundle::Kind| match k {
2863        htl::bundle::Kind::Bytecode => "bytecode",
2864        htl::bundle::Kind::Source => "source",
2865    };
2866    let payload = match (
2867        b.modules
2868            .iter()
2869            .any(|m| m.kind == htl::bundle::Kind::Bytecode),
2870        b.modules
2871            .iter()
2872            .any(|m| m.kind == htl::bundle::Kind::Source),
2873    ) {
2874        (true, true) => "mixed",
2875        (false, true) => "source",
2876        // Bytecode, or no modules at all: what the loader would treat it as.
2877        _ => "bytecode",
2878    };
2879    let info = BundleInfo {
2880        file: file.display().to_string(),
2881        format,
2882        htl_version: (!b.htl_version.is_empty()).then(|| b.htl_version.clone()),
2883        payload,
2884        lua: htl::bundle::LuaHeader::parse(&b.fingerprint),
2885        entry: b.entry.clone(),
2886        modules: b
2887            .modules
2888            .iter()
2889            .map(|m| BundleModuleInfo {
2890                name: m.name.clone(),
2891                kind: kind_name(m.kind),
2892                bytes: m.payload.len(),
2893            })
2894            .collect(),
2895        host_modules: b.host_modules.clone(),
2896    };
2897    if json {
2898        report::emit(&info)?;
2899        return Ok(ExitCode::SUCCESS);
2900    }
2901
2902    println!(
2903        "{}: htl bundle, format {}, built by {}",
2904        info.file,
2905        info.format,
2906        match &info.htl_version {
2907            Some(v) => format!("htl {v}"),
2908            None => "htl (version not recorded)".to_string(),
2909        }
2910    );
2911    println!("  payload:  {}", info.payload);
2912    let lua = match &info.lua {
2913        Some(h) => h.to_string(),
2914        None if !b.fingerprint.is_empty() => {
2915            format!("unreadable fingerprint ({} bytes)", b.fingerprint.len())
2916        }
2917        None if info.format == 1 => {
2918            "not recorded (a format 1 bundle carries no fingerprint)".into()
2919        }
2920        None => "any (source payload, no bytecode to bind)".into(),
2921    };
2922    println!("  lua:      {lua}");
2923    println!("  entry:    {}", info.entry);
2924    let modules: Vec<String> = info
2925        .modules
2926        .iter()
2927        .map(|m| {
2928            if info.payload == "mixed" {
2929                format!("{} ({})", m.name, m.kind)
2930            } else {
2931                m.name.clone()
2932            }
2933        })
2934        .collect();
2935    println!(
2936        "  modules:  {}",
2937        if modules.is_empty() {
2938            "(none)".to_string()
2939        } else {
2940            modules.join(", ")
2941        }
2942    );
2943    println!(
2944        "  host:     {}",
2945        if info.host_modules.is_empty() {
2946            "(none)".to_string()
2947        } else {
2948            info.host_modules.join(", ")
2949        }
2950    );
2951    Ok(ExitCode::SUCCESS)
2952}