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
709fn register_libraries() {
727 static ONCE: std::sync::Once = std::sync::Once::new();
728 ONCE.call_once(|| {
729 htl::registry::register_installer("htl-std", htl_std::install, htl_std::PROVIDES)
730 .expect("\"htl-std\" registered twice");
731 });
732}
733
734pub fn run() -> ExitCode {
742 register_libraries();
743 let mut argv: Vec<String> = std::env::args().collect();
745 let is_cargo = Path::new(&argv[0])
746 .file_stem()
747 .and_then(|s| s.to_str())
748 .map(|s| s == "cargo-htl")
749 .unwrap_or(false);
750 if is_cargo && argv.get(1).map(String::as_str) == Some("htl") {
751 argv.remove(1);
752 }
753 match real_main(Cli::parse_from(argv)) {
754 Ok(code) => code,
755 Err(e) => {
756 eprintln!("htl: {e:#}");
757 ExitCode::from(2)
758 }
759 }
760}
761
762fn real_main(cli: Cli) -> Result<ExitCode> {
763 match cli.cmd {
764 Cmd::Check {
765 paths,
766 strict,
767 lint,
768 list_lints,
769 explain,
770 format,
771 no_cache,
772 cache_mode,
773 explain_cache,
774 statistics,
775 } => cmd_check(
776 &paths,
777 lint.as_deref(),
778 CheckFlags {
779 strict,
780 list_lints,
781 explain_rule: explain,
782 json: format == Format::Json,
783 use_cache: !no_cache,
784 cache_mode: cache_mode.map(Into::into),
785 explain: explain_cache,
786 statistics,
787 },
788 ),
789 Cmd::Fmt {
790 paths,
791 check,
792 indent,
793 } => cmd_fmt(&paths, check, indent),
794 Cmd::Test {
795 paths,
796 filter,
797 lib,
798 lint,
799 fail_fast,
800 allow_empty,
801 verbose,
802 quiet,
803 slow,
804 update,
805 coverage,
806 coverage_lines,
807 lcov,
808 junit,
809 seed,
810 format,
811 no_cache,
812 explain_cache,
813 } => cmd_test(
814 &paths,
815 filter.as_deref(),
816 &lib,
817 lint.as_deref(),
818 TestFlags {
819 fail_fast,
820 allow_empty,
821 verbose,
822 quiet,
823 slow,
824 update,
825 coverage: coverage || lcov.is_some(),
826 coverage_lines,
827 lcov,
828 junit,
829 json: format == Format::Json,
830 no_cache,
831 explain: explain_cache,
832 seed,
833 },
834 ),
835 Cmd::Pkg { cmd } => match cmd {
836 PkgCmd::Install => cmd_pkg_install(),
837 PkgCmd::Add {
838 name,
839 git,
840 tag,
841 rev,
842 branch,
843 entry,
844 target_dir,
845 } => cmd_pkg_add(htl::pkg::mlua_pkg::ops::AddSpec {
846 name,
847 git,
848 tag,
849 rev,
850 branch,
851 entry,
852 target_dir,
853 }),
854 PkgCmd::Update {
855 name,
856 dry_run,
857 force,
858 } => cmd_pkg_update(htl::pkg::mlua_pkg::ops::UpdateOpts {
859 name,
860 dry_run,
861 force,
862 }),
863 PkgCmd::Clean { all } => cmd_pkg_clean(all),
864 PkgCmd::Patch { dep, force } => cmd_pkg_patch(&dep, force),
865 },
866 Cmd::Types { cmd } => match cmd {
867 TypesCmd::Add {
868 library,
869 from,
870 force,
871 } => cmd_types_add(&library, from.as_deref(), force),
872 },
873 Cmd::Cache { cmd } => match cmd {
874 CacheCmd::Clear { path } => cmd_cache_clear(path.as_deref()),
875 CacheCmd::Status {
876 path,
877 format,
878 entries,
879 } => cmd_cache_status(path.as_deref(), format == Format::Json, entries),
880 },
881 Cmd::Dts { dir } => cmd_dts(dir.as_deref()),
882 Cmd::New {
883 name,
884 lib,
885 embed,
886 target,
887 htl,
888 no_x,
889 } => cmd_new(&name, lib, embed, target.as_deref(), htl.as_deref(), no_x),
890 Cmd::Init {
891 dir,
892 lib,
893 embed,
894 target,
895 htl,
896 no_x,
897 } => cmd_init(
898 dir.as_deref(),
899 lib,
900 embed,
901 target.as_deref(),
902 htl.as_deref(),
903 no_x,
904 ),
905 Cmd::Pin {
906 htl,
907 dir,
908 no_update,
909 } => pin::cmd_pin(&htl, dir, no_update),
910 Cmd::Gen { file, out } => cmd_gen(&file, out.as_deref()),
911 Cmd::Run { file, args } => cmd_run(&file, &args),
912 Cmd::Fix {
913 paths,
914 rule,
915 unsafe_fixes,
916 dry_run,
917 diff,
918 allow_dirty,
919 allow_no_vcs,
920 exit_non_zero_on_fix,
921 format,
922 } => cmd_fix(
923 &paths,
924 FixFlags {
925 rule,
926 unsafe_fixes,
927 dry_run: dry_run || diff,
928 diff,
929 allow_dirty,
930 allow_no_vcs,
931 exit_non_zero_on_fix,
932 json: format == Format::Json,
933 },
934 ),
935 Cmd::Build {
936 entry,
937 out,
938 main,
939 debug,
940 source,
941 extra,
942 host,
943 no_cache,
944 explain_cache,
945 } => cmd_build(
946 &entry,
947 &out,
948 &main,
949 htl::link::LinkOptions {
950 debug,
951 source,
952 extra,
953 host,
954 entry_name: None,
955 },
956 BuildCache {
957 use_cache: !no_cache,
958 explain: explain_cache,
959 },
960 ),
961 Cmd::Unused {
962 paths,
963 format,
964 exit_non_zero_on_unused,
965 no_cache,
966 explain_cache,
967 } => cmd_unused(
968 &paths,
969 UnusedFlags {
970 json: format == Format::Json,
971 fail_on_unused: exit_non_zero_on_unused,
972 use_cache: !no_cache,
973 explain: explain_cache,
974 },
975 ),
976 Cmd::Adopt {
977 paths,
978 format,
979 detail,
980 no_cache,
981 explain_cache,
982 } => cmd_adopt(
983 &paths,
984 AdoptFlags {
985 json: format == Format::Json,
986 detail,
987 use_cache: !no_cache,
988 explain: explain_cache,
989 },
990 ),
991 Cmd::Resolve {
992 module,
993 path,
994 format,
995 } => cmd_resolve(&module, path.as_deref(), format == Format::Json),
996 Cmd::Bundle { cmd } => match cmd {
997 BundleCmd::Info { file, format } => cmd_bundle_info(&file, format == Format::Json),
998 },
999 }
1000}
1001
1002fn text_sink() -> project::Sink<report::Out> {
1013 project::Sink::new(report::Out::new(false, false))
1014}
1015
1016fn judged(found: &htl::verdict::Findings, policy: &htl::verdict::Policy) -> String {
1020 let mut out = String::new();
1021 if policy.capped {
1022 return out;
1023 }
1024 if found.denied > 0 {
1025 out.push_str(&format!(", {} at deny", found.denied));
1026 }
1027 if policy.strict && found.warnings + found.lints > 0 {
1028 out.push_str(&format!(
1029 ", {} warning(s) and {} lint(s) under strict",
1030 found.warnings, found.lints
1031 ));
1032 }
1033 out
1034}
1035
1036fn config_lang(h: &Htl, cfg: &project::Config) -> Result<()> {
1042 h.set_lang(&project::lang_of(cfg))
1043}
1044
1045fn config_lints(h: &Htl, cfg: &project::Config) -> Result<htl::lint::Lints> {
1046 let spec = cfg
1047 .as_ref()
1048 .map(|(_, _, c)| c.lint_spec())
1049 .unwrap_or_default();
1050 let lints = htl::lint::Lints::parse(&spec)?;
1051 h.select_lints(lints.selection())?;
1052 Ok(lints)
1053}
1054
1055fn auto_dts(start: &Path) -> Result<()> {
1066 auto_dts_to(start, true)
1067}
1068
1069fn auto_dts_to(start: &Path, write: bool) -> Result<()> {
1073 let mut project = None;
1074 if let Some((root, _, cfg)) = load_config(start)? {
1075 let model = htl::model::Project::load(&root, cfg)?;
1077 let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
1078 let (results, problems) = htl::contract::publish_to(&root, &contracts, write);
1079 announce_dts_to(&results, &root, write);
1080 for p in &problems {
1081 eprintln!("dts: {p}");
1082 }
1083 project = Some(root);
1084 }
1085 let Some(root) = htl::dts::find_cargo_package_root(start) else {
1086 return Ok(());
1087 };
1088 let results =
1089 htl::dts::generate_crate_to(&root, write).map_err(|e| anyhow::anyhow!("htl dts: {e}"))?;
1090 announce_dts_to(&results, &root, write);
1091 let types_root = project.unwrap_or_else(|| root.clone());
1092 let report = dep_dts_to(&root, &types_root, write);
1093 announce_dts_to(&report.written, &types_root, write);
1094 announce_dep_report(&report, "dts: ");
1095 Ok(())
1096}
1097
1098#[derive(Default)]
1105struct DepReport {
1106 written: Vec<(PathBuf, bool)>,
1108 not_written: Vec<String>,
1110 left_in_place: Vec<String>,
1113 unresolved: Option<String>,
1118}
1119
1120fn dep_dts(cargo_root: &Path, types_root: &Path) -> DepReport {
1127 dep_dts_to(cargo_root, types_root, true)
1128}
1129
1130fn dep_dts_to(cargo_root: &Path, types_root: &Path, write: bool) -> DepReport {
1132 let decls = match htl::dep_dts::resolve(cargo_root) {
1133 Ok(d) => d,
1134 Err(e) => {
1135 return DepReport {
1136 unresolved: Some(e),
1137 ..DepReport::default()
1138 };
1139 }
1140 };
1141 let types = match decl_root(types_root) {
1144 Ok(t) => t,
1145 Err(e) => {
1146 return DepReport {
1147 unresolved: Some(format!("{e:#}")),
1148 ..DepReport::default()
1149 };
1150 }
1151 };
1152 let left_in_place = htl::dep_dts::orphans(&types, &decls);
1153 let (written, not_written) = htl::dep_dts::materialise_to(&types, &decls, write);
1154 DepReport {
1155 written,
1156 not_written,
1157 left_in_place,
1158 unresolved: None,
1159 }
1160}
1161
1162fn announce_dep_report(report: &DepReport, prefix: &str) {
1167 for p in &report.not_written {
1168 eprintln!("{prefix}not written: {p}");
1169 }
1170 for p in &report.left_in_place {
1171 eprintln!("{prefix}left in place: {p}");
1172 }
1173 if let Some(e) = &report.unresolved {
1174 eprintln!("{prefix}{e}");
1175 }
1176}
1177
1178fn announce_dts_to(results: &[(PathBuf, bool)], root: &Path, wrote: bool) {
1181 for (target, changed) in results {
1182 if *changed {
1183 let target = target.strip_prefix(root).unwrap_or(target).display();
1184 if wrote {
1185 eprintln!("dts: wrote {target}");
1186 } else {
1187 eprintln!(
1188 "dts: would write {target} (dry run: not written; checked against the \
1189 file on disk)"
1190 );
1191 }
1192 }
1193 }
1194}
1195
1196fn cmd_dts(dir: Option<&Path>) -> Result<ExitCode> {
1197 let start = match dir {
1198 Some(d) => d.to_path_buf(),
1199 None => std::env::current_dir()?,
1200 };
1201 let mut results = Vec::new();
1204 let mut failed = false;
1205 let mut project = None;
1206 if let Some((croot, _, cfg)) = load_config(&start)? {
1207 let model = htl::model::Project::load(&croot, cfg)?;
1208 let contracts: Vec<_> = model.contracts.iter().map(|c| c.terms.clone()).collect();
1209 let (published, problems) = htl::contract::publish(&croot, &contracts);
1210 for p in &problems {
1211 eprintln!(" {p}");
1212 }
1213 failed = !problems.is_empty();
1216 results.extend(published);
1217 project = Some(croot);
1218 }
1219 let code = |failed: bool| {
1220 if failed {
1221 ExitCode::FAILURE
1222 } else {
1223 ExitCode::SUCCESS
1224 }
1225 };
1226 let Some(root) = htl::dts::find_cargo_package_root(&start) else {
1227 if results.is_empty() && !failed {
1228 bail!(
1229 "no Cargo.toml with a [package] section, and no ---@contract type to publish, \
1230 at or above {}",
1231 start.display()
1232 );
1233 }
1234 report_dts(&results, &start);
1235 return Ok(code(failed));
1236 };
1237 results.extend(htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("{e}"))?);
1238 let types_root = project.unwrap_or_else(|| root.clone());
1239 let report = dep_dts(&root, &types_root);
1240 announce_dep_report(&report, " ");
1241 failed = failed || !report.not_written.is_empty();
1244 results.extend(report.written);
1245 report_dts(&results, &root);
1246 Ok(code(failed))
1247}
1248
1249fn report_dts(results: &[(PathBuf, bool)], root: &Path) {
1250 let mut written = 0usize;
1251 for (target, w) in results {
1252 let rel = target.strip_prefix(root).unwrap_or(target).display();
1253 eprintln!(" {} {}", if *w { "wrote " } else { "unchanged" }, rel);
1254 written += usize::from(*w);
1255 }
1256 eprintln!(
1257 "htl dts: {} declaration(s) from {}, {} written",
1258 results.len(),
1259 root.display(),
1260 written
1261 );
1262}
1263
1264fn apply_model(
1271 h: &Htl,
1272 cfg: &project::Config,
1273 start: &Path,
1274) -> Result<Option<htl::model::Project>> {
1275 let model = project::model_of(cfg, start)?;
1276 if let Some(m) = &model {
1277 h.apply_model(m, htl::model::View::Source)?;
1278 }
1279 Ok(model)
1280}
1281
1282fn report_scaffold(dir: &Path, written: &[PathBuf], kept: &[PathBuf]) {
1286 let rel = |p: &PathBuf| p.strip_prefix(dir).unwrap_or(p).display().to_string();
1287 for p in written {
1288 eprintln!(" created {}", rel(p));
1289 }
1290 for p in kept {
1291 eprintln!(" kept {} (already there)", rel(p));
1292 }
1293 if kept.is_empty() {
1294 eprintln!(
1295 "htl: {} file(s) written under {}",
1296 written.len(),
1297 dir.display()
1298 );
1299 } else {
1300 eprintln!(
1301 "htl: {} file(s) written, {} kept under {}",
1302 written.len(),
1303 kept.len(),
1304 dir.display()
1305 );
1306 }
1307}
1308
1309fn cmd_new(
1310 name: &str,
1311 lib: bool,
1312 embed: bool,
1313 target: Option<&str>,
1314 htl: Option<&str>,
1315 no_x: bool,
1316) -> Result<ExitCode> {
1317 let dir = PathBuf::from(name);
1318 let pkg_name = dir
1319 .file_name()
1320 .and_then(|s| s.to_str())
1321 .ok_or_else(|| anyhow::anyhow!("invalid project name: {name}"))?
1322 .to_string();
1323 let target = scaffold::resolve_target(target, embed, lib)?;
1327 let htl = scaffold::HtlPin::parse(htl)?;
1328 let opts = scaffold::Options {
1329 lib,
1330 target,
1331 htl,
1332 no_x,
1333 };
1334 let done = scaffold::scaffold(&dir, &pkg_name, &opts, true)?;
1335 report_scaffold(&dir, &done.written, &[]);
1336 let fetch = if opts.writes_htlx() {
1339 "htl pkg install && "
1340 } else {
1341 ""
1342 };
1343 let then = match opts.target.map(|t| t.target) {
1349 Some(BuildTarget::Window) => "htl check . && cargo run",
1350 _ => "htl test",
1351 };
1352 eprintln!("next: cd {} && {fetch}{then}", dir.display());
1353 Ok(ExitCode::SUCCESS)
1354}
1355
1356fn cmd_init(
1357 dir: Option<&Path>,
1358 lib: bool,
1359 embed: bool,
1360 target: Option<&str>,
1361 htl: Option<&str>,
1362 no_x: bool,
1363) -> Result<ExitCode> {
1364 let dir = match dir {
1365 Some(d) => d.to_path_buf(),
1366 None => std::env::current_dir()?,
1367 };
1368 let abs = std::fs::canonicalize(&dir).unwrap_or(dir.clone());
1369 let name = abs
1370 .file_name()
1371 .and_then(|s| s.to_str())
1372 .ok_or_else(|| anyhow::anyhow!("cannot derive a project name from {}", abs.display()))?
1373 .to_string();
1374 let asked_for_a_target = target.is_some() || embed;
1375 let target = scaffold::resolve_target(target, embed, lib)?;
1376 let htl = scaffold::HtlPin::parse(htl)?;
1377 let opts = scaffold::Options {
1378 lib,
1379 target,
1380 htl,
1381 no_x,
1382 };
1383 let done = scaffold::scaffold(&dir, &name, &opts, false)?;
1384 let kept: &[PathBuf] = if asked_for_a_target { &done.kept } else { &[] };
1387 if done.written.is_empty() && kept.is_empty() {
1388 eprintln!("htl init: nothing to do, all scaffold files already exist");
1389 } else {
1390 report_scaffold(&dir, &done.written, kept);
1391 }
1392 Ok(ExitCode::SUCCESS)
1393}
1394
1395fn pkg_project() -> Result<htl::pkg::MluaProject> {
1401 let cwd = std::env::current_dir()?;
1402 let root = htl::model::Project::find_root(&cwd)?.map(|r| r.root);
1403 root.filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
1404 .map(|r| htl::pkg::MluaProject::at(&r))
1405 .with_context(|| {
1406 format!(
1407 "no {} above {}: `htl pkg` runs in a project",
1408 htl::pkg::MANIFEST_NAME,
1409 cwd.display()
1410 )
1411 })
1412}
1413
1414fn decl_root(root: &Path) -> Result<PathBuf> {
1418 let cfg = load_config(root)?;
1419 Ok(project::model_of(&cfg, root)?
1420 .and_then(|m| m.own().roots.decl.clone())
1421 .unwrap_or_else(|| root.join("types")))
1422}
1423
1424fn cmd_pkg_install() -> Result<ExitCode> {
1426 let project = pkg_project()?;
1427 let report = project.install()?;
1428 report_install(&report, &project);
1429 let project = htl::pkg::MluaProject::at(&project.root);
1433 report_types_sync(
1434 &project.sync_types(&decl_root(&project.root)?)?,
1435 &project.root,
1436 );
1437 report_patch_drift(&project);
1438 Ok(ExitCode::SUCCESS)
1439}
1440
1441fn report_install(
1443 report: &htl::pkg::mlua_pkg::ops::InstallReport,
1444 project: &htl::pkg::MluaProject,
1445) {
1446 use htl::pkg::mlua_pkg::ops::Placement;
1447 for w in &report.warnings {
1448 if w.contains("patch_dir") && w.contains("not used") {
1452 continue;
1453 }
1454 eprintln!("warning: {w}");
1455 }
1456 let rel = |p: &Path| {
1457 p.strip_prefix(&project.root)
1458 .unwrap_or(p)
1459 .display()
1460 .to_string()
1461 };
1462 for p in &report.packages {
1463 let sha: String = p.sha.chars().take(7).collect();
1464 let where_it_is = match (&p.placement, p.patched) {
1465 (_, true) => format!("from {}", rel(p.root())),
1466 (Placement::Copied(dest), _) => format!("copied to {}", rel(dest)),
1467 (Placement::Symlink(_), _) => p.entry.display().to_string(),
1468 };
1469 eprintln!(" install {} {sha} ({where_it_is})", p.name);
1470 }
1471 let n = report.packages.len();
1472 if report.transitive > 0 {
1473 eprintln!(
1474 "htl pkg install: {n} package(s), {} of them transitive",
1475 report.transitive
1476 );
1477 } else {
1478 eprintln!("htl pkg install: {n} package(s)");
1479 }
1480}
1481
1482fn cmd_pkg_add(spec: htl::pkg::mlua_pkg::ops::AddSpec) -> Result<ExitCode> {
1490 use htl::pkg::mlua_pkg::ops::AddOutcome;
1491 let cwd = std::env::current_dir()?;
1492 let root = htl::model::Project::find_root(&cwd)?
1493 .map(|r| r.root)
1494 .unwrap_or(cwd);
1495 let project = htl::pkg::MluaProject::at(&root);
1496 let name = spec.name.clone();
1497 let done = project.add(spec)?;
1498 let manifest = project
1499 .manifest
1500 .strip_prefix(&project.root)
1501 .unwrap_or(&project.manifest)
1502 .display();
1503 if done.report.manifest_created {
1504 eprintln!(" created {manifest}");
1505 }
1506 let verb = match done.report.outcome {
1507 AddOutcome::Added => "added",
1508 AddOutcome::Replaced => "updated",
1509 };
1510 eprintln!(" {verb} {name} in {manifest}");
1511 if let Some(dir) = &done.kept_patch_dir {
1512 eprintln!(
1516 " kept patch_dir = {} ({name} is patched)",
1517 dir.display()
1518 );
1519 }
1520 eprintln!("htl pkg add: run `htl pkg install` to fetch it");
1521 Ok(ExitCode::SUCCESS)
1522}
1523
1524fn cmd_pkg_update(opts: htl::pkg::mlua_pkg::ops::UpdateOpts) -> Result<ExitCode> {
1526 use htl::pkg::mlua_pkg::ops::UpdateOutcome;
1527 let project = pkg_project()?;
1528 let dry_run = opts.dry_run;
1529 let report = project.update(opts)?;
1530 if report.entries.is_empty() {
1531 eprintln!("htl pkg update: no dependency selected");
1532 return Ok(ExitCode::SUCCESS);
1533 }
1534 for (name, outcome) in &report.entries {
1535 match outcome {
1536 UpdateOutcome::TagBumped { old, new } => {
1537 eprintln!(" update {name}: tag {old} -> {new}")
1538 }
1539 UpdateOutcome::PrefixResolved { pin, resolved } => eprintln!(
1540 " update {name}: prefix '{pin}' is {resolved} (the manifest keeps the prefix)"
1541 ),
1542 UpdateOutcome::Refresh => eprintln!(" update {name}: refresh (branch or unpinned)"),
1543 UpdateOutcome::Skipped(why) => eprintln!(" skip {name}: {why}"),
1544 }
1545 }
1546 if dry_run {
1547 eprintln!("htl pkg update: dry run; nothing was written");
1548 return Ok(ExitCode::SUCCESS);
1549 }
1550 if let Some(install) = &report.install {
1551 report_install(install, &project);
1552 let project = htl::pkg::MluaProject::at(&project.root);
1553 report_types_sync(
1554 &project.sync_types(&decl_root(&project.root)?)?,
1555 &project.root,
1556 );
1557 report_patch_drift(&project);
1558 }
1559 Ok(ExitCode::SUCCESS)
1560}
1561
1562fn cmd_pkg_clean(all: bool) -> Result<ExitCode> {
1564 use htl::pkg::mlua_pkg::ops::CleanReport;
1565 let project = pkg_project()?;
1566 match project.clean(all)? {
1567 CleanReport::CacheRemoved => eprintln!("htl pkg clean: removed every cached package"),
1568 CleanReport::NoLockfile => {
1569 eprintln!("htl pkg clean: no lockfile, so nothing was ever cached")
1570 }
1571 CleanReport::StaleRemoved { removed: 0 } => eprintln!("htl pkg clean: nothing to remove"),
1572 CleanReport::StaleRemoved { removed } => eprintln!(
1573 "htl pkg clean: removed {removed} cache entr{} the lockfile no longer refers to",
1574 if removed == 1 { "y" } else { "ies" }
1575 ),
1576 }
1577 Ok(ExitCode::SUCCESS)
1578}
1579
1580fn report_patch_drift(project: &htl::pkg::MluaProject) {
1589 let short = |s: &str| s.chars().take(7).collect::<String>();
1590 for s in project.patch_status() {
1591 if s.in_use {
1592 continue;
1593 }
1594 let rel = s
1595 .dir
1596 .strip_prefix(&project.root)
1597 .unwrap_or(&s.dir)
1598 .display();
1599 let why = match (&s.base, &s.locked) {
1600 _ if !s.dir.is_dir() => "the copy is not there".to_string(),
1601 (None, _) => "the lockfile records no revision it was taken from".to_string(),
1602 (Some(b), Some(l)) => {
1603 format!("taken from {}, {} is now at {}", short(b), s.name, short(l))
1604 }
1605 (Some(b), None) => format!("taken from {}, and nothing is locked", short(b)),
1606 };
1607 eprintln!(" patch {rel} is not in use ({why})");
1608 eprintln!(
1609 " carry the change forward: commit it, then `htl pkg patch {}`",
1610 s.name
1611 );
1612 eprintln!(" drop it: remove patch_dir from mlua-pkg.toml and delete {rel}");
1613 }
1614}
1615
1616fn cmd_pkg_patch(dep: &str, force: bool) -> Result<ExitCode> {
1621 let project = pkg_project().context("a patch belongs to a project, so this runs in one")?;
1622 let done = project.patch(dep, force)?;
1623 let report = &done.report;
1624 let rel = report
1625 .patch_dir
1626 .strip_prefix(&project.root)
1627 .unwrap_or(&report.patch_dir);
1628 let verb = if report.created { "patched" } else { "rebuilt" };
1629 let base: String = report.base.chars().take(7).collect();
1630 eprintln!(" {verb} {} ({dep} at {base})", rel.display());
1631 if !done.dropped.is_empty() {
1635 eprintln!(
1636 " dropped {} (the repository's, not the package's)",
1637 done.dropped.join(", ")
1638 );
1639 }
1640 eprintln!("htl: it is the project's code now — edit it, commit it, then `htl pkg install`.");
1641 Ok(ExitCode::SUCCESS)
1642}
1643
1644fn report_types_sync(sync: &htl::pkg::TypesSync, root: &Path) {
1648 let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).display().to_string();
1649 for (path, dep) in &sync.written {
1650 eprintln!(" types {} (from {dep})", rel(path));
1651 }
1652 for (path, dep) in &sync.taken {
1653 eprintln!(" kept {} ({dep} publishes one too)", rel(path));
1654 }
1655}
1656
1657fn cmd_types_add(library: &str, from: Option<&Path>, force: bool) -> Result<ExitCode> {
1661 let project = pkg_project().context("`types/` is a project's, so this runs in one")?;
1662 let types = decl_root(&project.root)?;
1663 let sync = match from {
1664 Some(dir) => project.add_types_from(dir, library, "local", force, &types)?,
1665 None => project.add_types(library, force, &types)?,
1666 };
1667 report_types_sync(&sync, &project.root);
1668 if sync.written.is_empty() && !sync.taken.is_empty() {
1669 eprintln!("htl: nothing written; --force replaces what is already there");
1670 }
1671 Ok(ExitCode::SUCCESS)
1672}
1673
1674struct UnusedFlags {
1676 json: bool,
1677 fail_on_unused: bool,
1680 use_cache: bool,
1681 explain: bool,
1682}
1683
1684struct AdoptFlags {
1686 json: bool,
1687 detail: bool,
1690 use_cache: bool,
1691 explain: bool,
1692}
1693
1694struct CheckFlags {
1696 strict: bool,
1697 list_lints: bool,
1698 explain_rule: Option<String>,
1700 json: bool,
1701 use_cache: bool,
1702 cache_mode: Option<cache::Mode>,
1703 explain: bool,
1704 statistics: bool,
1706}
1707
1708struct TestFlags {
1709 fail_fast: bool,
1710 allow_empty: bool,
1712 verbose: bool,
1713 quiet: bool,
1714 slow: Option<f64>,
1715 update: bool,
1716 coverage: bool,
1717 coverage_lines: bool,
1718 lcov: Option<PathBuf>,
1720 junit: Option<PathBuf>,
1722 json: bool,
1723 no_cache: bool,
1724 explain: bool,
1725 seed: Option<u64>,
1726}
1727
1728fn print_coverage(cov: &report::CoverageReport, with_lines: bool) {
1729 let width = cov
1730 .modules
1731 .iter()
1732 .map(|m| m.path.len())
1733 .max()
1734 .unwrap_or(4)
1735 .max(5);
1736 for m in &cov.modules {
1737 eprintln!(
1738 "coverage: {:<width$} {:>5}/{:<5} {:5.1}%",
1739 m.path,
1740 m.executed,
1741 m.total,
1742 100.0 * m.executed as f64 / m.total as f64
1743 );
1744 if !m.never_ran.is_empty() {
1745 let names: Vec<String> = m
1746 .never_ran
1747 .iter()
1748 .map(|f| format!("{} ({})", f.name, f.line))
1749 .collect();
1750 eprintln!(" never ran: {}", names.join(", "));
1751 }
1752 if with_lines && !m.unexecuted.is_empty() {
1753 let spans: Vec<String> = m
1754 .unexecuted
1755 .iter()
1756 .map(|(a, b)| {
1757 if a == b {
1758 a.to_string()
1759 } else {
1760 format!("{a}-{b}")
1761 }
1762 })
1763 .collect();
1764 eprintln!(" unexecuted: {}", spans.join(", "));
1765 }
1766 }
1767 if cov.total > 0 {
1768 eprintln!(
1769 "coverage: {:<width$} {:>5}/{:<5} {:5.1}% (statements)",
1770 "total",
1771 cov.executed,
1772 cov.total,
1773 100.0 * cov.executed as f64 / cov.total as f64
1774 );
1775 } else {
1776 eprintln!("coverage: no .tl module reached");
1777 }
1778}
1779
1780fn junit_suite(rep: &htl::testing::FileReport) -> junit::Suite {
1788 let mut left: Vec<&str> = rep.failures.iter().map(String::as_str).collect();
1789 let cases = rep
1790 .tests
1791 .iter()
1792 .map(|t| {
1793 let failure = (!t.ok)
1794 .then(|| {
1795 let head = format!("{}: ", t.name);
1796 let at = left.iter().position(|m| m.starts_with(&head))?;
1797 Some(left.remove(at)[head.len()..].to_string())
1798 })
1799 .flatten();
1800 junit::Case {
1801 name: t.name.clone(),
1802 ms: t.ms,
1803 failure: failure.or_else(|| (!t.ok).then(|| "failed".to_string())),
1806 }
1807 })
1808 .collect();
1809 let error = if !rep.check.ok() {
1810 Some(junit::Error {
1811 message: "type check failed".to_string(),
1812 kind: "check",
1813 body: rep
1814 .check
1815 .error_items
1816 .iter()
1817 .map(|d| d.clone().spelled().to_string())
1818 .collect::<Vec<_>>()
1819 .join("\n"),
1820 })
1821 } else {
1822 rep.error.as_ref().map(|e| junit::Error {
1823 message: e.clone(),
1824 kind: "error",
1825 body: e.clone(),
1826 })
1827 };
1828 junit::Suite {
1829 file: htl::diagnostic::display_path(&rep.path),
1830 duration_ms: rep.duration_ms,
1831 error,
1832 cases,
1833 }
1834}
1835
1836fn cmd_test(
1837 paths: &[PathBuf],
1838 filter: Option<&str>,
1839 lib: &str,
1840 lint: Option<&str>,
1841 flags: TestFlags,
1842) -> Result<ExitCode> {
1843 let paths = if paths.is_empty() {
1844 vec![PathBuf::from(".")]
1845 } else {
1846 paths.to_vec()
1847 };
1848 if let Some(first) = paths.first() {
1849 auto_dts(first)?;
1850 }
1851 let cfg = load_config(&paths[0])?;
1855 let model = project::model_of(&cfg, &paths[0])?;
1856 let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Test);
1857 let files = htl::testing::discover_tests_for(&paths, &skip, lib)?;
1858 project::refuse_flat_root(model.as_ref(), &paths, &files)?;
1861 let empty = files.is_empty();
1865 if empty {
1866 eprintln!("htl test: no test files found (looked for .tl files that require(\"{lib}\"))");
1867 }
1868 let opts = project::TestOptions {
1869 config: &cfg,
1870 model: model.as_ref(),
1871 lint,
1872 lib,
1873 filter,
1874 run: htl::testing::RunOptions {
1875 fail_fast: flags.fail_fast,
1876 update_snapshots: flags.update,
1877 coverage: flags.coverage,
1878 seed: flags.seed,
1880 async_: Default::default(),
1882 lang: Default::default(),
1883 },
1884 cache: project::cache_options(
1885 !flags.no_cache,
1886 Some(cache::Mode::PerModule),
1887 &cfg,
1888 flags.explain,
1889 ),
1890 };
1891
1892 let mut sink = project::Sink::new(report::Out::new(flags.json, false));
1893 let mut json_files: Vec<report::TestFile> = Vec::new();
1894 let mut junit_suites: Vec<junit::Suite> = Vec::new();
1895 let rep = if empty {
1899 project::TestReport {
1902 files: Vec::new(),
1903 ran: 0,
1904 passed: 0,
1905 failed: 0,
1906 files_with_errors: 0,
1907 replayed: 0,
1908 seed: flags.seed.unwrap_or(0),
1909 duration_ms: 0.0,
1910 coverage: None,
1911 }
1912 } else {
1913 project::test(&mut sink, &files, &opts, &mut |rep, sink| {
1914 if flags.json {
1915 json_files.push(report::TestFile::from_report(rep, sink.out().take()));
1916 }
1917 if flags.junit.is_some() {
1918 junit_suites.push(junit_suite(rep));
1919 }
1920 let f = htl::diagnostic::display_path(&rep.path);
1922 let tag = if rep.ok() { "ok " } else { "FAIL" };
1923 let detail = if !rep.check.ok() {
1924 "type check failed".to_string()
1925 } else if let Some(e) = &rep.error {
1926 format!("error: {}", e.lines().next().unwrap_or_default())
1929 } else if rep.file_level {
1930 "ran to completion (no test library used)".to_string()
1931 } else {
1932 format!("{} passed, {} failed", rep.passed, rep.failed)
1933 };
1934 let show_file = !flags.json && (!flags.quiet || !rep.ok());
1937 if show_file {
1938 eprintln!("{tag} {f} ({detail}, {:.0} ms)", rep.duration_ms);
1939 if let Some(e) = &rep.error {
1940 for line in e.lines().skip(1) {
1941 eprintln!(" {line}");
1942 }
1943 }
1944 }
1945 for tr in &rep.tests {
1946 let slow = flags.slow.is_some_and(|ms| tr.ms >= ms);
1947 if !flags.json && (flags.verbose || slow) {
1948 if flags.quiet && !show_file {
1949 eprintln!("slow {f} {} ({:.1} ms)", tr.name, tr.ms);
1951 continue;
1952 }
1953 let mark = if tr.ok { "ok " } else { "FAIL" };
1954 let note = if slow && !flags.verbose {
1955 " [slow]"
1956 } else {
1957 ""
1958 };
1959 eprintln!(" {mark} {} ({:.1} ms){note}", tr.name, tr.ms);
1960 }
1961 }
1962 if !flags.json {
1963 for m in &rep.failures {
1964 eprintln!(" - {m}");
1965 }
1966 for p in &rep.snapshots_written {
1968 eprintln!(
1969 "snapshot written: {}",
1970 htl::diagnostic::display_path(Path::new(p))
1971 );
1972 }
1973 for p in &rep.snapshots_updated {
1974 eprintln!(
1975 "snapshot updated: {}",
1976 htl::diagnostic::display_path(Path::new(p))
1977 );
1978 }
1979 }
1980 })?
1981 };
1982
1983 if let Some(out) = &flags.junit {
1984 std::fs::write(out, junit::document(&junit_suites, rep.duration_ms))
1987 .with_context(|| format!("writing {}", out.display()))?;
1988 }
1989 if let (Some(out), Some(cov)) = (&flags.lcov, &rep.coverage) {
1990 let root = match &cfg {
1993 Some((dir, _, _)) => dir.clone(),
1994 None => std::env::current_dir()?,
1995 };
1996 let root = std::fs::canonicalize(&root).unwrap_or(root);
1997 std::fs::write(out, cov.lcov(&root))
1998 .with_context(|| format!("writing {}", out.display()))?;
1999 }
2000 let ok = rep.ok() && (!empty || flags.allow_empty);
2003 if flags.json {
2004 let summary = report::TestSummary {
2005 files: rep.files.len(),
2006 files_run: rep.ran,
2007 passed: rep.passed,
2008 failed: rep.failed,
2009 files_with_errors: rep.files_with_errors,
2010 replayed: rep.replayed,
2011 duration_ms: rep.duration_ms,
2012 ok,
2013 seed: rep.seed,
2014 };
2015 report::emit(&report::TestReport {
2016 files: json_files,
2017 summary,
2018 coverage: rep.coverage,
2019 })?;
2020 } else if !empty || flags.allow_empty {
2021 if let Some(cov) = &rep.coverage {
2023 print_coverage(cov, flags.coverage_lines);
2024 if let Some(out) = &flags.lcov {
2025 eprintln!("coverage: lcov written to {}", out.display());
2026 }
2027 }
2028 eprintln!(
2029 "htl test: {} file(s), {} passed, {} failed, {} file(s) with errors{}{} ({:.0} ms)",
2030 rep.ran,
2031 rep.passed,
2032 rep.failed,
2033 rep.files_with_errors,
2034 if rep.skipped() > 0 {
2035 format!(", {} file(s) not run (--fail-fast)", rep.skipped())
2036 } else {
2037 String::new()
2038 },
2039 if rep.replayed > 0 {
2041 format!(", {} checked from cache", rep.replayed)
2042 } else {
2043 String::new()
2044 },
2045 rep.duration_ms
2046 );
2047 if !empty {
2051 eprintln!(
2052 "htl test: seed {} (repeat with --seed {})",
2053 rep.seed, rep.seed
2054 );
2055 }
2056 }
2057 Ok(if ok {
2058 ExitCode::SUCCESS
2059 } else {
2060 ExitCode::FAILURE
2061 })
2062}
2063
2064fn report_patched(paths: &[PathBuf]) {
2070 let roots: Vec<PathBuf> = paths
2071 .iter()
2072 .filter_map(|p| std::fs::canonicalize(p).ok())
2073 .collect();
2074 let cwd = std::env::current_dir().unwrap_or_default();
2075 let Some(project) = paths
2078 .first()
2079 .and_then(|p| htl::model::Project::find_root(p).ok().flatten())
2080 .map(|r| r.root)
2081 .filter(|r| r.join(htl::pkg::MANIFEST_NAME).is_file())
2082 .map(|r| htl::pkg::MluaProject::at(&r))
2083 else {
2084 return;
2085 };
2086 for p in &project.patches {
2087 let canon = std::fs::canonicalize(&p.dir).unwrap_or_else(|_| p.dir.clone());
2088 if !roots.iter().any(|r| canon.starts_with(r)) {
2089 continue;
2090 }
2091 let shown = p.dir.strip_prefix(&cwd).unwrap_or(&p.dir);
2092 eprintln!(" patched {} ({})", shown.display(), p.name);
2093 }
2094}
2095
2096fn load_config(first: &Path) -> Result<project::Config> {
2108 let cfg = project::config_of(first)?;
2109 if let Some((_, path, c)) = &cfg {
2110 htl::config::check_toolchain(c, path, env!("CARGO_PKG_VERSION"))?;
2111 }
2112 Ok(cfg)
2113}
2114
2115fn warn_cargo_htl_mismatch(first: &Path) {
2142 let Some(root) = htl::dts::find_cargo_package_root(first) else {
2143 return;
2144 };
2145 let Ok(text) = fs::read_to_string(root.join("Cargo.toml")) else {
2146 return;
2147 };
2148 let Ok(manifest) = text.parse::<toml::Table>() else {
2149 return;
2150 };
2151 let Some(dep) = manifest.get("dependencies").and_then(|d| d.get("htl")) else {
2152 return;
2153 };
2154 let req_text = match dep {
2155 toml::Value::String(s) => s.as_str(),
2156 toml::Value::Table(t) => match t.get("version").and_then(toml::Value::as_str) {
2157 Some(s) => s,
2158 None => return,
2159 },
2160 _ => return,
2161 };
2162 let running = env!("CARGO_PKG_VERSION");
2163 let (Ok(req), Ok(version)) = (
2164 semver::VersionReq::parse(req_text),
2165 semver::Version::parse(running),
2166 ) else {
2167 return;
2168 };
2169 if req.matches(&version) {
2170 return;
2171 }
2172 eprintln!(
2175 "htl {running}; Cargo.toml asks for htl {req_text} — the crate and the CLI are \
2176 meant to move together (cargo install htl-cli --version {req_text}, or bump the \
2177 dependency)"
2178 );
2179}
2180
2181fn cmd_fmt(paths: &[PathBuf], check: bool, indent: Option<usize>) -> Result<ExitCode> {
2182 let paths = if paths.is_empty() {
2183 vec![PathBuf::from(".")]
2184 } else {
2185 paths.to_vec()
2186 };
2187 let cfg = load_config(&paths[0])?;
2188 let indent = indent
2189 .or_else(|| cfg.as_ref().and_then(|(_, _, c)| c.fmt.indent))
2190 .unwrap_or(3);
2191 let h = Htl::new()?;
2192 config_lang(&h, &cfg)?;
2193 let model = project::model_of(&cfg, &paths[0])?;
2197 let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
2198 let files = htl::collect_tl_skipping(&paths, &skip)?;
2199 let (mut changed, mut failed) = (0usize, 0usize);
2200 for f in &files {
2201 let before = fs::read_to_string(f).with_context(|| format!("reading {}", f.display()))?;
2202 let after = match h.format_file(f, indent) {
2203 Ok(s) => s,
2204 Err(e) => {
2205 eprintln!("error: {e}");
2206 failed += 1;
2207 continue;
2208 }
2209 };
2210 if after != before {
2211 changed += 1;
2212 if check {
2213 eprintln!("would reformat: {}", f.display());
2214 } else {
2215 fs::write(f, after).with_context(|| format!("writing {}", f.display()))?;
2216 eprintln!("reformatted: {}", f.display());
2217 }
2218 }
2219 }
2220 eprintln!(
2221 "htl fmt: {} file(s), {} {}, {} failed",
2222 files.len(),
2223 changed,
2224 if check { "would change" } else { "reformatted" },
2225 failed
2226 );
2227 let fail = failed > 0 || (check && changed > 0);
2228 Ok(if fail {
2229 ExitCode::FAILURE
2230 } else {
2231 ExitCode::SUCCESS
2232 })
2233}
2234
2235struct FixFlags {
2236 rule: Vec<String>,
2237 unsafe_fixes: bool,
2238 dry_run: bool,
2239 diff: bool,
2240 allow_dirty: bool,
2241 allow_no_vcs: bool,
2242 exit_non_zero_on_fix: bool,
2243 json: bool,
2244}
2245
2246fn cmd_fix(paths: &[PathBuf], flags: FixFlags) -> Result<ExitCode> {
2247 use htl::fix::{FixOptions, fix_file, git_dirty, unified_diff};
2248 let paths = if paths.is_empty() {
2249 vec![PathBuf::from(".")]
2250 } else {
2251 paths.to_vec()
2252 };
2253 let cfg = load_config(&paths[0])?;
2254 auto_dts_to(&paths[0], !flags.dry_run)?;
2256 let model = project::model_of(&cfg, &paths[0])?;
2257 let scope = project::Scope::new(&cfg, model.as_ref(), &paths[0], None)?;
2260 let h = project::checker(
2261 model.as_ref(),
2262 scope.lints.selection(),
2263 &project::lang_of(&cfg),
2264 )?;
2265 let opts = FixOptions {
2266 unsafe_fixes: flags.unsafe_fixes,
2267 promoted: cfg
2268 .as_ref()
2269 .map(|(_, _, c)| c.fix.unsafe_.clone())
2270 .unwrap_or_default(),
2271 disabled: cfg
2272 .as_ref()
2273 .map(|(_, _, c)| c.fix.disable.clone())
2274 .unwrap_or_default(),
2275 only: flags.rule.clone(),
2276 dry_run: flags.dry_run,
2277 };
2278 opts.validate()?;
2281 let skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Own);
2285 let (files, outside) = project::held_by_modules(
2287 model.as_ref(),
2288 &paths,
2289 htl::collect_tl_skipping(&paths, &skip)?,
2290 )?;
2291 if let Some(note) = project::outside_modules_note(model.as_ref(), &outside, "fixed") {
2292 eprintln!("htl fix: {note}");
2293 }
2294 let check_skip = project::not_walked(model.as_ref(), &paths, htl::model::Purpose::Check);
2298 let checked_only: Vec<PathBuf> = project::held_by_modules(
2299 model.as_ref(),
2300 &paths,
2301 htl::collect_tl_skipping(&paths, &check_skip)?,
2302 )?
2303 .0
2304 .into_iter()
2305 .filter(|f| !files.contains(f))
2306 .collect();
2307
2308 if !flags.dry_run {
2310 let mut dirty = Vec::new();
2311 let mut no_vcs = Vec::new();
2312 for f in &files {
2313 match git_dirty(f)? {
2314 Some(true) => dirty.push(f.clone()),
2315 Some(false) => {}
2316 None => no_vcs.push(f.clone()),
2317 }
2318 }
2319 if !dirty.is_empty() && !flags.allow_dirty {
2320 bail!(
2321 "htl fix rewrites files in place and relies on git to undo it; these have uncommitted changes:\n {}\ncommit or stash them, or pass --allow-dirty",
2322 dirty
2323 .iter()
2324 .map(|p| p.display().to_string())
2325 .collect::<Vec<_>>()
2326 .join("\n ")
2327 );
2328 }
2329 if !no_vcs.is_empty() && !flags.allow_no_vcs {
2330 bail!(
2331 "htl fix rewrites files in place and relies on git to undo it; these are not in a git repository:\n {}\npass --allow-no-vcs to proceed without that safety net",
2332 no_vcs
2333 .iter()
2334 .map(|p| p.display().to_string())
2335 .collect::<Vec<_>>()
2336 .join("\n ")
2337 );
2338 }
2339 }
2340
2341 let mut sink = project::Sink::new(report::Out::new(flags.json, false));
2342 sink.judge_by(scope.lints.selection());
2344 let origins = project::Origins::new(model.as_ref());
2348 let walk = scope.walk(&cfg, model.as_ref(), &origins);
2349 let walked: Vec<PathBuf> = files.iter().chain(&checked_only).cloned().collect();
2350 sink.walking(&walked);
2351 let (mut applied, mut skipped, mut json_files) = (Vec::new(), Vec::new(), Vec::new());
2352 let (mut changed, mut deferred, mut reverted) = (0usize, 0usize, 0usize);
2353 let mut found = htl::verdict::Findings::default();
2354 let mut infos: Vec<(PathBuf, htl::CheckInfo)> = Vec::with_capacity(walked.len());
2355 for f in &files {
2356 let saved = h.search_path()?;
2359 project::file_view(&h, model.as_ref(), f)?;
2360 let before = if flags.diff {
2361 std::fs::read_to_string(f).ok()
2362 } else {
2363 None
2364 };
2365 let out = fix_file(&h, f, &opts)?;
2366 if out.contents.is_some() {
2367 changed += 1;
2368 }
2369 deferred += out.deferred;
2370 if out.reverted.is_some() {
2371 reverted += 1;
2372 }
2373 if !flags.json {
2374 for a in &out.applied {
2375 eprintln!(
2376 "fixed: {}:{}: {} ({}{})",
2377 project::display_path(f),
2378 a.line,
2379 a.rule,
2380 a.applicability.as_str(),
2381 if flags.dry_run { ", not written" } else { "" }
2382 );
2383 }
2384 for s in &out.skipped {
2385 eprintln!(
2386 "skipped: {}:{}: {} — {}",
2387 project::display_path(f),
2388 s.line,
2389 s.rule,
2390 s.reason
2391 );
2392 }
2393 if let Some(r) = &out.reverted {
2394 eprintln!("reverted: {}: {r}", project::display_path(f));
2395 }
2396 if let Some(o) = &out.oscillation {
2397 eprintln!(
2398 "stopped: {}: fixes of {o} undo each other",
2399 project::display_path(f)
2400 );
2401 }
2402 if out.deferred > 0 {
2403 eprintln!(
2404 "deferred: {}: {} edit(s) overlapped applied ones; run htl fix again",
2405 project::display_path(f),
2406 out.deferred
2407 );
2408 }
2409 if flags.diff
2410 && let (Some(b), Some(a)) = (&before, &out.contents)
2411 {
2412 print!("{}", unified_diff(&project::display_path(f), b, a));
2413 }
2414 if flags.diff
2417 && let (Some(b), Some(s)) = (
2418 out.contents.as_ref().or(before.as_ref()),
2419 out.suggested.as_ref(),
2420 )
2421 {
2422 print!(
2423 "{}",
2424 unified_diff(&format!("{} (suggested)", project::display_path(f)), b, s)
2425 );
2426 }
2427 }
2428 found.lints += project::file_findings(&h, &mut sink, f, &out.check, &walk)?;
2431 h.set_search_path(&saved)?;
2432 found.errors += out.check.errors.len();
2433 found.warnings += out.check.warnings.len();
2434 infos.push((f.clone(), out.check.clone()));
2435 if flags.json {
2436 applied.extend(out.applied.iter().map(|a| report::FixApplied {
2437 file: project::display_path(f),
2438 line: a.line,
2439 rule: a.rule.clone(),
2440 applicability: a.applicability.as_str(),
2441 pass: a.pass,
2442 }));
2443 skipped.extend(out.skipped.iter().map(|s| report::FixSkipped {
2444 file: project::display_path(f),
2445 line: s.line,
2446 rule: s.rule.clone(),
2447 reason: s.reason.clone(),
2448 }));
2449 json_files.push(report::FixFile {
2450 path: project::display_path(f),
2451 changed: out.contents.is_some(),
2452 deferred: out.deferred,
2453 reverted: out.reverted.clone(),
2454 oscillation: out.oscillation.clone(),
2455 diagnostics: sink.out().take(),
2456 });
2457 }
2458 }
2459 for f in &checked_only {
2461 let m = project::check_one(&h, &mut sink, f, &walk)?;
2462 found.errors += m.errors;
2463 found.warnings += m.warnings;
2464 found.lints += m.lints;
2465 infos.push((f.clone(), m.requires_only()));
2466 if flags.json {
2467 json_files.push(report::FixFile {
2468 path: project::display_path(f),
2469 changed: false,
2470 deferred: 0,
2471 reverted: None,
2472 oscillation: None,
2473 diagnostics: sink.out().take(),
2474 });
2475 }
2476 }
2477 let mut whole = scope.whole(&cfg, model.as_ref());
2480 whole.publish = !flags.dry_run;
2481 let w = project::project_findings(&mut sink, &whole, &infos);
2482 found.errors += w.errors;
2483 found.lints += w.lints;
2484 let project_diagnostics = if flags.json {
2485 sink.out().take()
2486 } else {
2487 Vec::new()
2488 };
2489 found.errors += sink.dependency_error_count();
2492 found.denied = sink.denied();
2493 let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
2495 let errors_remaining = found.errors;
2496 let n_applied = if flags.json { applied.len() } else { 0 };
2497 let fail =
2498 htl::verdict::verdict(&found, &policy) || (flags.exit_non_zero_on_fix && changed > 0);
2499 if flags.json {
2500 let n_skipped = skipped.len();
2501 report::emit(&report::FixReport {
2502 dry_run: flags.dry_run,
2503 applied,
2504 skipped,
2505 files: json_files,
2506 summary: report::FixSummary {
2507 files: files.len(),
2508 files_changed: changed,
2509 applied: n_applied,
2510 skipped: n_skipped,
2511 deferred,
2512 reverted,
2513 errors_remaining,
2514 warnings: found.warnings,
2515 lints: found.lints,
2516 denied: found.denied,
2517 strict: policy.strict,
2518 ok: !fail,
2519 },
2520 diagnostics: project_diagnostics,
2521 })?;
2522 } else {
2523 let judged = judged(&found, &policy);
2527 eprintln!(
2528 "htl fix: {} file(s){}, {} changed{}, {} error(s) remaining{}{}",
2529 files.len(),
2530 if checked_only.is_empty() {
2531 String::new()
2532 } else {
2533 format!(" + {} checked in patched dependencies", checked_only.len())
2534 },
2535 changed,
2536 if flags.dry_run {
2537 " (dry run, nothing written)"
2538 } else {
2539 ""
2540 },
2541 errors_remaining,
2542 judged,
2543 if deferred > 0 {
2544 format!(", {deferred} deferred")
2545 } else {
2546 String::new()
2547 }
2548 );
2549 }
2550 Ok(if fail {
2551 ExitCode::FAILURE
2552 } else {
2553 ExitCode::SUCCESS
2554 })
2555}
2556
2557fn cmd_check(paths: &[PathBuf], lint: Option<&str>, flags: CheckFlags) -> Result<ExitCode> {
2569 let CheckFlags {
2570 list_lints,
2571 json,
2572 use_cache,
2573 cache_mode,
2574 explain,
2575 statistics,
2576 ..
2577 } = flags;
2578 let mut sink = project::Sink::new(report::Out::new(json, statistics));
2579 let paths = if paths.is_empty() {
2580 vec![PathBuf::from(".")]
2581 } else {
2582 paths.to_vec()
2583 };
2584 if let Some(rule) = flags.explain_rule.as_deref() {
2593 let Some(r) = htl::lint::explained(rule) else {
2594 eprintln!("unknown lint rule: {rule}");
2595 return Ok(ExitCode::from(2));
2596 };
2597 println!("{} (default: {})\n\n{}", r.name, r.default, r.explain);
2598 return Ok(ExitCode::SUCCESS);
2599 }
2600 if list_lints {
2601 let width = htl::lint::rule_names()
2606 .iter()
2607 .map(|r| r.len())
2608 .max()
2609 .unwrap_or(0);
2610 for (name, level) in htl::lint::rule_defaults() {
2611 println!("{name:width$} {level}");
2612 }
2613 return Ok(ExitCode::SUCCESS);
2617 }
2618 let cfg = load_config(&paths[0])?;
2620 warn_cargo_htl_mismatch(&paths[0]);
2621 let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), flags.strict);
2622 if let Some(first) = paths.first() {
2626 auto_dts(first)?;
2627 }
2628 let walk_model = project::model_of(&cfg, &paths[0])?;
2633 if walk_model.is_none()
2638 && let Some(dir) = paths.iter().find(|p| p.is_dir())
2639 {
2640 bail!(
2641 "no {} or {} in {} or any directory above it: a directory is checked as a \
2642 project. Run `htl init` there to make it one, or name the .tl files to check \
2643 each on its own",
2644 htl::config::CONFIG_NAME,
2645 htl::pkg::MANIFEST_NAME,
2646 fs::canonicalize(dir)
2649 .unwrap_or_else(|_| dir.clone())
2650 .display()
2651 );
2652 }
2653 let skip = project::not_walked(walk_model.as_ref(), &paths, htl::model::Purpose::Check);
2654 let (files, outside) = project::held_by_modules(
2655 walk_model.as_ref(),
2656 &paths,
2657 htl::collect_tl_skipping(&paths, &skip)?,
2658 )?;
2659 if let Some(note) = project::outside_modules_note(walk_model.as_ref(), &outside, "checked") {
2660 eprintln!("htl check: {note}");
2661 }
2662 if !json {
2663 report_patched(&paths);
2664 }
2665
2666 let rep = project::check(
2670 &mut sink,
2671 &files,
2672 &project::Options {
2673 paths: &paths,
2674 config: &cfg,
2675 model: walk_model.as_ref(),
2676 lint,
2677 cache: project::cache_options(use_cache, cache_mode, &cfg, explain),
2678 },
2679 )?;
2680 let fail = report_check(
2681 sink.out(),
2682 json,
2683 statistics,
2684 &rep,
2685 &policy,
2686 patched_files(walk_model.as_ref(), &rep.files),
2687 )?;
2688 Ok(if fail {
2689 ExitCode::FAILURE
2690 } else {
2691 ExitCode::SUCCESS
2692 })
2693}
2694
2695fn cmd_unused(paths: &[PathBuf], flags: UnusedFlags) -> Result<ExitCode> {
2702 let UnusedFlags {
2703 json,
2704 fail_on_unused,
2705 use_cache,
2706 explain,
2707 } = flags;
2708 let paths = if paths.is_empty() {
2709 vec![PathBuf::from(".")]
2710 } else {
2711 paths.to_vec()
2712 };
2713 let cfg = load_config(&paths[0])?;
2714 auto_dts(&paths[0])?;
2717 let model = project::model_of(&cfg, &paths[0])?;
2718 let rep = htl::unused::unused(&htl::unused::Options {
2719 paths: &paths,
2720 config: &cfg,
2721 model: model.as_ref(),
2722 cache: project::cache_options(use_cache, None, &cfg, explain),
2723 })?;
2724 let s = &rep.summary;
2725 if json {
2726 report::emit(&rep)?;
2727 } else if s.no_entry {
2728 eprintln!(
2729 "htl unused: nothing to start from, so nothing is reported. An entry is \
2730 main.tl in the source root ([layout] source) or beside the manifest, a test file, a module under a [[contract]] directory, or a name \
2731 in [build] extra / host"
2732 );
2733 } else {
2734 if s.check_errors > 0 {
2735 eprintln!(
2736 "htl unused: {} error(s) in the check this graph comes from — what those \
2737 files require is missing from it (htl check)",
2738 s.check_errors
2739 );
2740 }
2741 for m in &rep.modules {
2742 match &m.module {
2743 Some(n) => eprintln!("module: {} ({n})", m.path),
2744 None => eprintln!("module: {}", m.path),
2745 }
2746 }
2747 for d in &rep.dependencies {
2748 eprintln!("dependency: {}", d.name);
2749 }
2750 eprintln!(
2751 "htl unused: {}, {} [{} considered, {} reached, {}]",
2752 count(s.modules, "module", "modules"),
2753 count(s.dependencies, "dependency", "dependencies"),
2754 s.considered,
2755 s.reached,
2756 count(s.entries, "entry", "entries"),
2757 );
2758 }
2759 Ok(if fail_on_unused && !s.ok {
2760 ExitCode::FAILURE
2761 } else {
2762 ExitCode::SUCCESS
2763 })
2764}
2765
2766fn cmd_adopt(paths: &[PathBuf], flags: AdoptFlags) -> Result<ExitCode> {
2773 let AdoptFlags {
2774 json,
2775 detail,
2776 use_cache,
2777 explain,
2778 } = flags;
2779 let paths = if paths.is_empty() {
2780 vec![PathBuf::from(".")]
2781 } else {
2782 paths.to_vec()
2783 };
2784 let cfg = load_config(&paths[0])?;
2785 auto_dts(&paths[0])?;
2788 let model = project::model_of(&cfg, &paths[0])?;
2789 let rep = htl::adopt::adopt(&htl::adopt::Options {
2790 paths: &paths,
2791 config: &cfg,
2792 model: model.as_ref(),
2793 cache: project::cache_options(use_cache, None, &cfg, explain),
2794 })?;
2795 if json {
2796 report::emit(&rep)?;
2797 } else {
2798 print_adopt(&rep, detail);
2799 }
2800 Ok(ExitCode::SUCCESS)
2803}
2804
2805fn adopt_marker_width() -> usize {
2808 htl::adopt::FEATURES
2809 .iter()
2810 .map(|m| format!("---@{m}").len())
2811 .max()
2812 .unwrap_or(0)
2813 + 2
2814}
2815
2816fn print_adopt(rep: &htl::adopt::Report, detail: bool) {
2819 let width = adopt_marker_width();
2820 eprintln!(
2821 "{:<width$} {:>4} {:>10}",
2822 "feature",
2823 "used",
2824 "applicable",
2825 width = width
2826 );
2827 for f in &rep.features {
2828 let applicable = match f.applicable {
2829 Some(n) => n.to_string(),
2830 None => "-".to_string(),
2831 };
2832 eprintln!(
2833 "{:<width$} {:>4} {:>10}",
2834 format!("---@{}", f.marker),
2835 f.used,
2836 applicable,
2837 width = width
2838 );
2839 }
2840 if detail {
2841 let line_width = rep
2845 .features
2846 .iter()
2847 .flat_map(|f| {
2848 f.sites
2849 .iter()
2850 .map(|s| format!("{}:{}", s.file.display(), s.line))
2851 .chain(
2852 f.candidates
2853 .iter()
2854 .map(|c| format!("{}:{}", c.file.display(), c.line)),
2855 )
2856 })
2857 .map(|s| s.len())
2858 .max()
2859 .unwrap_or(0);
2860 for f in &rep.features {
2861 for s in &f.sites {
2862 eprintln!(
2863 " {:<width$}{:<line_width$} {}",
2864 format!("---@{}", f.marker),
2865 format!("{}:{}", s.file.display(), s.line),
2866 s.name,
2867 width = width,
2868 line_width = line_width
2869 );
2870 }
2871 for c in &f.candidates {
2874 let sites = if c.sites == 1 {
2875 "1 site".to_string()
2876 } else {
2877 format!("{} sites", c.sites)
2878 };
2879 eprintln!(
2880 " {:<width$}{:<line_width$} {} (applicable: {}, {sites})",
2881 format!("---@{}", f.marker),
2882 format!("{}:{}", c.file.display(), c.line),
2883 c.name,
2884 c.reason,
2885 width = width,
2886 line_width = line_width
2887 );
2888 }
2889 }
2890 }
2891 let s = &rep.summary;
2892 if s.check_errors > 0 {
2893 eprintln!(
2894 "htl adopt: {} error(s) in the project's check (htl check says which); a file \
2895 with a syntax error contributes no markers",
2896 s.check_errors
2897 );
2898 }
2899 if s.markers == 0 {
2900 eprintln!(
2901 "htl adopt: {} of {} features used, no markers",
2902 s.used, s.features
2903 );
2904 } else {
2905 eprintln!(
2906 "htl adopt: {} of {} features used, {} in {}",
2907 s.used,
2908 s.features,
2909 count(s.markers, "marker", "markers"),
2910 count(s.files, "file", "files"),
2911 );
2912 }
2913}
2914
2915fn cmd_resolve(module: &str, path: Option<&Path>, json: bool) -> Result<ExitCode> {
2924 let start = path.unwrap_or(Path::new("."));
2925 let cfg = load_config(start)?;
2926 auto_dts(start)?;
2930 let h = Htl::new()?;
2931 h.install_std()?;
2934 h.install_registered()?;
2944 let model = apply_model(&h, &cfg, start)?;
2945 let rep = htl::resolve::resolve(
2946 &h,
2947 module,
2948 cfg.as_ref().map(|(r, _, _)| r.as_path()),
2949 model.as_ref(),
2950 )?;
2951 if json {
2952 report::emit(&rep)?;
2953 } else {
2954 print_resolution(&rep);
2955 }
2956 Ok(if rep.summary.ok {
2957 ExitCode::SUCCESS
2958 } else {
2959 ExitCode::FAILURE
2960 })
2961}
2962
2963fn print_resolution(r: &htl::resolve::Resolution) {
2967 let ambiguous = r
2968 .candidates
2969 .iter()
2970 .any(|c| c.status == htl::resolve::Status::Ambiguous);
2971 let typed_by = r
2975 .read
2976 .as_ref()
2977 .map(|d| format!(", typed by {d}"))
2978 .unwrap_or_default();
2979 match (&r.read, &r.error, &r.provided_by) {
2980 (_, Some(e), _) => println!("htl resolve {}: error: {e}", r.module),
2981 (Some(read), None, Some(by)) if r.provider == Some(htl::model::Provider::Declared) => {
2985 println!(
2986 "htl resolve {}: {read}, provided by the environment ({by})",
2987 r.module
2988 )
2989 }
2990 (_, None, Some(by)) => {
2991 println!(
2992 "htl resolve {}: provided by the host ({by}){typed_by}",
2993 r.module
2994 )
2995 }
2996 (Some(read), None, None) => println!("htl resolve {}: {read}", r.module),
2997 (None, None, None) if ambiguous => println!(
2998 "htl resolve {}: more than one module implements it, and no order picks one",
2999 r.module
3000 ),
3001 (None, None, None) => println!(
3002 "htl resolve {}: nothing in the project or on the search path answers require(\"{}\")",
3003 r.module, r.module
3004 ),
3005 }
3006 if !r.candidates.is_empty() {
3007 let w = |f: fn(&htl::resolve::Candidate) -> usize, head: usize| {
3008 r.candidates.iter().map(f).max().unwrap_or(0).max(head)
3009 };
3010 let file = w(|c| c.path.len(), 4);
3011 let kind = w(|c| c.kind.as_str().len(), 4);
3012 let read_at = r
3013 .candidates
3014 .iter()
3015 .find(|c| c.status == htl::resolve::Status::Read)
3016 .map(|c| c.order);
3017 println!();
3018 println!(" order {:file$} {:kind$} status", "file", "kind");
3019 for c in &r.candidates {
3020 let status = match (c.status, c.shadowed_by, read_at) {
3021 (htl::resolve::Status::Shadowed, Some(by), _) => format!("shadowed by {by}"),
3022 (htl::resolve::Status::Runtime, _, Some(by)) => format!("runtime, typed by {by}"),
3024 (s, _, _) => s.as_str().to_string(),
3025 };
3026 let origin = match &c.origin {
3027 Some(o) => format!(" ({})", o.describe()),
3028 None => String::new(),
3029 };
3030 println!(
3031 " {:<5} {:file$} {:kind$} {status}{origin}",
3032 c.order,
3033 c.path,
3034 c.kind.as_str()
3035 );
3036 }
3037 }
3038 println!();
3039 match r.answered_by {
3040 htl::resolve::AnsweredBy::Model => println!(" answered by the project model"),
3041 htl::resolve::AnsweredBy::Path => {
3044 println!(" searched, in order: {}", r.searched.join(", "))
3045 }
3046 }
3047}
3048
3049fn count(n: usize, one: &str, many: &str) -> String {
3052 format!("{n} {}", if n == 1 { one } else { many })
3053}
3054
3055fn cmd_cache_clear(path: Option<&Path>) -> Result<ExitCode> {
3065 let root = cache_root(path)?;
3066 let dir = root.join(".htl").join("cache");
3067 if !dir.is_dir() {
3068 eprintln!("htl cache: nothing stored at {}", dir.display());
3069 return Ok(ExitCode::SUCCESS);
3070 }
3071 let n = fs::read_dir(&dir)
3072 .map(|rd| {
3073 rd.flatten()
3074 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
3075 .count()
3076 })
3077 .unwrap_or(0);
3078 fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
3079 eprintln!(
3080 "htl cache: removed {n} {} from {}",
3081 if n == 1 { "entry" } else { "entries" },
3082 dir.display()
3083 );
3084 Ok(ExitCode::SUCCESS)
3085}
3086
3087fn cache_root(path: Option<&Path>) -> Result<PathBuf> {
3090 let start = path.unwrap_or(Path::new("."));
3091 let model = htl::model::Project::find_root(start)?.map(|r| r.root);
3092 Ok(model.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))))
3093}
3094
3095fn cmd_cache_status(path: Option<&Path>, json: bool, list_entries: bool) -> Result<ExitCode> {
3101 let c = cache::describe(&cache_root(path)?);
3102 if json {
3103 report::emit(&c)?;
3104 return Ok(ExitCode::SUCCESS);
3105 }
3106
3107 if c.entries.is_empty() {
3108 println!("htl cache: empty ({})", c.dir);
3109 return Ok(ExitCode::SUCCESS);
3110 }
3111 let mut by_kind: std::collections::BTreeMap<&str, (usize, u64)> = Default::default();
3112 for e in &c.entries {
3113 let slot = by_kind.entry(e.kind.as_str()).or_default();
3114 slot.0 += 1;
3115 slot.1 += e.bytes;
3116 }
3117 println!(
3118 "htl cache: {} entries, {} at {}",
3119 c.entries.len(),
3120 human_bytes(c.bytes),
3121 c.dir
3122 );
3123 for (kind, (n, bytes)) in &by_kind {
3124 let what = match *kind {
3125 cache::CHECK => "checked modules",
3126 cache::GEN => "checked and generated test files (htl test)",
3127 cache::MODULE => "generated modules (htl test / build, include_bundle!)",
3128 cache::RUN => "whole runs",
3129 _ => "entries this build cannot read",
3130 };
3131 println!(" {n:>5} {what} ({})", human_bytes(*bytes));
3132 }
3133 if let (Some(min), Some(max)) = (
3134 c.entries.iter().map(|e| e.age_secs).min(),
3135 c.entries.iter().map(|e| e.age_secs).max(),
3136 ) {
3137 println!(
3138 " last used between {} and {} ago",
3139 human_age(min),
3140 human_age(max)
3141 );
3142 }
3143 if list_entries {
3144 println!();
3145 for e in &c.entries {
3146 println!(
3147 " {:<6} {:>8} {}",
3148 e.kind,
3149 human_bytes(e.bytes),
3150 e.subjects.join(", ")
3151 );
3152 }
3153 }
3154 Ok(ExitCode::SUCCESS)
3155}
3156
3157fn human_bytes(n: u64) -> String {
3158 if n >= 1 << 20 {
3159 format!("{:.1} MB", n as f64 / (1u64 << 20) as f64)
3160 } else if n >= 1 << 10 {
3161 format!("{:.0} KB", n as f64 / (1u64 << 10) as f64)
3162 } else {
3163 format!("{n} B")
3164 }
3165}
3166
3167fn human_age(secs: u64) -> String {
3168 match secs {
3169 s if s < 90 => format!("{s}s"),
3170 s if s < 5400 => format!("{}m", s / 60),
3171 s if s < 172_800 => format!("{}h", s / 3600),
3172 s => format!("{}d", s / 86_400),
3173 }
3174}
3175
3176fn patched_files(model: Option<&htl::model::Project>, files: &[PathBuf]) -> usize {
3182 let Some(model) = model else {
3183 return 0;
3184 };
3185 if !model
3186 .modules
3187 .iter()
3188 .any(|m| m.owner == htl::model::Owner::Patched)
3189 {
3190 return 0;
3191 }
3192 files
3193 .iter()
3194 .filter(|f| {
3195 model
3196 .home_of(f)
3197 .is_some_and(|m| m.owner == htl::model::Owner::Patched)
3198 })
3199 .count()
3200}
3201
3202fn print_statistics(rows: &[report::RuleStatistic]) {
3206 let width = rows.iter().map(|r| r.rule.len()).max().unwrap_or(0);
3207 for r in rows {
3208 eprintln!(
3209 "{:>5} {:<width$} {}",
3210 r.count,
3211 r.rule,
3212 statistics_marker(r)
3213 );
3214 }
3215}
3216
3217fn statistics_marker(r: &report::RuleStatistic) -> &'static str {
3222 if r.fixable == r.count {
3223 "[*]"
3224 } else if r.fixable + r.unsafe_fixable == 0 {
3225 "[ ]"
3226 } else {
3227 "[-]"
3228 }
3229}
3230
3231#[cfg(test)]
3232mod statistics_marker_tests {
3233 use super::statistics_marker;
3234 use crate::report::RuleStatistic;
3235
3236 fn stat(count: usize, fixable: usize, unsafe_fixable: usize) -> RuleStatistic {
3237 RuleStatistic {
3238 rule: "r".to_string(),
3239 count,
3240 fixable,
3241 unsafe_fixable,
3242 }
3243 }
3244
3245 #[test]
3247 fn full_safe_coverage_is_a_star() {
3248 assert_eq!(statistics_marker(&stat(2, 2, 0)), "[*]");
3249 }
3250
3251 #[test]
3253 fn no_fix_at_all_is_blank() {
3254 assert_eq!(statistics_marker(&stat(2, 0, 0)), "[ ]");
3255 }
3256
3257 #[test]
3259 fn a_mix_of_fixable_and_not_is_a_dash() {
3260 assert_eq!(statistics_marker(&stat(3, 1, 0)), "[-]");
3261 }
3262
3263 #[test]
3266 fn full_coverage_split_between_safe_and_unsafe_is_a_dash() {
3267 assert_eq!(statistics_marker(&stat(2, 1, 1)), "[-]");
3268 }
3269
3270 #[test]
3272 fn full_unsafe_only_coverage_is_a_dash() {
3273 assert_eq!(statistics_marker(&stat(2, 0, 2)), "[-]");
3274 }
3275}
3276
3277fn report_check(
3286 out: &mut report::Out,
3287 json: bool,
3288 statistics: bool,
3289 rep: &project::Report,
3290 policy: &htl::verdict::Policy,
3291 patched: usize,
3292) -> Result<bool> {
3293 let (files, replayed) = (rep.files.len(), rep.replayed);
3294 let (errors, warnings, lints) = (rep.errors, rep.warnings, rep.lints);
3295 let strict = policy.strict;
3296 let fail = htl::verdict::verdict(&rep.findings(), policy);
3297 let all_cached = rep.all_cached();
3298 if json {
3299 report::emit(&report::CheckReport {
3300 files,
3301 patched,
3302 diagnostics: out.take(),
3303 summary: report::CheckSummary {
3304 errors,
3305 warnings,
3306 lints,
3307 denied: rep.denied,
3308 strict,
3309 ok: !fail,
3310 cached: all_cached,
3311 replayed,
3312 },
3313 statistics: statistics.then(|| out.statistics()),
3314 })?;
3315 } else {
3316 if statistics {
3317 print_statistics(&out.statistics());
3318 }
3319 let cached = if all_cached {
3321 " [cached]".to_string()
3322 } else if replayed > 0 {
3323 format!(" [{replayed}/{files} cached]")
3324 } else {
3325 String::new()
3326 };
3327 let denied = match rep.denied {
3332 0 => String::new(),
3333 n => format!(", {n} at deny"),
3334 };
3335 let counted = match patched {
3339 0 => format!("{files} file(s)"),
3340 n => format!("{} file(s) + {n} in patched dependencies", files - n),
3341 };
3342 for rule in out.rules_said() {
3347 if htl::lint::explained(rule).is_some() {
3348 eprintln!("htl check --explain {rule}");
3349 }
3350 }
3351 eprintln!(
3352 "htl check: {counted}, {errors} error(s), {warnings} warning(s), {lints} lint(s){denied}{}{cached}",
3353 if strict { " [strict]" } else { "" }
3354 );
3355 }
3356 Ok(fail)
3357}
3358
3359fn cmd_gen(file: &Path, out: Option<&Path>) -> Result<ExitCode> {
3360 let h = Htl::new()?;
3361 auto_dts(file)?;
3362 let cfg = load_config(file)?;
3366 config_lints(&h, &cfg)?;
3367 config_lang(&h, &cfg)?;
3368 let model = apply_model(&h, &cfg, file)?;
3369 project::file_view(&h, model.as_ref(), file)?;
3370 h.install_std()?;
3371 h.install_registered()?;
3372 let (code, c) = h.gen_lua(file)?;
3373 text_sink().checkinfo(&c);
3374 let (Some(code), false) = (code, runs_fail(&c)) else {
3377 return Ok(ExitCode::FAILURE);
3378 };
3379 match out {
3383 Some(p) => fs::write(p, code).with_context(|| format!("writing {}", p.display()))?,
3384 None => print!("{code}"),
3385 }
3386 Ok(ExitCode::SUCCESS)
3387}
3388
3389fn cmd_run(file: &Path, args: &[String]) -> Result<ExitCode> {
3390 let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
3391 let h = Htl::new()?;
3392 auto_dts(file)?;
3393 let cfg = load_config(file)?;
3398 config_lints(&h, &cfg)?;
3399 config_lang(&h, &cfg)?;
3400 h.configure_async(async_config(&cfg))?;
3401 let model = apply_model(&h, &cfg, file)?;
3402 h.install_test_lib()?;
3403 h.install_std()?;
3404 h.install_registered()?;
3405 h.install_task_lib()?;
3406 if Bundle::is_bundle(&bytes) {
3407 let b = Bundle::decode(&bytes)?;
3408 let main = h.load_bundle(&b, args)?;
3411 return run_root(&h, Entry::Main(main), args);
3412 }
3413 project::file_view(&h, model.as_ref(), file)?;
3415 h.install_searcher()?;
3416 h.set_arg(&file.to_string_lossy(), args)?;
3417 let (code, c) = h.gen_lua(file)?;
3418 text_sink().checkinfo(&c);
3419 let (Some(code), false) = (code, runs_fail(&c)) else {
3421 return Ok(ExitCode::FAILURE);
3422 };
3423 run_root(
3424 &h,
3425 Entry::Chunk {
3426 code,
3427 name: format!("@{}", file.display()),
3428 },
3429 args,
3430 )
3431}
3432
3433enum Entry {
3435 Chunk { code: String, name: String },
3436 Main(htl::mlua::Function),
3437}
3438
3439fn async_config(cfg: &project::Config) -> &htl::config::AsyncConfig {
3441 static DEFAULT: htl::config::AsyncConfig = htl::config::AsyncConfig {
3442 grace_ms: None,
3443 preempt: None,
3444 };
3445 match cfg {
3446 Some((_, _, c)) => &c.async_,
3447 None => &DEFAULT,
3448 }
3449}
3450
3451fn run_root(h: &Htl, entry: Entry, args: &[String]) -> Result<ExitCode> {
3468 let token = htl::mlua_isle::runtime::CancelToken::new();
3469 {
3470 let token = token.clone();
3471 std::thread::Builder::new()
3472 .name("htl-ctrl-c".into())
3473 .spawn(move || {
3474 let Ok(rt) = tokio::runtime::Builder::new_current_thread()
3475 .enable_all()
3476 .build()
3477 else {
3478 return;
3479 };
3480 rt.block_on(async {
3481 if tokio::signal::ctrl_c().await.is_ok() {
3482 token.cancel();
3483 }
3484 if tokio::signal::ctrl_c().await.is_ok() {
3485 std::process::exit(130);
3486 }
3487 });
3488 })
3489 .context("starting the Ctrl-C watcher")?;
3490 }
3491 let rt = tokio::runtime::Builder::new_current_thread()
3492 .enable_all()
3493 .build()
3494 .context("building the executor's runtime")?;
3495 let local = tokio::task::LocalSet::new();
3496 let out = local.block_on(&rt, async {
3497 match entry {
3498 Entry::Chunk { code, name } => h.run_async(&code, &name, args, &token).await,
3499 Entry::Main(main) => {
3500 let va: htl::mlua::Variadic<String> = args.iter().cloned().collect();
3501 h.call_async(main, va, &token).await.map(|_| ())
3502 }
3503 }
3504 });
3505 Ok(match out {
3506 Ok(()) => ExitCode::SUCCESS,
3507 Err(e) if htl::is_cancelled(&e) => {
3508 eprintln!("htl run: interrupted");
3509 ExitCode::from(130)
3510 }
3511 Err(e) => {
3512 eprintln!("{}", htl::developer_message(&e));
3513 ExitCode::FAILURE
3514 }
3515 })
3516}
3517
3518fn runs_fail(c: &htl::CheckInfo) -> bool {
3522 htl::verdict::verdict(
3523 &htl::verdict::Findings {
3524 errors: c.errors.len(),
3525 warnings: c.warnings.len(),
3526 lints: c.lints.len(),
3527 denied: 0,
3528 },
3529 &htl::verdict::Policy::ERRORS_ONLY,
3530 )
3531}
3532
3533struct BuildCache {
3538 use_cache: bool,
3539 explain: bool,
3540}
3541
3542fn cmd_build(
3543 entry: &Path,
3544 out: &Path,
3545 main: &str,
3546 mut opts: htl::link::LinkOptions,
3547 cache_flags: BuildCache,
3548) -> Result<ExitCode> {
3549 let h = Htl::new()?;
3550 auto_dts(entry)?;
3551 h.install_std()?;
3555 h.install_registered()?;
3556 let cfg = load_config(entry)?;
3557 let lints = config_lints(&h, &cfg)?;
3560 config_lang(&h, &cfg)?;
3561 let policy = htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
3562 let model = apply_model(&h, &cfg, entry)?;
3563 if let Some(m) = &model {
3567 opts.host.extend(m.provided().map(|(n, _)| n.to_string()));
3568 }
3569 if let Some((_, _, cfg)) = &cfg {
3570 opts.extra.extend(cfg.build.extra.iter().cloned());
3571 opts.host.extend(cfg.build.host.iter().cloned());
3572 if let Some(t) = cfg.build.target.filter(|t| *t != BuildTarget::Hb) {
3578 eprintln!(
3579 "htl build: this project's target is `{}` — what runs its output is {} — and `htl build` writes a `.hb` bundle, which is the `hb` target. Build it with `cargo build`; to bundle its scripts anyway, drop `[build] target` from htl.toml.",
3580 t.name(),
3581 t.runs_it()
3582 );
3583 return Ok(ExitCode::FAILURE);
3584 }
3585 }
3586 if entry.is_dir() {
3587 if cache_flags.explain {
3588 eprintln!("htl cache: the directory form of `htl build` is not cached");
3589 }
3590 let skip = project::not_walked(
3593 model.as_ref(),
3594 &[entry.to_path_buf()],
3595 htl::model::Purpose::Check,
3596 );
3597 return cmd_build_dir(&h, entry, out, main, &opts, &skip, &cfg);
3598 }
3599 project::file_view(&h, model.as_ref(), entry)?;
3600 opts.entry_name = model.as_ref().and_then(|m| m.locate(entry).map(|p| p.name));
3603 let root = project::store_root(model.as_ref());
3609 let spec = cfg
3610 .as_ref()
3611 .map(|(_, _, c)| c.lint_spec())
3612 .unwrap_or_default();
3613 let lint = (!spec.is_empty()).then_some(spec.as_str());
3614 let cache_opts = project::cache_options(
3615 cache_flags.use_cache,
3616 Some(cache::Mode::PerModule),
3617 &cfg,
3618 cache_flags.explain,
3619 );
3620 let store = project::with_model(
3621 project::store(&root, cache_opts, None, "htl build"),
3622 model.as_ref(),
3623 );
3624 let link_store = store.as_ref().map(|c| htl::link::LinkStore {
3625 cache: c,
3626 lint,
3627 root: &root,
3628 config: cfg.as_ref().map(|(_, p, c)| (p.as_path(), c)),
3629 });
3630 let linked = htl::link::link_with(&h, entry, &opts, link_store)?;
3631 project::explain_cache(store.as_ref(), cache_opts);
3632 let mut sink = text_sink();
3635 sink.judge_by(lints.selection());
3636 for (p, c) in &linked.checks {
3637 sink.checkinfo(&linked.reported(p, c));
3638 }
3639 let n_err = linked.errors.len();
3640 let found = htl::verdict::Findings {
3641 errors: n_err,
3642 warnings: linked.checks.iter().map(|(_, c)| c.warnings.len()).sum(),
3643 lints: linked.lints.len(),
3644 denied: sink.denied(),
3645 };
3646 for d in &linked.link_errors {
3649 sink.diagnostic(d);
3650 }
3651 if htl::verdict::verdict(&found, &policy) {
3652 eprintln!(
3653 "htl build: {n_err} error(s){}, bundle not written",
3654 judged(&found, &policy)
3655 );
3656 return Ok(ExitCode::FAILURE);
3657 }
3658 let buf = linked.bundle()?.encode();
3659 fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
3660 let typed = linked.modules.iter().filter(|m| m.typed).count();
3661 let cached = if typed > 0 && linked.cached == typed {
3664 " [cached]".to_string()
3665 } else if linked.cached > 0 {
3666 format!(" [{}/{typed} cached]", linked.cached)
3667 } else {
3668 String::new()
3669 };
3670 eprintln!(
3671 "htl build: {} module(s) ({typed} typed, {} lua) -> {} ({} bytes{}{}){cached}",
3672 linked.modules.len(),
3673 linked.modules.len() - typed,
3674 out.display(),
3675 buf.len(),
3676 if opts.source {
3677 ", source"
3678 } else {
3679 ", bytecode"
3680 },
3681 if opts.debug { " with debug info" } else { "" }
3682 );
3683 if !linked.host_modules.is_empty() {
3684 eprintln!(
3685 "htl build: host must provide: {}",
3686 linked.host_modules.join(", ")
3687 );
3688 }
3689 Ok(ExitCode::SUCCESS)
3690}
3691
3692fn cmd_build_dir(
3694 h: &Htl,
3695 dir: &Path,
3696 out: &Path,
3697 entry: &str,
3698 opts: &htl::link::LinkOptions,
3699 skip: &[PathBuf],
3700 cfg: &project::Config,
3701) -> Result<ExitCode> {
3702 let lints = config_lints(h, cfg)?;
3704 config_lang(h, cfg)?;
3705 let policy = &htl::verdict::Policy::resolve(cfg.as_ref().map(|(_, _, c)| c), false);
3706 h.add_path(dir)?;
3707 let files = htl::collect_tl_skipping(&[dir.to_path_buf()], skip)?;
3708 let mut b = Bundle {
3709 entry: entry.to_string(),
3710 htl_version: env!("CARGO_PKG_VERSION").into(),
3711 ..Default::default()
3712 };
3713 let mut found = htl::verdict::Findings::default();
3714 let mut sink = text_sink();
3715 sink.judge_by(lints.selection());
3716 for f in &files {
3717 let rel = f.strip_prefix(dir).unwrap_or(f);
3719 let name = htl::naming::name_of("", rel)
3720 .with_context(|| format!("cannot derive a module name for {}", f.display()))?;
3721 let (code, c) = h.gen_lua(f)?;
3722 sink.checkinfo(&c);
3723 found.errors += c.errors.len();
3724 found.warnings += c.warnings.len();
3725 found.lints += c.lints.len();
3726 let Some(code) = code else { continue };
3727 let (kind, payload) = if opts.source {
3728 (htl::bundle::Kind::Source, code.into_bytes())
3729 } else {
3730 (
3731 htl::bundle::Kind::Bytecode,
3732 h.compile_with(&name, &code, !opts.debug)?,
3733 )
3734 };
3735 b.modules.push(htl::bundle::Module {
3736 name,
3737 kind,
3738 payload,
3739 });
3740 }
3741 found.denied = sink.denied();
3742 if htl::verdict::verdict(&found, policy) {
3743 eprintln!(
3744 "htl build: {} error(s){}, bundle not written",
3745 found.errors,
3746 judged(&found, policy)
3747 );
3748 return Ok(ExitCode::FAILURE);
3749 }
3750 if b.module(entry).is_none() {
3751 bail!(
3752 "entry module '{entry}' not found among {} module(s)",
3753 b.modules.len()
3754 );
3755 }
3756 if !opts.source {
3757 b.fingerprint = h.fingerprint()?;
3758 }
3759 let buf = b.encode();
3760 fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
3761 eprintln!(
3762 "htl build: {} module(s) -> {} ({} bytes)",
3763 b.modules.len(),
3764 out.display(),
3765 buf.len()
3766 );
3767 Ok(ExitCode::SUCCESS)
3768}
3769
3770#[derive(serde::Serialize)]
3777struct BundleInfo {
3778 file: String,
3779 format: u8,
3780 htl_version: Option<String>,
3781 payload: &'static str,
3783 lua: Option<htl::bundle::LuaHeader>,
3784 entry: String,
3785 modules: Vec<BundleModuleInfo>,
3786 host_modules: Vec<String>,
3787}
3788
3789#[derive(serde::Serialize)]
3790struct BundleModuleInfo {
3791 name: String,
3792 kind: &'static str,
3793 bytes: usize,
3794}
3795
3796fn cmd_bundle_info(file: &Path, json: bool) -> Result<ExitCode> {
3797 let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
3798 let Some(format) = htl::bundle::format_version(&bytes) else {
3799 bail!("{} is not an htl bundle (bad magic)", file.display());
3800 };
3801 let b = Bundle::decode(&bytes)?;
3802 let kind_name = |k: htl::bundle::Kind| match k {
3803 htl::bundle::Kind::Bytecode => "bytecode",
3804 htl::bundle::Kind::Source => "source",
3805 };
3806 let payload = match (
3807 b.modules
3808 .iter()
3809 .any(|m| m.kind == htl::bundle::Kind::Bytecode),
3810 b.modules
3811 .iter()
3812 .any(|m| m.kind == htl::bundle::Kind::Source),
3813 ) {
3814 (true, true) => "mixed",
3815 (false, true) => "source",
3816 _ => "bytecode",
3818 };
3819 let info = BundleInfo {
3820 file: file.display().to_string(),
3821 format,
3822 htl_version: (!b.htl_version.is_empty()).then(|| b.htl_version.clone()),
3823 payload,
3824 lua: htl::bundle::LuaHeader::parse(&b.fingerprint),
3825 entry: b.entry.clone(),
3826 modules: b
3827 .modules
3828 .iter()
3829 .map(|m| BundleModuleInfo {
3830 name: m.name.clone(),
3831 kind: kind_name(m.kind),
3832 bytes: m.payload.len(),
3833 })
3834 .collect(),
3835 host_modules: b.host_modules.clone(),
3836 };
3837 if json {
3838 report::emit(&info)?;
3839 return Ok(ExitCode::SUCCESS);
3840 }
3841
3842 println!(
3843 "{}: htl bundle, format {}, built by {}",
3844 info.file,
3845 info.format,
3846 match &info.htl_version {
3847 Some(v) => format!("htl {v}"),
3848 None => "htl (version not recorded)".to_string(),
3849 }
3850 );
3851 println!(" payload: {}", info.payload);
3852 let lua = match &info.lua {
3853 Some(h) => h.to_string(),
3854 None if !b.fingerprint.is_empty() => {
3855 format!("unreadable fingerprint ({} bytes)", b.fingerprint.len())
3856 }
3857 None if info.format == 1 => {
3858 "not recorded (a format 1 bundle carries no fingerprint)".into()
3859 }
3860 None => "any (source payload, no bytecode to bind)".into(),
3861 };
3862 println!(" lua: {lua}");
3863 println!(" entry: {}", info.entry);
3864 let modules: Vec<String> = info
3865 .modules
3866 .iter()
3867 .map(|m| {
3868 if info.payload == "mixed" {
3869 format!("{} ({})", m.name, m.kind)
3870 } else {
3871 m.name.clone()
3872 }
3873 })
3874 .collect();
3875 println!(
3876 " modules: {}",
3877 if modules.is_empty() {
3878 "(none)".to_string()
3879 } else {
3880 modules.join(", ")
3881 }
3882 );
3883 println!(
3884 " host: {}",
3885 if info.host_modules.is_empty() {
3886 "(none)".to_string()
3887 } else {
3888 info.host_modules.join(", ")
3889 }
3890 );
3891 Ok(ExitCode::SUCCESS)
3892}