Skip to main content

htl_cli/
lib.rs

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