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