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 pin;
12pub mod report;
13mod scaffold;
14
15/// Output format of every command that has `--format`. One enum, so its help must be
16/// true of all of them: `check` / `test` / `fix` / `unused` / `adopt` print their JSON
17/// document on stdout and nothing on stderr, and their text form on stderr only, so the
18/// two never mix; `cache status` / `bundle info` / `resolve` are reports rather than runs,
19/// so both of their forms go to stdout. The exit code is the same in either form.
20#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
21enum Format {
22    /// Human-readable lines
23    Text,
24    /// One JSON document on stdout (README, "Machine-readable output":
25    /// https://github.com/ynishi/htl#machine-readable-output)
26    Json,
27}
28
29/// How `htl check` grains its cache. Separate from whether it caches at all, which is
30/// `--no-cache`.
31#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
32enum CacheModeArg {
33    /// One entry per module: an edit costs that module and what depends on it
34    PerModule,
35    /// One entry per run: any edit re-checks everything, a run with no edits reads one file
36    WholeRun,
37}
38
39#[derive(Subcommand)]
40enum TypesCmd {
41    /// Copy a library's declarations from teal-types into `types/`, and record which
42    /// commit they came from
43    Add {
44        /// The library as teal-types names it (`luasocket`, `lpeg`, …)
45        library: String,
46        /// Take them from a checkout of teal-types already on disk instead of fetching
47        #[arg(long)]
48        from: Option<PathBuf>,
49        /// Replace declarations that are already in `types/`
50        #[arg(long)]
51        force: bool,
52    },
53}
54
55#[derive(Subcommand)]
56enum PkgCmd {
57    /// Fetch every dependency `mlua-pkg.toml` declares and write `mlua-pkg.lock`
58    Install,
59    /// Write a dependency into `mlua-pkg.toml`; `install` is what fetches it
60    Add {
61        /// The name `require()` will use for it
62        name: String,
63        /// Remote git URL
64        git: String,
65        /// Pin to a tag: exact (`v1.0.0`), or a prefix that follows its patches (`v1.0`)
66        #[arg(long)]
67        tag: Option<String>,
68        /// Pin to a commit
69        #[arg(long)]
70        rev: Option<String>,
71        /// Track a branch (a build from it is not reproducible)
72        #[arg(long)]
73        branch: Option<String>,
74        /// The subdirectory `require()` resolves through, when it is not the one the
75        /// package declares
76        #[arg(long)]
77        entry: Option<PathBuf>,
78        /// Copy the package into this directory instead of linking it (manifest-relative,
79        /// rewritten by every install)
80        #[arg(long)]
81        target_dir: Option<PathBuf>,
82    },
83    /// Refresh dependencies, bump the pins that follow releases, then install
84    Update {
85        /// One dependency; every one when omitted
86        name: Option<String>,
87        /// Print the plan and write nothing
88        #[arg(long)]
89        dry_run: bool,
90        /// Bump exact tag pins too, to the highest release the remote has
91        #[arg(long)]
92        force: bool,
93    },
94    /// Remove cached packages the lockfile no longer refers to
95    Clean {
96        /// Remove the whole cache rather than the unreferenced entries
97        #[arg(long)]
98        all: bool,
99    },
100    /// Take a dependency's source into `patches/<dep>/`: a copy the project owns, edits
101    /// and commits, which install resolves the dependency from
102    Patch {
103        /// The dependency as `mlua-pkg.toml` names it
104        dep: String,
105        /// Refresh the copy even when it has uncommitted changes (they are discarded)
106        #[arg(long)]
107        force: bool,
108    },
109}
110
111#[derive(Subcommand)]
112enum CacheCmd {
113    /// Delete this project's stored check results
114    Clear {
115        /// A path inside the project; the store is .htl/cache at the project root, the
116        /// nearest htl.toml or mlua-pkg.toml above
117        path: Option<PathBuf>,
118    },
119    /// Report what the store holds
120    Status {
121        /// A path inside the project; the store is .htl/cache at the project root, the
122        /// nearest htl.toml or mlua-pkg.toml above
123        path: Option<PathBuf>,
124        /// Output format
125        #[arg(long, value_enum, default_value_t = Format::Text)]
126        format: Format,
127        /// List every entry rather than counting them by kind
128        #[arg(long)]
129        entries: bool,
130    },
131}
132
133#[derive(Subcommand)]
134enum BundleCmd {
135    /// Print what a bundle records: format, the htl that built it, payload kind, the Lua
136    /// its bytecode was compiled for, entry, modules, host-provided names
137    Info {
138        /// The `.hb` file
139        file: PathBuf,
140        /// Output format
141        #[arg(long, value_enum, default_value_t = Format::Text)]
142        format: Format,
143    },
144}
145
146impl From<CacheModeArg> for cache::Mode {
147    fn from(m: CacheModeArg) -> Self {
148        match m {
149            CacheModeArg::PerModule => cache::Mode::PerModule,
150            CacheModeArg::WholeRun => cache::Mode::WholeRun,
151        }
152    }
153}
154
155use anyhow::{Context, Result, bail};
156use clap::{Parser, Subcommand};
157use htl::BuildTarget;
158use htl::Htl;
159use htl::bundle::Bundle;
160// The project layer: which files a check walks, what it replays from the run cache and
161// what it keeps there, and which of a run's findings are said. Shared with `include_tl!`,
162// which asks the same of the same store.
163use htl::project;
164use std::fs;
165use std::path::{Path, PathBuf};
166use std::process::ExitCode;
167
168#[derive(Parser)]
169#[command(
170    name = "htl",
171    version,
172    about = "Teal, hidden: run / check / build .tl on mlua",
173    long_about = "\
174Teal, hidden: run / check / build .tl on mlua.
175
176htl is a toolchain for Teal, and a way to embed one. It type-checks `.tl` sources with \
177Teal's own checker, runs and tests them on an embedded mlua state, formats them, and \
178links them into a single stripped-bytecode bundle. A Rust host embeds the same engine, \
179so the scripts it ships are checked when the host is built rather than when its user \
180first runs one.
181
182The guide, with every command and what a project looks like:
183  https://github.com/ynishi/htl
184
185The API a Rust host holds — `include_tl!`, `#[host_module]`, the run cache:
186  https://docs.rs/htl"
187)]
188struct Cli {
189    #[command(subcommand)]
190    cmd: Cmd,
191}
192
193#[derive(Subcommand)]
194enum Cmd {
195    /// Type-check .tl files or directories (htl lints are reported as `lint:`)
196    ///
197    /// A module reached through `require` is checked with the file that required it, and
198    /// what has not changed is replayed from `.htl/`. README, "Lints":
199    /// https://github.com/ynishi/htl#lints-htl-check-include_tl
200    #[command(after_long_help = "\
201Examples:
202  htl check src                  every .tl under src/
203  htl check src --strict         every warn counts as deny: warnings and lints fail
204  htl check src --lint nil-index=deny,no-any=warn
205                                 one rule fails the run, another is advice
206  htl check src --lint -tl:hint  a warning kind of the Teal compiler silenced
207  htl check --list-lints         every rule with its default level, then exit
208  htl check --explain union-exhaustive
209                                 why the rule exists and how to decide its cases
210  htl check src --statistics     how many findings each rule produced, not the findings
211
212The store is .htl/cache at the project root, the nearest htl.toml or mlua-pkg.toml above
213the paths; --no-cache skips it, --explain-cache says why a lookup missed.
214Caching: https://github.com/ynishi/htl#caching
215")]
216    Check {
217        paths: Vec<PathBuf>,
218        /// Treat every `warn` as `deny`: warnings and lints fail the run
219        #[arg(long)]
220        strict: bool,
221        /// Rule levels over the defaults, e.g. `nil-index=deny,no-any=warn` (`-rule` =
222        /// allow, `+rule` = warn)
223        // A spec that silences a rule starts with `-`, and without this clap reads
224        // `--lint -contract` as a cluster of short flags and answers `unexpected argument
225        // '-c'`: the documented way to turn one rule off never reached the spec parser.
226        #[arg(long, allow_hyphen_values = true)]
227        lint: Option<String>,
228        /// List every lint rule with its default level and exit
229        #[arg(long)]
230        list_lints: bool,
231        /// Print a rule's explanation — what it catches, why, the fix, the judgment call —
232        /// and exit; the name is the one a finding prints in `[htl <rule>]`
233        #[arg(long, value_name = "RULE")]
234        explain: Option<String>,
235        /// Output format
236        #[arg(long, value_enum, default_value_t = Format::Text)]
237        format: Format,
238        /// Check even if an identical run is cached, and do not store this one
239        #[arg(long)]
240        no_cache: bool,
241        /// How the cache is grained; overrides `[cache] mode` in htl.toml
242        #[arg(long, value_enum)]
243        cache_mode: Option<CacheModeArg>,
244        /// Say why the cache was not used, and what this run did with it
245        #[arg(long)]
246        explain_cache: bool,
247        /// Print how many findings each rule produced, instead of the findings
248        /// themselves: one row per rule with at least one, count first, `[*]` when every
249        /// finding of it has a fix `htl fix` applies, `[-]` when only some do or only
250        /// with `--unsafe`, `[ ]` when none has one; rules with no finding are not
251        /// listed. The summary line and the exit code are unchanged. With `--format
252        /// json`, `statistics` carries the same rows and `diagnostics` is empty
253        #[arg(long)]
254        statistics: bool,
255    },
256    /// Run tests: every `.tl` that requires the test library, one isolated state per file
257    ///
258    /// README, "Tests": https://github.com/ynishi/htl#tests
259    #[command(after_long_help = "\
260Examples:
261  htl test                       every .tl that requires htl.test
262  htl test tests --filter parser only tests whose \"suite > name\" contains it
263  htl test --coverage --coverage-lines
264                                 which lines of each module the suite never reached
265  htl test --junit report.xml    also write the run as a JUnit report, for a CI
266")]
267    Test {
268        paths: Vec<PathBuf>,
269        /// Only run tests whose "suite > name" contains this substring
270        #[arg(long)]
271        filter: Option<String>,
272        /// Assertion library module consulted for the verdict (must expose `run(filter)`)
273        #[arg(long, default_value = htl::testing::DEFAULT_LIB)]
274        lib: String,
275        /// Lint rules on top of the defaults, e.g. `+no-any`
276        #[arg(long, allow_hyphen_values = true)]
277        lint: Option<String>,
278        /// Stop at the first failure (within a file, and across files)
279        #[arg(long)]
280        fail_fast: bool,
281        /// Pass when no test file is found (the summary still says 0 files)
282        ///
283        /// Without it, finding nothing exits 1: a test file is found by what it loads, not
284        /// by its name, so a wrong `--lib` or a wrong directory finds nothing and would
285        /// otherwise pass silently. For a project whose gate runs `htl test` before its
286        /// first test exists; remove the flag when that test arrives. With test files
287        /// present it changes nothing.
288        #[arg(long)]
289        allow_empty: bool,
290        /// Print every test with its time (default: only failures and files)
291        #[arg(short, long)]
292        verbose: bool,
293        /// Only failures (with details), errors, and the summary line; no per-file `ok` lines
294        #[arg(short, long, conflicts_with = "verbose")]
295        quiet: bool,
296        /// Also print tests slower than this many milliseconds
297        #[arg(long, value_name = "MS")]
298        slow: Option<f64>,
299        /// Rewrite snapshots (`to_match_snapshot`) that differ instead of failing
300        #[arg(long)]
301        update: bool,
302        /// Report executed statements per `.tl` module the tests reached (slower: a line hook)
303        #[arg(long)]
304        coverage: bool,
305        /// With --coverage, also list the unexecuted line ranges of each module
306        #[arg(long, requires = "coverage")]
307        coverage_lines: bool,
308        /// Also write the coverage as an lcov tracefile here (implies --coverage)
309        #[arg(long, value_name = "FILE")]
310        lcov: Option<PathBuf>,
311        /// Also write the run as a JUnit XML report here, for a CI that reads test results
312        #[arg(long, value_name = "FILE")]
313        junit: Option<PathBuf>,
314        /// Seed the random stream tests draw from; printed every run, so a failure repeats
315        #[arg(long)]
316        seed: Option<u64>,
317        /// Output format
318        #[arg(long, value_enum, default_value_t = Format::Text)]
319        format: Format,
320        /// Check and generate every file even if a cached form is available, and store none
321        #[arg(long)]
322        no_cache: bool,
323        /// Say why the cache was not used, and what this run did with it
324        #[arg(long)]
325        explain_cache: bool,
326    },
327    /// Apply the fixes diagnostics carry (safe ones by default)
328    ///
329    /// The working tree is the undo: a file git reports as modified or staged is refused
330    /// (`--allow-dirty`), and so is a file outside a repository (`--allow-no-vcs`), since a
331    /// rewrite git could not give back is one nobody can review. `--dry-run` reports
332    /// without writing; `--diff` prints a unified diff per file instead, and a `suggest`
333    /// fix — never applied — is listed as skipped and printed there as a second diff
334    /// headed `<file> (suggested)`. The `.d.tl` declarations the project publishes are
335    /// regenerated first, as `htl check` regenerates them; a dry run works them out and
336    /// writes none.
337    ///
338    /// README, "Fixing": https://github.com/ynishi/htl#fixing-htl-fix
339    #[command(after_long_help = "\
340Examples:
341  htl fix src                    apply the safe fixes to every .tl under src/
342  htl fix src --diff --dry-run   what would change, as a unified diff per file
343  htl fix src --rule forward-ref only that rule's fixes
344  htl fix src --unsafe           also the fixes that may change what the program does
345")]
346    Fix {
347        paths: Vec<PathBuf>,
348        /// Only fixes of these rules: any rule `htl check --list-lints` names, or
349        /// `forward-ref` / `tl:error`, the classes an error's fix is filed under
350        #[arg(long, value_delimiter = ',')]
351        rule: Vec<String>,
352        /// Also apply `unsafe` fixes (may change what the program does)
353        #[arg(long = "unsafe")]
354        unsafe_fixes: bool,
355        /// Compute and report, write nothing
356        #[arg(long)]
357        dry_run: bool,
358        /// Like --dry-run, and print a unified diff per file that would change
359        #[arg(long)]
360        diff: bool,
361        /// Fix files that git reports as modified or staged
362        #[arg(long)]
363        allow_dirty: bool,
364        /// Fix files that are not inside a git repository
365        #[arg(long)]
366        allow_no_vcs: bool,
367        /// Exit 1 when any file was changed (for CI)
368        #[arg(long)]
369        exit_non_zero_on_fix: bool,
370        /// Output format
371        #[arg(long, value_enum, default_value_t = Format::Text)]
372        format: Format,
373    },
374    /// Write the `.d.tl` files this project declares: those `#[host_module(dts = ..)]` /
375    /// `#[teal(dts = ..)]` ask for in a Rust crate, without building it, and the module
376    /// each `---@contract` type is declared in (check / run / test / build do both)
377    ///
378    /// Each declaration is reported as `wrote`, `unchanged`, or `not written`, one line
379    /// each. The commands that generate before they work (`check` / `run` / `test` /
380    /// `build` / `fix` / `unused` / `adopt` / `resolve` / `gen`) do the same job first and print only
381    /// what moved, prefixed `dts:` — `dts: wrote …`, `dts: not written: …`, `dts: left in
382    /// place: …` — and never an `unchanged` line; a dependency's declarations land under
383    /// `types/<crate>/` from every one of them. The exit code is about `not written` and
384    /// nothing else: non-zero when a declaration this command was asked to write could
385    /// not be written. A file already under `types/` that no dependency ships any more is
386    /// reported as `left in place` — nothing was asked for, nothing is deleted, and the
387    /// exit code does not move.
388    Dts {
389        /// Crate root or any path inside it (default: current directory)
390        dir: Option<PathBuf>,
391    },
392    /// Create a new Teal project directory
393    ///
394    /// README, "Layout of a project": https://github.com/ynishi/htl#layout-of-a-project-htl-new
395    #[command(after_long_help = "\
396Examples:
397  htl new hello                    src/main.tl, a module, tests/, mlua-pkg.toml
398  htl new hello --lib              a library: no entry script
399  htl new hello --embed            the same, plus a Rust host (--target bin)
400  htl new hello --target cdylib --lib
401                                   a library behind a C ABI, for a caller that is not Rust
402  htl new hello --embed --htl main
403                                   built against the unreleased htl (a git pin on main)
404  htl new hello --embed --htl path:../htl
405                                   built against a local checkout of this repository
406  htl new hello --no-x             without the htlx dependency the manifest gets by default
407
408Build targets: https://docs.rs/htl/latest/htl/build_target/enum.BuildTarget.html
409Layout of a project: https://github.com/ynishi/htl#layout-of-a-project-htl-new
410")]
411    New {
412        name: String,
413        /// Library only (no src/main.tl)
414        #[arg(long)]
415        lib: bool,
416        /// Also emit a Rust host: shorthand for --target bin
417        #[arg(long)]
418        embed: bool,
419        /// What will run this project's output: a target writes Cargo.toml + src/lib.rs
420        /// (the #[host_module], the embedded module, preload) and, when there is an entry
421        /// script, a thin src/main.rs
422        #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
423        target: Option<String>,
424        /// The htl the project depends on: `release`, `main`, or `path:<checkout>`.
425        /// Without it, the htl this binary was built with — its version on crates.io, or
426        /// the checkout it was built in
427        #[arg(long, value_name = "REQ")]
428        htl: Option<String>,
429        /// Leave the htlx (htl-x collections) dependency out of mlua-pkg.toml
430        #[arg(long)]
431        no_x: bool,
432    },
433    /// Fill in the scaffold files that are missing in an existing directory
434    Init {
435        dir: Option<PathBuf>,
436        #[arg(long)]
437        lib: bool,
438        /// Shorthand for --target bin
439        #[arg(long)]
440        embed: bool,
441        /// Fill in this target's files, and report the ones that were already there
442        #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
443        target: Option<String>,
444        /// The htl the project depends on: `release`, `main`, or `path:<checkout>`.
445        /// Without it, the htl this binary was built with — its version on crates.io, or
446        /// the checkout it was built in
447        #[arg(long, value_name = "REQ")]
448        htl: Option<String>,
449        /// Leave the htlx (htl-x collections) dependency out of mlua-pkg.toml
450        #[arg(long)]
451        no_x: bool,
452    },
453    /// Move the htl a project `htl new` already wrote depends on
454    ///
455    /// Rewrites `Cargo.toml`'s `htl` line (and `htl-mq`'s, under `--target window`),
456    /// `mise.toml`, and `[toolchain] htl` in `htl.toml` when the project has one, then runs
457    /// `cargo update` so `Cargo.lock` agrees — the same four things `--htl` decides for a
458    /// project that does not exist yet (see `htl new`). `release` is this CLI's own
459    /// version, `main` its repository's branch, `path:<checkout>` a local clone — a
460    /// relative one resolved against the current directory, the way the shell reads it,
461    /// not against `dir`, and refused when there is no `crates/htl/Cargo.toml` under it;
462    /// a number is refused, the way `htl new --htl <number>` is, naming the release's own
463    /// CLI instead. `--no-update` writes the three files and prints the `cargo update` to
464    /// run by hand rather than running it.
465    ///
466    /// A `Cargo.toml` whose `htl` (or `htl-mq`) line this command does not recognise —
467    /// anything but a bare version, or a table naming exactly one of `version` / `git` +
468    /// `branch` / `path` plus an optional `features` list — is left untouched: the fallback
469    /// is the `[patch.crates-io]` block this refusal prints. README, "Running against an
470    /// unpublished htl": https://github.com/ynishi/htl#running-against-an-unpublished-htl
471    ///
472    /// Exit 0 once everything above is moved; 2 when `--htl` is not one of the three (or
473    /// names no checkout), there is no `Cargo.toml` to move, the line is not recognised,
474    /// or `cargo update` fails (the files are rewritten either way — only the lock is left
475    /// unresolved).
476    #[command(after_long_help = "\
477Examples:
478  htl pin path:../htl            from this project's own directory, move it onto a sibling
479                                  checkout, for a change that has to be built against it
480  htl pin release                move it back once that checkout's change is released
481")]
482    Pin {
483        /// `release`, `main`, or `path:<checkout>` — the same names `htl new --htl` takes
484        htl: String,
485        /// Project root or any path inside it (default: current directory)
486        dir: Option<PathBuf>,
487        /// Write the three files and print the `cargo update` to run, rather than running it
488        #[arg(long)]
489        no_update: bool,
490    },
491    /// Package management at the nearest `mlua-pkg.toml` project root: install / add /
492    /// update / clean / patch, through mlua-pkg's library rather than its binary
493    Pkg {
494        #[command(subcommand)]
495        cmd: PkgCmd,
496    },
497    /// Bring declarations for a library into `types/`
498    Types {
499        #[command(subcommand)]
500        cmd: TypesCmd,
501    },
502    /// Manage the check cache
503    ///
504    /// README, "Caching": https://github.com/ynishi/htl#caching
505    Cache {
506        #[command(subcommand)]
507        cmd: CacheCmd,
508    },
509    /// Format .tl files in place (indentation / blank lines / trailing whitespace)
510    Fmt {
511        paths: Vec<PathBuf>,
512        /// Do not write; exit 1 if any file would change
513        #[arg(long)]
514        check: bool,
515        /// Indent width in spaces (default: `[fmt] indent` in htl.toml, else 3)
516        #[arg(long)]
517        indent: Option<usize>,
518    },
519    /// Emit readable Lua for one .tl file (escape hatch)
520    ///
521    /// Line n of the output is line n of the .tl, so a run-time error names the .tl line.
522    /// A comment-only line (`--` or `---` after indentation, not a `--[[` opener) survives
523    /// verbatim at its line, `---` doc included, and so do the comment lines after the last
524    /// line of code (the `---` after a module's `return`): the output ends with the last of
525    /// them. A trailing comment (after code) and a block comment (`--[[ ... ]]`) do not
526    /// survive: the trailing one is dropped from its line, and every line of the block comes
527    /// out empty, a `--` line inside it included.
528    Gen {
529        file: PathBuf,
530        #[arg(short, long)]
531        out: Option<PathBuf>,
532    },
533    /// Run a .tl script or a .hb bundle
534    Run {
535        file: PathBuf,
536        #[arg(trailing_var_arg = true)]
537        args: Vec<String>,
538    },
539    /// Compile a directory of .tl into a stripped-bytecode bundle
540    ///
541    /// A bundle is the `hb` target, so this refuses a project whose `[build] target` is
542    /// another one — a `bin` or a `cdylib` is built with `cargo build`.
543    ///
544    /// README, "Bundles": https://github.com/ynishi/htl#bundles-htl-build
545    #[command(after_long_help = "\
546Examples:
547  htl build src/main.tl -o app.hb
548                                 the entry's require closure, as one bundle
549  htl build src/main.tl -o app.hb --debug
550                                 keep line numbers and local names in the bytecode
551  htl build src/main.tl -o app.hb --host mymod
552                                 leave a module the host provides out of the bundle
553  htl run app.hb                 run what was built
554
555Caching: https://github.com/ynishi/htl#caching
556")]
557    /// The closure is judged by the project's `[lint.rules]` as `htl check` judges it — a
558    /// rule the project turned off is not reported here either — and no bundle is written
559    /// when it fails. A project whose `[build] target` is not `hb` is refused, naming the
560    /// command that does build it: the key records a decision the project made rather
561    /// than a note about itself, and dropping it from `htl.toml` is how a project with
562    /// Rust in it asks for a bundle anyway.
563    Build {
564        /// Entry `.tl` file: it and everything it requires are bundled, replaying from
565        /// the run cache what still holds (a directory bundles every `.tl` under it, the
566        /// older snapshot form, which is not cached)
567        entry: PathBuf,
568        #[arg(short, long, default_value = "app.hb")]
569        out: PathBuf,
570        /// Entry module name when `entry` is a directory
571        #[arg(short, long, default_value = "main")]
572        main: String,
573        /// Keep debug info (line numbers, local names) in the bytecode
574        #[arg(long)]
575        debug: bool,
576        /// Store generated Lua source instead of bytecode: for a big-endian target, a Lua
577        /// with non-default number types, or a bundle that must outlive a Lua upgrade
578        #[arg(long)]
579        source: bool,
580        /// Modules to bundle that only a dynamic require reaches (also `[build] extra`)
581        #[arg(long, value_delimiter = ',')]
582        extra: Vec<String>,
583        /// Modules the host provides, besides the project's own list (`#[host_module]`, `[build] host`, `std.*`; `.d.tl`-only modules are implied)
584        #[arg(long, value_delimiter = ',')]
585        host: Vec<String>,
586        /// Generate every module even if its cached form still holds, and do not store
587        /// (the directory form is never cached)
588        #[arg(long)]
589        no_cache: bool,
590        /// Say why the cache was not used, and what this run did with it
591        #[arg(long)]
592        explain_cache: bool,
593    },
594    /// Report what no entry's `require` closure reaches: modules, and `mlua-pkg.toml`
595    /// dependencies
596    ///
597    /// README, "Unused": https://github.com/ynishi/htl#unused-htl-unused
598    #[command(after_long_help = "\
599Examples:
600  htl unused                     modules and dependencies no entry reaches
601  htl unused --exit-non-zero-on-unused
602                                 the same report, and a non-zero exit for a CI
603  htl unused --format json       the same report as one JSON document
604")]
605    Unused {
606        /// What to report on (default: the working directory). The walk is the project's
607        /// either way: a module reached only from `tests/` is reached
608        paths: Vec<PathBuf>,
609        /// Output format
610        #[arg(long, value_enum, default_value_t = Format::Text)]
611        format: Format,
612        /// Exit 1 when anything is reported (for CI)
613        #[arg(long)]
614        exit_non_zero_on_unused: bool,
615        /// Build the graph from a fresh check even if a cached one is available, and
616        /// store none
617        #[arg(long)]
618        no_cache: bool,
619        /// Say why the cache was not used, and what this run did with it
620        #[arg(long)]
621        explain_cache: bool,
622    },
623    /// Report how many declarations carry each of htl's nine markers, and where
624    ///
625    /// `applicable` is how many declarations a lint has found the evidence to call
626    /// candidates for a marker. Two rows have one so far: `---@struct`'s is what
627    /// `unmarked-struct` would report, a record built whole at every one of its
628    /// construction sites and left unmarked; `---@sealed`'s is what `unmarked-sealed`
629    /// would report, a record built and cast only in the file that declares it and left
630    /// unmarked. Every other row is empty (`-`), not `0`: a feature with no evidence
631    /// counted is a different claim from a feature nothing is applicable to, and this
632    /// command does not guess between them. `--detail` lists each candidate after the
633    /// row's marked declarations, with `(applicable: <reason>, N site(s))`. It is a
634    /// report, not a gate: the exit code is always 0.
635    /// README, "Adoption": https://github.com/ynishi/htl#adoption-htl-adopt
636    #[command(after_long_help = "\
637Examples:
638  htl adopt                      which of htl's nine markers this project writes, and how much
639  htl adopt --detail             the same, plus every marked declaration's file, line and name
640  htl adopt --format json        the same report as one JSON document
641")]
642    Adopt {
643        /// What to report on (default: the working directory). The walk behind the
644        /// census is always the whole project, so the check resolves and replays as
645        /// usual; the counts are of the files under the paths given here.
646        paths: Vec<PathBuf>,
647        /// Output format
648        #[arg(long, value_enum, default_value_t = Format::Text)]
649        format: Format,
650        /// List every marked declaration under the table, file:line and name, grouped by
651        /// feature, and each `applicable` candidate after them; the plain form prints
652        /// the table alone
653        #[arg(long)]
654        detail: bool,
655        /// Build the census from a fresh check even if a cached one is available, and
656        /// store none
657        #[arg(long)]
658        no_cache: bool,
659        /// Say why the cache was not used, and what this run did with it
660        #[arg(long)]
661        explain_cache: bool,
662    },
663    /// Which file `require("<module>")` resolves to, and what that hides
664    ///
665    /// The whole chain in search order: what is read, what is reachable and not read, and
666    /// which crate or dependency each one came from. An override on the search path is the
667    /// mechanism working, and this is how to see it. README, "Which file a name resolves
668    /// to": https://github.com/ynishi/htl#which-file-a-name-resolves-to-htl-resolve
669    #[command(after_long_help = "\
670Examples:
671  htl resolve mq                 the chain for require(\"mq\")
672  htl resolve socket.http        a name with dots, as a require spells it
673  htl resolve mq --format json   the same rows as one JSON document
674
675Exits 1 when the name resolves to nothing, when two files implement it, or when a file of
676the project implements a name the host provides, so a script can ask.
677
678`htl.test` is answered like a host-provided name: no file of the project implements it
679(`htl test` preloads it into the state it runs), and its one row is the declaration the
680binary carries, `provided by the environment`.
681")]
682    Resolve {
683        /// The module name a `require` would spell (`mq`, `socket.http`)
684        module: String,
685        /// A path inside the project (default: the working directory)
686        path: Option<PathBuf>,
687        /// Output format
688        #[arg(long, value_enum, default_value_t = Format::Text)]
689        format: Format,
690    },
691    /// Read a `.hb` bundle without running it
692    ///
693    /// README, "Bundles": https://github.com/ynishi/htl#bundles-htl-build
694    Bundle {
695        #[command(subcommand)]
696        cmd: BundleCmd,
697    },
698}
699
700/// The command line as clap holds it, before any argument is parsed.
701///
702/// The help is documentation, and the tests that keep it from rotting read it from here
703/// rather than from a copy kept beside them: they walk this tree and ask each command,
704/// argument and value for the strings it would print.
705pub fn command() -> clap::Command {
706    <Cli as clap::CommandFactory>::command()
707}
708
709/// Parse the command line and run the command; the exit code.
710///
711/// An exit of 1 is a verdict — an error in a file, a finding at `deny`, a failing test, a
712/// name that resolves to nothing ([`htl::verdict`]). A command that could not get as far
713/// as a verdict — a directory in no project, an `htl.toml` that does not parse, a file it
714/// cannot read, a flag it does not take — says why and exits 2, whichever command it was
715/// (clap exits 2 on a bad flag, and an `Err` from any command lands on the same arm).
716pub fn run() -> ExitCode {
717    // Invoked as `cargo htl ...` -> argv = ["cargo-htl", "htl", ...]; drop the "htl".
718    let mut argv: Vec<String> = std::env::args().collect();
719    let is_cargo = Path::new(&argv[0])
720        .file_stem()
721        .and_then(|s| s.to_str())
722        .map(|s| s == "cargo-htl")
723        .unwrap_or(false);
724    if is_cargo && argv.get(1).map(String::as_str) == Some("htl") {
725        argv.remove(1);
726    }
727    match real_main(Cli::parse_from(argv)) {
728        Ok(code) => code,
729        Err(e) => {
730            eprintln!("htl: {e:#}");
731            ExitCode::from(2)
732        }
733    }
734}
735
736fn real_main(cli: Cli) -> Result<ExitCode> {
737    match cli.cmd {
738        Cmd::Check {
739            paths,
740            strict,
741            lint,
742            list_lints,
743            explain,
744            format,
745            no_cache,
746            cache_mode,
747            explain_cache,
748            statistics,
749        } => cmd_check(
750            &paths,
751            lint.as_deref(),
752            CheckFlags {
753                strict,
754                list_lints,
755                explain_rule: explain,
756                json: format == Format::Json,
757                use_cache: !no_cache,
758                cache_mode: cache_mode.map(Into::into),
759                explain: explain_cache,
760                statistics,
761            },
762        ),
763        Cmd::Fmt {
764            paths,
765            check,
766            indent,
767        } => cmd_fmt(&paths, check, indent),
768        Cmd::Test {
769            paths,
770            filter,
771            lib,
772            lint,
773            fail_fast,
774            allow_empty,
775            verbose,
776            quiet,
777            slow,
778            update,
779            coverage,
780            coverage_lines,
781            lcov,
782            junit,
783            seed,
784            format,
785            no_cache,
786            explain_cache,
787        } => cmd_test(
788            &paths,
789            filter.as_deref(),
790            &lib,
791            lint.as_deref(),
792            TestFlags {
793                fail_fast,
794                allow_empty,
795                verbose,
796                quiet,
797                slow,
798                update,
799                coverage: coverage || lcov.is_some(),
800                coverage_lines,
801                lcov,
802                junit,
803                json: format == Format::Json,
804                no_cache,
805                explain: explain_cache,
806                seed,
807            },
808        ),
809        Cmd::Pkg { cmd } => match cmd {
810            PkgCmd::Install => cmd_pkg_install(),
811            PkgCmd::Add {
812                name,
813                git,
814                tag,
815                rev,
816                branch,
817                entry,
818                target_dir,
819            } => cmd_pkg_add(htl::pkg::mlua_pkg::ops::AddSpec {
820                name,
821                git,
822                tag,
823                rev,
824                branch,
825                entry,
826                target_dir,
827            }),
828            PkgCmd::Update {
829                name,
830                dry_run,
831                force,
832            } => cmd_pkg_update(htl::pkg::mlua_pkg::ops::UpdateOpts {
833                name,
834                dry_run,
835                force,
836            }),
837            PkgCmd::Clean { all } => cmd_pkg_clean(all),
838            PkgCmd::Patch { dep, force } => cmd_pkg_patch(&dep, force),
839        },
840        Cmd::Types { cmd } => match cmd {
841            TypesCmd::Add {
842                library,
843                from,
844                force,
845            } => cmd_types_add(&library, from.as_deref(), force),
846        },
847        Cmd::Cache { cmd } => match cmd {
848            CacheCmd::Clear { path } => cmd_cache_clear(path.as_deref()),
849            CacheCmd::Status {
850                path,
851                format,
852                entries,
853            } => cmd_cache_status(path.as_deref(), format == Format::Json, entries),
854        },
855        Cmd::Dts { dir } => cmd_dts(dir.as_deref()),
856        Cmd::New {
857            name,
858            lib,
859            embed,
860            target,
861            htl,
862            no_x,
863        } => cmd_new(&name, lib, embed, target.as_deref(), htl.as_deref(), no_x),
864        Cmd::Init {
865            dir,
866            lib,
867            embed,
868            target,
869            htl,
870            no_x,
871        } => cmd_init(
872            dir.as_deref(),
873            lib,
874            embed,
875            target.as_deref(),
876            htl.as_deref(),
877            no_x,
878        ),
879        Cmd::Pin {
880            htl,
881            dir,
882            no_update,
883        } => pin::cmd_pin(&htl, dir, no_update),
884        Cmd::Gen { file, out } => cmd_gen(&file, out.as_deref()),
885        Cmd::Run { file, args } => cmd_run(&file, &args),
886        Cmd::Fix {
887            paths,
888            rule,
889            unsafe_fixes,
890            dry_run,
891            diff,
892            allow_dirty,
893            allow_no_vcs,
894            exit_non_zero_on_fix,
895            format,
896        } => cmd_fix(
897            &paths,
898            FixFlags {
899                rule,
900                unsafe_fixes,
901                dry_run: dry_run || diff,
902                diff,
903                allow_dirty,
904                allow_no_vcs,
905                exit_non_zero_on_fix,
906                json: format == Format::Json,
907            },
908        ),
909        Cmd::Build {
910            entry,
911            out,
912            main,
913            debug,
914            source,
915            extra,
916            host,
917            no_cache,
918            explain_cache,
919        } => cmd_build(
920            &entry,
921            &out,
922            &main,
923            htl::link::LinkOptions {
924                debug,
925                source,
926                extra,
927                host,
928                entry_name: None,
929            },
930            BuildCache {
931                use_cache: !no_cache,
932                explain: explain_cache,
933            },
934        ),
935        Cmd::Unused {
936            paths,
937            format,
938            exit_non_zero_on_unused,
939            no_cache,
940            explain_cache,
941        } => cmd_unused(
942            &paths,
943            UnusedFlags {
944                json: format == Format::Json,
945                fail_on_unused: exit_non_zero_on_unused,
946                use_cache: !no_cache,
947                explain: explain_cache,
948            },
949        ),
950        Cmd::Adopt {
951            paths,
952            format,
953            detail,
954            no_cache,
955            explain_cache,
956        } => cmd_adopt(
957            &paths,
958            AdoptFlags {
959                json: format == Format::Json,
960                detail,
961                use_cache: !no_cache,
962                explain: explain_cache,
963            },
964        ),
965        Cmd::Resolve {
966            module,
967            path,
968            format,
969        } => cmd_resolve(&module, path.as_deref(), format == Format::Json),
970        Cmd::Bundle { cmd } => match cmd {
971            BundleCmd::Info { file, format } => cmd_bundle_info(&file, format == Format::Json),
972        },
973    }
974}
975
976/// The reporting layer, for the commands that report without a `--format` of their own.
977///
978/// `htl check` and `htl test` hand their findings to a [`project::Sink`] over a
979/// [`report::Out`]; `gen` / `run` / `build` used to loop `eprintln!` over the three
980/// vectors themselves, so the same finding read differently depending on which verb was
981/// typed. They come through here instead, and there is one renderer again.
982///
983/// One sink per command run, not per file: what the layer decides once per run — a
984/// dependency's error said once, and never on behalf of a file the run checks itself —
985/// is then once per *command*, which is what `htl build` over a closure of modules wants.
986fn text_sink() -> project::Sink<report::Out> {
987    project::Sink::new(report::Out::new(false, false))
988}
989
990/// What else a verdict counted besides errors, for a summary line: a finding at `deny`,
991/// and under `strict` every warning and lint. Empty when neither. Without it a run that
992/// failed on a lint would end in `0 error(s)`.
993fn judged(found: &htl::verdict::Findings, policy: &htl::verdict::Policy) -> String {
994    let mut out = String::new();
995    if policy.capped {
996        return out;
997    }
998    if found.denied > 0 {
999        out.push_str(&format!(", {} at deny", found.denied));
1000    }
1001    if policy.strict && found.warnings + found.lints > 0 {
1002        out.push_str(&format!(
1003            ", {} warning(s) and {} lint(s) under strict",
1004            found.warnings, found.lints
1005        ));
1006    }
1007    out
1008}
1009
1010/// The lint selection `htl.toml` puts in force, applied to `h`: the rules `htl check`
1011/// reports under, at the levels it judges them by. A command that checks without it
1012/// reports what the project turned off and judges nothing.
1013/// Hand the checker the project's `[lang]`: whether `async` / `await` are keywords in the
1014/// files it is about to read. Beside [`config_lints`] on every command that parses.
1015fn config_lang(h: &Htl, cfg: &project::Config) -> Result<()> {
1016    h.set_lang(&project::lang_of(cfg))
1017}
1018
1019fn config_lints(h: &Htl, cfg: &project::Config) -> Result<htl::lint::Lints> {
1020    let spec = cfg
1021        .as_ref()
1022        .map(|(_, _, c)| c.lint_spec())
1023        .unwrap_or_default();
1024    let lints = htl::lint::Lints::parse(&spec)?;
1025    h.select_lints(lints.selection())?;
1026    Ok(lints)
1027}
1028
1029/// (Re)generate the `.d.tl` files this project declares: the ones a Rust crate's
1030/// `#[host_module]` / `#[derive(TealRecord)]` ask for, so the checker sees Rust-side
1031/// modules before any `cargo build`, and the module each `---@contract` type is declared
1032/// in, which is what an outside author writes their modules against. Quiet unless
1033/// something was written.
1034///
1035/// A contract that could not be published is said here, on every command that generates:
1036/// `htl check` reports it again as a lint (which `strict` makes fatal) and `htl dts`
1037/// exits non-zero on it, but `run` / `test` / `build` have neither, and a declaration
1038/// that is quietly not written is one an outside author finds missing later.
1039fn auto_dts(start: &Path) -> Result<()> {
1040    auto_dts_to(start, true)
1041}
1042
1043/// [`auto_dts`], writing only when `write` is set. A dry run (`htl fix --dry-run` /
1044/// `--diff`) works out every declaration the same way and says which it would write, and
1045/// what it then checks is the declarations as they are on disk — which is why it says so.
1046fn auto_dts_to(start: &Path, write: bool) -> Result<()> {
1047    let mut project = None;
1048    if let Some((root, _, cfg)) = load_config(start)? {
1049        // The contracts the project's model holds, published from there.
1050        let model = htl::model::Project::load(&root, cfg)?;
1051        let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
1052        let (results, problems) = htl::contract::publish_to(&root, &contracts, write);
1053        announce_dts_to(&results, &root, write);
1054        for p in &problems {
1055            eprintln!("dts: {p}");
1056        }
1057        project = Some(root);
1058    }
1059    let Some(root) = htl::dts::find_cargo_package_root(start) else {
1060        return Ok(());
1061    };
1062    let results =
1063        htl::dts::generate_crate_to(&root, write).map_err(|e| anyhow::anyhow!("htl dts: {e}"))?;
1064    announce_dts_to(&results, &root, write);
1065    let types_root = project.unwrap_or_else(|| root.clone());
1066    let report = dep_dts_to(&root, &types_root, write);
1067    announce_dts_to(&report.written, &types_root, write);
1068    announce_dep_report(&report, "dts: ");
1069    Ok(())
1070}
1071
1072/// What `htl dts` has to say about the declarations its dependencies ship. Three kinds,
1073/// kept apart because they mean three different things to the reader and to the exit code
1074/// — which is the distinction the single `[htl <rule>]` suffix they all used to carry was
1075/// hiding. None of them is a lint: no rule name, nothing to configure or silence, and
1076/// nothing that reaches the `Sink`, so `htl check` neither counts one nor carries one in
1077/// `--format json` — it prints them, prefixed `dts:`, exactly as this command does.
1078#[derive(Default)]
1079struct DepReport {
1080    /// `(target, written)` pairs, in the shape the rest of the report prints.
1081    written: Vec<(PathBuf, bool)>,
1082    /// Asked for and not written. This, and only this, is what `htl dts` exits non-zero on.
1083    not_written: Vec<String>,
1084    /// Under `types/` and no longer shipped by anything. Reported, never deleted, and it
1085    /// fails nothing: what the file is for is the project's to say.
1086    left_in_place: Vec<String>,
1087    /// The crate graph would not resolve, so nothing was asked for — cargo could not be
1088    /// run, or the project's lockfile does not cover its manifest and the graph is read
1089    /// with `--locked`. Either way the committed declarations stand and the check that
1090    /// follows names the module if one is missing, which is why this fails nothing.
1091    unresolved: Option<String>,
1092}
1093
1094/// Materialise the declarations this project's dependencies ship, under
1095/// `<declaration root>/<crate>/` — the declaration root of the project at `types_root`,
1096/// `types/` unless its `htl.toml` says otherwise — and report on what happened to each.
1097///
1098/// The graph comes from `cargo metadata`, so this costs a subprocess on every command that
1099/// generates. Nothing is built, and nothing is downloaded for dependencies already fetched.
1100fn dep_dts(cargo_root: &Path, types_root: &Path) -> DepReport {
1101    dep_dts_to(cargo_root, types_root, true)
1102}
1103
1104/// [`dep_dts`], writing only when `write` is set.
1105fn dep_dts_to(cargo_root: &Path, types_root: &Path, write: bool) -> DepReport {
1106    let decls = match htl::dep_dts::resolve(cargo_root) {
1107        Ok(d) => d,
1108        Err(e) => {
1109            return DepReport {
1110                unresolved: Some(e),
1111                ..DepReport::default()
1112            };
1113        }
1114    };
1115    // Orphans before materialising: the note beside a crate's declarations is what says
1116    // which crate they came from, and the write below rewrites it.
1117    let types = match decl_root(types_root) {
1118        Ok(t) => t,
1119        Err(e) => {
1120            return DepReport {
1121                unresolved: Some(format!("{e:#}")),
1122                ..DepReport::default()
1123            };
1124        }
1125    };
1126    let left_in_place = htl::dep_dts::orphans(&types, &decls);
1127    let (written, not_written) = htl::dep_dts::materialise_to(&types, &decls, write);
1128    DepReport {
1129        written,
1130        not_written,
1131        left_in_place,
1132        unresolved: None,
1133    }
1134}
1135
1136/// The three report lists, each said as what it is. `wrote` / `unchanged` name what
1137/// happened to a declaration, and so do these: a reader who has never heard the words
1138/// `shipped-declaration` or `orphaned-declaration` can still tell which line failed the
1139/// command and which one is a file sitting there to decide about.
1140fn announce_dep_report(report: &DepReport, prefix: &str) {
1141    for p in &report.not_written {
1142        eprintln!("{prefix}not written: {p}");
1143    }
1144    for p in &report.left_in_place {
1145        eprintln!("{prefix}left in place: {p}");
1146    }
1147    if let Some(e) = &report.unresolved {
1148        eprintln!("{prefix}{e}");
1149    }
1150}
1151
1152/// What generation wrote, or for a run that did not write (`wrote` unset) what it would
1153/// have.
1154fn announce_dts_to(results: &[(PathBuf, bool)], root: &Path, wrote: bool) {
1155    for (target, changed) in results {
1156        if *changed {
1157            let target = target.strip_prefix(root).unwrap_or(target).display();
1158            if wrote {
1159                eprintln!("dts: wrote {target}");
1160            } else {
1161                eprintln!(
1162                    "dts: would write {target} (dry run: not written; checked against the \
1163                     file on disk)"
1164                );
1165            }
1166        }
1167    }
1168}
1169
1170fn cmd_dts(dir: Option<&Path>) -> Result<ExitCode> {
1171    let start = match dir {
1172        Some(d) => d.to_path_buf(),
1173        None => std::env::current_dir()?,
1174    };
1175    // The contract types first: a project may publish one without having a Rust host at
1176    // all, and the `bail!` below would then be wrong about there being nothing to do.
1177    let mut results = Vec::new();
1178    let mut failed = false;
1179    let mut project = None;
1180    if let Some((croot, _, cfg)) = load_config(&start)? {
1181        let model = htl::model::Project::load(&croot, cfg)?;
1182        let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
1183        let (published, problems) = htl::contract::publish(&croot, &contracts);
1184        for p in &problems {
1185            eprintln!("  {p}");
1186        }
1187        // Asked to generate and did not: the command says so in its exit code, or a CI
1188        // step that regenerates declarations would pass having written nothing.
1189        failed = !problems.is_empty();
1190        results.extend(published);
1191        project = Some(croot);
1192    }
1193    let code = |failed: bool| {
1194        if failed {
1195            ExitCode::FAILURE
1196        } else {
1197            ExitCode::SUCCESS
1198        }
1199    };
1200    let Some(root) = htl::dts::find_cargo_package_root(&start) else {
1201        if results.is_empty() && !failed {
1202            bail!(
1203                "no Cargo.toml with a [package] section, and no ---@contract type to publish, \
1204                 at or above {}",
1205                start.display()
1206            );
1207        }
1208        report_dts(&results, &start);
1209        return Ok(code(failed));
1210    };
1211    results.extend(htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("{e}"))?);
1212    let types_root = project.unwrap_or_else(|| root.clone());
1213    let report = dep_dts(&root, &types_root);
1214    announce_dep_report(&report, "  ");
1215    // An orphan, and a graph that would not resolve, are reports. A declaration asked for
1216    // and not written is a failure, the same as a contract that could not be published.
1217    failed = failed || !report.not_written.is_empty();
1218    results.extend(report.written);
1219    report_dts(&results, &root);
1220    Ok(code(failed))
1221}
1222
1223fn report_dts(results: &[(PathBuf, bool)], root: &Path) {
1224    let mut written = 0usize;
1225    for (target, w) in results {
1226        let rel = target.strip_prefix(root).unwrap_or(target).display();
1227        eprintln!("  {} {}", if *w { "wrote    " } else { "unchanged" }, rel);
1228        written += usize::from(*w);
1229    }
1230    eprintln!(
1231        "htl dts: {} declaration(s) from {}, {} written",
1232        results.len(),
1233        root.display(),
1234        written
1235    );
1236}
1237
1238/// The project `start` belongs to, with `h` set up for its sources the way `htl check`
1239/// sets up its checker: the model's directories on the search path, its installed
1240/// dependencies made reachable. `None`, with nothing on the path, outside a project.
1241///
1242/// What one file may read beyond that — the test root, for a file under it; its own
1243/// directory, for a file in no project — is [`project::file_view`], asked per file.
1244fn apply_model(
1245    h: &Htl,
1246    cfg: &project::Config,
1247    start: &Path,
1248) -> Result<Option<htl::model::Project>> {
1249    let model = project::model_of(cfg, start)?;
1250    if let Some(m) = &model {
1251        h.apply_model(m, htl::model::View::Source)?;
1252    }
1253    Ok(model)
1254}
1255
1256/// What the run wrote, and — when a target was asked for by name — what it left alone. The
1257/// kept list is what makes `htl init --target bin` on an older project say which of that
1258/// target's files were already there instead of skipping them in silence.
1259fn report_scaffold(dir: &Path, written: &[PathBuf], kept: &[PathBuf]) {
1260    let rel = |p: &PathBuf| p.strip_prefix(dir).unwrap_or(p).display().to_string();
1261    for p in written {
1262        eprintln!("  created {}", rel(p));
1263    }
1264    for p in kept {
1265        eprintln!("  kept    {} (already there)", rel(p));
1266    }
1267    if kept.is_empty() {
1268        eprintln!(
1269            "htl: {} file(s) written under {}",
1270            written.len(),
1271            dir.display()
1272        );
1273    } else {
1274        eprintln!(
1275            "htl: {} file(s) written, {} kept under {}",
1276            written.len(),
1277            kept.len(),
1278            dir.display()
1279        );
1280    }
1281}
1282
1283fn cmd_new(
1284    name: &str,
1285    lib: bool,
1286    embed: bool,
1287    target: Option<&str>,
1288    htl: Option<&str>,
1289    no_x: bool,
1290) -> Result<ExitCode> {
1291    let dir = PathBuf::from(name);
1292    let pkg_name = dir
1293        .file_name()
1294        .and_then(|s| s.to_str())
1295        .ok_or_else(|| anyhow::anyhow!("invalid project name: {name}"))?
1296        .to_string();
1297    // Before the directory is touched: an unknown target, or one that disagrees with
1298    // --lib, fails here and leaves nothing behind. So does an htl this scaffold does not
1299    // write for — a release by number — so it is settled first too.
1300    let target = scaffold::resolve_target(target, embed, lib)?;
1301    let htl = scaffold::HtlPin::parse(htl)?;
1302    let opts = scaffold::Options {
1303        lib,
1304        target,
1305        htl,
1306        no_x,
1307    };
1308    let done = scaffold::scaffold(&dir, &pkg_name, &opts, true)?;
1309    report_scaffold(&dir, &done.written, &[]);
1310    // The manifest names a dependency: the fetch comes before the first test, or the
1311    // first test is a `module not found`.
1312    let fetch = if opts.writes_htlx() {
1313        "htl pkg install && "
1314    } else {
1315        ""
1316    };
1317    // The window target's first build needs two files nothing has written yet: `htl check`
1318    // materialises the dependency's declaration as `types/htl-mq/mq.d.tl` (from its
1319    // `[package.metadata.htl] dts`) and writes `src/fx.d.tl` from the host module, and
1320    // `cargo build` reads the first of them when `include_bundle!` links `mq`. So the
1321    // check comes before the run rather than after it.
1322    let then = match opts.target.map(|t| t.target) {
1323        Some(BuildTarget::Window) => "htl check . && cargo run",
1324        _ => "htl test",
1325    };
1326    eprintln!("next: cd {} && {fetch}{then}", dir.display());
1327    Ok(ExitCode::SUCCESS)
1328}
1329
1330fn cmd_init(
1331    dir: Option<&Path>,
1332    lib: bool,
1333    embed: bool,
1334    target: Option<&str>,
1335    htl: Option<&str>,
1336    no_x: bool,
1337) -> Result<ExitCode> {
1338    let dir = match dir {
1339        Some(d) => d.to_path_buf(),
1340        None => std::env::current_dir()?,
1341    };
1342    let abs = std::fs::canonicalize(&dir).unwrap_or(dir.clone());
1343    let name = abs
1344        .file_name()
1345        .and_then(|s| s.to_str())
1346        .ok_or_else(|| anyhow::anyhow!("cannot derive a project name from {}", abs.display()))?
1347        .to_string();
1348    let asked_for_a_target = target.is_some() || embed;
1349    let target = scaffold::resolve_target(target, embed, lib)?;
1350    let htl = scaffold::HtlPin::parse(htl)?;
1351    let opts = scaffold::Options {
1352        lib,
1353        target,
1354        htl,
1355        no_x,
1356    };
1357    let done = scaffold::scaffold(&dir, &name, &opts, false)?;
1358    // A target was named: say what it would have written and found already there. Without
1359    // one the old one-liner stands, so a plain re-run does not list the whole tree.
1360    let kept: &[PathBuf] = if asked_for_a_target { &done.kept } else { &[] };
1361    if done.written.is_empty() && kept.is_empty() {
1362        eprintln!("htl init: nothing to do, all scaffold files already exist");
1363    } else {
1364        report_scaffold(&dir, &done.written, kept);
1365    }
1366    Ok(ExitCode::SUCCESS)
1367}
1368
1369/// The project `htl pkg` acts on: the one above the working directory, found the way
1370/// every command finds it ([`htl::model::Project::find_root`]), with its `mlua-pkg.toml`.
1371///
1372/// mlua-pkg reports a missing manifest as an I/O error that does not name the file, and the
1373/// path htl looked for is the whole of the answer, so it is checked here.
1374fn pkg_project() -> Result<htl::pkg::MluaProject> {
1375    let cwd = std::env::current_dir()?;
1376    let root = htl::model::Project::find_root(&cwd)?.map(|r| r.root);
1377    root.filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
1378        .map(|r| htl::pkg::MluaProject::at(&r))
1379        .with_context(|| {
1380            format!(
1381                "no {} above {}: `htl pkg` runs in a project",
1382                htl::pkg::MANIFEST_NAME,
1383                cwd.display()
1384            )
1385        })
1386}
1387
1388/// The declaration root of the project at `root`, from its model: `[layout] types`, which
1389/// is `types/` unless `htl.toml` says otherwise — where the declarations htl brings into a
1390/// project are written.
1391fn decl_root(root: &Path) -> Result<PathBuf> {
1392    let cfg = load_config(root)?;
1393    Ok(project::model_of(&cfg, root)?
1394        .and_then(|m| m.own().roots.decl.clone())
1395        .unwrap_or_else(|| root.join("types")))
1396}
1397
1398/// `htl pkg install`: fetch what the manifest declares, then bring in what the deps publish.
1399fn cmd_pkg_install() -> Result<ExitCode> {
1400    let project = pkg_project()?;
1401    let report = project.install()?;
1402    report_install(&report, &project);
1403    // Re-read the project: install wrote the lockfile the two reports below are read from.
1404    // A dep publishes its declarations at `types/` in its package root, which is not where
1405    // `require` looks, so they are copied in for the checker to see.
1406    let project = htl::pkg::MluaProject::at(&project.root);
1407    report_types_sync(
1408        &project.sync_types(&decl_root(&project.root)?)?,
1409        &project.root,
1410    );
1411    report_patch_drift(&project);
1412    Ok(ExitCode::SUCCESS)
1413}
1414
1415/// What install did, in the shape the other reports use. The library prints nothing.
1416fn report_install(
1417    report: &htl::pkg::mlua_pkg::ops::InstallReport,
1418    project: &htl::pkg::MluaProject,
1419) {
1420    use htl::pkg::mlua_pkg::ops::Placement;
1421    for w in &report.warnings {
1422        // A patch that was not used is reported below in htl's own verbs, where both ways
1423        // out are named. The library's line points at `mlua-pkg patch --force`, which
1424        // rebuilds the copy without asking git whether what is in it was committed.
1425        if w.contains("patch_dir") && w.contains("not used") {
1426            continue;
1427        }
1428        eprintln!("warning: {w}");
1429    }
1430    let rel = |p: &Path| {
1431        p.strip_prefix(&project.root)
1432            .unwrap_or(p)
1433            .display()
1434            .to_string()
1435    };
1436    for p in &report.packages {
1437        let sha: String = p.sha.chars().take(7).collect();
1438        let where_it_is = match (&p.placement, p.patched) {
1439            (_, true) => format!("from {}", rel(p.root())),
1440            (Placement::Copied(dest), _) => format!("copied to {}", rel(dest)),
1441            (Placement::Symlink(_), _) => p.entry.display().to_string(),
1442        };
1443        eprintln!("  install {} {sha} ({where_it_is})", p.name);
1444    }
1445    let n = report.packages.len();
1446    if report.transitive > 0 {
1447        eprintln!(
1448            "htl pkg install: {n} package(s), {} of them transitive",
1449            report.transitive
1450        );
1451    } else {
1452        eprintln!("htl pkg install: {n} package(s)");
1453    }
1454}
1455
1456/// `htl pkg add <name> <git>`: the manifest entry, without fetching anything.
1457///
1458/// This is the one verb that may run outside a project: mlua-pkg writes a manifest when
1459/// there is none. It writes it at the project's root — beside `htl.toml`, when the working
1460/// directory is in a project that has one — and in the working directory only outside any
1461/// project. Written in a subdirectory, it would give the project a second root, which
1462/// every command then refuses.
1463fn cmd_pkg_add(spec: htl::pkg::mlua_pkg::ops::AddSpec) -> Result<ExitCode> {
1464    use htl::pkg::mlua_pkg::ops::AddOutcome;
1465    let cwd = std::env::current_dir()?;
1466    let root = htl::model::Project::find_root(&cwd)?
1467        .map(|r| r.root)
1468        .unwrap_or(cwd);
1469    let project = htl::pkg::MluaProject::at(&root);
1470    let name = spec.name.clone();
1471    let done = project.add(spec)?;
1472    let manifest = project
1473        .manifest
1474        .strip_prefix(&project.root)
1475        .unwrap_or(&project.manifest)
1476        .display();
1477    if done.report.manifest_created {
1478        eprintln!("  created {manifest}");
1479    }
1480    let verb = match done.report.outcome {
1481        AddOutcome::Added => "added",
1482        AddOutcome::Replaced => "updated",
1483    };
1484    eprintln!("  {verb}   {name} in {manifest}");
1485    if let Some(dir) = &done.kept_patch_dir {
1486        // `add` rewrites the entry, and its spec has no room for a patch. Putting the key
1487        // back is the difference between the project resolving that dependency from its own
1488        // copy and resolving it from upstream with the copy left unread in the tree.
1489        eprintln!(
1490            "  kept    patch_dir = {} ({name} is patched)",
1491            dir.display()
1492        );
1493    }
1494    eprintln!("htl pkg add: run `htl pkg install` to fetch it");
1495    Ok(ExitCode::SUCCESS)
1496}
1497
1498/// `htl pkg update [name]`: what each pin does next, then the install that follows.
1499fn cmd_pkg_update(opts: htl::pkg::mlua_pkg::ops::UpdateOpts) -> Result<ExitCode> {
1500    use htl::pkg::mlua_pkg::ops::UpdateOutcome;
1501    let project = pkg_project()?;
1502    let dry_run = opts.dry_run;
1503    let report = project.update(opts)?;
1504    if report.entries.is_empty() {
1505        eprintln!("htl pkg update: no dependency selected");
1506        return Ok(ExitCode::SUCCESS);
1507    }
1508    for (name, outcome) in &report.entries {
1509        match outcome {
1510            UpdateOutcome::TagBumped { old, new } => {
1511                eprintln!("  update  {name}: tag {old} -> {new}")
1512            }
1513            UpdateOutcome::PrefixResolved { pin, resolved } => eprintln!(
1514                "  update  {name}: prefix '{pin}' is {resolved} (the manifest keeps the prefix)"
1515            ),
1516            UpdateOutcome::Refresh => eprintln!("  update  {name}: refresh (branch or unpinned)"),
1517            UpdateOutcome::Skipped(why) => eprintln!("  skip    {name}: {why}"),
1518        }
1519    }
1520    if dry_run {
1521        eprintln!("htl pkg update: dry run; nothing was written");
1522        return Ok(ExitCode::SUCCESS);
1523    }
1524    if let Some(install) = &report.install {
1525        report_install(install, &project);
1526        let project = htl::pkg::MluaProject::at(&project.root);
1527        report_types_sync(
1528            &project.sync_types(&decl_root(&project.root)?)?,
1529            &project.root,
1530        );
1531        report_patch_drift(&project);
1532    }
1533    Ok(ExitCode::SUCCESS)
1534}
1535
1536/// `htl pkg clean`: the cache, which is machine-local and rebuilt by the next install.
1537fn cmd_pkg_clean(all: bool) -> Result<ExitCode> {
1538    use htl::pkg::mlua_pkg::ops::CleanReport;
1539    let project = pkg_project()?;
1540    match project.clean(all)? {
1541        CleanReport::CacheRemoved => eprintln!("htl pkg clean: removed every cached package"),
1542        CleanReport::NoLockfile => {
1543            eprintln!("htl pkg clean: no lockfile, so nothing was ever cached")
1544        }
1545        CleanReport::StaleRemoved { removed: 0 } => eprintln!("htl pkg clean: nothing to remove"),
1546        CleanReport::StaleRemoved { removed } => eprintln!(
1547            "htl pkg clean: removed {removed} cache entr{} the lockfile no longer refers to",
1548            if removed == 1 { "y" } else { "ies" }
1549        ),
1550    }
1551    Ok(ExitCode::SUCCESS)
1552}
1553
1554/// A patched copy the dependency is no longer resolved from, said after every install
1555/// until it is refreshed or removed.
1556///
1557/// A patch is bound to the revision it was taken from, and an upgrade moves the pin off it.
1558/// Install does not fail over that — the project builds against the new upstream — so the
1559/// only thing that keeps the copy from being forgotten in the tree is being told about it
1560/// each time. Both ways out are named, in htl's verbs: mlua-pkg's own warning points at
1561/// `mlua-pkg patch --force`, which skips the question htl asks git before overwriting.
1562fn report_patch_drift(project: &htl::pkg::MluaProject) {
1563    let short = |s: &str| s.chars().take(7).collect::<String>();
1564    for s in project.patch_status() {
1565        if s.in_use {
1566            continue;
1567        }
1568        let rel = s
1569            .dir
1570            .strip_prefix(&project.root)
1571            .unwrap_or(&s.dir)
1572            .display();
1573        let why = match (&s.base, &s.locked) {
1574            _ if !s.dir.is_dir() => "the copy is not there".to_string(),
1575            (None, _) => "the lockfile records no revision it was taken from".to_string(),
1576            (Some(b), Some(l)) => {
1577                format!("taken from {}, {} is now at {}", short(b), s.name, short(l))
1578            }
1579            (Some(b), None) => format!("taken from {}, and nothing is locked", short(b)),
1580        };
1581        eprintln!("  patch   {rel} is not in use ({why})");
1582        eprintln!(
1583            "          carry the change forward: commit it, then `htl pkg patch {}`",
1584            s.name
1585        );
1586        eprintln!("          drop it: remove patch_dir from mlua-pkg.toml and delete {rel}");
1587    }
1588}
1589
1590/// `htl pkg patch <dep>`: the dependency's source, taken into `patches/<dep>/` where the
1591/// project owns it. Not a passthrough — htl decides the directory, writes `patch_dir` into
1592/// the manifest and answers the "may this be overwritten" question against git; the copy
1593/// and the `patch_base` bookkeeping are mlua-pkg's. See `Project::patch`.
1594fn cmd_pkg_patch(dep: &str, force: bool) -> Result<ExitCode> {
1595    let project = pkg_project().context("a patch belongs to a project, so this runs in one")?;
1596    let done = project.patch(dep, force)?;
1597    let report = &done.report;
1598    let rel = report
1599        .patch_dir
1600        .strip_prefix(&project.root)
1601        .unwrap_or(&report.patch_dir);
1602    let verb = if report.created { "patched" } else { "rebuilt" };
1603    let base: String = report.base.chars().take(7).collect();
1604    eprintln!("  {verb} {} ({dep} at {base})", rel.display());
1605    // Only when there was something to drop: on a dependency whose repository holds
1606    // nothing but the package this line would be noise, and the reader would learn the
1607    // rule from a line that says nothing happened.
1608    if !done.dropped.is_empty() {
1609        eprintln!(
1610            "  dropped {} (the repository's, not the package's)",
1611            done.dropped.join(", ")
1612        );
1613    }
1614    eprintln!("htl: it is the project's code now — edit it, commit it, then `htl pkg install`.");
1615    Ok(ExitCode::SUCCESS)
1616}
1617
1618/// What the deps published, in the shape `htl init` reports its scaffold. A name that was
1619/// already taken is said out loud: nothing was overwritten, and the project is the one
1620/// that decides which declaration it wants.
1621fn report_types_sync(sync: &htl::pkg::TypesSync, root: &Path) {
1622    let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).display().to_string();
1623    for (path, dep) in &sync.written {
1624        eprintln!("  types   {} (from {dep})", rel(path));
1625    }
1626    for (path, dep) in &sync.taken {
1627        eprintln!("  kept    {} ({dep} publishes one too)", rel(path));
1628    }
1629}
1630
1631/// `htl types add <library>`: the declarations a library did not ship, from the collection
1632/// that has them. The revision is recorded because nothing else in that ecosystem does —
1633/// see `Project::add_types`.
1634fn cmd_types_add(library: &str, from: Option<&Path>, force: bool) -> Result<ExitCode> {
1635    let project = pkg_project().context("`types/` is a project's, so this runs in one")?;
1636    let types = decl_root(&project.root)?;
1637    let sync = match from {
1638        Some(dir) => project.add_types_from(dir, library, "local", force, &types)?,
1639        None => project.add_types(library, force, &types)?,
1640    };
1641    report_types_sync(&sync, &project.root);
1642    if sync.written.is_empty() && !sync.taken.is_empty() {
1643        eprintln!("htl: nothing written; --force replaces what is already there");
1644    }
1645    Ok(ExitCode::SUCCESS)
1646}
1647
1648/// What `htl unused` was asked for, beyond the paths.
1649struct UnusedFlags {
1650    json: bool,
1651    /// Exit 1 when anything was reported. Off by default: "unused" is a question about
1652    /// intent, so CI opts in rather than out.
1653    fail_on_unused: bool,
1654    use_cache: bool,
1655    explain: bool,
1656}
1657
1658/// What `htl adopt` was asked for, beyond the paths.
1659struct AdoptFlags {
1660    json: bool,
1661    /// List every marked declaration under the table, and each `applicable` candidate
1662    /// after them; the plain form prints the table alone.
1663    detail: bool,
1664    use_cache: bool,
1665    explain: bool,
1666}
1667
1668/// What `htl check` was asked for, beyond the paths and the lint selection.
1669struct CheckFlags {
1670    strict: bool,
1671    list_lints: bool,
1672    /// `--explain <rule>`: print the rule's explanation and exit.
1673    explain_rule: Option<String>,
1674    json: bool,
1675    use_cache: bool,
1676    cache_mode: Option<cache::Mode>,
1677    explain: bool,
1678    /// `--statistics`: the per-rule table in place of the findings.
1679    statistics: bool,
1680}
1681
1682struct TestFlags {
1683    fail_fast: bool,
1684    /// Finding no test file is a pass rather than a failure.
1685    allow_empty: bool,
1686    verbose: bool,
1687    quiet: bool,
1688    slow: Option<f64>,
1689    update: bool,
1690    coverage: bool,
1691    coverage_lines: bool,
1692    /// Where to write the lcov tracefile, if asked for.
1693    lcov: Option<PathBuf>,
1694    /// Where to write the JUnit XML report, if asked for.
1695    junit: Option<PathBuf>,
1696    json: bool,
1697    no_cache: bool,
1698    explain: bool,
1699    seed: Option<u64>,
1700}
1701
1702fn print_coverage(cov: &report::CoverageReport, with_lines: bool) {
1703    let width = cov
1704        .modules
1705        .iter()
1706        .map(|m| m.path.len())
1707        .max()
1708        .unwrap_or(4)
1709        .max(5);
1710    for m in &cov.modules {
1711        eprintln!(
1712            "coverage: {:<width$}  {:>5}/{:<5} {:5.1}%",
1713            m.path,
1714            m.executed,
1715            m.total,
1716            100.0 * m.executed as f64 / m.total as f64
1717        );
1718        if !m.never_ran.is_empty() {
1719            let names: Vec<String> = m
1720                .never_ran
1721                .iter()
1722                .map(|f| format!("{} ({})", f.name, f.line))
1723                .collect();
1724            eprintln!("          never ran: {}", names.join(", "));
1725        }
1726        if with_lines && !m.unexecuted.is_empty() {
1727            let spans: Vec<String> = m
1728                .unexecuted
1729                .iter()
1730                .map(|(a, b)| {
1731                    if a == b {
1732                        a.to_string()
1733                    } else {
1734                        format!("{a}-{b}")
1735                    }
1736                })
1737                .collect();
1738            eprintln!("          unexecuted: {}", spans.join(", "));
1739        }
1740    }
1741    if cov.total > 0 {
1742        eprintln!(
1743            "coverage: {:<width$}  {:>5}/{:<5} {:5.1}%  (statements)",
1744            "total",
1745            cov.executed,
1746            cov.total,
1747            100.0 * cov.executed as f64 / cov.total as f64
1748        );
1749    } else {
1750        eprintln!("coverage: no .tl module reached");
1751    }
1752}
1753
1754/// One file's report as a JUnit suite.
1755///
1756/// The assertion library reports a failure as `"<suite > test>: <message>"` and its tests
1757/// by the same composed name, so a failing case takes back the message printed under the
1758/// file by matching that prefix — including the traceback a runtime error carries, which
1759/// belongs in the report for the same reason it belongs on the terminal: it is the part
1760/// that says where.
1761fn junit_suite(rep: &htl::testing::FileReport) -> junit::Suite {
1762    let mut left: Vec<&str> = rep.failures.iter().map(String::as_str).collect();
1763    let cases = rep
1764        .tests
1765        .iter()
1766        .map(|t| {
1767            let failure = (!t.ok)
1768                .then(|| {
1769                    let head = format!("{}: ", t.name);
1770                    let at = left.iter().position(|m| m.starts_with(&head))?;
1771                    Some(left.remove(at)[head.len()..].to_string())
1772                })
1773                .flatten();
1774            junit::Case {
1775                name: t.name.clone(),
1776                ms: t.ms,
1777                // A failing test whose message could not be matched still failed: say so
1778                // rather than reporting it as passed.
1779                failure: failure.or_else(|| (!t.ok).then(|| "failed".to_string())),
1780            }
1781        })
1782        .collect();
1783    let error = if !rep.check.ok() {
1784        Some(junit::Error {
1785            message: "type check failed".to_string(),
1786            kind: "check",
1787            body: rep
1788                .check
1789                .error_items
1790                .iter()
1791                .map(|d| d.clone().spelled().to_string())
1792                .collect::<Vec<_>>()
1793                .join("\n"),
1794        })
1795    } else {
1796        rep.error.as_ref().map(|e| junit::Error {
1797            message: e.clone(),
1798            kind: "error",
1799            body: e.clone(),
1800        })
1801    };
1802    junit::Suite {
1803        file: htl::diagnostic::display_path(&rep.path),
1804        duration_ms: rep.duration_ms,
1805        error,
1806        cases,
1807    }
1808}
1809
1810fn cmd_test(
1811    paths: &[PathBuf],
1812    filter: Option<&str>,
1813    lib: &str,
1814    lint: Option<&str>,
1815    flags: TestFlags,
1816) -> Result<ExitCode> {
1817    let paths = if paths.is_empty() {
1818        vec![PathBuf::from(".")]
1819    } else {
1820        paths.to_vec()
1821    };
1822    if let Some(first) = paths.first() {
1823        auto_dts(first)?;
1824    }
1825    // A patched dependency's tests are its suite, not this project's: `htl pkg patch`
1826    // takes the whole package root, tests included, and running them here would report a
1827    // library's own failures as the project's.
1828    let cfg = load_config(&paths[0])?;
1829    let model = project::model_of(&cfg, &paths[0])?;
1830    let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Test);
1831    let files = htl::testing::discover_tests_for(&paths, &skip, lib)?;
1832    // A test at the root of a project laid out flat without saying so would only fail on
1833    // its first `require`; say what is wrong instead, as `check` does.
1834    project::refuse_flat_root(model.as_ref(), &paths, &files)?;
1835    // Finding nothing goes through the same report as any run: under `--allow-empty` its
1836    // summary line, and under `--format json` its document whether allowed or not, so a
1837    // reader of stdout always gets one.
1838    let empty = files.is_empty();
1839    if empty {
1840        eprintln!("htl test: no test files found (looked for .tl files that require(\"{lib}\"))");
1841    }
1842    let opts = project::TestOptions {
1843        config: &cfg,
1844        model: model.as_ref(),
1845        lint,
1846        lib,
1847        filter,
1848        run: htl::testing::RunOptions {
1849            fail_fast: flags.fail_fast,
1850            update_snapshots: flags.update,
1851            coverage: flags.coverage,
1852            // Given, or drawn for the run and printed below, so that it can be given back.
1853            seed: flags.seed,
1854            // `project::test` fills it from the config it is handed.
1855            async_: Default::default(),
1856            lang: Default::default(),
1857        },
1858        cache: project::cache_options(
1859            !flags.no_cache,
1860            Some(cache::Mode::PerModule),
1861            &cfg,
1862            flags.explain,
1863        ),
1864    };
1865
1866    let mut sink = project::Sink::new(report::Out::new(flags.json, false));
1867    let mut json_files: Vec<report::TestFile> = Vec::new();
1868    let mut junit_suites: Vec<junit::Suite> = Vec::new();
1869    // What is left of the run here: how a file reads on a terminal, and what the document
1870    // says about it. Which files run, in what isolation, from what store — and what they
1871    // draw — is `project::test`'s.
1872    let rep = if empty {
1873        // Nothing to run, so no session to open and no store to touch: the run's report
1874        // with every count at zero, and no file having drawn from the seed.
1875        project::TestReport {
1876            files: Vec::new(),
1877            ran: 0,
1878            passed: 0,
1879            failed: 0,
1880            files_with_errors: 0,
1881            replayed: 0,
1882            seed: flags.seed.unwrap_or(0),
1883            duration_ms: 0.0,
1884            coverage: None,
1885        }
1886    } else {
1887        project::test(&mut sink, &files, &opts, &mut |rep, sink| {
1888            if flags.json {
1889                json_files.push(report::TestFile::from_report(rep, sink.out().take()));
1890            }
1891            if flags.junit.is_some() {
1892                junit_suites.push(junit_suite(rep));
1893            }
1894            // Spelled as `htl check` spells the same file, whatever path the walk was handed.
1895            let f = htl::diagnostic::display_path(&rep.path);
1896            let tag = if rep.ok() { "ok  " } else { "FAIL" };
1897            let detail = if !rep.check.ok() {
1898                "type check failed".to_string()
1899            } else if let Some(e) = &rep.error {
1900                // The cause on the file's own line, its frames under it: a traceback inside
1901                // the parenthesised summary would push `12 ms` past a screen of stack.
1902                format!("error: {}", e.lines().next().unwrap_or_default())
1903            } else if rep.file_level {
1904                "ran to completion (no test library used)".to_string()
1905            } else {
1906                format!("{} passed, {} failed", rep.passed, rep.failed)
1907            };
1908            // Quiet: a passing file is silence; failures, errors and slow tests still show.
1909            // JSON: nothing on stderr, the document carries it all.
1910            let show_file = !flags.json && (!flags.quiet || !rep.ok());
1911            if show_file {
1912                eprintln!("{tag} {f}  ({detail}, {:.0} ms)", rep.duration_ms);
1913                if let Some(e) = &rep.error {
1914                    for line in e.lines().skip(1) {
1915                        eprintln!("      {line}");
1916                    }
1917                }
1918            }
1919            for tr in &rep.tests {
1920                let slow = flags.slow.is_some_and(|ms| tr.ms >= ms);
1921                if !flags.json && (flags.verbose || slow) {
1922                    if flags.quiet && !show_file {
1923                        // The file line was skipped: name the file with the slow test.
1924                        eprintln!("slow {f}  {}  ({:.1} ms)", tr.name, tr.ms);
1925                        continue;
1926                    }
1927                    let mark = if tr.ok { "ok  " } else { "FAIL" };
1928                    let note = if slow && !flags.verbose {
1929                        "  [slow]"
1930                    } else {
1931                        ""
1932                    };
1933                    eprintln!("      {mark} {}  ({:.1} ms){note}", tr.name, tr.ms);
1934                }
1935            }
1936            if !flags.json {
1937                for m in &rep.failures {
1938                    eprintln!("      - {m}");
1939                }
1940                // A snapshot written or rewritten is a change on disk: always say so, even in -q.
1941                for p in &rep.snapshots_written {
1942                    eprintln!(
1943                        "snapshot written: {}",
1944                        htl::diagnostic::display_path(Path::new(p))
1945                    );
1946                }
1947                for p in &rep.snapshots_updated {
1948                    eprintln!(
1949                        "snapshot updated: {}",
1950                        htl::diagnostic::display_path(Path::new(p))
1951                    );
1952                }
1953            }
1954        })?
1955    };
1956
1957    if let Some(out) = &flags.junit {
1958        // The run's own total, not the sum of the files: it is the number the summary
1959        // line prints, and the report is there to agree with the summary line.
1960        std::fs::write(out, junit::document(&junit_suites, rep.duration_ms))
1961            .with_context(|| format!("writing {}", out.display()))?;
1962    }
1963    if let (Some(out), Some(cov)) = (&flags.lcov, &rep.coverage) {
1964        // Against the project root rather than the working directory: a tracefile is
1965        // uploaded from wherever CI ran the command and resolved against the repository.
1966        let root = match &cfg {
1967            Some((dir, _, _)) => dir.clone(),
1968            None => std::env::current_dir()?,
1969        };
1970        let root = std::fs::canonicalize(&root).unwrap_or(root);
1971        std::fs::write(out, cov.lcov(&root))
1972            .with_context(|| format!("writing {}", out.display()))?;
1973    }
1974    // An empty run is a pass only when asked for; the document's `ok` says what the exit
1975    // code says, so a reader of either sees the same refusal.
1976    let ok = rep.ok() && (!empty || flags.allow_empty);
1977    if flags.json {
1978        let summary = report::TestSummary {
1979            files: rep.files.len(),
1980            files_run: rep.ran,
1981            passed: rep.passed,
1982            failed: rep.failed,
1983            files_with_errors: rep.files_with_errors,
1984            replayed: rep.replayed,
1985            duration_ms: rep.duration_ms,
1986            ok,
1987            seed: rep.seed,
1988        };
1989        report::emit(&report::TestReport {
1990            files: json_files,
1991            summary,
1992            coverage: rep.coverage,
1993        })?;
1994    } else if !empty || flags.allow_empty {
1995        // A refused empty run says so with the notice alone, as it always has.
1996        if let Some(cov) = &rep.coverage {
1997            print_coverage(cov, flags.coverage_lines);
1998            if let Some(out) = &flags.lcov {
1999                eprintln!("coverage: lcov written to {}", out.display());
2000            }
2001        }
2002        eprintln!(
2003            "htl test: {} file(s), {} passed, {} failed, {} file(s) with errors{}{} ({:.0} ms)",
2004            rep.ran,
2005            rep.passed,
2006            rep.failed,
2007            rep.files_with_errors,
2008            if rep.skipped() > 0 {
2009                format!(", {} file(s) not run (--fail-fast)", rep.skipped())
2010            } else {
2011                String::new()
2012            },
2013            // Says the checking was reused, not the run: every one of these files ran.
2014            if rep.replayed > 0 {
2015                format!(", {} checked from cache", rep.replayed)
2016            } else {
2017                String::new()
2018            },
2019            rep.duration_ms
2020        );
2021        // Always, not only on failure: the seed of a run that passed is what reproduces
2022        // the run that passes, and a failure two commits later is compared against it.
2023        // A run of no files drew nothing, so there is nothing to repeat.
2024        if !empty {
2025            eprintln!(
2026                "htl test: seed {} (repeat with --seed {})",
2027                rep.seed, rep.seed
2028            );
2029        }
2030    }
2031    Ok(if ok {
2032        ExitCode::SUCCESS
2033    } else {
2034        ExitCode::FAILURE
2035    })
2036}
2037
2038/// Name the patched dependencies this walk enters, in the shape the other reports use.
2039///
2040/// Only the ones actually below a given root: `htl check src` walks the project's own
2041/// sources and nothing under `patches/`, and saying otherwise would be a claim about files
2042/// that were not read.
2043fn report_patched(paths: &[PathBuf]) {
2044    let roots: Vec<PathBuf> = paths
2045        .iter()
2046        .filter_map(|p| std::fs::canonicalize(p).ok())
2047        .collect();
2048    let cwd = std::env::current_dir().unwrap_or_default();
2049    // The project found the way every command finds it; a failure to find one was said by
2050    // the command itself, which ran first.
2051    let Some(project) = paths
2052        .first()
2053        .and_then(|p| htl::model::Project::find_root(p).ok().flatten())
2054        .map(|r| r.root)
2055        .filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
2056        .map(|r| htl::pkg::MluaProject::at(&r))
2057    else {
2058        return;
2059    };
2060    for p in &project.patches {
2061        let canon = std::fs::canonicalize(&p.dir).unwrap_or_else(|_| p.dir.clone());
2062        if !roots.iter().any(|r| canon.starts_with(r)) {
2063            continue;
2064        }
2065        let shown = p.dir.strip_prefix(&cwd).unwrap_or(&p.dir);
2066        eprintln!("  patched {} ({})", shown.display(), p.name);
2067    }
2068}
2069
2070/// Nearest `htl.toml` above the first path: `(dir holding it, path, config)`.
2071///
2072/// Where `[toolchain] htl` is answered, and the only place: every command that reads the
2073/// config comes through here, and the pin has to be settled before the command reads a
2074/// source file — which is a property of this function, not something each command could
2075/// be trusted to repeat. `htl new` / `htl init` do not call it, so a mismatch never stops
2076/// anyone from creating a project.
2077///
2078/// The version compared is this binary's, which is the one the pin is about. The `htl`
2079/// crate a Rust host builds against is Cargo's, pinned in `Cargo.toml` — a separate
2080/// question, and the one [`warn_cargo_htl_mismatch`] answers.
2081fn load_config(first: &Path) -> Result<project::Config> {
2082    let cfg = project::config_of(first)?;
2083    if let Some((_, path, c)) = &cfg {
2084        htl::config::check_toolchain(c, path, env!("CARGO_PKG_VERSION"))?;
2085    }
2086    Ok(cfg)
2087}
2088
2089/// Say so, once, when the `Cargo.toml` around this project asks for an `htl` crate this
2090/// command is not.
2091///
2092/// The two halves of htl are released together and a project uses both: the crate the host
2093/// links, and the command that checks the Teal beside it. A project left at `htl = "0.5.1"`
2094/// while the installed CLI had moved to 0.6.0 was checked by one and built against the
2095/// other, and nothing in either output mentioned the other one — which is the whole of the
2096/// failure, since either version alone was fine.
2097///
2098/// **A warning, not an error, and not one of the summary's `warning(s)`** — that count is
2099/// the checker's, and this is not about the sources. A project goes to a hard error over a
2100/// version skew for one of two reasons, and htl has neither: the format between the halves
2101/// is unstable, so a mismatched pair miscompiles rather than failing (wasm-bindgen refuses
2102/// a JS glue built by another version); or the diagnostic downstream is opaque, so the
2103/// person would otherwise read a type error from deep inside a dependency (cargo's
2104/// `rust-version`). Here both halves worked — the run that produced this report is the
2105/// evidence — and the line is worth printing only because the person has no other way to
2106/// notice. npm's `engines` is the same shape and warns by default; Prisma says nothing at
2107/// all, and its silence is filed as a bug.
2108///
2109/// Read from the `Cargo.toml` of the crate the project sits in, `[dependencies] htl` only:
2110/// a string, or a table with `version`. A table without one — `path`, `git`, or a
2111/// `workspace = true` inheritance — states no requirement here and is passed over without
2112/// a word, which is exactly what a scaffold written by a checkout-built CLI produces. No
2113/// `Cargo.toml`, no `[dependencies]`, no `htl` key, or a requirement cargo itself would
2114/// reject: nothing is printed, because there is nothing this can be surer about than cargo.
2115fn warn_cargo_htl_mismatch(first: &Path) {
2116    let Some(root) = htl::dts::find_cargo_package_root(first) else {
2117        return;
2118    };
2119    let Ok(text) = fs::read_to_string(root.join("Cargo.toml")) else {
2120        return;
2121    };
2122    let Ok(manifest) = text.parse::<toml::Table>() else {
2123        return;
2124    };
2125    let Some(dep) = manifest.get("dependencies").and_then(|d| d.get("htl")) else {
2126        return;
2127    };
2128    let req_text = match dep {
2129        toml::Value::String(s) => s.as_str(),
2130        toml::Value::Table(t) => match t.get("version").and_then(toml::Value::as_str) {
2131            Some(s) => s,
2132            None => return,
2133        },
2134        _ => return,
2135    };
2136    let running = env!("CARGO_PKG_VERSION");
2137    let (Ok(req), Ok(version)) = (
2138        semver::VersionReq::parse(req_text),
2139        semver::Version::parse(running),
2140    ) else {
2141        return;
2142    };
2143    if req.matches(&version) {
2144        return;
2145    }
2146    // Both ways out are named because either is the right one: the project may be the
2147    // thing that is current, in which case the command is what moves.
2148    eprintln!(
2149        "htl {running}; Cargo.toml asks for htl {req_text} — the crate and the CLI are \
2150         meant to move together (cargo install htl-cli --version {req_text}, or bump the \
2151         dependency)"
2152    );
2153}
2154
2155fn cmd_fmt(paths: &[PathBuf], check: bool, indent: Option<usize>) -> Result<ExitCode> {
2156    let paths = if paths.is_empty() {
2157        vec![PathBuf::from(".")]
2158    } else {
2159        paths.to_vec()
2160    };
2161    let cfg = load_config(&paths[0])?;
2162    let indent = indent
2163        .or_else(|| cfg.as_ref().and_then(|(_, _, c)| c.fmt.indent))
2164        .unwrap_or(3);
2165    let h = Htl::new()?;
2166    config_lang(&h, &cfg)?;
2167    // Not a dependency's files, a patched one included: formatting the copy would turn
2168    // every one of its files into a diff against the revision it was taken from, and bury
2169    // the project's own change somewhere inside that.
2170    let model = project::model_of(&cfg, &paths[0])?;
2171    let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
2172    let files = htl::collect_tl_skipping(&paths, &skip)?;
2173    let (mut changed, mut failed) = (0usize, 0usize);
2174    for f in &files {
2175        let before = fs::read_to_string(f).with_context(|| format!("reading {}", f.display()))?;
2176        let after = match h.format_file(f, indent) {
2177            Ok(s) => s,
2178            Err(e) => {
2179                eprintln!("error: {e}");
2180                failed += 1;
2181                continue;
2182            }
2183        };
2184        if after != before {
2185            changed += 1;
2186            if check {
2187                eprintln!("would reformat: {}", f.display());
2188            } else {
2189                fs::write(f, after).with_context(|| format!("writing {}", f.display()))?;
2190                eprintln!("reformatted: {}", f.display());
2191            }
2192        }
2193    }
2194    eprintln!(
2195        "htl fmt: {} file(s), {} {}, {} failed",
2196        files.len(),
2197        changed,
2198        if check { "would change" } else { "reformatted" },
2199        failed
2200    );
2201    let fail = failed > 0 || (check && changed > 0);
2202    Ok(if fail {
2203        ExitCode::FAILURE
2204    } else {
2205        ExitCode::SUCCESS
2206    })
2207}
2208
2209struct FixFlags {
2210    rule: Vec<String>,
2211    unsafe_fixes: bool,
2212    dry_run: bool,
2213    diff: bool,
2214    allow_dirty: bool,
2215    allow_no_vcs: bool,
2216    exit_non_zero_on_fix: bool,
2217    json: bool,
2218}
2219
2220fn cmd_fix(paths: &[PathBuf], flags: FixFlags) -> Result<ExitCode> {
2221    use htl::fix::{FixOptions, fix_file, git_dirty, unified_diff};
2222    let paths = if paths.is_empty() {
2223        vec![PathBuf::from(".")]
2224    } else {
2225        paths.to_vec()
2226    };
2227    let cfg = load_config(&paths[0])?;
2228    // A dry run writes nothing, the declarations generated before the check included.
2229    auto_dts_to(&paths[0], !flags.dry_run)?;
2230    let model = project::model_of(&cfg, &paths[0])?;
2231    // What `htl check` holds a file to, resolved the same way and read by the same checker,
2232    // so a file this run leaves reports what a check of it would.
2233    let scope = project::Scope::new(&cfg, model.as_ref(), &paths[0], None)?;
2234    let h = project::checker(
2235        model.as_ref(),
2236        scope.lints.selection(),
2237        &project::lang_of(&cfg),
2238    )?;
2239    let opts = FixOptions {
2240        unsafe_fixes: flags.unsafe_fixes,
2241        promoted: cfg
2242            .as_ref()
2243            .map(|(_, _, c)| c.fix.unsafe_.clone())
2244            .unwrap_or_default(),
2245        disabled: cfg
2246            .as_ref()
2247            .map(|(_, _, c)| c.fix.disable.clone())
2248            .unwrap_or_default(),
2249        only: flags.rule.clone(),
2250        dry_run: flags.dry_run,
2251    };
2252    // Here as well as inside `fix_file`, so a misspelt rule is answered even when the
2253    // paths hold no `.tl` at all — the request is wrong either way.
2254    opts.validate()?;
2255    // Written as `htl fmt` walks, not as `htl check` does: this command rewrites files, so a
2256    // patched dependency is left alone whatever the fixes would be. An edit there belongs
2257    // in the diff the project makes against the revision it took, written by a person.
2258    let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
2259    // Only what a module of the project holds, as `htl check` walks it.
2260    let (files, outside) = project::held_by_modules(
2261        model.as_ref(),
2262        &paths,
2263        htl::collect_tl_skipping(&paths, &skip)?,
2264    )?;
2265    if let Some(note) = project::outside_modules_note(model.as_ref(), &outside, "fixed") {
2266        eprintln!("htl fix: {note}");
2267    }
2268    // But checked as `htl check` walks: the copy is still the project's code, and what is
2269    // wrong in it is what the two commands both judge the tree by. Only checked, never
2270    // handed to `fix_file`.
2271    let check_skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Check);
2272    let checked_only: Vec<PathBuf> = project::held_by_modules(
2273        model.as_ref(),
2274        &paths,
2275        htl::collect_tl_skipping(&paths, &check_skip)?,
2276    )?
2277    .0
2278    .into_iter()
2279    .filter(|f| !files.contains(f))
2280    .collect();
2281
2282    // The working tree is the undo: refuse to rewrite what git could not give back.
2283    if !flags.dry_run {
2284        let mut dirty = Vec::new();
2285        let mut no_vcs = Vec::new();
2286        for f in &files {
2287            match git_dirty(f)? {
2288                Some(true) => dirty.push(f.clone()),
2289                Some(false) => {}
2290                None => no_vcs.push(f.clone()),
2291            }
2292        }
2293        if !dirty.is_empty() && !flags.allow_dirty {
2294            bail!(
2295                "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",
2296                dirty
2297                    .iter()
2298                    .map(|p| p.display().to_string())
2299                    .collect::<Vec<_>>()
2300                    .join("\n  ")
2301            );
2302        }
2303        if !no_vcs.is_empty() && !flags.allow_no_vcs {
2304            bail!(
2305                "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",
2306                no_vcs
2307                    .iter()
2308                    .map(|p| p.display().to_string())
2309                    .collect::<Vec<_>>()
2310                    .join("\n  ")
2311            );
2312        }
2313    }
2314
2315    let mut sink = project::Sink::new(report::Out::new(flags.json, false));
2316    // Judged by the levels `htl check` judges by: a finding under a rule at `deny` fails.
2317    sink.judge_by(scope.lints.selection());
2318    // Dependencies are reported as `htl check` reports them and never rewritten: a fix
2319    // under `.htl/` goes at the next install, one under `[check] paths` is not this
2320    // project's. `fix_file` only ever writes the file it was given.
2321    let origins = project::Origins::new(model.as_ref());
2322    let walk = scope.walk(&cfg, model.as_ref(), &origins);
2323    let walked: Vec<PathBuf> = files.iter().chain(&checked_only).cloned().collect();
2324    sink.walking(&walked);
2325    let (mut applied, mut skipped, mut json_files) = (Vec::new(), Vec::new(), Vec::new());
2326    let (mut changed, mut deferred, mut reverted) = (0usize, 0usize, 0usize);
2327    let mut found = htl::verdict::Findings::default();
2328    let mut infos: Vec<(PathBuf, htl::CheckInfo)> = Vec::with_capacity(walked.len());
2329    for f in &files {
2330        // Put back after each file, as `htl check` does, so a file is fixed against what
2331        // it may read and not also against the directories of the files before it.
2332        let saved = h.search_path()?;
2333        project::file_view(&h, model.as_ref(), f)?;
2334        let before = if flags.diff {
2335            std::fs::read_to_string(f).ok()
2336        } else {
2337            None
2338        };
2339        let out = fix_file(&h, f, &opts)?;
2340        if out.contents.is_some() {
2341            changed += 1;
2342        }
2343        deferred += out.deferred;
2344        if out.reverted.is_some() {
2345            reverted += 1;
2346        }
2347        if !flags.json {
2348            for a in &out.applied {
2349                eprintln!(
2350                    "fixed: {}:{}: {} ({}{})",
2351                    project::display_path(f),
2352                    a.line,
2353                    a.rule,
2354                    a.applicability.as_str(),
2355                    if flags.dry_run { ", not written" } else { "" }
2356                );
2357            }
2358            for s in &out.skipped {
2359                eprintln!(
2360                    "skipped: {}:{}: {} — {}",
2361                    project::display_path(f),
2362                    s.line,
2363                    s.rule,
2364                    s.reason
2365                );
2366            }
2367            if let Some(r) = &out.reverted {
2368                eprintln!("reverted: {}: {r}", project::display_path(f));
2369            }
2370            if let Some(o) = &out.oscillation {
2371                eprintln!(
2372                    "stopped: {}: fixes of {o} undo each other",
2373                    project::display_path(f)
2374                );
2375            }
2376            if out.deferred > 0 {
2377                eprintln!(
2378                    "deferred: {}: {} edit(s) overlapped applied ones; run htl fix again",
2379                    project::display_path(f),
2380                    out.deferred
2381                );
2382            }
2383            if flags.diff
2384                && let (Some(b), Some(a)) = (&before, &out.contents)
2385            {
2386                print!("{}", unified_diff(&project::display_path(f), b, a));
2387            }
2388            // A suggestion is never written, so the diff is the only place it is shown.
2389            // Against what was applied, when something was: the two are one edit session.
2390            if flags.diff
2391                && let (Some(b), Some(s)) = (
2392                    out.contents.as_ref().or(before.as_ref()),
2393                    out.suggested.as_ref(),
2394                )
2395            {
2396                print!(
2397                    "{}",
2398                    unified_diff(&format!("{} (suggested)", project::display_path(f)), b, s)
2399                );
2400            }
2401        }
2402        // What the file says as it is left, the way `htl check` would say it: the checker's
2403        // result and this layer's lints, while the path it was checked under is in place.
2404        found.lints += project::file_findings(&h, &mut sink, f, &out.check, &walk)?;
2405        h.set_search_path(&saved)?;
2406        found.errors += out.check.errors.len();
2407        found.warnings += out.check.warnings.len();
2408        infos.push((f.clone(), out.check.clone()));
2409        if flags.json {
2410            applied.extend(out.applied.iter().map(|a| report::FixApplied {
2411                file: project::display_path(f),
2412                line: a.line,
2413                rule: a.rule.clone(),
2414                applicability: a.applicability.as_str(),
2415                pass: a.pass,
2416            }));
2417            skipped.extend(out.skipped.iter().map(|s| report::FixSkipped {
2418                file: project::display_path(f),
2419                line: s.line,
2420                rule: s.rule.clone(),
2421                reason: s.reason.clone(),
2422            }));
2423            json_files.push(report::FixFile {
2424                path: project::display_path(f),
2425                changed: out.contents.is_some(),
2426                deferred: out.deferred,
2427                reverted: out.reverted.clone(),
2428                oscillation: out.oscillation.clone(),
2429                diagnostics: sink.out().take(),
2430            });
2431        }
2432    }
2433    // A patched copy: checked as `htl check` checks it, and not fixed.
2434    for f in &checked_only {
2435        let m = project::check_one(&h, &mut sink, f, &walk)?;
2436        found.errors += m.errors;
2437        found.warnings += m.warnings;
2438        found.lints += m.lints;
2439        infos.push((f.clone(), m.requires_only()));
2440        if flags.json {
2441            json_files.push(report::FixFile {
2442                path: project::display_path(f),
2443                changed: false,
2444                deferred: 0,
2445                reverted: None,
2446                oscillation: None,
2447                diagnostics: sink.out().take(),
2448            });
2449        }
2450    }
2451    // What the project says about itself as a whole.
2452    // A dry run publishes nothing either.
2453    let mut whole = scope.whole(&cfg, model.as_ref());
2454    whole.publish = !flags.dry_run;
2455    let w = project::project_findings(&mut sink, &whole, &infos);
2456    found.errors += w.errors;
2457    found.lints += w.lints;
2458    let project_diagnostics = if flags.json {
2459        sink.out().take()
2460    } else {
2461        Vec::new()
2462    };
2463    // A broken dependency is an error `htl fix` cannot remove; it remains, as `htl check`
2464    // would count it.
2465    found.errors += sink.dependency_error_count();
2466    found.denied = sink.denied();
2467    // Judged as `htl check` judges the same tree: the same findings, the same policy.
2468    let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
2469    let errors_remaining = found.errors;
2470    let n_applied = if flags.json { applied.len() } else { 0 };
2471    let fail =
2472        htl::verdict::verdict(&found, &policy) || (flags.exit_non_zero_on_fix && changed > 0);
2473    if flags.json {
2474        let n_skipped = skipped.len();
2475        report::emit(&report::FixReport {
2476            dry_run: flags.dry_run,
2477            applied,
2478            skipped,
2479            files: json_files,
2480            summary: report::FixSummary {
2481                files: files.len(),
2482                files_changed: changed,
2483                applied: n_applied,
2484                skipped: n_skipped,
2485                deferred,
2486                reverted,
2487                errors_remaining,
2488                warnings: found.warnings,
2489                lints: found.lints,
2490                denied: found.denied,
2491                strict: policy.strict,
2492                ok: !fail,
2493            },
2494            diagnostics: project_diagnostics,
2495        })?;
2496    } else {
2497        // What else the verdict counted, said only when it did: a finding at `deny`, and
2498        // under `strict` every warning and lint. Without it a run that failed on a lint
2499        // would end in `0 error(s) remaining`.
2500        let judged = judged(&found, &policy);
2501        eprintln!(
2502            "htl fix: {} file(s){}, {} changed{}, {} error(s) remaining{}{}",
2503            files.len(),
2504            if checked_only.is_empty() {
2505                String::new()
2506            } else {
2507                format!(" + {} checked in patched dependencies", checked_only.len())
2508            },
2509            changed,
2510            if flags.dry_run {
2511                " (dry run, nothing written)"
2512            } else {
2513                ""
2514            },
2515            errors_remaining,
2516            judged,
2517            if deferred > 0 {
2518                format!(", {deferred} deferred")
2519            } else {
2520                String::new()
2521            }
2522        );
2523    }
2524    Ok(if fail {
2525        ExitCode::FAILURE
2526    } else {
2527        ExitCode::SUCCESS
2528    })
2529}
2530
2531/// Type-check a tree, replaying the modules whose inputs have not moved.
2532///
2533/// The order here is load-bearing. Generating `.d.tl` and collecting the file list come
2534/// first, because both produce inputs the keys are built from. Every module is looked up
2535/// before any is checked, so that a run where nothing moved never builds a checker at all —
2536/// that costs about 13.5 ms (`crates/htl-core/benches/check.rs`), which is most of what a
2537/// fully replayed run has to save on a small project.
2538///
2539/// A module that misses re-checks its dependencies as part of its own check, since the
2540/// checker's store starts empty. So an edit costs the edited module, whatever depends on
2541/// it, and whatever those pull in — less than the project, more than the minimum.
2542fn cmd_check(paths: &[PathBuf], lint: Option<&str>, flags: CheckFlags) -> Result<ExitCode> {
2543    let CheckFlags {
2544        list_lints,
2545        json,
2546        use_cache,
2547        cache_mode,
2548        explain,
2549        statistics,
2550        ..
2551    } = flags;
2552    let mut sink = project::Sink::new(report::Out::new(json, statistics));
2553    let paths = if paths.is_empty() {
2554        vec![PathBuf::from(".")]
2555    } else {
2556        paths.to_vec()
2557    };
2558    // Listing the rules reports nothing about the project and shares nothing with a run —
2559    // and now not even a Lua state: the registry is Rust (`htl_core::lint::RULES`), which
2560    // is what lets the rules the project layer reports under be listed beside the ones
2561    // `lint.lua` implements.
2562    // `--explain <rule>`: the rule's explanation, and nothing else. The name is the one a
2563    // finding prints in its `[htl <rule>]` suffix, so a reader hands the flag what they
2564    // were shown; a name no check reports under — a typo, or a fix class — is refused the
2565    // way `--lint` refuses it, on stderr, with the exit code an unusable argument gets.
2566    if let Some(rule) = flags.explain_rule.as_deref() {
2567        let Some(r) = htl::lint::explained(rule) else {
2568            eprintln!("unknown lint rule: {rule}");
2569            return Ok(ExitCode::from(2));
2570        };
2571        println!("{}  (default: {})\n\n{}", r.name, r.default, r.explain);
2572        return Ok(ExitCode::SUCCESS);
2573    }
2574    if list_lints {
2575        // The name and the level a project that says nothing gets. Two columns rather than
2576        // one because the default is a level now, and the five rules at `allow` are
2577        // otherwise invisible: a reader would have to turn one on to find out it was off.
2578        // Still one rule per line, name first, so it reads and greps as it always did.
2579        let width = htl::lint::rule_names()
2580            .iter()
2581            .map(|r| r.len())
2582            .max()
2583            .unwrap_or(0);
2584        for (name, level) in htl::lint::rule_defaults() {
2585            println!("{name:width$}  {level}");
2586        }
2587        // No pointer to `--explain` here: every rule listed has an explanation (the
2588        // registry's test holds it to that), and the listing is name-level pairs that
2589        // tests and greps read line by line. `--help` and a finding's own hint carry it.
2590        return Ok(ExitCode::SUCCESS);
2591    }
2592    // htl.toml first, then --lint, so the flag wins; `strict` from the file unless flagged.
2593    let cfg = load_config(&paths[0])?;
2594    warn_cargo_htl_mismatch(&paths[0]);
2595    let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), flags.strict);
2596    // `.d.tl` written from Rust source is an input to the check, so it is regenerated
2597    // before anything hashes the tree: a hit computed over stale declarations would be a
2598    // hit on a different question from the one being asked.
2599    if let Some(first) = paths.first() {
2600        auto_dts(first)?;
2601    }
2602    // A patched dependency is walked with the project's own sources — it is the project's
2603    // code, and its errors are the project's to fix. Which dependency each directory
2604    // stands in for is said here, so that an error under it is read as that dependency's
2605    // without the reader having to know the manifest.
2606    let walk_model = project::model_of(&cfg, &paths[0])?;
2607    // A directory is checked as a project: which of its files is which module, and what
2608    // they may read, is the project's to say. With none there is no answer to give, and
2609    // checking each file as a thing on its own would answer a different question without
2610    // saying so. A file named on its own is that question, asked outright, and is checked.
2611    if walk_model.is_none()
2612        && let Some(dir) = paths.iter().find(|p| p.is_dir())
2613    {
2614        bail!(
2615            "no {} or {} in {} or any directory above it: a directory is checked as a \
2616             project. Run `htl init` there to make it one, or name the .tl files to check \
2617             each on its own",
2618            htl::config::CONFIG_NAME,
2619            htl::pkg::MANIFEST_NAME,
2620            // Absolute: where the search started is the whole of the answer, and `.`
2621            // relative to itself would say nothing.
2622            fs::canonicalize(dir)
2623                .unwrap_or_else(|_| dir.clone())
2624                .display()
2625        );
2626    }
2627    let skip = project::not_walked(walk_model.as_ref(), &paths, htl::model::Purpose::Check);
2628    let (files, outside) = project::held_by_modules(
2629        walk_model.as_ref(),
2630        &paths,
2631        htl::collect_tl_skipping(&paths, &skip)?,
2632    )?;
2633    if let Some(note) = project::outside_modules_note(walk_model.as_ref(), &outside, "checked") {
2634        eprintln!("htl check: {note}");
2635    }
2636    if !json {
2637        report_patched(&paths);
2638    }
2639
2640    // The walk, the store and every decision about them are the library's: `include_tl!`
2641    // asks the same questions of the same store, and the two answering them separately is
2642    // what let them disagree. What is left here is the flags, the summary and the exit code.
2643    let rep = project::check(
2644        &mut sink,
2645        &files,
2646        &project::Options {
2647            paths: &paths,
2648            config: &cfg,
2649            model: walk_model.as_ref(),
2650            lint,
2651            cache: project::cache_options(use_cache, cache_mode, &cfg, explain),
2652        },
2653    )?;
2654    let fail = report_check(
2655        sink.out(),
2656        json,
2657        statistics,
2658        &rep,
2659        &policy,
2660        patched_files(walk_model.as_ref(), &rep.files),
2661    )?;
2662    Ok(if fail {
2663        ExitCode::FAILURE
2664    } else {
2665        ExitCode::SUCCESS
2666    })
2667}
2668
2669/// Report what no entry's `require` closure reaches.
2670///
2671/// The graph is the check's — `htl check` resolves every `require` already, and the
2672/// `require-cycle` lint reads the same edges — so this is that walk plus the entries the
2673/// project declares (`htl::unused`). What is left here is the flags, the printing and the
2674/// exit code.
2675fn cmd_unused(paths: &[PathBuf], flags: UnusedFlags) -> Result<ExitCode> {
2676    let UnusedFlags {
2677        json,
2678        fail_on_unused,
2679        use_cache,
2680        explain,
2681    } = flags;
2682    let paths = if paths.is_empty() {
2683        vec![PathBuf::from(".")]
2684    } else {
2685        paths.to_vec()
2686    };
2687    let cfg = load_config(&paths[0])?;
2688    // A `.d.tl` written from Rust source is an input to the check the graph comes from,
2689    // exactly as it is for `htl check`.
2690    auto_dts(&paths[0])?;
2691    let model = project::model_of(&cfg, &paths[0])?;
2692    let rep = htl::unused::unused(&htl::unused::Options {
2693        paths: &paths,
2694        config: &cfg,
2695        model: model.as_ref(),
2696        cache: project::cache_options(use_cache, None, &cfg, explain),
2697    })?;
2698    let s = &rep.summary;
2699    if json {
2700        report::emit(&rep)?;
2701    } else if s.no_entry {
2702        eprintln!(
2703            "htl unused: nothing to start from, so nothing is reported. An entry is \
2704             main.tl in the source root ([layout] source) or beside the manifest, a test file, a module under a [[contract]] directory, or a name \
2705             in [build] extra / host"
2706        );
2707    } else {
2708        if s.check_errors > 0 {
2709            eprintln!(
2710                "htl unused: {} error(s) in the check this graph comes from — what those \
2711                 files require is missing from it (htl check)",
2712                s.check_errors
2713            );
2714        }
2715        for m in &rep.modules {
2716            match &m.module {
2717                Some(n) => eprintln!("module: {} ({n})", m.path),
2718                None => eprintln!("module: {}", m.path),
2719            }
2720        }
2721        for d in &rep.dependencies {
2722            eprintln!("dependency: {}", d.name);
2723        }
2724        eprintln!(
2725            "htl unused: {}, {} [{} considered, {} reached, {}]",
2726            count(s.modules, "module", "modules"),
2727            count(s.dependencies, "dependency", "dependencies"),
2728            s.considered,
2729            s.reached,
2730            count(s.entries, "entry", "entries"),
2731        );
2732    }
2733    Ok(if fail_on_unused && !s.ok {
2734        ExitCode::FAILURE
2735    } else {
2736        ExitCode::SUCCESS
2737    })
2738}
2739
2740/// Report how many declarations carry each of htl's nine markers, and where.
2741///
2742/// The census is the check's — `htl check` already read every marker by position while
2743/// checking a file, exactly as the lints it drives do — so this is that census folded into
2744/// the nine features (`htl::adopt`). What is left here is the flags, the table, and the
2745/// exit code, which never moves: a report, not a gate.
2746fn cmd_adopt(paths: &[PathBuf], flags: AdoptFlags) -> Result<ExitCode> {
2747    let AdoptFlags {
2748        json,
2749        detail,
2750        use_cache,
2751        explain,
2752    } = flags;
2753    let paths = if paths.is_empty() {
2754        vec![PathBuf::from(".")]
2755    } else {
2756        paths.to_vec()
2757    };
2758    let cfg = load_config(&paths[0])?;
2759    // A `.d.tl` written from Rust source is an input to the check the census comes from,
2760    // exactly as it is for `htl check` and `htl unused`.
2761    auto_dts(&paths[0])?;
2762    let model = project::model_of(&cfg, &paths[0])?;
2763    let rep = htl::adopt::adopt(&htl::adopt::Options {
2764        paths: &paths,
2765        config: &cfg,
2766        model: model.as_ref(),
2767        cache: project::cache_options(use_cache, None, &cfg, explain),
2768    })?;
2769    if json {
2770        report::emit(&rep)?;
2771    } else {
2772        print_adopt(&rep, detail);
2773    }
2774    // Always 0: `htl adopt` reports what the project has adopted, and does not judge it
2775    // (the module doc says why — a threshold invites marking records to move the number).
2776    Ok(ExitCode::SUCCESS)
2777}
2778
2779/// The marker column's width, in both the table and `--detail`'s lines: the longest of
2780/// htl's nine, `---@extensible`, plus two spaces.
2781fn adopt_marker_width() -> usize {
2782    htl::adopt::FEATURES
2783        .iter()
2784        .map(|m| format!("---@{m}").len())
2785        .max()
2786        .unwrap_or(0)
2787        + 2
2788}
2789
2790/// The table, `--detail`'s lines when asked for, and the summary line — the text form of
2791/// an [`htl::adopt::Report`].
2792fn print_adopt(rep: &htl::adopt::Report, detail: bool) {
2793    let width = adopt_marker_width();
2794    eprintln!(
2795        "{:<width$} {:>4}  {:>10}",
2796        "feature",
2797        "used",
2798        "applicable",
2799        width = width
2800    );
2801    for f in &rep.features {
2802        let applicable = match f.applicable {
2803            Some(n) => n.to_string(),
2804            None => "-".to_string(),
2805        };
2806        eprintln!(
2807            "{:<width$} {:>4}  {:>10}",
2808            format!("---@{}", f.marker),
2809            f.used,
2810            applicable,
2811            width = width
2812        );
2813    }
2814    if detail {
2815        // Padded to the longest `file:line` of every site and every candidate about to
2816        // be printed, not per feature: one column, so the names line up down the whole
2817        // list, a candidate's line included.
2818        let line_width = rep
2819            .features
2820            .iter()
2821            .flat_map(|f| {
2822                f.sites
2823                    .iter()
2824                    .map(|s| format!("{}:{}", s.file.display(), s.line))
2825                    .chain(
2826                        f.candidates
2827                            .iter()
2828                            .map(|c| format!("{}:{}", c.file.display(), c.line)),
2829                    )
2830            })
2831            .map(|s| s.len())
2832            .max()
2833            .unwrap_or(0);
2834        for f in &rep.features {
2835            for s in &f.sites {
2836                eprintln!(
2837                    "  {:<width$}{:<line_width$}  {}",
2838                    format!("---@{}", f.marker),
2839                    format!("{}:{}", s.file.display(), s.line),
2840                    s.name,
2841                    width = width,
2842                    line_width = line_width
2843                );
2844            }
2845            // A candidate's line ends with how many construction sites made it one, so
2846            // a reader can tell it from a marked declaration above it.
2847            for c in &f.candidates {
2848                let sites = if c.sites == 1 {
2849                    "1 site".to_string()
2850                } else {
2851                    format!("{} sites", c.sites)
2852                };
2853                eprintln!(
2854                    "  {:<width$}{:<line_width$}  {}  (applicable: {}, {sites})",
2855                    format!("---@{}", f.marker),
2856                    format!("{}:{}", c.file.display(), c.line),
2857                    c.name,
2858                    c.reason,
2859                    width = width,
2860                    line_width = line_width
2861                );
2862            }
2863        }
2864    }
2865    let s = &rep.summary;
2866    if s.check_errors > 0 {
2867        eprintln!(
2868            "htl adopt: {} error(s) in the project's check (htl check says which); a file \
2869             with a syntax error contributes no markers",
2870            s.check_errors
2871        );
2872    }
2873    if s.markers == 0 {
2874        eprintln!(
2875            "htl adopt: {} of {} features used, no markers",
2876            s.used, s.features
2877        );
2878    } else {
2879        eprintln!(
2880            "htl adopt: {} of {} features used, {} in {}",
2881            s.used,
2882            s.features,
2883            count(s.markers, "marker", "markers"),
2884            count(s.files, "file", "files"),
2885        );
2886    }
2887}
2888
2889/// Say which file a module name resolves to, and what that hides.
2890///
2891/// The chain comes from the library ([`htl::resolve`]), over a checker set up exactly as a
2892/// check of this project sets one up — the installed deps, then the config's search paths,
2893/// in that order, because `add_path` prepends and the order is the whole answer. Asking
2894/// any other way would report a path nothing else uses.
2895///
2896/// A report, so both forms go to stdout (README, "Machine-readable output").
2897fn cmd_resolve(module: &str, path: Option<&Path>, json: bool) -> Result<ExitCode> {
2898    let start = path.unwrap_or(Path::new("."));
2899    let cfg = load_config(start)?;
2900    // The declarations a check generates before it reads anything are inputs to the
2901    // answer — `types/<crate>/` is written by `htl dts` — and a report without them would
2902    // describe a project nobody checks.
2903    auto_dts(start)?;
2904    let h = Htl::new()?;
2905    // First, so that the project's own directories go in front of it as they do under
2906    // `htl run`: `add_path` prepends, and the report prints the order it searched.
2907    h.install_std()?;
2908    let model = apply_model(&h, &cfg, start)?;
2909    let rep = htl::resolve::resolve(
2910        &h,
2911        module,
2912        cfg.as_ref().map(|(r, _, _)| r.as_path()),
2913        model.as_ref(),
2914    )?;
2915    if json {
2916        report::emit(&rep)?;
2917    } else {
2918        print_resolution(&rep);
2919    }
2920    Ok(if rep.summary.ok {
2921        ExitCode::SUCCESS
2922    } else {
2923        ExitCode::FAILURE
2924    })
2925}
2926
2927/// The text form of a resolution: a table in search order, then who answered — the project
2928/// model, or the search path and the directories it consulted. The order column is the reason one row is read and the others are not, which
2929/// is why it is printed rather than left to be looked up.
2930fn print_resolution(r: &htl::resolve::Resolution) {
2931    let ambiguous = r
2932        .candidates
2933        .iter()
2934        .any(|c| c.status == htl::resolve::Status::Ambiguous);
2935    // A name the host provides: what answers it at run time is the host, and a row read
2936    // for it is only the declaration it is typed from. Refused when a file implements it
2937    // too, and then the header is the error, as a check reports it.
2938    let typed_by = r
2939        .read
2940        .as_ref()
2941        .map(|d| format!(", typed by {d}"))
2942        .unwrap_or_default();
2943    match (&r.read, &r.error, &r.provided_by) {
2944        (_, Some(e), _) => println!("htl resolve {}: error: {e}", r.module),
2945        // Declared and nothing else: the environment provides it — a library installed on
2946        // the machine, a module registered where the model cannot read it. The declaration
2947        // is the file read, and comes first, as any file the name resolves to does.
2948        (Some(read), None, Some(by)) if r.provider == Some(htl::model::Provider::Declared) => {
2949            println!(
2950                "htl resolve {}: {read}, provided by the environment ({by})",
2951                r.module
2952            )
2953        }
2954        (_, None, Some(by)) => {
2955            println!(
2956                "htl resolve {}: provided by the host ({by}){typed_by}",
2957                r.module
2958            )
2959        }
2960        (Some(read), None, None) => println!("htl resolve {}: {read}", r.module),
2961        (None, None, None) if ambiguous => println!(
2962            "htl resolve {}: more than one module implements it, and no order picks one",
2963            r.module
2964        ),
2965        (None, None, None) => println!(
2966            "htl resolve {}: nothing in the project or on the search path answers require(\"{}\")",
2967            r.module, r.module
2968        ),
2969    }
2970    if !r.candidates.is_empty() {
2971        let w = |f: fn(&htl::resolve::Candidate) -> usize, head: usize| {
2972            r.candidates.iter().map(f).max().unwrap_or(0).max(head)
2973        };
2974        let file = w(|c| c.path.len(), 4);
2975        let kind = w(|c| c.kind.as_str().len(), 4);
2976        let read_at = r
2977            .candidates
2978            .iter()
2979            .find(|c| c.status == htl::resolve::Status::Read)
2980            .map(|c| c.order);
2981        println!();
2982        println!("  order  {:file$}  {:kind$}  status", "file", "kind");
2983        for c in &r.candidates {
2984            let status = match (c.status, c.shadowed_by, read_at) {
2985                (htl::resolve::Status::Shadowed, Some(by), _) => format!("shadowed by {by}"),
2986                // Not hidden by the row that is read: typed by it, and loaded by the run.
2987                (htl::resolve::Status::Runtime, _, Some(by)) => format!("runtime, typed by {by}"),
2988                (s, _, _) => s.as_str().to_string(),
2989            };
2990            let origin = match &c.origin {
2991                Some(o) => format!("  ({})", o.describe()),
2992                None => String::new(),
2993            };
2994            println!(
2995                "  {:<5}  {:file$}  {:kind$}  {status}{origin}",
2996                c.order,
2997                c.path,
2998                c.kind.as_str()
2999            );
3000        }
3001    }
3002    println!();
3003    match r.answered_by {
3004        htl::resolve::AnsweredBy::Model => println!("  answered by the project model"),
3005        // The name is not the project's: where the search looked is half the answer, and
3006        // all of it when nothing was found.
3007        htl::resolve::AnsweredBy::Path => {
3008            println!("  searched, in order: {}", r.searched.join(", "))
3009        }
3010    }
3011}
3012
3013/// `1 module` / `2 modules`: a count whose noun agrees with it, for a line short enough
3014/// that `module(s)` would be the loudest thing on it.
3015fn count(n: usize, one: &str, many: &str) -> String {
3016    format!("{n} {}", if n == 1 { one } else { many })
3017}
3018
3019/// Delete this project's cache store.
3020///
3021/// The store sits beside `htl.toml`, which is not necessarily where anyone is standing:
3022/// `htl check src` run from anywhere in a repo writes to the project root. That is the
3023/// reason this exists rather than leaving people to work out which directory to remove.
3024///
3025/// Only `.htl/cache` goes. `.htl/` itself is left in place for whatever else may come to
3026/// live there, and the path is built here rather than taken from an argument, so there is
3027/// no spelling of the command that removes anything else.
3028fn cmd_cache_clear(path: Option<&Path>) -> Result<ExitCode> {
3029    let root = cache_root(path)?;
3030    let dir = root.join(".htl").join("cache");
3031    if !dir.is_dir() {
3032        eprintln!("htl cache: nothing stored at {}", dir.display());
3033        return Ok(ExitCode::SUCCESS);
3034    }
3035    let n = fs::read_dir(&dir)
3036        .map(|rd| {
3037            rd.flatten()
3038                .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
3039                .count()
3040        })
3041        .unwrap_or(0);
3042    fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
3043    eprintln!(
3044        "htl cache: removed {n} {} from {}",
3045        if n == 1 { "entry" } else { "entries" },
3046        dir.display()
3047    );
3048    Ok(ExitCode::SUCCESS)
3049}
3050
3051/// The directory a cache command works on: the project's root, as every command keeps its
3052/// store there ([`project::store_root`]), or the working directory outside a project.
3053fn cache_root(path: Option<&Path>) -> Result<PathBuf> {
3054    let start = path.unwrap_or(Path::new("."));
3055    let model = htl::model::Project::find_root(start)?.map(|r| r.root);
3056    Ok(model.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))))
3057}
3058
3059/// Say what the store holds.
3060///
3061/// Answers "what is stored", not "what would be reused": an entry listed here can still miss
3062/// on the next run because a file it recorded has changed. The two are different questions
3063/// and conflating them would make this command lie in the more dangerous direction.
3064fn cmd_cache_status(path: Option<&Path>, json: bool, list_entries: bool) -> Result<ExitCode> {
3065    let c = cache::describe(&cache_root(path)?);
3066    if json {
3067        report::emit(&c)?;
3068        return Ok(ExitCode::SUCCESS);
3069    }
3070
3071    if c.entries.is_empty() {
3072        println!("htl cache: empty ({})", c.dir);
3073        return Ok(ExitCode::SUCCESS);
3074    }
3075    let mut by_kind: std::collections::BTreeMap<&str, (usize, u64)> = Default::default();
3076    for e in &c.entries {
3077        let slot = by_kind.entry(e.kind.as_str()).or_default();
3078        slot.0 += 1;
3079        slot.1 += e.bytes;
3080    }
3081    println!(
3082        "htl cache: {} entries, {} at {}",
3083        c.entries.len(),
3084        human_bytes(c.bytes),
3085        c.dir
3086    );
3087    for (kind, (n, bytes)) in &by_kind {
3088        let what = match *kind {
3089            cache::CHECK => "checked modules",
3090            cache::GEN => "checked and generated test files (htl test)",
3091            cache::MODULE => "generated modules (htl test / build, include_bundle!)",
3092            cache::RUN => "whole runs",
3093            _ => "entries this build cannot read",
3094        };
3095        println!("  {n:>5} {what} ({})", human_bytes(*bytes));
3096    }
3097    if let (Some(min), Some(max)) = (
3098        c.entries.iter().map(|e| e.age_secs).min(),
3099        c.entries.iter().map(|e| e.age_secs).max(),
3100    ) {
3101        println!(
3102            "  last used between {} and {} ago",
3103            human_age(min),
3104            human_age(max)
3105        );
3106    }
3107    if list_entries {
3108        println!();
3109        for e in &c.entries {
3110            println!(
3111                "  {:<6} {:>8}  {}",
3112                e.kind,
3113                human_bytes(e.bytes),
3114                e.subjects.join(", ")
3115            );
3116        }
3117    }
3118    Ok(ExitCode::SUCCESS)
3119}
3120
3121fn human_bytes(n: u64) -> String {
3122    if n >= 1 << 20 {
3123        format!("{:.1} MB", n as f64 / (1u64 << 20) as f64)
3124    } else if n >= 1 << 10 {
3125        format!("{:.0} KB", n as f64 / (1u64 << 10) as f64)
3126    } else {
3127        format!("{n} B")
3128    }
3129}
3130
3131fn human_age(secs: u64) -> String {
3132    match secs {
3133        s if s < 90 => format!("{s}s"),
3134        s if s < 5400 => format!("{}m", s / 60),
3135        s if s < 172_800 => format!("{}h", s / 3600),
3136        s => format!("{}d", s / 86_400),
3137    }
3138}
3139
3140/// How many of the files a walk visited came out of a patched dependency: the files in the
3141/// home of a module the project owns as a patch ([`htl::model::Project::home_of`]) — its
3142/// tests included, which no name reaches. Zero outside a project and for a
3143/// project with no patch, which is what keeps the summary line below unchanged for
3144/// everyone who has never run `htl pkg patch`.
3145fn patched_files(model: Option<&htl::model::Project>, files: &[PathBuf]) -> usize {
3146    let Some(model) = model else {
3147        return 0;
3148    };
3149    if !model
3150        .modules
3151        .iter()
3152        .any(|m| m.owner == htl::model::Owner::Patched)
3153    {
3154        return 0;
3155    }
3156    files
3157        .iter()
3158        .filter(|f| {
3159            model
3160                .home_of(f)
3161                .is_some_and(|m| m.owner == htl::model::Owner::Patched)
3162        })
3163        .count()
3164}
3165
3166/// `htl check --statistics`'s table: one row per rule, count first, the rule names left
3167/// aligned on the longest of them. Nothing is printed for an empty slice — a run with no
3168/// finding leaves the summary line to say `0 error(s), 0 warning(s), 0 lint(s)` on its own.
3169fn print_statistics(rows: &[report::RuleStatistic]) {
3170    let width = rows.iter().map(|r| r.rule.len()).max().unwrap_or(0);
3171    for r in rows {
3172        eprintln!(
3173            "{:>5}  {:<width$}  {}",
3174            r.count,
3175            r.rule,
3176            statistics_marker(r)
3177        );
3178    }
3179}
3180
3181/// `[*]`: every finding of the rule carries a fix `htl fix` applies without being asked
3182/// (`safe`) or shows (`suggest`). `[ ]`: none does. `[-]`: the rest — some findings fixable
3183/// and some not, or every one fixable but only some `safe`/`suggest`, the remainder
3184/// needing `--unsafe`.
3185fn statistics_marker(r: &report::RuleStatistic) -> &'static str {
3186    if r.fixable == r.count {
3187        "[*]"
3188    } else if r.fixable + r.unsafe_fixable == 0 {
3189        "[ ]"
3190    } else {
3191        "[-]"
3192    }
3193}
3194
3195#[cfg(test)]
3196mod statistics_marker_tests {
3197    use super::statistics_marker;
3198    use crate::report::RuleStatistic;
3199
3200    fn stat(count: usize, fixable: usize, unsafe_fixable: usize) -> RuleStatistic {
3201        RuleStatistic {
3202            rule: "r".to_string(),
3203            count,
3204            fixable,
3205            unsafe_fixable,
3206        }
3207    }
3208
3209    /// Every finding fixable, and none of it `--unsafe`-only.
3210    #[test]
3211    fn full_safe_coverage_is_a_star() {
3212        assert_eq!(statistics_marker(&stat(2, 2, 0)), "[*]");
3213    }
3214
3215    /// No finding carries a fix at all.
3216    #[test]
3217    fn no_fix_at_all_is_blank() {
3218        assert_eq!(statistics_marker(&stat(2, 0, 0)), "[ ]");
3219    }
3220
3221    /// Some fixable, some not: a genuine mix.
3222    #[test]
3223    fn a_mix_of_fixable_and_not_is_a_dash() {
3224        assert_eq!(statistics_marker(&stat(3, 1, 0)), "[-]");
3225    }
3226
3227    /// Full coverage, but not every one of it `safe`/`suggest`: the `--unsafe` ones keep
3228    /// it from being a plain `[*]`.
3229    #[test]
3230    fn full_coverage_split_between_safe_and_unsafe_is_a_dash() {
3231        assert_eq!(statistics_marker(&stat(2, 1, 1)), "[-]");
3232    }
3233
3234    /// Full coverage, every one of it `--unsafe`-only.
3235    #[test]
3236    fn full_unsafe_only_coverage_is_a_dash() {
3237        assert_eq!(statistics_marker(&stat(2, 0, 2)), "[-]");
3238    }
3239}
3240
3241/// The one place a check reports its totals, so a replayed module and a checked one cannot
3242/// drift apart in how they are summarized. Returns whether the run counts as a failure.
3243///
3244/// `patched` is how many of those files are a patched dependency's ([`patched_files`]),
3245/// split out of the count rather than added to it. One `htl pkg patch` turned a project's
3246/// `15 file(s)` into `25 file(s)` with nothing said, and a file count that moves for a
3247/// reason the line does not give is a file count a reader cannot use: the dependency's
3248/// `tests/` are now in the walk, they are not the project's, and the line has to say so.
3249fn report_check(
3250    out: &mut report::Out,
3251    json: bool,
3252    statistics: bool,
3253    rep: &project::Report,
3254    policy: &htl::verdict::Policy,
3255    patched: usize,
3256) -> Result<bool> {
3257    let (files, replayed) = (rep.files.len(), rep.replayed);
3258    let (errors, warnings, lints) = (rep.errors, rep.warnings, rep.lints);
3259    let strict = policy.strict;
3260    let fail = htl::verdict::verdict(&rep.findings(), policy);
3261    let all_cached = rep.all_cached();
3262    if json {
3263        report::emit(&report::CheckReport {
3264            files,
3265            patched,
3266            diagnostics: out.take(),
3267            summary: report::CheckSummary {
3268                errors,
3269                warnings,
3270                lints,
3271                denied: rep.denied,
3272                strict,
3273                ok: !fail,
3274                cached: all_cached,
3275                replayed,
3276            },
3277            statistics: statistics.then(|| out.statistics()),
3278        })?;
3279    } else {
3280        if statistics {
3281            print_statistics(&out.statistics());
3282        }
3283        // Say nothing when nothing was replayed; say how much when it was only some.
3284        let cached = if all_cached {
3285            " [cached]".to_string()
3286        } else if replayed > 0 {
3287            format!(" [{replayed}/{files} cached]")
3288        } else {
3289            String::new()
3290        };
3291        // The three counts say what kinds of thing the run said; `at deny` says how much
3292        // of that it failed on, and is left out when it is none of it — its being there at
3293        // all is the news. A run with two warnings and one denied lint reads as
3294        // `0 error(s), 2 warning(s), 1 lint(s), 1 at deny`.
3295        let denied = match rep.denied {
3296            0 => String::new(),
3297            n => format!(", {n} at deny"),
3298        };
3299        // A project with no patch reads exactly as it read before the split existed: the
3300        // second number appears only when there is something on the other side of it, and
3301        // the two always add up to the one number that was there.
3302        let counted = match patched {
3303            0 => format!("{files} file(s)"),
3304            n => format!("{} file(s) + {n} in patched dependencies", files - n),
3305        };
3306        // Where the why is, once per rule this run said something under, after the
3307        // findings and before the summary — the way cargo names `cargo fix` once rather
3308        // than on every line. A finding's message names the site; the explanation names
3309        // the rule. Only rules that have one (every lint does; an error has no rule).
3310        for rule in out.rules_said() {
3311            if htl::lint::explained(rule).is_some() {
3312                eprintln!("htl check --explain {rule}");
3313            }
3314        }
3315        eprintln!(
3316            "htl check: {counted}, {errors} error(s), {warnings} warning(s), {lints} lint(s){denied}{}{cached}",
3317            if strict { " [strict]" } else { "" }
3318        );
3319    }
3320    Ok(fail)
3321}
3322
3323fn cmd_gen(file: &Path, out: Option<&Path>) -> Result<ExitCode> {
3324    let h = Htl::new()?;
3325    auto_dts(file)?;
3326    // The search path `htl check` gives this file, so `htl gen` resolves what `htl check`
3327    // resolved and a file the checker accepts is one this command can emit. Same calls, in
3328    // the same order, as `cmd_run` and `cmd_build`.
3329    let cfg = load_config(file)?;
3330    config_lints(&h, &cfg)?;
3331    config_lang(&h, &cfg)?;
3332    let model = apply_model(&h, &cfg, file)?;
3333    project::file_view(&h, model.as_ref(), file)?;
3334    h.install_std()?;
3335    let (code, c) = h.gen_lua(file)?;
3336    text_sink().checkinfo(&c);
3337    // Judged on its errors alone (`Policy::ERRORS_ONLY`): the warnings and lints above are
3338    // reported, and `htl check` is where they are judged.
3339    let (Some(code), false) = (code, runs_fail(&c)) else {
3340        return Ok(ExitCode::FAILURE);
3341    };
3342    // Written as it came back. This command used to append the final newline itself, which
3343    // made it the one consumer of `gen_lua` whose output was a whole file; the generator
3344    // does it for all of them now (`H.gen` in `prelude.lua` says why).
3345    match out {
3346        Some(p) => fs::write(p, code).with_context(|| format!("writing {}", p.display()))?,
3347        None => print!("{code}"),
3348    }
3349    Ok(ExitCode::SUCCESS)
3350}
3351
3352fn cmd_run(file: &Path, args: &[String]) -> Result<ExitCode> {
3353    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
3354    let h = Htl::new()?;
3355    auto_dts(file)?;
3356    // The search path `htl check` gives this file, so `htl run` resolves what `htl check`
3357    // resolved rather than failing on a `require` the checker was happy with. Same calls
3358    // as `cmd_gen` and `cmd_build`; before the bundle branch because a bundle carries its
3359    // own modules and gains nothing from it either way.
3360    let cfg = load_config(file)?;
3361    config_lints(&h, &cfg)?;
3362    config_lang(&h, &cfg)?;
3363    h.configure_async(async_config(&cfg))?;
3364    let model = apply_model(&h, &cfg, file)?;
3365    h.install_test_lib()?;
3366    h.install_std()?;
3367    h.install_task_lib()?;
3368    if Bundle::is_bundle(&bytes) {
3369        let b = Bundle::decode(&bytes)?;
3370        // A bundle's frames are as good as its payload: stripped bytecode has no lines to
3371        // show, and `htl build --debug` is what keeps them.
3372        let main = h.load_bundle(&b, args)?;
3373        return run_root(&h, Entry::Main(main), args);
3374    }
3375    // Check first so lints/warnings are visible before the script runs.
3376    project::file_view(&h, model.as_ref(), file)?;
3377    h.install_searcher()?;
3378    h.set_arg(&file.to_string_lossy(), args)?;
3379    let (code, c) = h.gen_lua(file)?;
3380    text_sink().checkinfo(&c);
3381    // As `htl gen`: errors stop it, the rest is reported (`Policy::ERRORS_ONLY`).
3382    let (Some(code), false) = (code, runs_fail(&c)) else {
3383        return Ok(ExitCode::FAILURE);
3384    };
3385    run_root(
3386        &h,
3387        Entry::Chunk {
3388            code,
3389            name: format!("@{}", file.display()),
3390        },
3391        args,
3392    )
3393}
3394
3395/// What `htl run` runs as the program's root: a generated chunk, or a bundle's entry.
3396enum Entry {
3397    Chunk { code: String, name: String },
3398    Main(htl::mlua::Function),
3399}
3400
3401/// The `[async]` of a loaded `htl.toml`, or the default when there is no file.
3402fn async_config(cfg: &project::Config) -> &htl::config::AsyncConfig {
3403    static DEFAULT: htl::config::AsyncConfig = htl::config::AsyncConfig {
3404        grace_ms: None,
3405        preempt: None,
3406    };
3407    match cfg {
3408        Some((_, _, c)) => &c.async_,
3409        None => &DEFAULT,
3410    }
3411}
3412
3413/// Run the program as a root coroutine on the executor, with Ctrl-C cancelling it.
3414///
3415/// The runtime is a current-thread tokio runtime with its time driver (the grace is a
3416/// tokio timeout) and a `LocalSet`, built for this run; `Htl::run_async` is awaited to
3417/// the end, so when it resolves nothing the program started is alive.
3418///
3419/// Ctrl-C is watched from a thread of its own rather than a task on this runtime: a
3420/// program in a CPU loop never yields to the runtime, so a task here would never get to
3421/// run, while the cancel hook reads the token from any thread at its next check. The
3422/// first Ctrl-C cancels the root — the program gets its grace to clean up — and a second
3423/// one ends the process, for a program that does not.
3424///
3425/// A cancelled run prints `htl run: interrupted` and exits 130, the shell's own code for
3426/// it; a program that raised prints the innermost cause and the frames that reached it
3427/// (`htl run` is a development command, so the frames are the default; `htl::user_message`
3428/// is what an embedding host shows people who did not write the Teal).
3429fn run_root(h: &Htl, entry: Entry, args: &[String]) -> Result<ExitCode> {
3430    let token = htl::mlua_isle::runtime::CancelToken::new();
3431    {
3432        let token = token.clone();
3433        std::thread::Builder::new()
3434            .name("htl-ctrl-c".into())
3435            .spawn(move || {
3436                let Ok(rt) = tokio::runtime::Builder::new_current_thread()
3437                    .enable_all()
3438                    .build()
3439                else {
3440                    return;
3441                };
3442                rt.block_on(async {
3443                    if tokio::signal::ctrl_c().await.is_ok() {
3444                        token.cancel();
3445                    }
3446                    if tokio::signal::ctrl_c().await.is_ok() {
3447                        std::process::exit(130);
3448                    }
3449                });
3450            })
3451            .context("starting the Ctrl-C watcher")?;
3452    }
3453    let rt = tokio::runtime::Builder::new_current_thread()
3454        .enable_all()
3455        .build()
3456        .context("building the executor's runtime")?;
3457    let local = tokio::task::LocalSet::new();
3458    let out = local.block_on(&rt, async {
3459        match entry {
3460            Entry::Chunk { code, name } => h.run_async(&code, &name, args, &token).await,
3461            Entry::Main(main) => {
3462                let va: htl::mlua::Variadic<String> = args.iter().cloned().collect();
3463                h.call_async(main, va, &token).await.map(|_| ())
3464            }
3465        }
3466    });
3467    Ok(match out {
3468        Ok(()) => ExitCode::SUCCESS,
3469        Err(e) if htl::is_cancelled(&e) => {
3470            eprintln!("htl run: interrupted");
3471            ExitCode::from(130)
3472        }
3473        Err(e) => {
3474            eprintln!("{}", htl::developer_message(&e));
3475            ExitCode::FAILURE
3476        }
3477    })
3478}
3479
3480/// Whether `htl run` / `htl gen` stop at the check `c`: [`htl::verdict::verdict`] under
3481/// [`Policy::ERRORS_ONLY`](htl::verdict::Policy::ERRORS_ONLY), so an error does and
3482/// nothing else.
3483fn runs_fail(c: &htl::CheckInfo) -> bool {
3484    htl::verdict::verdict(
3485        &htl::verdict::Findings {
3486            errors: c.errors.len(),
3487            warnings: c.warnings.len(),
3488            lints: c.lints.len(),
3489            denied: 0,
3490        },
3491        &htl::verdict::Policy::ERRORS_ONLY,
3492    )
3493}
3494
3495/// The run cache as `htl build` was asked to use it: `--no-cache` and `--explain-cache`,
3496/// the two switches that mean something for one closure. There is no `--cache-mode`: a
3497/// build's entries are per module, as `htl test`'s are, since a build is many modules and
3498/// an edit to one should cost that one and its dependents rather than the closure.
3499struct BuildCache {
3500    use_cache: bool,
3501    explain: bool,
3502}
3503
3504fn cmd_build(
3505    entry: &Path,
3506    out: &Path,
3507    main: &str,
3508    mut opts: htl::link::LinkOptions,
3509    cache_flags: BuildCache,
3510) -> Result<ExitCode> {
3511    let h = Htl::new()?;
3512    auto_dts(entry)?;
3513    // `std.*` resolves to its declaration and nothing else, so the linker files it under
3514    // the host's modules — which is what it is: the binary that runs the bundle preloads
3515    // it, as `htl run` does before `run_bundle`.
3516    h.install_std()?;
3517    let cfg = load_config(entry)?;
3518    // The rules and levels `htl check` uses: a bundle is judged as a check of its closure
3519    // would be, and a rule the project turned off is not reported here either.
3520    let lints = config_lints(&h, &cfg)?;
3521    config_lang(&h, &cfg)?;
3522    let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
3523    let model = apply_model(&h, &cfg, entry)?;
3524    // The names the host provides are the model's — `#[host_module]`s in the crate around
3525    // the project, `[build] host`, `std.*` — so the bundle leaves out what the host
3526    // registers without anyone restating it; `--host` adds to them.
3527    if let Some(m) = &model {
3528        opts.host.extend(m.provided().map(|(n, _)| n.to_string()));
3529    }
3530    if let Some((_, _, cfg)) = &cfg {
3531        opts.extra.extend(cfg.build.extra.iter().cloned());
3532        opts.host.extend(cfg.build.host.iter().cloned());
3533        // The one thing `[build] target` changes: this command produces the `hb` target and
3534        // nothing else, so a project that records another is told which command does build
3535        // it rather than handed a bundle nothing in it was going to load. Here rather than
3536        // further down because both forms of `htl build` pass through — the directory form
3537        // returns a few lines below — and because nothing has been written yet.
3538        if let Some(t) = cfg.build.target.filter(|t| *t != BuildTarget::Hb) {
3539            eprintln!(
3540                "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.",
3541                t.name(),
3542                t.runs_it()
3543            );
3544            return Ok(ExitCode::FAILURE);
3545        }
3546    }
3547    if entry.is_dir() {
3548        if cache_flags.explain {
3549            eprintln!("htl cache: the directory form of `htl build` is not cached");
3550        }
3551        // Not into an installed or vendored copy — a dependency's files, which the model
3552        // knows — and into a patch, which is the project's code.
3553        let skip = project::not_walked(
3554            model.as_ref(),
3555            &[entry.to_path_buf()],
3556            htl::model::Purpose::Check,
3557        );
3558        return cmd_build_dir(&h, entry, out, main, &opts, &skip, &cfg);
3559    }
3560    project::file_view(&h, model.as_ref(), entry)?;
3561    // The name the entry is served under: the one the project's model gives the file,
3562    // which is what a `require` of it elsewhere in the project writes.
3563    opts.entry_name = model.as_ref().and_then(|m| m.locate(entry).map(|p| p.name));
3564    // The store: `module` entries keyed the way `htl test` and the macros key them — the
3565    // file the module is and the lint selection `htl.toml` puts in force — so a module any
3566    // of them generated is one the build replays, and the reverse. Nothing is swept here:
3567    // a build sees one closure, and only `htl check`, which sees the project, bounds the
3568    // store (`cache.rs`).
3569    let root = project::store_root(model.as_ref());
3570    let spec = cfg
3571        .as_ref()
3572        .map(|(_, _, c)| c.lint_spec())
3573        .unwrap_or_default();
3574    let lint = (!spec.is_empty()).then_some(spec.as_str());
3575    let cache_opts = project::cache_options(
3576        cache_flags.use_cache,
3577        Some(cache::Mode::PerModule),
3578        &cfg,
3579        cache_flags.explain,
3580    );
3581    let store = project::with_model(
3582        project::store(&root, cache_opts, None, "htl build"),
3583        model.as_ref(),
3584    );
3585    let link_store = store.as_ref().map(|c| htl::link::LinkStore {
3586        cache: c,
3587        lint,
3588        root: &root,
3589        config: cfg.as_ref().map(|(_, p, c)| (p.as_path(), c)),
3590    });
3591    let linked = htl::link::link_with(&h, entry, &opts, link_store)?;
3592    project::explain_cache(store.as_ref(), cache_opts);
3593    // One sink for the whole closure: a build is many modules, and what the layer says
3594    // once per run is said once for the build rather than once per module.
3595    let mut sink = text_sink();
3596    sink.judge_by(lints.selection());
3597    for (p, c) in &linked.checks {
3598        sink.checkinfo(&linked.reported(p, c));
3599    }
3600    let n_err = linked.errors.len();
3601    let found = htl::verdict::Findings {
3602        errors: n_err,
3603        warnings: linked.checks.iter().map(|(_, c)| c.warnings.len()).sum(),
3604        lints: linked.lints.len(),
3605        denied: sink.denied(),
3606    };
3607    // The checks' own errors went through the sink above; the linker's are its own list,
3608    // said through the same sink so they read as the checks' do.
3609    for d in &linked.link_errors {
3610        sink.diagnostic(d);
3611    }
3612    if htl::verdict::verdict(&found, &policy) {
3613        eprintln!(
3614            "htl build: {n_err} error(s){}, bundle not written",
3615            judged(&found, &policy)
3616        );
3617        return Ok(ExitCode::FAILURE);
3618    }
3619    let buf = linked.bundle()?.encode();
3620    fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
3621    let typed = linked.modules.iter().filter(|m| m.typed).count();
3622    // The same suffix `htl check` prints: everything from the store, some of it, or
3623    // nothing said when none was.
3624    let cached = if typed > 0 && linked.cached == typed {
3625        " [cached]".to_string()
3626    } else if linked.cached > 0 {
3627        format!(" [{}/{typed} cached]", linked.cached)
3628    } else {
3629        String::new()
3630    };
3631    eprintln!(
3632        "htl build: {} module(s) ({typed} typed, {} lua) -> {} ({} bytes{}{}){cached}",
3633        linked.modules.len(),
3634        linked.modules.len() - typed,
3635        out.display(),
3636        buf.len(),
3637        if opts.source {
3638            ", source"
3639        } else {
3640            ", bytecode"
3641        },
3642        if opts.debug { " with debug info" } else { "" }
3643    );
3644    if !linked.host_modules.is_empty() {
3645        eprintln!(
3646            "htl build: host must provide: {}",
3647            linked.host_modules.join(", ")
3648        );
3649    }
3650    Ok(ExitCode::SUCCESS)
3651}
3652
3653/// The older form: every `.tl` under a directory, module names from their paths.
3654fn cmd_build_dir(
3655    h: &Htl,
3656    dir: &Path,
3657    out: &Path,
3658    entry: &str,
3659    opts: &htl::link::LinkOptions,
3660    skip: &[PathBuf],
3661    cfg: &project::Config,
3662) -> Result<ExitCode> {
3663    // Judged as the file form is: `htl.toml`'s rules and levels, its `strict`.
3664    let lints = config_lints(h, cfg)?;
3665    config_lang(h, cfg)?;
3666    let policy = &htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
3667    h.add_path(dir)?;
3668    let files = htl::collect_tl_skipping(&[dir.to_path_buf()], skip)?;
3669    let mut b = Bundle {
3670        entry: entry.to_string(),
3671        htl_version: env!("CARGO_PKG_VERSION").into(),
3672        ..Default::default()
3673    };
3674    let mut found = htl::verdict::Findings::default();
3675    let mut sink = text_sink();
3676    sink.judge_by(lints.selection());
3677    for f in &files {
3678        // Named against the directory the bundle is built from, by the naming rule.
3679        let rel = f.strip_prefix(dir).unwrap_or(f);
3680        let name = htl::naming::name_of("", rel)
3681            .with_context(|| format!("cannot derive a module name for {}", f.display()))?;
3682        let (code, c) = h.gen_lua(f)?;
3683        sink.checkinfo(&c);
3684        found.errors += c.errors.len();
3685        found.warnings += c.warnings.len();
3686        found.lints += c.lints.len();
3687        let Some(code) = code else { continue };
3688        let (kind, payload) = if opts.source {
3689            (htl::bundle::Kind::Source, code.into_bytes())
3690        } else {
3691            (
3692                htl::bundle::Kind::Bytecode,
3693                h.compile_with(&name, &code, !opts.debug)?,
3694            )
3695        };
3696        b.modules.push(htl::bundle::Module {
3697            name,
3698            kind,
3699            payload,
3700        });
3701    }
3702    found.denied = sink.denied();
3703    if htl::verdict::verdict(&found, policy) {
3704        eprintln!(
3705            "htl build: {} error(s){}, bundle not written",
3706            found.errors,
3707            judged(&found, policy)
3708        );
3709        return Ok(ExitCode::FAILURE);
3710    }
3711    if b.module(entry).is_none() {
3712        bail!(
3713            "entry module '{entry}' not found among {} module(s)",
3714            b.modules.len()
3715        );
3716    }
3717    if !opts.source {
3718        b.fingerprint = h.fingerprint()?;
3719    }
3720    let buf = b.encode();
3721    fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
3722    eprintln!(
3723        "htl build: {} module(s) -> {} ({} bytes)",
3724        b.modules.len(),
3725        out.display(),
3726        buf.len()
3727    );
3728    Ok(ExitCode::SUCCESS)
3729}
3730
3731/// What `htl bundle info` reports: everything the file records and nothing it does not
3732/// (no Lua state is created, nothing is loaded), which is what a build step checks in and
3733/// a bug report pastes; `--format json` is the same fields. `lua` is the header the
3734/// bytecode was compiled for, in the fields the mismatch message names; `None` when the
3735/// bundle carries no fingerprint, which `payload` explains (`source`: the text says `any`)
3736/// or `format` does (`1`, before the fingerprint: `not recorded`).
3737#[derive(serde::Serialize)]
3738struct BundleInfo {
3739    file: String,
3740    format: u8,
3741    htl_version: Option<String>,
3742    /// `bytecode`, `source`, or `mixed` when modules disagree.
3743    payload: &'static str,
3744    lua: Option<htl::bundle::LuaHeader>,
3745    entry: String,
3746    modules: Vec<BundleModuleInfo>,
3747    host_modules: Vec<String>,
3748}
3749
3750#[derive(serde::Serialize)]
3751struct BundleModuleInfo {
3752    name: String,
3753    kind: &'static str,
3754    bytes: usize,
3755}
3756
3757fn cmd_bundle_info(file: &Path, json: bool) -> Result<ExitCode> {
3758    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
3759    let Some(format) = htl::bundle::format_version(&bytes) else {
3760        bail!("{} is not an htl bundle (bad magic)", file.display());
3761    };
3762    let b = Bundle::decode(&bytes)?;
3763    let kind_name = |k: htl::bundle::Kind| match k {
3764        htl::bundle::Kind::Bytecode => "bytecode",
3765        htl::bundle::Kind::Source => "source",
3766    };
3767    let payload = match (
3768        b.modules
3769            .iter()
3770            .any(|m| m.kind == htl::bundle::Kind::Bytecode),
3771        b.modules
3772            .iter()
3773            .any(|m| m.kind == htl::bundle::Kind::Source),
3774    ) {
3775        (true, true) => "mixed",
3776        (false, true) => "source",
3777        // Bytecode, or no modules at all: what the loader would treat it as.
3778        _ => "bytecode",
3779    };
3780    let info = BundleInfo {
3781        file: file.display().to_string(),
3782        format,
3783        htl_version: (!b.htl_version.is_empty()).then(|| b.htl_version.clone()),
3784        payload,
3785        lua: htl::bundle::LuaHeader::parse(&b.fingerprint),
3786        entry: b.entry.clone(),
3787        modules: b
3788            .modules
3789            .iter()
3790            .map(|m| BundleModuleInfo {
3791                name: m.name.clone(),
3792                kind: kind_name(m.kind),
3793                bytes: m.payload.len(),
3794            })
3795            .collect(),
3796        host_modules: b.host_modules.clone(),
3797    };
3798    if json {
3799        report::emit(&info)?;
3800        return Ok(ExitCode::SUCCESS);
3801    }
3802
3803    println!(
3804        "{}: htl bundle, format {}, built by {}",
3805        info.file,
3806        info.format,
3807        match &info.htl_version {
3808            Some(v) => format!("htl {v}"),
3809            None => "htl (version not recorded)".to_string(),
3810        }
3811    );
3812    println!("  payload:  {}", info.payload);
3813    let lua = match &info.lua {
3814        Some(h) => h.to_string(),
3815        None if !b.fingerprint.is_empty() => {
3816            format!("unreadable fingerprint ({} bytes)", b.fingerprint.len())
3817        }
3818        None if info.format == 1 => {
3819            "not recorded (a format 1 bundle carries no fingerprint)".into()
3820        }
3821        None => "any (source payload, no bytecode to bind)".into(),
3822    };
3823    println!("  lua:      {lua}");
3824    println!("  entry:    {}", info.entry);
3825    let modules: Vec<String> = info
3826        .modules
3827        .iter()
3828        .map(|m| {
3829            if info.payload == "mixed" {
3830                format!("{} ({})", m.name, m.kind)
3831            } else {
3832                m.name.clone()
3833            }
3834        })
3835        .collect();
3836    println!(
3837        "  modules:  {}",
3838        if modules.is_empty() {
3839            "(none)".to_string()
3840        } else {
3841            modules.join(", ")
3842        }
3843    );
3844    println!(
3845        "  host:     {}",
3846        if info.host_modules.is_empty() {
3847            "(none)".to_string()
3848        } else {
3849            info.host_modules.join(", ")
3850        }
3851    );
3852    Ok(ExitCode::SUCCESS)
3853}