1use htl::cache;
10mod junit;
11mod pin;
12pub mod report;
13mod scaffold;
14
15#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
21enum Format {
22 Text,
24 Json,
27}
28
29#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
32enum CacheModeArg {
33 PerModule,
35 WholeRun,
37}
38
39#[derive(Subcommand)]
40enum TypesCmd {
41 Add {
44 library: String,
46 #[arg(long)]
48 from: Option<PathBuf>,
49 #[arg(long)]
51 force: bool,
52 },
53}
54
55#[derive(Subcommand)]
56enum PkgCmd {
57 Install,
59 Add {
61 name: String,
63 git: String,
65 #[arg(long)]
67 tag: Option<String>,
68 #[arg(long)]
70 rev: Option<String>,
71 #[arg(long)]
73 branch: Option<String>,
74 #[arg(long)]
77 entry: Option<PathBuf>,
78 #[arg(long)]
81 target_dir: Option<PathBuf>,
82 },
83 Update {
85 name: Option<String>,
87 #[arg(long)]
89 dry_run: bool,
90 #[arg(long)]
92 force: bool,
93 },
94 Clean {
96 #[arg(long)]
98 all: bool,
99 },
100 Patch {
103 dep: String,
105 #[arg(long)]
107 force: bool,
108 },
109}
110
111#[derive(Subcommand)]
112enum CacheCmd {
113 Clear {
115 path: Option<PathBuf>,
118 },
119 Status {
121 path: Option<PathBuf>,
124 #[arg(long, value_enum, default_value_t = Format::Text)]
126 format: Format,
127 #[arg(long)]
129 entries: bool,
130 },
131}
132
133#[derive(Subcommand)]
134enum BundleCmd {
135 Info {
138 file: PathBuf,
140 #[arg(long, value_enum, default_value_t = Format::Text)]
142 format: Format,
143 },
144}
145
146impl From<CacheModeArg> for cache::Mode {
147 fn from(m: CacheModeArg) -> Self {
148 match m {
149 CacheModeArg::PerModule => cache::Mode::PerModule,
150 CacheModeArg::WholeRun => cache::Mode::WholeRun,
151 }
152 }
153}
154
155use anyhow::{Context, Result, bail};
156use clap::{Parser, Subcommand};
157use htl::BuildTarget;
158use htl::Htl;
159use htl::bundle::Bundle;
160use htl::project;
164use std::fs;
165use std::path::{Path, PathBuf};
166use std::process::ExitCode;
167
168#[derive(Parser)]
169#[command(
170 name = "htl",
171 version,
172 about = "Teal, hidden: run / check / build .tl on mlua",
173 long_about = "\
174Teal, hidden: run / check / build .tl on mlua.
175
176htl is a toolchain for Teal, and a way to embed one. It type-checks `.tl` sources with \
177Teal's own checker, runs and tests them on an embedded mlua state, formats them, and \
178links them into a single stripped-bytecode bundle. A Rust host embeds the same engine, \
179so the scripts it ships are checked when the host is built rather than when its user \
180first runs one.
181
182The guide, with every command and what a project looks like:
183 https://github.com/ynishi/htl
184
185The API a Rust host holds — `include_tl!`, `#[host_module]`, the run cache:
186 https://docs.rs/htl"
187)]
188struct Cli {
189 #[command(subcommand)]
190 cmd: Cmd,
191}
192
193#[derive(Subcommand)]
194enum Cmd {
195 #[command(after_long_help = "\
201Examples:
202 htl check src every .tl under src/
203 htl check src --strict every warn counts as deny: warnings and lints fail
204 htl check src --lint nil-index=deny,no-any=warn
205 one rule fails the run, another is advice
206 htl check src --lint -tl:hint a warning kind of the Teal compiler silenced
207 htl check --list-lints every rule with its default level, then exit
208 htl check --explain union-exhaustive
209 why the rule exists and how to decide its cases
210 htl check src --statistics how many findings each rule produced, not the findings
211
212The store is .htl/cache at the project root, the nearest htl.toml or mlua-pkg.toml above
213the paths; --no-cache skips it, --explain-cache says why a lookup missed.
214Caching: https://github.com/ynishi/htl#caching
215")]
216 Check {
217 paths: Vec<PathBuf>,
218 #[arg(long)]
220 strict: bool,
221 #[arg(long, allow_hyphen_values = true)]
227 lint: Option<String>,
228 #[arg(long)]
230 list_lints: bool,
231 #[arg(long, value_name = "RULE")]
234 explain: Option<String>,
235 #[arg(long, value_enum, default_value_t = Format::Text)]
237 format: Format,
238 #[arg(long)]
240 no_cache: bool,
241 #[arg(long, value_enum)]
243 cache_mode: Option<CacheModeArg>,
244 #[arg(long)]
246 explain_cache: bool,
247 #[arg(long)]
254 statistics: bool,
255 },
256 #[command(after_long_help = "\
260Examples:
261 htl test every .tl that requires htl.test
262 htl test tests --filter parser only tests whose \"suite > name\" contains it
263 htl test --coverage --coverage-lines
264 which lines of each module the suite never reached
265 htl test --junit report.xml also write the run as a JUnit report, for a CI
266")]
267 Test {
268 paths: Vec<PathBuf>,
269 #[arg(long)]
271 filter: Option<String>,
272 #[arg(long, default_value = htl::testing::DEFAULT_LIB)]
274 lib: String,
275 #[arg(long, allow_hyphen_values = true)]
277 lint: Option<String>,
278 #[arg(long)]
280 fail_fast: bool,
281 #[arg(long)]
289 allow_empty: bool,
290 #[arg(short, long)]
292 verbose: bool,
293 #[arg(short, long, conflicts_with = "verbose")]
295 quiet: bool,
296 #[arg(long, value_name = "MS")]
298 slow: Option<f64>,
299 #[arg(long)]
301 update: bool,
302 #[arg(long)]
304 coverage: bool,
305 #[arg(long, requires = "coverage")]
307 coverage_lines: bool,
308 #[arg(long, value_name = "FILE")]
310 lcov: Option<PathBuf>,
311 #[arg(long, value_name = "FILE")]
313 junit: Option<PathBuf>,
314 #[arg(long)]
316 seed: Option<u64>,
317 #[arg(long, value_enum, default_value_t = Format::Text)]
319 format: Format,
320 #[arg(long)]
322 no_cache: bool,
323 #[arg(long)]
325 explain_cache: bool,
326 },
327 #[command(after_long_help = "\
340Examples:
341 htl fix src apply the safe fixes to every .tl under src/
342 htl fix src --diff --dry-run what would change, as a unified diff per file
343 htl fix src --rule forward-ref only that rule's fixes
344 htl fix src --unsafe also the fixes that may change what the program does
345")]
346 Fix {
347 paths: Vec<PathBuf>,
348 #[arg(long, value_delimiter = ',')]
351 rule: Vec<String>,
352 #[arg(long = "unsafe")]
354 unsafe_fixes: bool,
355 #[arg(long)]
357 dry_run: bool,
358 #[arg(long)]
360 diff: bool,
361 #[arg(long)]
363 allow_dirty: bool,
364 #[arg(long)]
366 allow_no_vcs: bool,
367 #[arg(long)]
369 exit_non_zero_on_fix: bool,
370 #[arg(long, value_enum, default_value_t = Format::Text)]
372 format: Format,
373 },
374 Dts {
389 dir: Option<PathBuf>,
391 },
392 #[command(after_long_help = "\
396Examples:
397 htl new hello src/main.tl, a module, tests/, mlua-pkg.toml
398 htl new hello --lib a library: no entry script
399 htl new hello --embed the same, plus a Rust host (--target bin)
400 htl new hello --target cdylib --lib
401 a library behind a C ABI, for a caller that is not Rust
402 htl new hello --embed --htl main
403 built against the unreleased htl (a git pin on main)
404 htl new hello --embed --htl path:../htl
405 built against a local checkout of this repository
406 htl new hello --no-x without the htlx dependency the manifest gets by default
407
408Build targets: https://docs.rs/htl/latest/htl/build_target/enum.BuildTarget.html
409Layout of a project: https://github.com/ynishi/htl#layout-of-a-project-htl-new
410")]
411 New {
412 name: String,
413 #[arg(long)]
415 lib: bool,
416 #[arg(long)]
418 embed: bool,
419 #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
423 target: Option<String>,
424 #[arg(long, value_name = "REQ")]
428 htl: Option<String>,
429 #[arg(long)]
431 no_x: bool,
432 },
433 Init {
435 dir: Option<PathBuf>,
436 #[arg(long)]
437 lib: bool,
438 #[arg(long)]
440 embed: bool,
441 #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
443 target: Option<String>,
444 #[arg(long, value_name = "REQ")]
448 htl: Option<String>,
449 #[arg(long)]
451 no_x: bool,
452 },
453 #[command(after_long_help = "\
477Examples:
478 htl pin path:../htl from this project's own directory, move it onto a sibling
479 checkout, for a change that has to be built against it
480 htl pin release move it back once that checkout's change is released
481")]
482 Pin {
483 htl: String,
485 dir: Option<PathBuf>,
487 #[arg(long)]
489 no_update: bool,
490 },
491 Pkg {
494 #[command(subcommand)]
495 cmd: PkgCmd,
496 },
497 Types {
499 #[command(subcommand)]
500 cmd: TypesCmd,
501 },
502 Cache {
506 #[command(subcommand)]
507 cmd: CacheCmd,
508 },
509 Fmt {
511 paths: Vec<PathBuf>,
512 #[arg(long)]
514 check: bool,
515 #[arg(long)]
517 indent: Option<usize>,
518 },
519 Gen {
529 file: PathBuf,
530 #[arg(short, long)]
531 out: Option<PathBuf>,
532 },
533 Run {
535 file: PathBuf,
536 #[arg(trailing_var_arg = true)]
537 args: Vec<String>,
538 },
539 #[command(after_long_help = "\
546Examples:
547 htl build src/main.tl -o app.hb
548 the entry's require closure, as one bundle
549 htl build src/main.tl -o app.hb --debug
550 keep line numbers and local names in the bytecode
551 htl build src/main.tl -o app.hb --host mymod
552 leave a module the host provides out of the bundle
553 htl run app.hb run what was built
554
555Caching: https://github.com/ynishi/htl#caching
556")]
557 Build {
564 entry: PathBuf,
568 #[arg(short, long, default_value = "app.hb")]
569 out: PathBuf,
570 #[arg(short, long, default_value = "main")]
572 main: String,
573 #[arg(long)]
575 debug: bool,
576 #[arg(long)]
579 source: bool,
580 #[arg(long, value_delimiter = ',')]
582 extra: Vec<String>,
583 #[arg(long, value_delimiter = ',')]
585 host: Vec<String>,
586 #[arg(long)]
589 no_cache: bool,
590 #[arg(long)]
592 explain_cache: bool,
593 },
594 #[command(after_long_help = "\
599Examples:
600 htl unused modules and dependencies no entry reaches
601 htl unused --exit-non-zero-on-unused
602 the same report, and a non-zero exit for a CI
603 htl unused --format json the same report as one JSON document
604")]
605 Unused {
606 paths: Vec<PathBuf>,
609 #[arg(long, value_enum, default_value_t = Format::Text)]
611 format: Format,
612 #[arg(long)]
614 exit_non_zero_on_unused: bool,
615 #[arg(long)]
618 no_cache: bool,
619 #[arg(long)]
621 explain_cache: bool,
622 },
623 #[command(after_long_help = "\
637Examples:
638 htl adopt which of htl's nine markers this project writes, and how much
639 htl adopt --detail the same, plus every marked declaration's file, line and name
640 htl adopt --format json the same report as one JSON document
641")]
642 Adopt {
643 paths: Vec<PathBuf>,
647 #[arg(long, value_enum, default_value_t = Format::Text)]
649 format: Format,
650 #[arg(long)]
654 detail: bool,
655 #[arg(long)]
658 no_cache: bool,
659 #[arg(long)]
661 explain_cache: bool,
662 },
663 #[command(after_long_help = "\
670Examples:
671 htl resolve mq the chain for require(\"mq\")
672 htl resolve socket.http a name with dots, as a require spells it
673 htl resolve mq --format json the same rows as one JSON document
674
675Exits 1 when the name resolves to nothing, when two files implement it, or when a file of
676the project implements a name the host provides, so a script can ask.
677
678`htl.test` is answered like a host-provided name: no file of the project implements it
679(`htl test` preloads it into the state it runs), and its one row is the declaration the
680binary carries, `provided by the environment`.
681")]
682 Resolve {
683 module: String,
685 path: Option<PathBuf>,
687 #[arg(long, value_enum, default_value_t = Format::Text)]
689 format: Format,
690 },
691 Bundle {
695 #[command(subcommand)]
696 cmd: BundleCmd,
697 },
698}
699
700pub fn command() -> clap::Command {
706 <Cli as clap::CommandFactory>::command()
707}
708
709pub fn run() -> ExitCode {
717 let mut argv: Vec<String> = std::env::args().collect();
719 let is_cargo = Path::new(&argv[0])
720 .file_stem()
721 .and_then(|s| s.to_str())
722 .map(|s| s == "cargo-htl")
723 .unwrap_or(false);
724 if is_cargo && argv.get(1).map(String::as_str) == Some("htl") {
725 argv.remove(1);
726 }
727 match real_main(Cli::parse_from(argv)) {
728 Ok(code) => code,
729 Err(e) => {
730 eprintln!("htl: {e:#}");
731 ExitCode::from(2)
732 }
733 }
734}
735
736fn real_main(cli: Cli) -> Result<ExitCode> {
737 match cli.cmd {
738 Cmd::Check {
739 paths,
740 strict,
741 lint,
742 list_lints,
743 explain,
744 format,
745 no_cache,
746 cache_mode,
747 explain_cache,
748 statistics,
749 } => cmd_check(
750 &paths,
751 lint.as_deref(),
752 CheckFlags {
753 strict,
754 list_lints,
755 explain_rule: explain,
756 json: format == Format::Json,
757 use_cache: !no_cache,
758 cache_mode: cache_mode.map(Into::into),
759 explain: explain_cache,
760 statistics,
761 },
762 ),
763 Cmd::Fmt {
764 paths,
765 check,
766 indent,
767 } => cmd_fmt(&paths, check, indent),
768 Cmd::Test {
769 paths,
770 filter,
771 lib,
772 lint,
773 fail_fast,
774 allow_empty,
775 verbose,
776 quiet,
777 slow,
778 update,
779 coverage,
780 coverage_lines,
781 lcov,
782 junit,
783 seed,
784 format,
785 no_cache,
786 explain_cache,
787 } => cmd_test(
788 &paths,
789 filter.as_deref(),
790 &lib,
791 lint.as_deref(),
792 TestFlags {
793 fail_fast,
794 allow_empty,
795 verbose,
796 quiet,
797 slow,
798 update,
799 coverage: coverage || lcov.is_some(),
800 coverage_lines,
801 lcov,
802 junit,
803 json: format == Format::Json,
804 no_cache,
805 explain: explain_cache,
806 seed,
807 },
808 ),
809 Cmd::Pkg { cmd } => match cmd {
810 PkgCmd::Install => cmd_pkg_install(),
811 PkgCmd::Add {
812 name,
813 git,
814 tag,
815 rev,
816 branch,
817 entry,
818 target_dir,
819 } => cmd_pkg_add(htl::pkg::mlua_pkg::ops::AddSpec {
820 name,
821 git,
822 tag,
823 rev,
824 branch,
825 entry,
826 target_dir,
827 }),
828 PkgCmd::Update {
829 name,
830 dry_run,
831 force,
832 } => cmd_pkg_update(htl::pkg::mlua_pkg::ops::UpdateOpts {
833 name,
834 dry_run,
835 force,
836 }),
837 PkgCmd::Clean { all } => cmd_pkg_clean(all),
838 PkgCmd::Patch { dep, force } => cmd_pkg_patch(&dep, force),
839 },
840 Cmd::Types { cmd } => match cmd {
841 TypesCmd::Add {
842 library,
843 from,
844 force,
845 } => cmd_types_add(&library, from.as_deref(), force),
846 },
847 Cmd::Cache { cmd } => match cmd {
848 CacheCmd::Clear { path } => cmd_cache_clear(path.as_deref()),
849 CacheCmd::Status {
850 path,
851 format,
852 entries,
853 } => cmd_cache_status(path.as_deref(), format == Format::Json, entries),
854 },
855 Cmd::Dts { dir } => cmd_dts(dir.as_deref()),
856 Cmd::New {
857 name,
858 lib,
859 embed,
860 target,
861 htl,
862 no_x,
863 } => cmd_new(&name, lib, embed, target.as_deref(), htl.as_deref(), no_x),
864 Cmd::Init {
865 dir,
866 lib,
867 embed,
868 target,
869 htl,
870 no_x,
871 } => cmd_init(
872 dir.as_deref(),
873 lib,
874 embed,
875 target.as_deref(),
876 htl.as_deref(),
877 no_x,
878 ),
879 Cmd::Pin {
880 htl,
881 dir,
882 no_update,
883 } => pin::cmd_pin(&htl, dir, no_update),
884 Cmd::Gen { file, out } => cmd_gen(&file, out.as_deref()),
885 Cmd::Run { file, args } => cmd_run(&file, &args),
886 Cmd::Fix {
887 paths,
888 rule,
889 unsafe_fixes,
890 dry_run,
891 diff,
892 allow_dirty,
893 allow_no_vcs,
894 exit_non_zero_on_fix,
895 format,
896 } => cmd_fix(
897 &paths,
898 FixFlags {
899 rule,
900 unsafe_fixes,
901 dry_run: dry_run || diff,
902 diff,
903 allow_dirty,
904 allow_no_vcs,
905 exit_non_zero_on_fix,
906 json: format == Format::Json,
907 },
908 ),
909 Cmd::Build {
910 entry,
911 out,
912 main,
913 debug,
914 source,
915 extra,
916 host,
917 no_cache,
918 explain_cache,
919 } => cmd_build(
920 &entry,
921 &out,
922 &main,
923 htl::link::LinkOptions {
924 debug,
925 source,
926 extra,
927 host,
928 entry_name: None,
929 },
930 BuildCache {
931 use_cache: !no_cache,
932 explain: explain_cache,
933 },
934 ),
935 Cmd::Unused {
936 paths,
937 format,
938 exit_non_zero_on_unused,
939 no_cache,
940 explain_cache,
941 } => cmd_unused(
942 &paths,
943 UnusedFlags {
944 json: format == Format::Json,
945 fail_on_unused: exit_non_zero_on_unused,
946 use_cache: !no_cache,
947 explain: explain_cache,
948 },
949 ),
950 Cmd::Adopt {
951 paths,
952 format,
953 detail,
954 no_cache,
955 explain_cache,
956 } => cmd_adopt(
957 &paths,
958 AdoptFlags {
959 json: format == Format::Json,
960 detail,
961 use_cache: !no_cache,
962 explain: explain_cache,
963 },
964 ),
965 Cmd::Resolve {
966 module,
967 path,
968 format,
969 } => cmd_resolve(&module, path.as_deref(), format == Format::Json),
970 Cmd::Bundle { cmd } => match cmd {
971 BundleCmd::Info { file, format } => cmd_bundle_info(&file, format == Format::Json),
972 },
973 }
974}
975
976fn text_sink() -> project::Sink<report::Out> {
987 project::Sink::new(report::Out::new(false, false))
988}
989
990fn judged(found: &htl::verdict::Findings, policy: &htl::verdict::Policy) -> String {
994 let mut out = String::new();
995 if policy.capped {
996 return out;
997 }
998 if found.denied > 0 {
999 out.push_str(&format!(", {} at deny", found.denied));
1000 }
1001 if policy.strict && found.warnings + found.lints > 0 {
1002 out.push_str(&format!(
1003 ", {} warning(s) and {} lint(s) under strict",
1004 found.warnings, found.lints
1005 ));
1006 }
1007 out
1008}
1009
1010fn config_lang(h: &Htl, cfg: &project::Config) -> Result<()> {
1016 h.set_lang(&project::lang_of(cfg))
1017}
1018
1019fn config_lints(h: &Htl, cfg: &project::Config) -> Result<htl::lint::Lints> {
1020 let spec = cfg
1021 .as_ref()
1022 .map(|(_, _, c)| c.lint_spec())
1023 .unwrap_or_default();
1024 let lints = htl::lint::Lints::parse(&spec)?;
1025 h.select_lints(lints.selection())?;
1026 Ok(lints)
1027}
1028
1029fn auto_dts(start: &Path) -> Result<()> {
1040 auto_dts_to(start, true)
1041}
1042
1043fn auto_dts_to(start: &Path, write: bool) -> Result<()> {
1047 let mut project = None;
1048 if let Some((root, _, cfg)) = load_config(start)? {
1049 let model = htl::model::Project::load(&root, cfg)?;
1051 let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
1052 let (results, problems) = htl::contract::publish_to(&root, &contracts, write);
1053 announce_dts_to(&results, &root, write);
1054 for p in &problems {
1055 eprintln!("dts: {p}");
1056 }
1057 project = Some(root);
1058 }
1059 let Some(root) = htl::dts::find_cargo_package_root(start) else {
1060 return Ok(());
1061 };
1062 let results =
1063 htl::dts::generate_crate_to(&root, write).map_err(|e| anyhow::anyhow!("htl dts: {e}"))?;
1064 announce_dts_to(&results, &root, write);
1065 let types_root = project.unwrap_or_else(|| root.clone());
1066 let report = dep_dts_to(&root, &types_root, write);
1067 announce_dts_to(&report.written, &types_root, write);
1068 announce_dep_report(&report, "dts: ");
1069 Ok(())
1070}
1071
1072#[derive(Default)]
1079struct DepReport {
1080 written: Vec<(PathBuf, bool)>,
1082 not_written: Vec<String>,
1084 left_in_place: Vec<String>,
1087 unresolved: Option<String>,
1092}
1093
1094fn dep_dts(cargo_root: &Path, types_root: &Path) -> DepReport {
1101 dep_dts_to(cargo_root, types_root, true)
1102}
1103
1104fn dep_dts_to(cargo_root: &Path, types_root: &Path, write: bool) -> DepReport {
1106 let decls = match htl::dep_dts::resolve(cargo_root) {
1107 Ok(d) => d,
1108 Err(e) => {
1109 return DepReport {
1110 unresolved: Some(e),
1111 ..DepReport::default()
1112 };
1113 }
1114 };
1115 let types = match decl_root(types_root) {
1118 Ok(t) => t,
1119 Err(e) => {
1120 return DepReport {
1121 unresolved: Some(format!("{e:#}")),
1122 ..DepReport::default()
1123 };
1124 }
1125 };
1126 let left_in_place = htl::dep_dts::orphans(&types, &decls);
1127 let (written, not_written) = htl::dep_dts::materialise_to(&types, &decls, write);
1128 DepReport {
1129 written,
1130 not_written,
1131 left_in_place,
1132 unresolved: None,
1133 }
1134}
1135
1136fn announce_dep_report(report: &DepReport, prefix: &str) {
1141 for p in &report.not_written {
1142 eprintln!("{prefix}not written: {p}");
1143 }
1144 for p in &report.left_in_place {
1145 eprintln!("{prefix}left in place: {p}");
1146 }
1147 if let Some(e) = &report.unresolved {
1148 eprintln!("{prefix}{e}");
1149 }
1150}
1151
1152fn announce_dts_to(results: &[(PathBuf, bool)], root: &Path, wrote: bool) {
1155 for (target, changed) in results {
1156 if *changed {
1157 let target = target.strip_prefix(root).unwrap_or(target).display();
1158 if wrote {
1159 eprintln!("dts: wrote {target}");
1160 } else {
1161 eprintln!(
1162 "dts: would write {target} (dry run: not written; checked against the \
1163 file on disk)"
1164 );
1165 }
1166 }
1167 }
1168}
1169
1170fn cmd_dts(dir: Option<&Path>) -> Result<ExitCode> {
1171 let start = match dir {
1172 Some(d) => d.to_path_buf(),
1173 None => std::env::current_dir()?,
1174 };
1175 let mut results = Vec::new();
1178 let mut failed = false;
1179 let mut project = None;
1180 if let Some((croot, _, cfg)) = load_config(&start)? {
1181 let model = htl::model::Project::load(&croot, cfg)?;
1182 let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
1183 let (published, problems) = htl::contract::publish(&croot, &contracts);
1184 for p in &problems {
1185 eprintln!(" {p}");
1186 }
1187 failed = !problems.is_empty();
1190 results.extend(published);
1191 project = Some(croot);
1192 }
1193 let code = |failed: bool| {
1194 if failed {
1195 ExitCode::FAILURE
1196 } else {
1197 ExitCode::SUCCESS
1198 }
1199 };
1200 let Some(root) = htl::dts::find_cargo_package_root(&start) else {
1201 if results.is_empty() && !failed {
1202 bail!(
1203 "no Cargo.toml with a [package] section, and no ---@contract type to publish, \
1204 at or above {}",
1205 start.display()
1206 );
1207 }
1208 report_dts(&results, &start);
1209 return Ok(code(failed));
1210 };
1211 results.extend(htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("{e}"))?);
1212 let types_root = project.unwrap_or_else(|| root.clone());
1213 let report = dep_dts(&root, &types_root);
1214 announce_dep_report(&report, " ");
1215 failed = failed || !report.not_written.is_empty();
1218 results.extend(report.written);
1219 report_dts(&results, &root);
1220 Ok(code(failed))
1221}
1222
1223fn report_dts(results: &[(PathBuf, bool)], root: &Path) {
1224 let mut written = 0usize;
1225 for (target, w) in results {
1226 let rel = target.strip_prefix(root).unwrap_or(target).display();
1227 eprintln!(" {} {}", if *w { "wrote " } else { "unchanged" }, rel);
1228 written += usize::from(*w);
1229 }
1230 eprintln!(
1231 "htl dts: {} declaration(s) from {}, {} written",
1232 results.len(),
1233 root.display(),
1234 written
1235 );
1236}
1237
1238fn apply_model(
1245 h: &Htl,
1246 cfg: &project::Config,
1247 start: &Path,
1248) -> Result<Option<htl::model::Project>> {
1249 let model = project::model_of(cfg, start)?;
1250 if let Some(m) = &model {
1251 h.apply_model(m, htl::model::View::Source)?;
1252 }
1253 Ok(model)
1254}
1255
1256fn report_scaffold(dir: &Path, written: &[PathBuf], kept: &[PathBuf]) {
1260 let rel = |p: &PathBuf| p.strip_prefix(dir).unwrap_or(p).display().to_string();
1261 for p in written {
1262 eprintln!(" created {}", rel(p));
1263 }
1264 for p in kept {
1265 eprintln!(" kept {} (already there)", rel(p));
1266 }
1267 if kept.is_empty() {
1268 eprintln!(
1269 "htl: {} file(s) written under {}",
1270 written.len(),
1271 dir.display()
1272 );
1273 } else {
1274 eprintln!(
1275 "htl: {} file(s) written, {} kept under {}",
1276 written.len(),
1277 kept.len(),
1278 dir.display()
1279 );
1280 }
1281}
1282
1283fn cmd_new(
1284 name: &str,
1285 lib: bool,
1286 embed: bool,
1287 target: Option<&str>,
1288 htl: Option<&str>,
1289 no_x: bool,
1290) -> Result<ExitCode> {
1291 let dir = PathBuf::from(name);
1292 let pkg_name = dir
1293 .file_name()
1294 .and_then(|s| s.to_str())
1295 .ok_or_else(|| anyhow::anyhow!("invalid project name: {name}"))?
1296 .to_string();
1297 let target = scaffold::resolve_target(target, embed, lib)?;
1301 let htl = scaffold::HtlPin::parse(htl)?;
1302 let opts = scaffold::Options {
1303 lib,
1304 target,
1305 htl,
1306 no_x,
1307 };
1308 let done = scaffold::scaffold(&dir, &pkg_name, &opts, true)?;
1309 report_scaffold(&dir, &done.written, &[]);
1310 let fetch = if opts.writes_htlx() {
1313 "htl pkg install && "
1314 } else {
1315 ""
1316 };
1317 let then = match opts.target.map(|t| t.target) {
1323 Some(BuildTarget::Window) => "htl check . && cargo run",
1324 _ => "htl test",
1325 };
1326 eprintln!("next: cd {} && {fetch}{then}", dir.display());
1327 Ok(ExitCode::SUCCESS)
1328}
1329
1330fn cmd_init(
1331 dir: Option<&Path>,
1332 lib: bool,
1333 embed: bool,
1334 target: Option<&str>,
1335 htl: Option<&str>,
1336 no_x: bool,
1337) -> Result<ExitCode> {
1338 let dir = match dir {
1339 Some(d) => d.to_path_buf(),
1340 None => std::env::current_dir()?,
1341 };
1342 let abs = std::fs::canonicalize(&dir).unwrap_or(dir.clone());
1343 let name = abs
1344 .file_name()
1345 .and_then(|s| s.to_str())
1346 .ok_or_else(|| anyhow::anyhow!("cannot derive a project name from {}", abs.display()))?
1347 .to_string();
1348 let asked_for_a_target = target.is_some() || embed;
1349 let target = scaffold::resolve_target(target, embed, lib)?;
1350 let htl = scaffold::HtlPin::parse(htl)?;
1351 let opts = scaffold::Options {
1352 lib,
1353 target,
1354 htl,
1355 no_x,
1356 };
1357 let done = scaffold::scaffold(&dir, &name, &opts, false)?;
1358 let kept: &[PathBuf] = if asked_for_a_target { &done.kept } else { &[] };
1361 if done.written.is_empty() && kept.is_empty() {
1362 eprintln!("htl init: nothing to do, all scaffold files already exist");
1363 } else {
1364 report_scaffold(&dir, &done.written, kept);
1365 }
1366 Ok(ExitCode::SUCCESS)
1367}
1368
1369fn pkg_project() -> Result<htl::pkg::MluaProject> {
1375 let cwd = std::env::current_dir()?;
1376 let root = htl::model::Project::find_root(&cwd)?.map(|r| r.root);
1377 root.filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
1378 .map(|r| htl::pkg::MluaProject::at(&r))
1379 .with_context(|| {
1380 format!(
1381 "no {} above {}: `htl pkg` runs in a project",
1382 htl::pkg::MANIFEST_NAME,
1383 cwd.display()
1384 )
1385 })
1386}
1387
1388fn decl_root(root: &Path) -> Result<PathBuf> {
1392 let cfg = load_config(root)?;
1393 Ok(project::model_of(&cfg, root)?
1394 .and_then(|m| m.own().roots.decl.clone())
1395 .unwrap_or_else(|| root.join("types")))
1396}
1397
1398fn cmd_pkg_install() -> Result<ExitCode> {
1400 let project = pkg_project()?;
1401 let report = project.install()?;
1402 report_install(&report, &project);
1403 let project = htl::pkg::MluaProject::at(&project.root);
1407 report_types_sync(
1408 &project.sync_types(&decl_root(&project.root)?)?,
1409 &project.root,
1410 );
1411 report_patch_drift(&project);
1412 Ok(ExitCode::SUCCESS)
1413}
1414
1415fn report_install(
1417 report: &htl::pkg::mlua_pkg::ops::InstallReport,
1418 project: &htl::pkg::MluaProject,
1419) {
1420 use htl::pkg::mlua_pkg::ops::Placement;
1421 for w in &report.warnings {
1422 if w.contains("patch_dir") && w.contains("not used") {
1426 continue;
1427 }
1428 eprintln!("warning: {w}");
1429 }
1430 let rel = |p: &Path| {
1431 p.strip_prefix(&project.root)
1432 .unwrap_or(p)
1433 .display()
1434 .to_string()
1435 };
1436 for p in &report.packages {
1437 let sha: String = p.sha.chars().take(7).collect();
1438 let where_it_is = match (&p.placement, p.patched) {
1439 (_, true) => format!("from {}", rel(p.root())),
1440 (Placement::Copied(dest), _) => format!("copied to {}", rel(dest)),
1441 (Placement::Symlink(_), _) => p.entry.display().to_string(),
1442 };
1443 eprintln!(" install {} {sha} ({where_it_is})", p.name);
1444 }
1445 let n = report.packages.len();
1446 if report.transitive > 0 {
1447 eprintln!(
1448 "htl pkg install: {n} package(s), {} of them transitive",
1449 report.transitive
1450 );
1451 } else {
1452 eprintln!("htl pkg install: {n} package(s)");
1453 }
1454}
1455
1456fn cmd_pkg_add(spec: htl::pkg::mlua_pkg::ops::AddSpec) -> Result<ExitCode> {
1464 use htl::pkg::mlua_pkg::ops::AddOutcome;
1465 let cwd = std::env::current_dir()?;
1466 let root = htl::model::Project::find_root(&cwd)?
1467 .map(|r| r.root)
1468 .unwrap_or(cwd);
1469 let project = htl::pkg::MluaProject::at(&root);
1470 let name = spec.name.clone();
1471 let done = project.add(spec)?;
1472 let manifest = project
1473 .manifest
1474 .strip_prefix(&project.root)
1475 .unwrap_or(&project.manifest)
1476 .display();
1477 if done.report.manifest_created {
1478 eprintln!(" created {manifest}");
1479 }
1480 let verb = match done.report.outcome {
1481 AddOutcome::Added => "added",
1482 AddOutcome::Replaced => "updated",
1483 };
1484 eprintln!(" {verb} {name} in {manifest}");
1485 if let Some(dir) = &done.kept_patch_dir {
1486 eprintln!(
1490 " kept patch_dir = {} ({name} is patched)",
1491 dir.display()
1492 );
1493 }
1494 eprintln!("htl pkg add: run `htl pkg install` to fetch it");
1495 Ok(ExitCode::SUCCESS)
1496}
1497
1498fn cmd_pkg_update(opts: htl::pkg::mlua_pkg::ops::UpdateOpts) -> Result<ExitCode> {
1500 use htl::pkg::mlua_pkg::ops::UpdateOutcome;
1501 let project = pkg_project()?;
1502 let dry_run = opts.dry_run;
1503 let report = project.update(opts)?;
1504 if report.entries.is_empty() {
1505 eprintln!("htl pkg update: no dependency selected");
1506 return Ok(ExitCode::SUCCESS);
1507 }
1508 for (name, outcome) in &report.entries {
1509 match outcome {
1510 UpdateOutcome::TagBumped { old, new } => {
1511 eprintln!(" update {name}: tag {old} -> {new}")
1512 }
1513 UpdateOutcome::PrefixResolved { pin, resolved } => eprintln!(
1514 " update {name}: prefix '{pin}' is {resolved} (the manifest keeps the prefix)"
1515 ),
1516 UpdateOutcome::Refresh => eprintln!(" update {name}: refresh (branch or unpinned)"),
1517 UpdateOutcome::Skipped(why) => eprintln!(" skip {name}: {why}"),
1518 }
1519 }
1520 if dry_run {
1521 eprintln!("htl pkg update: dry run; nothing was written");
1522 return Ok(ExitCode::SUCCESS);
1523 }
1524 if let Some(install) = &report.install {
1525 report_install(install, &project);
1526 let project = htl::pkg::MluaProject::at(&project.root);
1527 report_types_sync(
1528 &project.sync_types(&decl_root(&project.root)?)?,
1529 &project.root,
1530 );
1531 report_patch_drift(&project);
1532 }
1533 Ok(ExitCode::SUCCESS)
1534}
1535
1536fn cmd_pkg_clean(all: bool) -> Result<ExitCode> {
1538 use htl::pkg::mlua_pkg::ops::CleanReport;
1539 let project = pkg_project()?;
1540 match project.clean(all)? {
1541 CleanReport::CacheRemoved => eprintln!("htl pkg clean: removed every cached package"),
1542 CleanReport::NoLockfile => {
1543 eprintln!("htl pkg clean: no lockfile, so nothing was ever cached")
1544 }
1545 CleanReport::StaleRemoved { removed: 0 } => eprintln!("htl pkg clean: nothing to remove"),
1546 CleanReport::StaleRemoved { removed } => eprintln!(
1547 "htl pkg clean: removed {removed} cache entr{} the lockfile no longer refers to",
1548 if removed == 1 { "y" } else { "ies" }
1549 ),
1550 }
1551 Ok(ExitCode::SUCCESS)
1552}
1553
1554fn report_patch_drift(project: &htl::pkg::MluaProject) {
1563 let short = |s: &str| s.chars().take(7).collect::<String>();
1564 for s in project.patch_status() {
1565 if s.in_use {
1566 continue;
1567 }
1568 let rel = s
1569 .dir
1570 .strip_prefix(&project.root)
1571 .unwrap_or(&s.dir)
1572 .display();
1573 let why = match (&s.base, &s.locked) {
1574 _ if !s.dir.is_dir() => "the copy is not there".to_string(),
1575 (None, _) => "the lockfile records no revision it was taken from".to_string(),
1576 (Some(b), Some(l)) => {
1577 format!("taken from {}, {} is now at {}", short(b), s.name, short(l))
1578 }
1579 (Some(b), None) => format!("taken from {}, and nothing is locked", short(b)),
1580 };
1581 eprintln!(" patch {rel} is not in use ({why})");
1582 eprintln!(
1583 " carry the change forward: commit it, then `htl pkg patch {}`",
1584 s.name
1585 );
1586 eprintln!(" drop it: remove patch_dir from mlua-pkg.toml and delete {rel}");
1587 }
1588}
1589
1590fn cmd_pkg_patch(dep: &str, force: bool) -> Result<ExitCode> {
1595 let project = pkg_project().context("a patch belongs to a project, so this runs in one")?;
1596 let done = project.patch(dep, force)?;
1597 let report = &done.report;
1598 let rel = report
1599 .patch_dir
1600 .strip_prefix(&project.root)
1601 .unwrap_or(&report.patch_dir);
1602 let verb = if report.created { "patched" } else { "rebuilt" };
1603 let base: String = report.base.chars().take(7).collect();
1604 eprintln!(" {verb} {} ({dep} at {base})", rel.display());
1605 if !done.dropped.is_empty() {
1609 eprintln!(
1610 " dropped {} (the repository's, not the package's)",
1611 done.dropped.join(", ")
1612 );
1613 }
1614 eprintln!("htl: it is the project's code now — edit it, commit it, then `htl pkg install`.");
1615 Ok(ExitCode::SUCCESS)
1616}
1617
1618fn report_types_sync(sync: &htl::pkg::TypesSync, root: &Path) {
1622 let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).display().to_string();
1623 for (path, dep) in &sync.written {
1624 eprintln!(" types {} (from {dep})", rel(path));
1625 }
1626 for (path, dep) in &sync.taken {
1627 eprintln!(" kept {} ({dep} publishes one too)", rel(path));
1628 }
1629}
1630
1631fn cmd_types_add(library: &str, from: Option<&Path>, force: bool) -> Result<ExitCode> {
1635 let project = pkg_project().context("`types/` is a project's, so this runs in one")?;
1636 let types = decl_root(&project.root)?;
1637 let sync = match from {
1638 Some(dir) => project.add_types_from(dir, library, "local", force, &types)?,
1639 None => project.add_types(library, force, &types)?,
1640 };
1641 report_types_sync(&sync, &project.root);
1642 if sync.written.is_empty() && !sync.taken.is_empty() {
1643 eprintln!("htl: nothing written; --force replaces what is already there");
1644 }
1645 Ok(ExitCode::SUCCESS)
1646}
1647
1648struct UnusedFlags {
1650 json: bool,
1651 fail_on_unused: bool,
1654 use_cache: bool,
1655 explain: bool,
1656}
1657
1658struct AdoptFlags {
1660 json: bool,
1661 detail: bool,
1664 use_cache: bool,
1665 explain: bool,
1666}
1667
1668struct CheckFlags {
1670 strict: bool,
1671 list_lints: bool,
1672 explain_rule: Option<String>,
1674 json: bool,
1675 use_cache: bool,
1676 cache_mode: Option<cache::Mode>,
1677 explain: bool,
1678 statistics: bool,
1680}
1681
1682struct TestFlags {
1683 fail_fast: bool,
1684 allow_empty: bool,
1686 verbose: bool,
1687 quiet: bool,
1688 slow: Option<f64>,
1689 update: bool,
1690 coverage: bool,
1691 coverage_lines: bool,
1692 lcov: Option<PathBuf>,
1694 junit: Option<PathBuf>,
1696 json: bool,
1697 no_cache: bool,
1698 explain: bool,
1699 seed: Option<u64>,
1700}
1701
1702fn print_coverage(cov: &report::CoverageReport, with_lines: bool) {
1703 let width = cov
1704 .modules
1705 .iter()
1706 .map(|m| m.path.len())
1707 .max()
1708 .unwrap_or(4)
1709 .max(5);
1710 for m in &cov.modules {
1711 eprintln!(
1712 "coverage: {:<width$} {:>5}/{:<5} {:5.1}%",
1713 m.path,
1714 m.executed,
1715 m.total,
1716 100.0 * m.executed as f64 / m.total as f64
1717 );
1718 if !m.never_ran.is_empty() {
1719 let names: Vec<String> = m
1720 .never_ran
1721 .iter()
1722 .map(|f| format!("{} ({})", f.name, f.line))
1723 .collect();
1724 eprintln!(" never ran: {}", names.join(", "));
1725 }
1726 if with_lines && !m.unexecuted.is_empty() {
1727 let spans: Vec<String> = m
1728 .unexecuted
1729 .iter()
1730 .map(|(a, b)| {
1731 if a == b {
1732 a.to_string()
1733 } else {
1734 format!("{a}-{b}")
1735 }
1736 })
1737 .collect();
1738 eprintln!(" unexecuted: {}", spans.join(", "));
1739 }
1740 }
1741 if cov.total > 0 {
1742 eprintln!(
1743 "coverage: {:<width$} {:>5}/{:<5} {:5.1}% (statements)",
1744 "total",
1745 cov.executed,
1746 cov.total,
1747 100.0 * cov.executed as f64 / cov.total as f64
1748 );
1749 } else {
1750 eprintln!("coverage: no .tl module reached");
1751 }
1752}
1753
1754fn junit_suite(rep: &htl::testing::FileReport) -> junit::Suite {
1762 let mut left: Vec<&str> = rep.failures.iter().map(String::as_str).collect();
1763 let cases = rep
1764 .tests
1765 .iter()
1766 .map(|t| {
1767 let failure = (!t.ok)
1768 .then(|| {
1769 let head = format!("{}: ", t.name);
1770 let at = left.iter().position(|m| m.starts_with(&head))?;
1771 Some(left.remove(at)[head.len()..].to_string())
1772 })
1773 .flatten();
1774 junit::Case {
1775 name: t.name.clone(),
1776 ms: t.ms,
1777 failure: failure.or_else(|| (!t.ok).then(|| "failed".to_string())),
1780 }
1781 })
1782 .collect();
1783 let error = if !rep.check.ok() {
1784 Some(junit::Error {
1785 message: "type check failed".to_string(),
1786 kind: "check",
1787 body: rep
1788 .check
1789 .error_items
1790 .iter()
1791 .map(|d| d.clone().spelled().to_string())
1792 .collect::<Vec<_>>()
1793 .join("\n"),
1794 })
1795 } else {
1796 rep.error.as_ref().map(|e| junit::Error {
1797 message: e.clone(),
1798 kind: "error",
1799 body: e.clone(),
1800 })
1801 };
1802 junit::Suite {
1803 file: htl::diagnostic::display_path(&rep.path),
1804 duration_ms: rep.duration_ms,
1805 error,
1806 cases,
1807 }
1808}
1809
1810fn cmd_test(
1811 paths: &[PathBuf],
1812 filter: Option<&str>,
1813 lib: &str,
1814 lint: Option<&str>,
1815 flags: TestFlags,
1816) -> Result<ExitCode> {
1817 let paths = if paths.is_empty() {
1818 vec![PathBuf::from(".")]
1819 } else {
1820 paths.to_vec()
1821 };
1822 if let Some(first) = paths.first() {
1823 auto_dts(first)?;
1824 }
1825 let cfg = load_config(&paths[0])?;
1829 let model = project::model_of(&cfg, &paths[0])?;
1830 let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Test);
1831 let files = htl::testing::discover_tests_for(&paths, &skip, lib)?;
1832 project::refuse_flat_root(model.as_ref(), &paths, &files)?;
1835 let empty = files.is_empty();
1839 if empty {
1840 eprintln!("htl test: no test files found (looked for .tl files that require(\"{lib}\"))");
1841 }
1842 let opts = project::TestOptions {
1843 config: &cfg,
1844 model: model.as_ref(),
1845 lint,
1846 lib,
1847 filter,
1848 run: htl::testing::RunOptions {
1849 fail_fast: flags.fail_fast,
1850 update_snapshots: flags.update,
1851 coverage: flags.coverage,
1852 seed: flags.seed,
1854 async_: Default::default(),
1856 lang: Default::default(),
1857 },
1858 cache: project::cache_options(
1859 !flags.no_cache,
1860 Some(cache::Mode::PerModule),
1861 &cfg,
1862 flags.explain,
1863 ),
1864 };
1865
1866 let mut sink = project::Sink::new(report::Out::new(flags.json, false));
1867 let mut json_files: Vec<report::TestFile> = Vec::new();
1868 let mut junit_suites: Vec<junit::Suite> = Vec::new();
1869 let rep = if empty {
1873 project::TestReport {
1876 files: Vec::new(),
1877 ran: 0,
1878 passed: 0,
1879 failed: 0,
1880 files_with_errors: 0,
1881 replayed: 0,
1882 seed: flags.seed.unwrap_or(0),
1883 duration_ms: 0.0,
1884 coverage: None,
1885 }
1886 } else {
1887 project::test(&mut sink, &files, &opts, &mut |rep, sink| {
1888 if flags.json {
1889 json_files.push(report::TestFile::from_report(rep, sink.out().take()));
1890 }
1891 if flags.junit.is_some() {
1892 junit_suites.push(junit_suite(rep));
1893 }
1894 let f = htl::diagnostic::display_path(&rep.path);
1896 let tag = if rep.ok() { "ok " } else { "FAIL" };
1897 let detail = if !rep.check.ok() {
1898 "type check failed".to_string()
1899 } else if let Some(e) = &rep.error {
1900 format!("error: {}", e.lines().next().unwrap_or_default())
1903 } else if rep.file_level {
1904 "ran to completion (no test library used)".to_string()
1905 } else {
1906 format!("{} passed, {} failed", rep.passed, rep.failed)
1907 };
1908 let show_file = !flags.json && (!flags.quiet || !rep.ok());
1911 if show_file {
1912 eprintln!("{tag} {f} ({detail}, {:.0} ms)", rep.duration_ms);
1913 if let Some(e) = &rep.error {
1914 for line in e.lines().skip(1) {
1915 eprintln!(" {line}");
1916 }
1917 }
1918 }
1919 for tr in &rep.tests {
1920 let slow = flags.slow.is_some_and(|ms| tr.ms >= ms);
1921 if !flags.json && (flags.verbose || slow) {
1922 if flags.quiet && !show_file {
1923 eprintln!("slow {f} {} ({:.1} ms)", tr.name, tr.ms);
1925 continue;
1926 }
1927 let mark = if tr.ok { "ok " } else { "FAIL" };
1928 let note = if slow && !flags.verbose {
1929 " [slow]"
1930 } else {
1931 ""
1932 };
1933 eprintln!(" {mark} {} ({:.1} ms){note}", tr.name, tr.ms);
1934 }
1935 }
1936 if !flags.json {
1937 for m in &rep.failures {
1938 eprintln!(" - {m}");
1939 }
1940 for p in &rep.snapshots_written {
1942 eprintln!(
1943 "snapshot written: {}",
1944 htl::diagnostic::display_path(Path::new(p))
1945 );
1946 }
1947 for p in &rep.snapshots_updated {
1948 eprintln!(
1949 "snapshot updated: {}",
1950 htl::diagnostic::display_path(Path::new(p))
1951 );
1952 }
1953 }
1954 })?
1955 };
1956
1957 if let Some(out) = &flags.junit {
1958 std::fs::write(out, junit::document(&junit_suites, rep.duration_ms))
1961 .with_context(|| format!("writing {}", out.display()))?;
1962 }
1963 if let (Some(out), Some(cov)) = (&flags.lcov, &rep.coverage) {
1964 let root = match &cfg {
1967 Some((dir, _, _)) => dir.clone(),
1968 None => std::env::current_dir()?,
1969 };
1970 let root = std::fs::canonicalize(&root).unwrap_or(root);
1971 std::fs::write(out, cov.lcov(&root))
1972 .with_context(|| format!("writing {}", out.display()))?;
1973 }
1974 let ok = rep.ok() && (!empty || flags.allow_empty);
1977 if flags.json {
1978 let summary = report::TestSummary {
1979 files: rep.files.len(),
1980 files_run: rep.ran,
1981 passed: rep.passed,
1982 failed: rep.failed,
1983 files_with_errors: rep.files_with_errors,
1984 replayed: rep.replayed,
1985 duration_ms: rep.duration_ms,
1986 ok,
1987 seed: rep.seed,
1988 };
1989 report::emit(&report::TestReport {
1990 files: json_files,
1991 summary,
1992 coverage: rep.coverage,
1993 })?;
1994 } else if !empty || flags.allow_empty {
1995 if let Some(cov) = &rep.coverage {
1997 print_coverage(cov, flags.coverage_lines);
1998 if let Some(out) = &flags.lcov {
1999 eprintln!("coverage: lcov written to {}", out.display());
2000 }
2001 }
2002 eprintln!(
2003 "htl test: {} file(s), {} passed, {} failed, {} file(s) with errors{}{} ({:.0} ms)",
2004 rep.ran,
2005 rep.passed,
2006 rep.failed,
2007 rep.files_with_errors,
2008 if rep.skipped() > 0 {
2009 format!(", {} file(s) not run (--fail-fast)", rep.skipped())
2010 } else {
2011 String::new()
2012 },
2013 if rep.replayed > 0 {
2015 format!(", {} checked from cache", rep.replayed)
2016 } else {
2017 String::new()
2018 },
2019 rep.duration_ms
2020 );
2021 if !empty {
2025 eprintln!(
2026 "htl test: seed {} (repeat with --seed {})",
2027 rep.seed, rep.seed
2028 );
2029 }
2030 }
2031 Ok(if ok {
2032 ExitCode::SUCCESS
2033 } else {
2034 ExitCode::FAILURE
2035 })
2036}
2037
2038fn report_patched(paths: &[PathBuf]) {
2044 let roots: Vec<PathBuf> = paths
2045 .iter()
2046 .filter_map(|p| std::fs::canonicalize(p).ok())
2047 .collect();
2048 let cwd = std::env::current_dir().unwrap_or_default();
2049 let Some(project) = paths
2052 .first()
2053 .and_then(|p| htl::model::Project::find_root(p).ok().flatten())
2054 .map(|r| r.root)
2055 .filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
2056 .map(|r| htl::pkg::MluaProject::at(&r))
2057 else {
2058 return;
2059 };
2060 for p in &project.patches {
2061 let canon = std::fs::canonicalize(&p.dir).unwrap_or_else(|_| p.dir.clone());
2062 if !roots.iter().any(|r| canon.starts_with(r)) {
2063 continue;
2064 }
2065 let shown = p.dir.strip_prefix(&cwd).unwrap_or(&p.dir);
2066 eprintln!(" patched {} ({})", shown.display(), p.name);
2067 }
2068}
2069
2070fn load_config(first: &Path) -> Result<project::Config> {
2082 let cfg = project::config_of(first)?;
2083 if let Some((_, path, c)) = &cfg {
2084 htl::config::check_toolchain(c, path, env!("CARGO_PKG_VERSION"))?;
2085 }
2086 Ok(cfg)
2087}
2088
2089fn warn_cargo_htl_mismatch(first: &Path) {
2116 let Some(root) = htl::dts::find_cargo_package_root(first) else {
2117 return;
2118 };
2119 let Ok(text) = fs::read_to_string(root.join("Cargo.toml")) else {
2120 return;
2121 };
2122 let Ok(manifest) = text.parse::<toml::Table>() else {
2123 return;
2124 };
2125 let Some(dep) = manifest.get("dependencies").and_then(|d| d.get("htl")) else {
2126 return;
2127 };
2128 let req_text = match dep {
2129 toml::Value::String(s) => s.as_str(),
2130 toml::Value::Table(t) => match t.get("version").and_then(toml::Value::as_str) {
2131 Some(s) => s,
2132 None => return,
2133 },
2134 _ => return,
2135 };
2136 let running = env!("CARGO_PKG_VERSION");
2137 let (Ok(req), Ok(version)) = (
2138 semver::VersionReq::parse(req_text),
2139 semver::Version::parse(running),
2140 ) else {
2141 return;
2142 };
2143 if req.matches(&version) {
2144 return;
2145 }
2146 eprintln!(
2149 "htl {running}; Cargo.toml asks for htl {req_text} — the crate and the CLI are \
2150 meant to move together (cargo install htl-cli --version {req_text}, or bump the \
2151 dependency)"
2152 );
2153}
2154
2155fn cmd_fmt(paths: &[PathBuf], check: bool, indent: Option<usize>) -> Result<ExitCode> {
2156 let paths = if paths.is_empty() {
2157 vec![PathBuf::from(".")]
2158 } else {
2159 paths.to_vec()
2160 };
2161 let cfg = load_config(&paths[0])?;
2162 let indent = indent
2163 .or_else(|| cfg.as_ref().and_then(|(_, _, c)| c.fmt.indent))
2164 .unwrap_or(3);
2165 let h = Htl::new()?;
2166 config_lang(&h, &cfg)?;
2167 let model = project::model_of(&cfg, &paths[0])?;
2171 let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
2172 let files = htl::collect_tl_skipping(&paths, &skip)?;
2173 let (mut changed, mut failed) = (0usize, 0usize);
2174 for f in &files {
2175 let before = fs::read_to_string(f).with_context(|| format!("reading {}", f.display()))?;
2176 let after = match h.format_file(f, indent) {
2177 Ok(s) => s,
2178 Err(e) => {
2179 eprintln!("error: {e}");
2180 failed += 1;
2181 continue;
2182 }
2183 };
2184 if after != before {
2185 changed += 1;
2186 if check {
2187 eprintln!("would reformat: {}", f.display());
2188 } else {
2189 fs::write(f, after).with_context(|| format!("writing {}", f.display()))?;
2190 eprintln!("reformatted: {}", f.display());
2191 }
2192 }
2193 }
2194 eprintln!(
2195 "htl fmt: {} file(s), {} {}, {} failed",
2196 files.len(),
2197 changed,
2198 if check { "would change" } else { "reformatted" },
2199 failed
2200 );
2201 let fail = failed > 0 || (check && changed > 0);
2202 Ok(if fail {
2203 ExitCode::FAILURE
2204 } else {
2205 ExitCode::SUCCESS
2206 })
2207}
2208
2209struct FixFlags {
2210 rule: Vec<String>,
2211 unsafe_fixes: bool,
2212 dry_run: bool,
2213 diff: bool,
2214 allow_dirty: bool,
2215 allow_no_vcs: bool,
2216 exit_non_zero_on_fix: bool,
2217 json: bool,
2218}
2219
2220fn cmd_fix(paths: &[PathBuf], flags: FixFlags) -> Result<ExitCode> {
2221 use htl::fix::{FixOptions, fix_file, git_dirty, unified_diff};
2222 let paths = if paths.is_empty() {
2223 vec![PathBuf::from(".")]
2224 } else {
2225 paths.to_vec()
2226 };
2227 let cfg = load_config(&paths[0])?;
2228 auto_dts_to(&paths[0], !flags.dry_run)?;
2230 let model = project::model_of(&cfg, &paths[0])?;
2231 let scope = project::Scope::new(&cfg, model.as_ref(), &paths[0], None)?;
2234 let h = project::checker(
2235 model.as_ref(),
2236 scope.lints.selection(),
2237 &project::lang_of(&cfg),
2238 )?;
2239 let opts = FixOptions {
2240 unsafe_fixes: flags.unsafe_fixes,
2241 promoted: cfg
2242 .as_ref()
2243 .map(|(_, _, c)| c.fix.unsafe_.clone())
2244 .unwrap_or_default(),
2245 disabled: cfg
2246 .as_ref()
2247 .map(|(_, _, c)| c.fix.disable.clone())
2248 .unwrap_or_default(),
2249 only: flags.rule.clone(),
2250 dry_run: flags.dry_run,
2251 };
2252 opts.validate()?;
2255 let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
2259 let (files, outside) = project::held_by_modules(
2261 model.as_ref(),
2262 &paths,
2263 htl::collect_tl_skipping(&paths, &skip)?,
2264 )?;
2265 if let Some(note) = project::outside_modules_note(model.as_ref(), &outside, "fixed") {
2266 eprintln!("htl fix: {note}");
2267 }
2268 let check_skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Check);
2272 let checked_only: Vec<PathBuf> = project::held_by_modules(
2273 model.as_ref(),
2274 &paths,
2275 htl::collect_tl_skipping(&paths, &check_skip)?,
2276 )?
2277 .0
2278 .into_iter()
2279 .filter(|f| !files.contains(f))
2280 .collect();
2281
2282 if !flags.dry_run {
2284 let mut dirty = Vec::new();
2285 let mut no_vcs = Vec::new();
2286 for f in &files {
2287 match git_dirty(f)? {
2288 Some(true) => dirty.push(f.clone()),
2289 Some(false) => {}
2290 None => no_vcs.push(f.clone()),
2291 }
2292 }
2293 if !dirty.is_empty() && !flags.allow_dirty {
2294 bail!(
2295 "htl fix rewrites files in place and relies on git to undo it; these have uncommitted changes:\n {}\ncommit or stash them, or pass --allow-dirty",
2296 dirty
2297 .iter()
2298 .map(|p| p.display().to_string())
2299 .collect::<Vec<_>>()
2300 .join("\n ")
2301 );
2302 }
2303 if !no_vcs.is_empty() && !flags.allow_no_vcs {
2304 bail!(
2305 "htl fix rewrites files in place and relies on git to undo it; these are not in a git repository:\n {}\npass --allow-no-vcs to proceed without that safety net",
2306 no_vcs
2307 .iter()
2308 .map(|p| p.display().to_string())
2309 .collect::<Vec<_>>()
2310 .join("\n ")
2311 );
2312 }
2313 }
2314
2315 let mut sink = project::Sink::new(report::Out::new(flags.json, false));
2316 sink.judge_by(scope.lints.selection());
2318 let origins = project::Origins::new(model.as_ref());
2322 let walk = scope.walk(&cfg, model.as_ref(), &origins);
2323 let walked: Vec<PathBuf> = files.iter().chain(&checked_only).cloned().collect();
2324 sink.walking(&walked);
2325 let (mut applied, mut skipped, mut json_files) = (Vec::new(), Vec::new(), Vec::new());
2326 let (mut changed, mut deferred, mut reverted) = (0usize, 0usize, 0usize);
2327 let mut found = htl::verdict::Findings::default();
2328 let mut infos: Vec<(PathBuf, htl::CheckInfo)> = Vec::with_capacity(walked.len());
2329 for f in &files {
2330 let saved = h.search_path()?;
2333 project::file_view(&h, model.as_ref(), f)?;
2334 let before = if flags.diff {
2335 std::fs::read_to_string(f).ok()
2336 } else {
2337 None
2338 };
2339 let out = fix_file(&h, f, &opts)?;
2340 if out.contents.is_some() {
2341 changed += 1;
2342 }
2343 deferred += out.deferred;
2344 if out.reverted.is_some() {
2345 reverted += 1;
2346 }
2347 if !flags.json {
2348 for a in &out.applied {
2349 eprintln!(
2350 "fixed: {}:{}: {} ({}{})",
2351 project::display_path(f),
2352 a.line,
2353 a.rule,
2354 a.applicability.as_str(),
2355 if flags.dry_run { ", not written" } else { "" }
2356 );
2357 }
2358 for s in &out.skipped {
2359 eprintln!(
2360 "skipped: {}:{}: {} — {}",
2361 project::display_path(f),
2362 s.line,
2363 s.rule,
2364 s.reason
2365 );
2366 }
2367 if let Some(r) = &out.reverted {
2368 eprintln!("reverted: {}: {r}", project::display_path(f));
2369 }
2370 if let Some(o) = &out.oscillation {
2371 eprintln!(
2372 "stopped: {}: fixes of {o} undo each other",
2373 project::display_path(f)
2374 );
2375 }
2376 if out.deferred > 0 {
2377 eprintln!(
2378 "deferred: {}: {} edit(s) overlapped applied ones; run htl fix again",
2379 project::display_path(f),
2380 out.deferred
2381 );
2382 }
2383 if flags.diff
2384 && let (Some(b), Some(a)) = (&before, &out.contents)
2385 {
2386 print!("{}", unified_diff(&project::display_path(f), b, a));
2387 }
2388 if flags.diff
2391 && let (Some(b), Some(s)) = (
2392 out.contents.as_ref().or(before.as_ref()),
2393 out.suggested.as_ref(),
2394 )
2395 {
2396 print!(
2397 "{}",
2398 unified_diff(&format!("{} (suggested)", project::display_path(f)), b, s)
2399 );
2400 }
2401 }
2402 found.lints += project::file_findings(&h, &mut sink, f, &out.check, &walk)?;
2405 h.set_search_path(&saved)?;
2406 found.errors += out.check.errors.len();
2407 found.warnings += out.check.warnings.len();
2408 infos.push((f.clone(), out.check.clone()));
2409 if flags.json {
2410 applied.extend(out.applied.iter().map(|a| report::FixApplied {
2411 file: project::display_path(f),
2412 line: a.line,
2413 rule: a.rule.clone(),
2414 applicability: a.applicability.as_str(),
2415 pass: a.pass,
2416 }));
2417 skipped.extend(out.skipped.iter().map(|s| report::FixSkipped {
2418 file: project::display_path(f),
2419 line: s.line,
2420 rule: s.rule.clone(),
2421 reason: s.reason.clone(),
2422 }));
2423 json_files.push(report::FixFile {
2424 path: project::display_path(f),
2425 changed: out.contents.is_some(),
2426 deferred: out.deferred,
2427 reverted: out.reverted.clone(),
2428 oscillation: out.oscillation.clone(),
2429 diagnostics: sink.out().take(),
2430 });
2431 }
2432 }
2433 for f in &checked_only {
2435 let m = project::check_one(&h, &mut sink, f, &walk)?;
2436 found.errors += m.errors;
2437 found.warnings += m.warnings;
2438 found.lints += m.lints;
2439 infos.push((f.clone(), m.requires_only()));
2440 if flags.json {
2441 json_files.push(report::FixFile {
2442 path: project::display_path(f),
2443 changed: false,
2444 deferred: 0,
2445 reverted: None,
2446 oscillation: None,
2447 diagnostics: sink.out().take(),
2448 });
2449 }
2450 }
2451 let mut whole = scope.whole(&cfg, model.as_ref());
2454 whole.publish = !flags.dry_run;
2455 let w = project::project_findings(&mut sink, &whole, &infos);
2456 found.errors += w.errors;
2457 found.lints += w.lints;
2458 let project_diagnostics = if flags.json {
2459 sink.out().take()
2460 } else {
2461 Vec::new()
2462 };
2463 found.errors += sink.dependency_error_count();
2466 found.denied = sink.denied();
2467 let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
2469 let errors_remaining = found.errors;
2470 let n_applied = if flags.json { applied.len() } else { 0 };
2471 let fail =
2472 htl::verdict::verdict(&found, &policy) || (flags.exit_non_zero_on_fix && changed > 0);
2473 if flags.json {
2474 let n_skipped = skipped.len();
2475 report::emit(&report::FixReport {
2476 dry_run: flags.dry_run,
2477 applied,
2478 skipped,
2479 files: json_files,
2480 summary: report::FixSummary {
2481 files: files.len(),
2482 files_changed: changed,
2483 applied: n_applied,
2484 skipped: n_skipped,
2485 deferred,
2486 reverted,
2487 errors_remaining,
2488 warnings: found.warnings,
2489 lints: found.lints,
2490 denied: found.denied,
2491 strict: policy.strict,
2492 ok: !fail,
2493 },
2494 diagnostics: project_diagnostics,
2495 })?;
2496 } else {
2497 let judged = judged(&found, &policy);
2501 eprintln!(
2502 "htl fix: {} file(s){}, {} changed{}, {} error(s) remaining{}{}",
2503 files.len(),
2504 if checked_only.is_empty() {
2505 String::new()
2506 } else {
2507 format!(" + {} checked in patched dependencies", checked_only.len())
2508 },
2509 changed,
2510 if flags.dry_run {
2511 " (dry run, nothing written)"
2512 } else {
2513 ""
2514 },
2515 errors_remaining,
2516 judged,
2517 if deferred > 0 {
2518 format!(", {deferred} deferred")
2519 } else {
2520 String::new()
2521 }
2522 );
2523 }
2524 Ok(if fail {
2525 ExitCode::FAILURE
2526 } else {
2527 ExitCode::SUCCESS
2528 })
2529}
2530
2531fn cmd_check(paths: &[PathBuf], lint: Option<&str>, flags: CheckFlags) -> Result<ExitCode> {
2543 let CheckFlags {
2544 list_lints,
2545 json,
2546 use_cache,
2547 cache_mode,
2548 explain,
2549 statistics,
2550 ..
2551 } = flags;
2552 let mut sink = project::Sink::new(report::Out::new(json, statistics));
2553 let paths = if paths.is_empty() {
2554 vec![PathBuf::from(".")]
2555 } else {
2556 paths.to_vec()
2557 };
2558 if let Some(rule) = flags.explain_rule.as_deref() {
2567 let Some(r) = htl::lint::explained(rule) else {
2568 eprintln!("unknown lint rule: {rule}");
2569 return Ok(ExitCode::from(2));
2570 };
2571 println!("{} (default: {})\n\n{}", r.name, r.default, r.explain);
2572 return Ok(ExitCode::SUCCESS);
2573 }
2574 if list_lints {
2575 let width = htl::lint::rule_names()
2580 .iter()
2581 .map(|r| r.len())
2582 .max()
2583 .unwrap_or(0);
2584 for (name, level) in htl::lint::rule_defaults() {
2585 println!("{name:width$} {level}");
2586 }
2587 return Ok(ExitCode::SUCCESS);
2591 }
2592 let cfg = load_config(&paths[0])?;
2594 warn_cargo_htl_mismatch(&paths[0]);
2595 let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), flags.strict);
2596 if let Some(first) = paths.first() {
2600 auto_dts(first)?;
2601 }
2602 let walk_model = project::model_of(&cfg, &paths[0])?;
2607 if walk_model.is_none()
2612 && let Some(dir) = paths.iter().find(|p| p.is_dir())
2613 {
2614 bail!(
2615 "no {} or {} in {} or any directory above it: a directory is checked as a \
2616 project. Run `htl init` there to make it one, or name the .tl files to check \
2617 each on its own",
2618 htl::config::CONFIG_NAME,
2619 htl::pkg::MANIFEST_NAME,
2620 fs::canonicalize(dir)
2623 .unwrap_or_else(|_| dir.clone())
2624 .display()
2625 );
2626 }
2627 let skip = project::not_walked(walk_model.as_ref(), &paths, htl::model::Purpose::Check);
2628 let (files, outside) = project::held_by_modules(
2629 walk_model.as_ref(),
2630 &paths,
2631 htl::collect_tl_skipping(&paths, &skip)?,
2632 )?;
2633 if let Some(note) = project::outside_modules_note(walk_model.as_ref(), &outside, "checked") {
2634 eprintln!("htl check: {note}");
2635 }
2636 if !json {
2637 report_patched(&paths);
2638 }
2639
2640 let rep = project::check(
2644 &mut sink,
2645 &files,
2646 &project::Options {
2647 paths: &paths,
2648 config: &cfg,
2649 model: walk_model.as_ref(),
2650 lint,
2651 cache: project::cache_options(use_cache, cache_mode, &cfg, explain),
2652 },
2653 )?;
2654 let fail = report_check(
2655 sink.out(),
2656 json,
2657 statistics,
2658 &rep,
2659 &policy,
2660 patched_files(walk_model.as_ref(), &rep.files),
2661 )?;
2662 Ok(if fail {
2663 ExitCode::FAILURE
2664 } else {
2665 ExitCode::SUCCESS
2666 })
2667}
2668
2669fn cmd_unused(paths: &[PathBuf], flags: UnusedFlags) -> Result<ExitCode> {
2676 let UnusedFlags {
2677 json,
2678 fail_on_unused,
2679 use_cache,
2680 explain,
2681 } = flags;
2682 let paths = if paths.is_empty() {
2683 vec![PathBuf::from(".")]
2684 } else {
2685 paths.to_vec()
2686 };
2687 let cfg = load_config(&paths[0])?;
2688 auto_dts(&paths[0])?;
2691 let model = project::model_of(&cfg, &paths[0])?;
2692 let rep = htl::unused::unused(&htl::unused::Options {
2693 paths: &paths,
2694 config: &cfg,
2695 model: model.as_ref(),
2696 cache: project::cache_options(use_cache, None, &cfg, explain),
2697 })?;
2698 let s = &rep.summary;
2699 if json {
2700 report::emit(&rep)?;
2701 } else if s.no_entry {
2702 eprintln!(
2703 "htl unused: nothing to start from, so nothing is reported. An entry is \
2704 main.tl in the source root ([layout] source) or beside the manifest, a test file, a module under a [[contract]] directory, or a name \
2705 in [build] extra / host"
2706 );
2707 } else {
2708 if s.check_errors > 0 {
2709 eprintln!(
2710 "htl unused: {} error(s) in the check this graph comes from — what those \
2711 files require is missing from it (htl check)",
2712 s.check_errors
2713 );
2714 }
2715 for m in &rep.modules {
2716 match &m.module {
2717 Some(n) => eprintln!("module: {} ({n})", m.path),
2718 None => eprintln!("module: {}", m.path),
2719 }
2720 }
2721 for d in &rep.dependencies {
2722 eprintln!("dependency: {}", d.name);
2723 }
2724 eprintln!(
2725 "htl unused: {}, {} [{} considered, {} reached, {}]",
2726 count(s.modules, "module", "modules"),
2727 count(s.dependencies, "dependency", "dependencies"),
2728 s.considered,
2729 s.reached,
2730 count(s.entries, "entry", "entries"),
2731 );
2732 }
2733 Ok(if fail_on_unused && !s.ok {
2734 ExitCode::FAILURE
2735 } else {
2736 ExitCode::SUCCESS
2737 })
2738}
2739
2740fn cmd_adopt(paths: &[PathBuf], flags: AdoptFlags) -> Result<ExitCode> {
2747 let AdoptFlags {
2748 json,
2749 detail,
2750 use_cache,
2751 explain,
2752 } = flags;
2753 let paths = if paths.is_empty() {
2754 vec![PathBuf::from(".")]
2755 } else {
2756 paths.to_vec()
2757 };
2758 let cfg = load_config(&paths[0])?;
2759 auto_dts(&paths[0])?;
2762 let model = project::model_of(&cfg, &paths[0])?;
2763 let rep = htl::adopt::adopt(&htl::adopt::Options {
2764 paths: &paths,
2765 config: &cfg,
2766 model: model.as_ref(),
2767 cache: project::cache_options(use_cache, None, &cfg, explain),
2768 })?;
2769 if json {
2770 report::emit(&rep)?;
2771 } else {
2772 print_adopt(&rep, detail);
2773 }
2774 Ok(ExitCode::SUCCESS)
2777}
2778
2779fn adopt_marker_width() -> usize {
2782 htl::adopt::FEATURES
2783 .iter()
2784 .map(|m| format!("---@{m}").len())
2785 .max()
2786 .unwrap_or(0)
2787 + 2
2788}
2789
2790fn print_adopt(rep: &htl::adopt::Report, detail: bool) {
2793 let width = adopt_marker_width();
2794 eprintln!(
2795 "{:<width$} {:>4} {:>10}",
2796 "feature",
2797 "used",
2798 "applicable",
2799 width = width
2800 );
2801 for f in &rep.features {
2802 let applicable = match f.applicable {
2803 Some(n) => n.to_string(),
2804 None => "-".to_string(),
2805 };
2806 eprintln!(
2807 "{:<width$} {:>4} {:>10}",
2808 format!("---@{}", f.marker),
2809 f.used,
2810 applicable,
2811 width = width
2812 );
2813 }
2814 if detail {
2815 let line_width = rep
2819 .features
2820 .iter()
2821 .flat_map(|f| {
2822 f.sites
2823 .iter()
2824 .map(|s| format!("{}:{}", s.file.display(), s.line))
2825 .chain(
2826 f.candidates
2827 .iter()
2828 .map(|c| format!("{}:{}", c.file.display(), c.line)),
2829 )
2830 })
2831 .map(|s| s.len())
2832 .max()
2833 .unwrap_or(0);
2834 for f in &rep.features {
2835 for s in &f.sites {
2836 eprintln!(
2837 " {:<width$}{:<line_width$} {}",
2838 format!("---@{}", f.marker),
2839 format!("{}:{}", s.file.display(), s.line),
2840 s.name,
2841 width = width,
2842 line_width = line_width
2843 );
2844 }
2845 for c in &f.candidates {
2848 let sites = if c.sites == 1 {
2849 "1 site".to_string()
2850 } else {
2851 format!("{} sites", c.sites)
2852 };
2853 eprintln!(
2854 " {:<width$}{:<line_width$} {} (applicable: {}, {sites})",
2855 format!("---@{}", f.marker),
2856 format!("{}:{}", c.file.display(), c.line),
2857 c.name,
2858 c.reason,
2859 width = width,
2860 line_width = line_width
2861 );
2862 }
2863 }
2864 }
2865 let s = &rep.summary;
2866 if s.check_errors > 0 {
2867 eprintln!(
2868 "htl adopt: {} error(s) in the project's check (htl check says which); a file \
2869 with a syntax error contributes no markers",
2870 s.check_errors
2871 );
2872 }
2873 if s.markers == 0 {
2874 eprintln!(
2875 "htl adopt: {} of {} features used, no markers",
2876 s.used, s.features
2877 );
2878 } else {
2879 eprintln!(
2880 "htl adopt: {} of {} features used, {} in {}",
2881 s.used,
2882 s.features,
2883 count(s.markers, "marker", "markers"),
2884 count(s.files, "file", "files"),
2885 );
2886 }
2887}
2888
2889fn cmd_resolve(module: &str, path: Option<&Path>, json: bool) -> Result<ExitCode> {
2898 let start = path.unwrap_or(Path::new("."));
2899 let cfg = load_config(start)?;
2900 auto_dts(start)?;
2904 let h = Htl::new()?;
2905 h.install_std()?;
2908 let model = apply_model(&h, &cfg, start)?;
2909 let rep = htl::resolve::resolve(
2910 &h,
2911 module,
2912 cfg.as_ref().map(|(r, _, _)| r.as_path()),
2913 model.as_ref(),
2914 )?;
2915 if json {
2916 report::emit(&rep)?;
2917 } else {
2918 print_resolution(&rep);
2919 }
2920 Ok(if rep.summary.ok {
2921 ExitCode::SUCCESS
2922 } else {
2923 ExitCode::FAILURE
2924 })
2925}
2926
2927fn print_resolution(r: &htl::resolve::Resolution) {
2931 let ambiguous = r
2932 .candidates
2933 .iter()
2934 .any(|c| c.status == htl::resolve::Status::Ambiguous);
2935 let typed_by = r
2939 .read
2940 .as_ref()
2941 .map(|d| format!(", typed by {d}"))
2942 .unwrap_or_default();
2943 match (&r.read, &r.error, &r.provided_by) {
2944 (_, Some(e), _) => println!("htl resolve {}: error: {e}", r.module),
2945 (Some(read), None, Some(by)) if r.provider == Some(htl::model::Provider::Declared) => {
2949 println!(
2950 "htl resolve {}: {read}, provided by the environment ({by})",
2951 r.module
2952 )
2953 }
2954 (_, None, Some(by)) => {
2955 println!(
2956 "htl resolve {}: provided by the host ({by}){typed_by}",
2957 r.module
2958 )
2959 }
2960 (Some(read), None, None) => println!("htl resolve {}: {read}", r.module),
2961 (None, None, None) if ambiguous => println!(
2962 "htl resolve {}: more than one module implements it, and no order picks one",
2963 r.module
2964 ),
2965 (None, None, None) => println!(
2966 "htl resolve {}: nothing in the project or on the search path answers require(\"{}\")",
2967 r.module, r.module
2968 ),
2969 }
2970 if !r.candidates.is_empty() {
2971 let w = |f: fn(&htl::resolve::Candidate) -> usize, head: usize| {
2972 r.candidates.iter().map(f).max().unwrap_or(0).max(head)
2973 };
2974 let file = w(|c| c.path.len(), 4);
2975 let kind = w(|c| c.kind.as_str().len(), 4);
2976 let read_at = r
2977 .candidates
2978 .iter()
2979 .find(|c| c.status == htl::resolve::Status::Read)
2980 .map(|c| c.order);
2981 println!();
2982 println!(" order {:file$} {:kind$} status", "file", "kind");
2983 for c in &r.candidates {
2984 let status = match (c.status, c.shadowed_by, read_at) {
2985 (htl::resolve::Status::Shadowed, Some(by), _) => format!("shadowed by {by}"),
2986 (htl::resolve::Status::Runtime, _, Some(by)) => format!("runtime, typed by {by}"),
2988 (s, _, _) => s.as_str().to_string(),
2989 };
2990 let origin = match &c.origin {
2991 Some(o) => format!(" ({})", o.describe()),
2992 None => String::new(),
2993 };
2994 println!(
2995 " {:<5} {:file$} {:kind$} {status}{origin}",
2996 c.order,
2997 c.path,
2998 c.kind.as_str()
2999 );
3000 }
3001 }
3002 println!();
3003 match r.answered_by {
3004 htl::resolve::AnsweredBy::Model => println!(" answered by the project model"),
3005 htl::resolve::AnsweredBy::Path => {
3008 println!(" searched, in order: {}", r.searched.join(", "))
3009 }
3010 }
3011}
3012
3013fn count(n: usize, one: &str, many: &str) -> String {
3016 format!("{n} {}", if n == 1 { one } else { many })
3017}
3018
3019fn cmd_cache_clear(path: Option<&Path>) -> Result<ExitCode> {
3029 let root = cache_root(path)?;
3030 let dir = root.join(".htl").join("cache");
3031 if !dir.is_dir() {
3032 eprintln!("htl cache: nothing stored at {}", dir.display());
3033 return Ok(ExitCode::SUCCESS);
3034 }
3035 let n = fs::read_dir(&dir)
3036 .map(|rd| {
3037 rd.flatten()
3038 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
3039 .count()
3040 })
3041 .unwrap_or(0);
3042 fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
3043 eprintln!(
3044 "htl cache: removed {n} {} from {}",
3045 if n == 1 { "entry" } else { "entries" },
3046 dir.display()
3047 );
3048 Ok(ExitCode::SUCCESS)
3049}
3050
3051fn cache_root(path: Option<&Path>) -> Result<PathBuf> {
3054 let start = path.unwrap_or(Path::new("."));
3055 let model = htl::model::Project::find_root(start)?.map(|r| r.root);
3056 Ok(model.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))))
3057}
3058
3059fn cmd_cache_status(path: Option<&Path>, json: bool, list_entries: bool) -> Result<ExitCode> {
3065 let c = cache::describe(&cache_root(path)?);
3066 if json {
3067 report::emit(&c)?;
3068 return Ok(ExitCode::SUCCESS);
3069 }
3070
3071 if c.entries.is_empty() {
3072 println!("htl cache: empty ({})", c.dir);
3073 return Ok(ExitCode::SUCCESS);
3074 }
3075 let mut by_kind: std::collections::BTreeMap<&str, (usize, u64)> = Default::default();
3076 for e in &c.entries {
3077 let slot = by_kind.entry(e.kind.as_str()).or_default();
3078 slot.0 += 1;
3079 slot.1 += e.bytes;
3080 }
3081 println!(
3082 "htl cache: {} entries, {} at {}",
3083 c.entries.len(),
3084 human_bytes(c.bytes),
3085 c.dir
3086 );
3087 for (kind, (n, bytes)) in &by_kind {
3088 let what = match *kind {
3089 cache::CHECK => "checked modules",
3090 cache::GEN => "checked and generated test files (htl test)",
3091 cache::MODULE => "generated modules (htl test / build, include_bundle!)",
3092 cache::RUN => "whole runs",
3093 _ => "entries this build cannot read",
3094 };
3095 println!(" {n:>5} {what} ({})", human_bytes(*bytes));
3096 }
3097 if let (Some(min), Some(max)) = (
3098 c.entries.iter().map(|e| e.age_secs).min(),
3099 c.entries.iter().map(|e| e.age_secs).max(),
3100 ) {
3101 println!(
3102 " last used between {} and {} ago",
3103 human_age(min),
3104 human_age(max)
3105 );
3106 }
3107 if list_entries {
3108 println!();
3109 for e in &c.entries {
3110 println!(
3111 " {:<6} {:>8} {}",
3112 e.kind,
3113 human_bytes(e.bytes),
3114 e.subjects.join(", ")
3115 );
3116 }
3117 }
3118 Ok(ExitCode::SUCCESS)
3119}
3120
3121fn human_bytes(n: u64) -> String {
3122 if n >= 1 << 20 {
3123 format!("{:.1} MB", n as f64 / (1u64 << 20) as f64)
3124 } else if n >= 1 << 10 {
3125 format!("{:.0} KB", n as f64 / (1u64 << 10) as f64)
3126 } else {
3127 format!("{n} B")
3128 }
3129}
3130
3131fn human_age(secs: u64) -> String {
3132 match secs {
3133 s if s < 90 => format!("{s}s"),
3134 s if s < 5400 => format!("{}m", s / 60),
3135 s if s < 172_800 => format!("{}h", s / 3600),
3136 s => format!("{}d", s / 86_400),
3137 }
3138}
3139
3140fn patched_files(model: Option<&htl::model::Project>, files: &[PathBuf]) -> usize {
3146 let Some(model) = model else {
3147 return 0;
3148 };
3149 if !model
3150 .modules
3151 .iter()
3152 .any(|m| m.owner == htl::model::Owner::Patched)
3153 {
3154 return 0;
3155 }
3156 files
3157 .iter()
3158 .filter(|f| {
3159 model
3160 .home_of(f)
3161 .is_some_and(|m| m.owner == htl::model::Owner::Patched)
3162 })
3163 .count()
3164}
3165
3166fn print_statistics(rows: &[report::RuleStatistic]) {
3170 let width = rows.iter().map(|r| r.rule.len()).max().unwrap_or(0);
3171 for r in rows {
3172 eprintln!(
3173 "{:>5} {:<width$} {}",
3174 r.count,
3175 r.rule,
3176 statistics_marker(r)
3177 );
3178 }
3179}
3180
3181fn statistics_marker(r: &report::RuleStatistic) -> &'static str {
3186 if r.fixable == r.count {
3187 "[*]"
3188 } else if r.fixable + r.unsafe_fixable == 0 {
3189 "[ ]"
3190 } else {
3191 "[-]"
3192 }
3193}
3194
3195#[cfg(test)]
3196mod statistics_marker_tests {
3197 use super::statistics_marker;
3198 use crate::report::RuleStatistic;
3199
3200 fn stat(count: usize, fixable: usize, unsafe_fixable: usize) -> RuleStatistic {
3201 RuleStatistic {
3202 rule: "r".to_string(),
3203 count,
3204 fixable,
3205 unsafe_fixable,
3206 }
3207 }
3208
3209 #[test]
3211 fn full_safe_coverage_is_a_star() {
3212 assert_eq!(statistics_marker(&stat(2, 2, 0)), "[*]");
3213 }
3214
3215 #[test]
3217 fn no_fix_at_all_is_blank() {
3218 assert_eq!(statistics_marker(&stat(2, 0, 0)), "[ ]");
3219 }
3220
3221 #[test]
3223 fn a_mix_of_fixable_and_not_is_a_dash() {
3224 assert_eq!(statistics_marker(&stat(3, 1, 0)), "[-]");
3225 }
3226
3227 #[test]
3230 fn full_coverage_split_between_safe_and_unsafe_is_a_dash() {
3231 assert_eq!(statistics_marker(&stat(2, 1, 1)), "[-]");
3232 }
3233
3234 #[test]
3236 fn full_unsafe_only_coverage_is_a_dash() {
3237 assert_eq!(statistics_marker(&stat(2, 0, 2)), "[-]");
3238 }
3239}
3240
3241fn report_check(
3250 out: &mut report::Out,
3251 json: bool,
3252 statistics: bool,
3253 rep: &project::Report,
3254 policy: &htl::verdict::Policy,
3255 patched: usize,
3256) -> Result<bool> {
3257 let (files, replayed) = (rep.files.len(), rep.replayed);
3258 let (errors, warnings, lints) = (rep.errors, rep.warnings, rep.lints);
3259 let strict = policy.strict;
3260 let fail = htl::verdict::verdict(&rep.findings(), policy);
3261 let all_cached = rep.all_cached();
3262 if json {
3263 report::emit(&report::CheckReport {
3264 files,
3265 patched,
3266 diagnostics: out.take(),
3267 summary: report::CheckSummary {
3268 errors,
3269 warnings,
3270 lints,
3271 denied: rep.denied,
3272 strict,
3273 ok: !fail,
3274 cached: all_cached,
3275 replayed,
3276 },
3277 statistics: statistics.then(|| out.statistics()),
3278 })?;
3279 } else {
3280 if statistics {
3281 print_statistics(&out.statistics());
3282 }
3283 let cached = if all_cached {
3285 " [cached]".to_string()
3286 } else if replayed > 0 {
3287 format!(" [{replayed}/{files} cached]")
3288 } else {
3289 String::new()
3290 };
3291 let denied = match rep.denied {
3296 0 => String::new(),
3297 n => format!(", {n} at deny"),
3298 };
3299 let counted = match patched {
3303 0 => format!("{files} file(s)"),
3304 n => format!("{} file(s) + {n} in patched dependencies", files - n),
3305 };
3306 for rule in out.rules_said() {
3311 if htl::lint::explained(rule).is_some() {
3312 eprintln!("htl check --explain {rule}");
3313 }
3314 }
3315 eprintln!(
3316 "htl check: {counted}, {errors} error(s), {warnings} warning(s), {lints} lint(s){denied}{}{cached}",
3317 if strict { " [strict]" } else { "" }
3318 );
3319 }
3320 Ok(fail)
3321}
3322
3323fn cmd_gen(file: &Path, out: Option<&Path>) -> Result<ExitCode> {
3324 let h = Htl::new()?;
3325 auto_dts(file)?;
3326 let cfg = load_config(file)?;
3330 config_lints(&h, &cfg)?;
3331 config_lang(&h, &cfg)?;
3332 let model = apply_model(&h, &cfg, file)?;
3333 project::file_view(&h, model.as_ref(), file)?;
3334 h.install_std()?;
3335 let (code, c) = h.gen_lua(file)?;
3336 text_sink().checkinfo(&c);
3337 let (Some(code), false) = (code, runs_fail(&c)) else {
3340 return Ok(ExitCode::FAILURE);
3341 };
3342 match out {
3346 Some(p) => fs::write(p, code).with_context(|| format!("writing {}", p.display()))?,
3347 None => print!("{code}"),
3348 }
3349 Ok(ExitCode::SUCCESS)
3350}
3351
3352fn cmd_run(file: &Path, args: &[String]) -> Result<ExitCode> {
3353 let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
3354 let h = Htl::new()?;
3355 auto_dts(file)?;
3356 let cfg = load_config(file)?;
3361 config_lints(&h, &cfg)?;
3362 config_lang(&h, &cfg)?;
3363 h.configure_async(async_config(&cfg))?;
3364 let model = apply_model(&h, &cfg, file)?;
3365 h.install_test_lib()?;
3366 h.install_std()?;
3367 h.install_task_lib()?;
3368 if Bundle::is_bundle(&bytes) {
3369 let b = Bundle::decode(&bytes)?;
3370 let main = h.load_bundle(&b, args)?;
3373 return run_root(&h, Entry::Main(main), args);
3374 }
3375 project::file_view(&h, model.as_ref(), file)?;
3377 h.install_searcher()?;
3378 h.set_arg(&file.to_string_lossy(), args)?;
3379 let (code, c) = h.gen_lua(file)?;
3380 text_sink().checkinfo(&c);
3381 let (Some(code), false) = (code, runs_fail(&c)) else {
3383 return Ok(ExitCode::FAILURE);
3384 };
3385 run_root(
3386 &h,
3387 Entry::Chunk {
3388 code,
3389 name: format!("@{}", file.display()),
3390 },
3391 args,
3392 )
3393}
3394
3395enum Entry {
3397 Chunk { code: String, name: String },
3398 Main(htl::mlua::Function),
3399}
3400
3401fn async_config(cfg: &project::Config) -> &htl::config::AsyncConfig {
3403 static DEFAULT: htl::config::AsyncConfig = htl::config::AsyncConfig {
3404 grace_ms: None,
3405 preempt: None,
3406 };
3407 match cfg {
3408 Some((_, _, c)) => &c.async_,
3409 None => &DEFAULT,
3410 }
3411}
3412
3413fn run_root(h: &Htl, entry: Entry, args: &[String]) -> Result<ExitCode> {
3430 let token = htl::mlua_isle::runtime::CancelToken::new();
3431 {
3432 let token = token.clone();
3433 std::thread::Builder::new()
3434 .name("htl-ctrl-c".into())
3435 .spawn(move || {
3436 let Ok(rt) = tokio::runtime::Builder::new_current_thread()
3437 .enable_all()
3438 .build()
3439 else {
3440 return;
3441 };
3442 rt.block_on(async {
3443 if tokio::signal::ctrl_c().await.is_ok() {
3444 token.cancel();
3445 }
3446 if tokio::signal::ctrl_c().await.is_ok() {
3447 std::process::exit(130);
3448 }
3449 });
3450 })
3451 .context("starting the Ctrl-C watcher")?;
3452 }
3453 let rt = tokio::runtime::Builder::new_current_thread()
3454 .enable_all()
3455 .build()
3456 .context("building the executor's runtime")?;
3457 let local = tokio::task::LocalSet::new();
3458 let out = local.block_on(&rt, async {
3459 match entry {
3460 Entry::Chunk { code, name } => h.run_async(&code, &name, args, &token).await,
3461 Entry::Main(main) => {
3462 let va: htl::mlua::Variadic<String> = args.iter().cloned().collect();
3463 h.call_async(main, va, &token).await.map(|_| ())
3464 }
3465 }
3466 });
3467 Ok(match out {
3468 Ok(()) => ExitCode::SUCCESS,
3469 Err(e) if htl::is_cancelled(&e) => {
3470 eprintln!("htl run: interrupted");
3471 ExitCode::from(130)
3472 }
3473 Err(e) => {
3474 eprintln!("{}", htl::developer_message(&e));
3475 ExitCode::FAILURE
3476 }
3477 })
3478}
3479
3480fn runs_fail(c: &htl::CheckInfo) -> bool {
3484 htl::verdict::verdict(
3485 &htl::verdict::Findings {
3486 errors: c.errors.len(),
3487 warnings: c.warnings.len(),
3488 lints: c.lints.len(),
3489 denied: 0,
3490 },
3491 &htl::verdict::Policy::ERRORS_ONLY,
3492 )
3493}
3494
3495struct BuildCache {
3500 use_cache: bool,
3501 explain: bool,
3502}
3503
3504fn cmd_build(
3505 entry: &Path,
3506 out: &Path,
3507 main: &str,
3508 mut opts: htl::link::LinkOptions,
3509 cache_flags: BuildCache,
3510) -> Result<ExitCode> {
3511 let h = Htl::new()?;
3512 auto_dts(entry)?;
3513 h.install_std()?;
3517 let cfg = load_config(entry)?;
3518 let lints = config_lints(&h, &cfg)?;
3521 config_lang(&h, &cfg)?;
3522 let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
3523 let model = apply_model(&h, &cfg, entry)?;
3524 if let Some(m) = &model {
3528 opts.host.extend(m.provided().map(|(n, _)| n.to_string()));
3529 }
3530 if let Some((_, _, cfg)) = &cfg {
3531 opts.extra.extend(cfg.build.extra.iter().cloned());
3532 opts.host.extend(cfg.build.host.iter().cloned());
3533 if let Some(t) = cfg.build.target.filter(|t| *t != BuildTarget::Hb) {
3539 eprintln!(
3540 "htl build: this project's target is `{}` — what runs its output is {} — and `htl build` writes a `.hb` bundle, which is the `hb` target. Build it with `cargo build`; to bundle its scripts anyway, drop `[build] target` from htl.toml.",
3541 t.name(),
3542 t.runs_it()
3543 );
3544 return Ok(ExitCode::FAILURE);
3545 }
3546 }
3547 if entry.is_dir() {
3548 if cache_flags.explain {
3549 eprintln!("htl cache: the directory form of `htl build` is not cached");
3550 }
3551 let skip = project::not_walked(
3554 model.as_ref(),
3555 &[entry.to_path_buf()],
3556 htl::model::Purpose::Check,
3557 );
3558 return cmd_build_dir(&h, entry, out, main, &opts, &skip, &cfg);
3559 }
3560 project::file_view(&h, model.as_ref(), entry)?;
3561 opts.entry_name = model.as_ref().and_then(|m| m.locate(entry).map(|p| p.name));
3564 let root = project::store_root(model.as_ref());
3570 let spec = cfg
3571 .as_ref()
3572 .map(|(_, _, c)| c.lint_spec())
3573 .unwrap_or_default();
3574 let lint = (!spec.is_empty()).then_some(spec.as_str());
3575 let cache_opts = project::cache_options(
3576 cache_flags.use_cache,
3577 Some(cache::Mode::PerModule),
3578 &cfg,
3579 cache_flags.explain,
3580 );
3581 let store = project::with_model(
3582 project::store(&root, cache_opts, None, "htl build"),
3583 model.as_ref(),
3584 );
3585 let link_store = store.as_ref().map(|c| htl::link::LinkStore {
3586 cache: c,
3587 lint,
3588 root: &root,
3589 config: cfg.as_ref().map(|(_, p, c)| (p.as_path(), c)),
3590 });
3591 let linked = htl::link::link_with(&h, entry, &opts, link_store)?;
3592 project::explain_cache(store.as_ref(), cache_opts);
3593 let mut sink = text_sink();
3596 sink.judge_by(lints.selection());
3597 for (p, c) in &linked.checks {
3598 sink.checkinfo(&linked.reported(p, c));
3599 }
3600 let n_err = linked.errors.len();
3601 let found = htl::verdict::Findings {
3602 errors: n_err,
3603 warnings: linked.checks.iter().map(|(_, c)| c.warnings.len()).sum(),
3604 lints: linked.lints.len(),
3605 denied: sink.denied(),
3606 };
3607 for d in &linked.link_errors {
3610 sink.diagnostic(d);
3611 }
3612 if htl::verdict::verdict(&found, &policy) {
3613 eprintln!(
3614 "htl build: {n_err} error(s){}, bundle not written",
3615 judged(&found, &policy)
3616 );
3617 return Ok(ExitCode::FAILURE);
3618 }
3619 let buf = linked.bundle()?.encode();
3620 fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
3621 let typed = linked.modules.iter().filter(|m| m.typed).count();
3622 let cached = if typed > 0 && linked.cached == typed {
3625 " [cached]".to_string()
3626 } else if linked.cached > 0 {
3627 format!(" [{}/{typed} cached]", linked.cached)
3628 } else {
3629 String::new()
3630 };
3631 eprintln!(
3632 "htl build: {} module(s) ({typed} typed, {} lua) -> {} ({} bytes{}{}){cached}",
3633 linked.modules.len(),
3634 linked.modules.len() - typed,
3635 out.display(),
3636 buf.len(),
3637 if opts.source {
3638 ", source"
3639 } else {
3640 ", bytecode"
3641 },
3642 if opts.debug { " with debug info" } else { "" }
3643 );
3644 if !linked.host_modules.is_empty() {
3645 eprintln!(
3646 "htl build: host must provide: {}",
3647 linked.host_modules.join(", ")
3648 );
3649 }
3650 Ok(ExitCode::SUCCESS)
3651}
3652
3653fn cmd_build_dir(
3655 h: &Htl,
3656 dir: &Path,
3657 out: &Path,
3658 entry: &str,
3659 opts: &htl::link::LinkOptions,
3660 skip: &[PathBuf],
3661 cfg: &project::Config,
3662) -> Result<ExitCode> {
3663 let lints = config_lints(h, cfg)?;
3665 config_lang(h, cfg)?;
3666 let policy = &htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
3667 h.add_path(dir)?;
3668 let files = htl::collect_tl_skipping(&[dir.to_path_buf()], skip)?;
3669 let mut b = Bundle {
3670 entry: entry.to_string(),
3671 htl_version: env!("CARGO_PKG_VERSION").into(),
3672 ..Default::default()
3673 };
3674 let mut found = htl::verdict::Findings::default();
3675 let mut sink = text_sink();
3676 sink.judge_by(lints.selection());
3677 for f in &files {
3678 let rel = f.strip_prefix(dir).unwrap_or(f);
3680 let name = htl::naming::name_of("", rel)
3681 .with_context(|| format!("cannot derive a module name for {}", f.display()))?;
3682 let (code, c) = h.gen_lua(f)?;
3683 sink.checkinfo(&c);
3684 found.errors += c.errors.len();
3685 found.warnings += c.warnings.len();
3686 found.lints += c.lints.len();
3687 let Some(code) = code else { continue };
3688 let (kind, payload) = if opts.source {
3689 (htl::bundle::Kind::Source, code.into_bytes())
3690 } else {
3691 (
3692 htl::bundle::Kind::Bytecode,
3693 h.compile_with(&name, &code, !opts.debug)?,
3694 )
3695 };
3696 b.modules.push(htl::bundle::Module {
3697 name,
3698 kind,
3699 payload,
3700 });
3701 }
3702 found.denied = sink.denied();
3703 if htl::verdict::verdict(&found, policy) {
3704 eprintln!(
3705 "htl build: {} error(s){}, bundle not written",
3706 found.errors,
3707 judged(&found, policy)
3708 );
3709 return Ok(ExitCode::FAILURE);
3710 }
3711 if b.module(entry).is_none() {
3712 bail!(
3713 "entry module '{entry}' not found among {} module(s)",
3714 b.modules.len()
3715 );
3716 }
3717 if !opts.source {
3718 b.fingerprint = h.fingerprint()?;
3719 }
3720 let buf = b.encode();
3721 fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
3722 eprintln!(
3723 "htl build: {} module(s) -> {} ({} bytes)",
3724 b.modules.len(),
3725 out.display(),
3726 buf.len()
3727 );
3728 Ok(ExitCode::SUCCESS)
3729}
3730
3731#[derive(serde::Serialize)]
3738struct BundleInfo {
3739 file: String,
3740 format: u8,
3741 htl_version: Option<String>,
3742 payload: &'static str,
3744 lua: Option<htl::bundle::LuaHeader>,
3745 entry: String,
3746 modules: Vec<BundleModuleInfo>,
3747 host_modules: Vec<String>,
3748}
3749
3750#[derive(serde::Serialize)]
3751struct BundleModuleInfo {
3752 name: String,
3753 kind: &'static str,
3754 bytes: usize,
3755}
3756
3757fn cmd_bundle_info(file: &Path, json: bool) -> Result<ExitCode> {
3758 let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
3759 let Some(format) = htl::bundle::format_version(&bytes) else {
3760 bail!("{} is not an htl bundle (bad magic)", file.display());
3761 };
3762 let b = Bundle::decode(&bytes)?;
3763 let kind_name = |k: htl::bundle::Kind| match k {
3764 htl::bundle::Kind::Bytecode => "bytecode",
3765 htl::bundle::Kind::Source => "source",
3766 };
3767 let payload = match (
3768 b.modules
3769 .iter()
3770 .any(|m| m.kind == htl::bundle::Kind::Bytecode),
3771 b.modules
3772 .iter()
3773 .any(|m| m.kind == htl::bundle::Kind::Source),
3774 ) {
3775 (true, true) => "mixed",
3776 (false, true) => "source",
3777 _ => "bytecode",
3779 };
3780 let info = BundleInfo {
3781 file: file.display().to_string(),
3782 format,
3783 htl_version: (!b.htl_version.is_empty()).then(|| b.htl_version.clone()),
3784 payload,
3785 lua: htl::bundle::LuaHeader::parse(&b.fingerprint),
3786 entry: b.entry.clone(),
3787 modules: b
3788 .modules
3789 .iter()
3790 .map(|m| BundleModuleInfo {
3791 name: m.name.clone(),
3792 kind: kind_name(m.kind),
3793 bytes: m.payload.len(),
3794 })
3795 .collect(),
3796 host_modules: b.host_modules.clone(),
3797 };
3798 if json {
3799 report::emit(&info)?;
3800 return Ok(ExitCode::SUCCESS);
3801 }
3802
3803 println!(
3804 "{}: htl bundle, format {}, built by {}",
3805 info.file,
3806 info.format,
3807 match &info.htl_version {
3808 Some(v) => format!("htl {v}"),
3809 None => "htl (version not recorded)".to_string(),
3810 }
3811 );
3812 println!(" payload: {}", info.payload);
3813 let lua = match &info.lua {
3814 Some(h) => h.to_string(),
3815 None if !b.fingerprint.is_empty() => {
3816 format!("unreadable fingerprint ({} bytes)", b.fingerprint.len())
3817 }
3818 None if info.format == 1 => {
3819 "not recorded (a format 1 bundle carries no fingerprint)".into()
3820 }
3821 None => "any (source payload, no bytecode to bind)".into(),
3822 };
3823 println!(" lua: {lua}");
3824 println!(" entry: {}", info.entry);
3825 let modules: Vec<String> = info
3826 .modules
3827 .iter()
3828 .map(|m| {
3829 if info.payload == "mixed" {
3830 format!("{} ({})", m.name, m.kind)
3831 } else {
3832 m.name.clone()
3833 }
3834 })
3835 .collect();
3836 println!(
3837 " modules: {}",
3838 if modules.is_empty() {
3839 "(none)".to_string()
3840 } else {
3841 modules.join(", ")
3842 }
3843 );
3844 println!(
3845 " host: {}",
3846 if info.host_modules.is_empty() {
3847 "(none)".to_string()
3848 } else {
3849 info.host_modules.join(", ")
3850 }
3851 );
3852 Ok(ExitCode::SUCCESS)
3853}