Skip to main content

htl_cli/
lib.rs

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