1use htl::cache;
10mod junit;
11mod report;
12mod scaffold;
13
14#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
19enum Format {
20 Text,
22 Json,
25}
26
27#[derive(Clone, Copy, PartialEq, Eq, Debug, clap::ValueEnum)]
30enum CacheModeArg {
31 PerModule,
33 WholeRun,
35}
36
37#[derive(Subcommand)]
38enum TypesCmd {
39 Add {
42 library: String,
44 #[arg(long)]
46 from: Option<PathBuf>,
47 #[arg(long)]
49 force: bool,
50 },
51}
52
53#[derive(Subcommand)]
54enum PkgCmd {
55 Install,
57 Add {
59 name: String,
61 git: String,
63 #[arg(long)]
65 tag: Option<String>,
66 #[arg(long)]
68 rev: Option<String>,
69 #[arg(long)]
71 branch: Option<String>,
72 #[arg(long)]
75 entry: Option<PathBuf>,
76 #[arg(long)]
79 target_dir: Option<PathBuf>,
80 },
81 Update {
83 name: Option<String>,
85 #[arg(long)]
87 dry_run: bool,
88 #[arg(long)]
90 force: bool,
91 },
92 Clean {
94 #[arg(long)]
96 all: bool,
97 },
98 Patch {
101 dep: String,
103 #[arg(long)]
105 force: bool,
106 },
107}
108
109#[derive(Subcommand)]
110enum CacheCmd {
111 Clear {
113 path: Option<PathBuf>,
115 },
116 Status {
118 path: Option<PathBuf>,
120 #[arg(long, value_enum, default_value_t = Format::Text)]
122 format: Format,
123 #[arg(long)]
125 entries: bool,
126 },
127}
128
129#[derive(Subcommand)]
130enum BundleCmd {
131 Info {
134 file: PathBuf,
136 #[arg(long, value_enum, default_value_t = Format::Text)]
138 format: Format,
139 },
140}
141
142impl From<CacheModeArg> for cache::Mode {
143 fn from(m: CacheModeArg) -> Self {
144 match m {
145 CacheModeArg::PerModule => cache::Mode::PerModule,
146 CacheModeArg::WholeRun => cache::Mode::WholeRun,
147 }
148 }
149}
150
151use anyhow::{Context, Result, bail};
152use clap::{Parser, Subcommand};
153use htl::BuildTarget;
154use htl::Htl;
155use htl::bundle::Bundle;
156use htl::project;
160use std::fs;
161use std::path::{Path, PathBuf};
162use std::process::ExitCode;
163
164#[derive(Parser)]
165#[command(
166 name = "htl",
167 version,
168 about = "Teal, hidden: run / check / build .tl on mlua",
169 long_about = "\
170Teal, hidden: run / check / build .tl on mlua.
171
172htl is a toolchain for Teal, and a way to embed one. It type-checks `.tl` sources with \
173Teal's own checker, runs and tests them on an embedded mlua state, formats them, and \
174links them into a single stripped-bytecode bundle. A Rust host embeds the same engine, \
175so the scripts it ships are checked when the host is built rather than when its user \
176first runs one.
177
178The guide, with every command and what a project looks like:
179 https://github.com/ynishi/htl
180
181The API a Rust host holds — `include_tl!`, `#[host_module]`, the run cache:
182 https://docs.rs/htl"
183)]
184struct Cli {
185 #[command(subcommand)]
186 cmd: Cmd,
187}
188
189#[derive(Subcommand)]
190enum Cmd {
191 #[command(after_long_help = "\
197Examples:
198 htl check src every .tl under src/
199 htl check src --strict every warn counts as deny: warnings and lints fail
200 htl check src --lint nil-index=deny,no-any=warn
201 one rule fails the run, another is advice
202 htl check src --lint -tl:hint a warning kind of the Teal compiler silenced
203 htl check --list-lints every rule with its default level, then exit
204
205Caching: https://github.com/ynishi/htl#caching
206")]
207 Check {
208 paths: Vec<PathBuf>,
209 #[arg(long)]
211 strict: bool,
212 #[arg(long, allow_hyphen_values = true)]
218 lint: Option<String>,
219 #[arg(long)]
221 list_lints: bool,
222 #[arg(long, value_enum, default_value_t = Format::Text)]
224 format: Format,
225 #[arg(long)]
227 no_cache: bool,
228 #[arg(long, value_enum)]
230 cache_mode: Option<CacheModeArg>,
231 #[arg(long)]
233 explain_cache: bool,
234 },
235 #[command(after_long_help = "\
239Examples:
240 htl test every *_test.tl and tests/**/*.tl
241 htl test tests --filter parser only tests whose \"suite > name\" contains it
242 htl test --coverage --coverage-lines
243 which lines of each module the suite never reached
244 htl test --junit report.xml also write the run as a JUnit report, for a CI
245")]
246 Test {
247 paths: Vec<PathBuf>,
248 #[arg(long)]
250 filter: Option<String>,
251 #[arg(long, default_value = htl::testing::DEFAULT_LIB)]
253 lib: String,
254 #[arg(long, allow_hyphen_values = true)]
256 lint: Option<String>,
257 #[arg(long)]
259 fail_fast: bool,
260 #[arg(short, long)]
262 verbose: bool,
263 #[arg(short, long, conflicts_with = "verbose")]
265 quiet: bool,
266 #[arg(long, value_name = "MS")]
268 slow: Option<f64>,
269 #[arg(long)]
271 update: bool,
272 #[arg(long)]
274 coverage: bool,
275 #[arg(long, requires = "coverage")]
277 coverage_lines: bool,
278 #[arg(long, value_name = "FILE")]
280 lcov: Option<PathBuf>,
281 #[arg(long, value_name = "FILE")]
283 junit: Option<PathBuf>,
284 #[arg(long)]
286 seed: Option<u64>,
287 #[arg(long, value_enum, default_value_t = Format::Text)]
289 format: Format,
290 #[arg(long)]
292 no_cache: bool,
293 #[arg(long)]
295 explain_cache: bool,
296 },
297 #[command(after_long_help = "\
301Examples:
302 htl fix src apply the safe fixes to every .tl under src/
303 htl fix src --diff --dry-run what would change, as a unified diff per file
304 htl fix src --rule forward-ref only that rule's fixes
305 htl fix src --unsafe also the fixes that may change what the program does
306")]
307 Fix {
308 paths: Vec<PathBuf>,
309 #[arg(long, value_delimiter = ',')]
312 rule: Vec<String>,
313 #[arg(long = "unsafe")]
315 unsafe_fixes: bool,
316 #[arg(long)]
318 dry_run: bool,
319 #[arg(long)]
321 diff: bool,
322 #[arg(long)]
324 allow_dirty: bool,
325 #[arg(long)]
327 allow_no_vcs: bool,
328 #[arg(long)]
330 exit_non_zero_on_fix: bool,
331 #[arg(long, value_enum, default_value_t = Format::Text)]
333 format: Format,
334 },
335 Dts {
345 dir: Option<PathBuf>,
347 },
348 #[command(after_long_help = "\
352Examples:
353 htl new hello src/main.tl, a module, tests/, mlua-pkg.toml
354 htl new hello --lib a library: no entry script
355 htl new hello --embed the same, plus a Rust host (--target bin)
356 htl new hello --target cdylib --lib
357 a library behind a C ABI, for a caller that is not Rust
358 htl new hello --embed --htl main
359 built against the unreleased htl (a git pin on main)
360 htl new hello --embed --htl path:../htl
361 built against a local checkout of this repository
362 htl new hello --no-x without the htlx dependency the manifest gets by default
363
364Build targets: https://github.com/ynishi/htl#build-targets---target-name
365The cdylib target: https://github.com/ynishi/htl#the-cdylib-target---target-cdylib
366")]
367 New {
368 name: String,
369 #[arg(long)]
371 lib: bool,
372 #[arg(long)]
374 embed: bool,
375 #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
379 target: Option<String>,
380 #[arg(long, value_name = "REQ")]
384 htl: Option<String>,
385 #[arg(long)]
387 no_x: bool,
388 },
389 Init {
391 dir: Option<PathBuf>,
392 #[arg(long)]
393 lib: bool,
394 #[arg(long)]
396 embed: bool,
397 #[arg(long, value_name = "NAME", value_parser = clap::builder::PossibleValuesParser::new(scaffold::target_names()))]
399 target: Option<String>,
400 #[arg(long, value_name = "REQ")]
404 htl: Option<String>,
405 #[arg(long)]
407 no_x: bool,
408 },
409 Pkg {
412 #[command(subcommand)]
413 cmd: PkgCmd,
414 },
415 Types {
417 #[command(subcommand)]
418 cmd: TypesCmd,
419 },
420 Cache {
424 #[command(subcommand)]
425 cmd: CacheCmd,
426 },
427 Fmt {
429 paths: Vec<PathBuf>,
430 #[arg(long)]
432 check: bool,
433 #[arg(long)]
435 indent: Option<usize>,
436 },
437 Gen {
439 file: PathBuf,
440 #[arg(short, long)]
441 out: Option<PathBuf>,
442 },
443 Run {
445 file: PathBuf,
446 #[arg(trailing_var_arg = true)]
447 args: Vec<String>,
448 },
449 #[command(after_long_help = "\
456Examples:
457 htl build src/main.tl -o app.hb
458 the entry's require closure, as one bundle
459 htl build src/main.tl -o app.hb --debug
460 keep line numbers and local names in the bytecode
461 htl build src/main.tl -o app.hb --host mymod
462 leave a module the host provides out of the bundle
463 htl run app.hb run what was built
464
465Caching: https://github.com/ynishi/htl#caching
466")]
467 Build {
468 entry: PathBuf,
472 #[arg(short, long, default_value = "app.hb")]
473 out: PathBuf,
474 #[arg(short, long, default_value = "main")]
476 main: String,
477 #[arg(long)]
479 debug: bool,
480 #[arg(long)]
483 source: bool,
484 #[arg(long, value_delimiter = ',')]
486 extra: Vec<String>,
487 #[arg(long, value_delimiter = ',')]
489 host: Vec<String>,
490 #[arg(long)]
493 no_cache: bool,
494 #[arg(long)]
496 explain_cache: bool,
497 },
498 #[command(after_long_help = "\
503Examples:
504 htl unused modules and dependencies no entry reaches
505 htl unused --exit-non-zero-on-unused
506 the same report, and a non-zero exit for a CI
507 htl unused --format json the same report as one JSON document
508")]
509 Unused {
510 paths: Vec<PathBuf>,
513 #[arg(long, value_enum, default_value_t = Format::Text)]
515 format: Format,
516 #[arg(long)]
518 exit_non_zero_on_unused: bool,
519 #[arg(long)]
522 no_cache: bool,
523 #[arg(long)]
525 explain_cache: bool,
526 },
527 #[command(after_long_help = "\
534Examples:
535 htl resolve mq the chain for require(\"mq\")
536 htl resolve socket.http a name with dots, as a require spells it
537 htl resolve mq --format json the same rows as one JSON document
538
539Exits 1 when the name resolves to nothing, so a script can ask.
540
541`htl.test` is not on a project's search path: `htl test` preloads it into the state it
542runs, and the declarations behind it come from the binary rather than the project.
543")]
544 Resolve {
545 module: String,
547 path: Option<PathBuf>,
549 #[arg(long, value_enum, default_value_t = Format::Text)]
551 format: Format,
552 },
553 Bundle {
557 #[command(subcommand)]
558 cmd: BundleCmd,
559 },
560}
561
562pub fn command() -> clap::Command {
568 <Cli as clap::CommandFactory>::command()
569}
570
571pub fn run() -> ExitCode {
572 let mut argv: Vec<String> = std::env::args().collect();
574 let is_cargo = Path::new(&argv[0])
575 .file_stem()
576 .and_then(|s| s.to_str())
577 .map(|s| s == "cargo-htl")
578 .unwrap_or(false);
579 if is_cargo && argv.get(1).map(String::as_str) == Some("htl") {
580 argv.remove(1);
581 }
582 match real_main(Cli::parse_from(argv)) {
583 Ok(code) => code,
584 Err(e) => {
585 eprintln!("htl: {e:#}");
586 ExitCode::from(2)
587 }
588 }
589}
590
591fn real_main(cli: Cli) -> Result<ExitCode> {
592 match cli.cmd {
593 Cmd::Check {
594 paths,
595 strict,
596 lint,
597 list_lints,
598 format,
599 no_cache,
600 cache_mode,
601 explain_cache,
602 } => cmd_check(
603 &paths,
604 lint.as_deref(),
605 CheckFlags {
606 strict,
607 list_lints,
608 json: format == Format::Json,
609 use_cache: !no_cache,
610 cache_mode: cache_mode.map(Into::into),
611 explain: explain_cache,
612 },
613 ),
614 Cmd::Fmt {
615 paths,
616 check,
617 indent,
618 } => cmd_fmt(&paths, check, indent),
619 Cmd::Test {
620 paths,
621 filter,
622 lib,
623 lint,
624 fail_fast,
625 verbose,
626 quiet,
627 slow,
628 update,
629 coverage,
630 coverage_lines,
631 lcov,
632 junit,
633 seed,
634 format,
635 no_cache,
636 explain_cache,
637 } => cmd_test(
638 &paths,
639 filter.as_deref(),
640 &lib,
641 lint.as_deref(),
642 TestFlags {
643 fail_fast,
644 verbose,
645 quiet,
646 slow,
647 update,
648 coverage: coverage || lcov.is_some(),
649 coverage_lines,
650 lcov,
651 junit,
652 json: format == Format::Json,
653 no_cache,
654 explain: explain_cache,
655 seed,
656 },
657 ),
658 Cmd::Pkg { cmd } => match cmd {
659 PkgCmd::Install => cmd_pkg_install(),
660 PkgCmd::Add {
661 name,
662 git,
663 tag,
664 rev,
665 branch,
666 entry,
667 target_dir,
668 } => cmd_pkg_add(htl::pkg::mlua_pkg::ops::AddSpec {
669 name,
670 git,
671 tag,
672 rev,
673 branch,
674 entry,
675 target_dir,
676 }),
677 PkgCmd::Update {
678 name,
679 dry_run,
680 force,
681 } => cmd_pkg_update(htl::pkg::mlua_pkg::ops::UpdateOpts {
682 name,
683 dry_run,
684 force,
685 }),
686 PkgCmd::Clean { all } => cmd_pkg_clean(all),
687 PkgCmd::Patch { dep, force } => cmd_pkg_patch(&dep, force),
688 },
689 Cmd::Types { cmd } => match cmd {
690 TypesCmd::Add {
691 library,
692 from,
693 force,
694 } => cmd_types_add(&library, from.as_deref(), force),
695 },
696 Cmd::Cache { cmd } => match cmd {
697 CacheCmd::Clear { path } => cmd_cache_clear(path.as_deref()),
698 CacheCmd::Status {
699 path,
700 format,
701 entries,
702 } => cmd_cache_status(path.as_deref(), format == Format::Json, entries),
703 },
704 Cmd::Dts { dir } => cmd_dts(dir.as_deref()),
705 Cmd::New {
706 name,
707 lib,
708 embed,
709 target,
710 htl,
711 no_x,
712 } => cmd_new(&name, lib, embed, target.as_deref(), htl.as_deref(), no_x),
713 Cmd::Init {
714 dir,
715 lib,
716 embed,
717 target,
718 htl,
719 no_x,
720 } => cmd_init(
721 dir.as_deref(),
722 lib,
723 embed,
724 target.as_deref(),
725 htl.as_deref(),
726 no_x,
727 ),
728 Cmd::Gen { file, out } => cmd_gen(&file, out.as_deref()),
729 Cmd::Run { file, args } => cmd_run(&file, &args),
730 Cmd::Fix {
731 paths,
732 rule,
733 unsafe_fixes,
734 dry_run,
735 diff,
736 allow_dirty,
737 allow_no_vcs,
738 exit_non_zero_on_fix,
739 format,
740 } => cmd_fix(
741 &paths,
742 FixFlags {
743 rule,
744 unsafe_fixes,
745 dry_run: dry_run || diff,
746 diff,
747 allow_dirty,
748 allow_no_vcs,
749 exit_non_zero_on_fix,
750 json: format == Format::Json,
751 },
752 ),
753 Cmd::Build {
754 entry,
755 out,
756 main,
757 debug,
758 source,
759 extra,
760 host,
761 no_cache,
762 explain_cache,
763 } => cmd_build(
764 &entry,
765 &out,
766 &main,
767 htl::link::LinkOptions {
768 debug,
769 source,
770 extra,
771 host,
772 },
773 BuildCache {
774 use_cache: !no_cache,
775 explain: explain_cache,
776 },
777 ),
778 Cmd::Unused {
779 paths,
780 format,
781 exit_non_zero_on_unused,
782 no_cache,
783 explain_cache,
784 } => cmd_unused(
785 &paths,
786 UnusedFlags {
787 json: format == Format::Json,
788 fail_on_unused: exit_non_zero_on_unused,
789 use_cache: !no_cache,
790 explain: explain_cache,
791 },
792 ),
793 Cmd::Resolve {
794 module,
795 path,
796 format,
797 } => cmd_resolve(&module, path.as_deref(), format == Format::Json),
798 Cmd::Bundle { cmd } => match cmd {
799 BundleCmd::Info { file, format } => cmd_bundle_info(&file, format == Format::Json),
800 },
801 }
802}
803
804fn text_sink() -> project::Sink<report::Out> {
815 project::Sink::new(report::Out::new(false))
816}
817
818fn auto_dts(start: &Path) -> Result<()> {
829 let mut project = None;
830 if let Some((root, _, cfg)) = load_config(start)? {
831 let (contracts, _) = htl::contract::resolve(&root, &cfg);
832 let (results, problems) = htl::contract::publish(&root, &contracts);
833 announce_dts(&results, &root);
834 for p in &problems {
835 eprintln!("dts: {p}");
836 }
837 project = Some(root);
838 }
839 let Some(root) = htl::dts::find_cargo_package_root(start) else {
840 return Ok(());
841 };
842 let results = htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("htl dts: {e}"))?;
843 announce_dts(&results, &root);
844 let types_root = project.unwrap_or_else(|| root.clone());
845 let report = dep_dts(&root, &types_root);
846 announce_dts(&report.written, &types_root);
847 announce_dep_report(&report, "dts: ");
848 Ok(())
849}
850
851#[derive(Default)]
858struct DepReport {
859 written: Vec<(PathBuf, bool)>,
861 not_written: Vec<String>,
863 left_in_place: Vec<String>,
866 unresolved: Option<String>,
871}
872
873fn dep_dts(cargo_root: &Path, types_root: &Path) -> DepReport {
879 let decls = match htl::dep_dts::resolve(cargo_root) {
880 Ok(d) => d,
881 Err(e) => {
882 return DepReport {
883 unresolved: Some(e),
884 ..DepReport::default()
885 };
886 }
887 };
888 let left_in_place = htl::dep_dts::orphans(types_root, &decls);
891 let (written, not_written) = htl::dep_dts::materialise(types_root, &decls);
892 DepReport {
893 written,
894 not_written,
895 left_in_place,
896 unresolved: None,
897 }
898}
899
900fn announce_dep_report(report: &DepReport, prefix: &str) {
905 for p in &report.not_written {
906 eprintln!("{prefix}not written: {p}");
907 }
908 for p in &report.left_in_place {
909 eprintln!("{prefix}left in place: {p}");
910 }
911 if let Some(e) = &report.unresolved {
912 eprintln!("{prefix}{e}");
913 }
914}
915
916fn announce_dts(results: &[(PathBuf, bool)], root: &Path) {
917 for (target, written) in results {
918 if *written {
919 eprintln!(
920 "dts: wrote {}",
921 target.strip_prefix(root).unwrap_or(target).display()
922 );
923 }
924 }
925}
926
927fn cmd_dts(dir: Option<&Path>) -> Result<ExitCode> {
928 let start = match dir {
929 Some(d) => d.to_path_buf(),
930 None => std::env::current_dir()?,
931 };
932 let mut results = Vec::new();
935 let mut failed = false;
936 let mut project = None;
937 if let Some((croot, _, cfg)) = load_config(&start)? {
938 let (contracts, _) = htl::contract::resolve(&croot, &cfg);
939 let (published, problems) = htl::contract::publish(&croot, &contracts);
940 for p in &problems {
941 eprintln!(" {p}");
942 }
943 failed = !problems.is_empty();
946 results.extend(published);
947 project = Some(croot);
948 }
949 let code = |failed: bool| {
950 if failed {
951 ExitCode::FAILURE
952 } else {
953 ExitCode::SUCCESS
954 }
955 };
956 let Some(root) = htl::dts::find_cargo_package_root(&start) else {
957 if results.is_empty() && !failed {
958 bail!(
959 "no Cargo.toml with a [package] section, and no ---@contract type to publish, \
960 at or above {}",
961 start.display()
962 );
963 }
964 report_dts(&results, &start);
965 return Ok(code(failed));
966 };
967 results.extend(htl::dts::generate_crate(&root).map_err(|e| anyhow::anyhow!("{e}"))?);
968 let types_root = project.unwrap_or_else(|| root.clone());
969 let report = dep_dts(&root, &types_root);
970 announce_dep_report(&report, " ");
971 failed = failed || !report.not_written.is_empty();
974 results.extend(report.written);
975 report_dts(&results, &root);
976 Ok(code(failed))
977}
978
979fn report_dts(results: &[(PathBuf, bool)], root: &Path) {
980 let mut written = 0usize;
981 for (target, w) in results {
982 let rel = target.strip_prefix(root).unwrap_or(target).display();
983 eprintln!(" {} {}", if *w { "wrote " } else { "unchanged" }, rel);
984 written += usize::from(*w);
985 }
986 eprintln!(
987 "htl dts: {} declaration(s) from {}, {} written",
988 results.len(),
989 root.display(),
990 written
991 );
992}
993
994fn apply_project(h: &Htl, start: &Path) -> Result<Option<htl::pkg::Project>> {
997 let Some(p) = htl::pkg::Project::find(start) else {
998 return Ok(None);
999 };
1000 h.apply_project(&p)?;
1001 Ok(Some(p))
1002}
1003
1004fn report_scaffold(dir: &Path, written: &[PathBuf], kept: &[PathBuf]) {
1008 let rel = |p: &PathBuf| p.strip_prefix(dir).unwrap_or(p).display().to_string();
1009 for p in written {
1010 eprintln!(" created {}", rel(p));
1011 }
1012 for p in kept {
1013 eprintln!(" kept {} (already there)", rel(p));
1014 }
1015 if kept.is_empty() {
1016 eprintln!(
1017 "htl: {} file(s) written under {}",
1018 written.len(),
1019 dir.display()
1020 );
1021 } else {
1022 eprintln!(
1023 "htl: {} file(s) written, {} kept under {}",
1024 written.len(),
1025 kept.len(),
1026 dir.display()
1027 );
1028 }
1029}
1030
1031fn cmd_new(
1032 name: &str,
1033 lib: bool,
1034 embed: bool,
1035 target: Option<&str>,
1036 htl: Option<&str>,
1037 no_x: bool,
1038) -> Result<ExitCode> {
1039 let dir = PathBuf::from(name);
1040 let pkg_name = dir
1041 .file_name()
1042 .and_then(|s| s.to_str())
1043 .ok_or_else(|| anyhow::anyhow!("invalid project name: {name}"))?
1044 .to_string();
1045 let target = scaffold::resolve_target(target, embed, lib)?;
1049 let htl = scaffold::HtlPin::parse(htl)?;
1050 let opts = scaffold::Options {
1051 lib,
1052 target,
1053 htl,
1054 no_x,
1055 };
1056 let done = scaffold::scaffold(&dir, &pkg_name, &opts, true)?;
1057 report_scaffold(&dir, &done.written, &[]);
1058 let fetch = if opts.writes_htlx() {
1061 "htl pkg install && "
1062 } else {
1063 ""
1064 };
1065 let then = match opts.target.map(|t| t.target) {
1071 Some(BuildTarget::Window) => "htl check . && cargo run",
1072 _ => "htl test",
1073 };
1074 eprintln!("next: cd {} && {fetch}{then}", dir.display());
1075 Ok(ExitCode::SUCCESS)
1076}
1077
1078fn cmd_init(
1079 dir: Option<&Path>,
1080 lib: bool,
1081 embed: bool,
1082 target: Option<&str>,
1083 htl: Option<&str>,
1084 no_x: bool,
1085) -> Result<ExitCode> {
1086 let dir = match dir {
1087 Some(d) => d.to_path_buf(),
1088 None => std::env::current_dir()?,
1089 };
1090 let abs = std::fs::canonicalize(&dir).unwrap_or(dir.clone());
1091 let name = abs
1092 .file_name()
1093 .and_then(|s| s.to_str())
1094 .ok_or_else(|| anyhow::anyhow!("cannot derive a project name from {}", abs.display()))?
1095 .to_string();
1096 let asked_for_a_target = target.is_some() || embed;
1097 let target = scaffold::resolve_target(target, embed, lib)?;
1098 let htl = scaffold::HtlPin::parse(htl)?;
1099 let opts = scaffold::Options {
1100 lib,
1101 target,
1102 htl,
1103 no_x,
1104 };
1105 let done = scaffold::scaffold(&dir, &name, &opts, false)?;
1106 let kept: &[PathBuf] = if asked_for_a_target { &done.kept } else { &[] };
1109 if done.written.is_empty() && kept.is_empty() {
1110 eprintln!("htl init: nothing to do, all scaffold files already exist");
1111 } else {
1112 report_scaffold(&dir, &done.written, kept);
1113 }
1114 Ok(ExitCode::SUCCESS)
1115}
1116
1117fn pkg_project() -> Result<htl::pkg::Project> {
1122 let cwd = std::env::current_dir()?;
1123 htl::pkg::Project::find(&cwd).with_context(|| {
1124 format!(
1125 "no {} above {}: `htl pkg` runs in a project",
1126 htl::pkg::MANIFEST_NAME,
1127 cwd.display()
1128 )
1129 })
1130}
1131
1132fn cmd_pkg_install() -> Result<ExitCode> {
1134 let project = pkg_project()?;
1135 let report = project.install()?;
1136 report_install(&report, &project);
1137 let project = htl::pkg::Project::at(&project.root);
1141 report_types_sync(&project.sync_types()?, &project.root);
1142 report_patch_drift(&project);
1143 Ok(ExitCode::SUCCESS)
1144}
1145
1146fn report_install(report: &htl::pkg::mlua_pkg::ops::InstallReport, project: &htl::pkg::Project) {
1148 use htl::pkg::mlua_pkg::ops::Placement;
1149 for w in &report.warnings {
1150 if w.contains("patch_dir") && w.contains("not used") {
1154 continue;
1155 }
1156 eprintln!("warning: {w}");
1157 }
1158 let rel = |p: &Path| {
1159 p.strip_prefix(&project.root)
1160 .unwrap_or(p)
1161 .display()
1162 .to_string()
1163 };
1164 for p in &report.packages {
1165 let sha: String = p.sha.chars().take(7).collect();
1166 let where_it_is = match (&p.placement, p.patched) {
1167 (_, true) => format!("from {}", rel(p.root())),
1168 (Placement::Copied(dest), _) => format!("copied to {}", rel(dest)),
1169 (Placement::Symlink(_), _) => p.entry.display().to_string(),
1170 };
1171 eprintln!(" install {} {sha} ({where_it_is})", p.name);
1172 }
1173 let n = report.packages.len();
1174 if report.transitive > 0 {
1175 eprintln!(
1176 "htl pkg install: {n} package(s), {} of them transitive",
1177 report.transitive
1178 );
1179 } else {
1180 eprintln!("htl pkg install: {n} package(s)");
1181 }
1182}
1183
1184fn cmd_pkg_add(spec: htl::pkg::mlua_pkg::ops::AddSpec) -> Result<ExitCode> {
1189 use htl::pkg::mlua_pkg::ops::AddOutcome;
1190 let cwd = std::env::current_dir()?;
1191 let project = htl::pkg::Project::find(&cwd).unwrap_or_else(|| htl::pkg::Project::at(&cwd));
1192 let name = spec.name.clone();
1193 let done = project.add(spec)?;
1194 let manifest = project
1195 .manifest
1196 .strip_prefix(&project.root)
1197 .unwrap_or(&project.manifest)
1198 .display();
1199 if done.report.manifest_created {
1200 eprintln!(" created {manifest}");
1201 }
1202 let verb = match done.report.outcome {
1203 AddOutcome::Added => "added",
1204 AddOutcome::Replaced => "updated",
1205 };
1206 eprintln!(" {verb} {name} in {manifest}");
1207 if let Some(dir) = &done.kept_patch_dir {
1208 eprintln!(
1212 " kept patch_dir = {} ({name} is patched)",
1213 dir.display()
1214 );
1215 }
1216 eprintln!("htl pkg add: run `htl pkg install` to fetch it");
1217 Ok(ExitCode::SUCCESS)
1218}
1219
1220fn cmd_pkg_update(opts: htl::pkg::mlua_pkg::ops::UpdateOpts) -> Result<ExitCode> {
1222 use htl::pkg::mlua_pkg::ops::UpdateOutcome;
1223 let project = pkg_project()?;
1224 let dry_run = opts.dry_run;
1225 let report = project.update(opts)?;
1226 if report.entries.is_empty() {
1227 eprintln!("htl pkg update: no dependency selected");
1228 return Ok(ExitCode::SUCCESS);
1229 }
1230 for (name, outcome) in &report.entries {
1231 match outcome {
1232 UpdateOutcome::TagBumped { old, new } => {
1233 eprintln!(" update {name}: tag {old} -> {new}")
1234 }
1235 UpdateOutcome::PrefixResolved { pin, resolved } => eprintln!(
1236 " update {name}: prefix '{pin}' is {resolved} (the manifest keeps the prefix)"
1237 ),
1238 UpdateOutcome::Refresh => eprintln!(" update {name}: refresh (branch or unpinned)"),
1239 UpdateOutcome::Skipped(why) => eprintln!(" skip {name}: {why}"),
1240 }
1241 }
1242 if dry_run {
1243 eprintln!("htl pkg update: dry run; nothing was written");
1244 return Ok(ExitCode::SUCCESS);
1245 }
1246 if let Some(install) = &report.install {
1247 report_install(install, &project);
1248 let project = htl::pkg::Project::at(&project.root);
1249 report_types_sync(&project.sync_types()?, &project.root);
1250 report_patch_drift(&project);
1251 }
1252 Ok(ExitCode::SUCCESS)
1253}
1254
1255fn cmd_pkg_clean(all: bool) -> Result<ExitCode> {
1257 use htl::pkg::mlua_pkg::ops::CleanReport;
1258 let project = pkg_project()?;
1259 match project.clean(all)? {
1260 CleanReport::CacheRemoved => eprintln!("htl pkg clean: removed every cached package"),
1261 CleanReport::NoLockfile => {
1262 eprintln!("htl pkg clean: no lockfile, so nothing was ever cached")
1263 }
1264 CleanReport::StaleRemoved { removed: 0 } => eprintln!("htl pkg clean: nothing to remove"),
1265 CleanReport::StaleRemoved { removed } => eprintln!(
1266 "htl pkg clean: removed {removed} cache entr{} the lockfile no longer refers to",
1267 if removed == 1 { "y" } else { "ies" }
1268 ),
1269 }
1270 Ok(ExitCode::SUCCESS)
1271}
1272
1273fn report_patch_drift(project: &htl::pkg::Project) {
1282 let short = |s: &str| s.chars().take(7).collect::<String>();
1283 for s in project.patch_status() {
1284 if s.in_use {
1285 continue;
1286 }
1287 let rel = s
1288 .dir
1289 .strip_prefix(&project.root)
1290 .unwrap_or(&s.dir)
1291 .display();
1292 let why = match (&s.base, &s.locked) {
1293 _ if !s.dir.is_dir() => "the copy is not there".to_string(),
1294 (None, _) => "the lockfile records no revision it was taken from".to_string(),
1295 (Some(b), Some(l)) => {
1296 format!("taken from {}, {} is now at {}", short(b), s.name, short(l))
1297 }
1298 (Some(b), None) => format!("taken from {}, and nothing is locked", short(b)),
1299 };
1300 eprintln!(" patch {rel} is not in use ({why})");
1301 eprintln!(
1302 " carry the change forward: commit it, then `htl pkg patch {}`",
1303 s.name
1304 );
1305 eprintln!(" drop it: remove patch_dir from mlua-pkg.toml and delete {rel}");
1306 }
1307}
1308
1309fn cmd_pkg_patch(dep: &str, force: bool) -> Result<ExitCode> {
1314 let cwd = std::env::current_dir()?;
1315 let project = htl::pkg::Project::find(&cwd).context(
1316 "no mlua-pkg.toml above the current directory: a patch belongs to a project, so this runs in one",
1317 )?;
1318 let done = project.patch(dep, force)?;
1319 let report = &done.report;
1320 let rel = report
1321 .patch_dir
1322 .strip_prefix(&project.root)
1323 .unwrap_or(&report.patch_dir);
1324 let verb = if report.created { "patched" } else { "rebuilt" };
1325 let base: String = report.base.chars().take(7).collect();
1326 eprintln!(" {verb} {} ({dep} at {base})", rel.display());
1327 if !done.dropped.is_empty() {
1331 eprintln!(
1332 " dropped {} (the repository's, not the package's)",
1333 done.dropped.join(", ")
1334 );
1335 }
1336 eprintln!("htl: it is the project's code now — edit it, commit it, then `htl pkg install`.");
1337 Ok(ExitCode::SUCCESS)
1338}
1339
1340fn report_types_sync(sync: &htl::pkg::TypesSync, root: &Path) {
1344 let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).display().to_string();
1345 for (path, dep) in &sync.written {
1346 eprintln!(" types {} (from {dep})", rel(path));
1347 }
1348 for (path, dep) in &sync.taken {
1349 eprintln!(" kept {} ({dep} publishes one too)", rel(path));
1350 }
1351}
1352
1353fn cmd_types_add(library: &str, from: Option<&Path>, force: bool) -> Result<ExitCode> {
1357 let cwd = std::env::current_dir()?;
1358 let project = htl::pkg::Project::find(&cwd).context(
1359 "no mlua-pkg.toml above the current directory: `types/` is a project's, so this runs in one",
1360 )?;
1361 let sync = match from {
1362 Some(dir) => project.add_types_from(dir, library, "local", force)?,
1363 None => project.add_types(library, force)?,
1364 };
1365 report_types_sync(&sync, &project.root);
1366 if sync.written.is_empty() && !sync.taken.is_empty() {
1367 eprintln!("htl: nothing written; --force replaces what is already there");
1368 }
1369 Ok(ExitCode::SUCCESS)
1370}
1371
1372struct UnusedFlags {
1374 json: bool,
1375 fail_on_unused: bool,
1378 use_cache: bool,
1379 explain: bool,
1380}
1381
1382struct CheckFlags {
1384 strict: bool,
1385 list_lints: bool,
1386 json: bool,
1387 use_cache: bool,
1388 cache_mode: Option<cache::Mode>,
1389 explain: bool,
1390}
1391
1392struct TestFlags {
1393 fail_fast: bool,
1394 verbose: bool,
1395 quiet: bool,
1396 slow: Option<f64>,
1397 update: bool,
1398 coverage: bool,
1399 coverage_lines: bool,
1400 lcov: Option<PathBuf>,
1402 junit: Option<PathBuf>,
1404 json: bool,
1405 no_cache: bool,
1406 explain: bool,
1407 seed: Option<u64>,
1408}
1409
1410fn print_coverage(cov: &report::CoverageReport, with_lines: bool) {
1411 let width = cov
1412 .modules
1413 .iter()
1414 .map(|m| m.path.len())
1415 .max()
1416 .unwrap_or(4)
1417 .max(5);
1418 for m in &cov.modules {
1419 eprintln!(
1420 "coverage: {:<width$} {:>5}/{:<5} {:5.1}%",
1421 m.path,
1422 m.executed,
1423 m.total,
1424 100.0 * m.executed as f64 / m.total as f64
1425 );
1426 if !m.never_ran.is_empty() {
1427 let names: Vec<String> = m
1428 .never_ran
1429 .iter()
1430 .map(|f| format!("{} ({})", f.name, f.line))
1431 .collect();
1432 eprintln!(" never ran: {}", names.join(", "));
1433 }
1434 if with_lines && !m.unexecuted.is_empty() {
1435 let spans: Vec<String> = m
1436 .unexecuted
1437 .iter()
1438 .map(|(a, b)| {
1439 if a == b {
1440 a.to_string()
1441 } else {
1442 format!("{a}-{b}")
1443 }
1444 })
1445 .collect();
1446 eprintln!(" unexecuted: {}", spans.join(", "));
1447 }
1448 }
1449 if cov.total > 0 {
1450 eprintln!(
1451 "coverage: {:<width$} {:>5}/{:<5} {:5.1}% (statements; code run inside coroutines is not seen)",
1452 "total",
1453 cov.executed,
1454 cov.total,
1455 100.0 * cov.executed as f64 / cov.total as f64
1456 );
1457 } else {
1458 eprintln!("coverage: no .tl module reached");
1459 }
1460}
1461
1462fn junit_suite(rep: &htl::testing::FileReport) -> junit::Suite {
1470 let mut left: Vec<&str> = rep.failures.iter().map(String::as_str).collect();
1471 let cases = rep
1472 .tests
1473 .iter()
1474 .map(|t| {
1475 let failure = (!t.ok)
1476 .then(|| {
1477 let head = format!("{}: ", t.name);
1478 let at = left.iter().position(|m| m.starts_with(&head))?;
1479 Some(left.remove(at)[head.len()..].to_string())
1480 })
1481 .flatten();
1482 junit::Case {
1483 name: t.name.clone(),
1484 ms: t.ms,
1485 failure: failure.or_else(|| (!t.ok).then(|| "failed".to_string())),
1488 }
1489 })
1490 .collect();
1491 let error = if !rep.check.ok() {
1492 Some(junit::Error {
1493 message: "type check failed".to_string(),
1494 kind: "check",
1495 body: rep.check.errors.join("\n"),
1496 })
1497 } else {
1498 rep.error.as_ref().map(|e| junit::Error {
1499 message: e.clone(),
1500 kind: "error",
1501 body: e.clone(),
1502 })
1503 };
1504 junit::Suite {
1505 file: rep.path.display().to_string(),
1506 duration_ms: rep.duration_ms,
1507 error,
1508 cases,
1509 }
1510}
1511
1512fn cmd_test(
1513 paths: &[PathBuf],
1514 filter: Option<&str>,
1515 lib: &str,
1516 lint: Option<&str>,
1517 flags: TestFlags,
1518) -> Result<ExitCode> {
1519 let paths = if paths.is_empty() {
1520 vec![PathBuf::from(".")]
1521 } else {
1522 paths.to_vec()
1523 };
1524 if let Some(first) = paths.first() {
1525 auto_dts(first)?;
1526 }
1527 let files = htl::testing::discover_tests_skipping(&paths, &project::patched(&paths))?;
1531 if files.is_empty() {
1532 eprintln!("htl test: no test files found (looked for *_test.tl and tests/**/*.tl)");
1533 return Ok(ExitCode::FAILURE);
1534 }
1535 let cfg = load_config(&paths[0])?;
1536 let opts = project::TestOptions {
1537 config: &cfg,
1538 lint,
1539 lib,
1540 filter,
1541 run: htl::testing::RunOptions {
1542 fail_fast: flags.fail_fast,
1543 update_snapshots: flags.update,
1544 coverage: flags.coverage,
1545 seed: flags.seed,
1547 },
1548 cache: project::cache_options(
1549 !flags.no_cache,
1550 Some(cache::Mode::PerModule),
1551 &cfg,
1552 flags.explain,
1553 ),
1554 };
1555
1556 let mut sink = project::Sink::new(report::Out::new(flags.json));
1557 let mut json_files: Vec<report::TestFile> = Vec::new();
1558 let mut junit_suites: Vec<junit::Suite> = Vec::new();
1559 let rep = project::test(&mut sink, &files, &opts, &mut |rep, sink| {
1563 if flags.json {
1564 json_files.push(report::TestFile::from_report(rep, sink.out().take()));
1565 }
1566 if flags.junit.is_some() {
1567 junit_suites.push(junit_suite(rep));
1568 }
1569 let f = &rep.path;
1570 let tag = if rep.ok() { "ok " } else { "FAIL" };
1571 let detail = if !rep.check.ok() {
1572 "type check failed".to_string()
1573 } else if let Some(e) = &rep.error {
1574 format!("error: {}", e.lines().next().unwrap_or_default())
1577 } else if rep.file_level {
1578 "ran to completion (no test library used)".to_string()
1579 } else {
1580 format!("{} passed, {} failed", rep.passed, rep.failed)
1581 };
1582 let show_file = !flags.json && (!flags.quiet || !rep.ok());
1585 if show_file {
1586 eprintln!(
1587 "{tag} {} ({detail}, {:.0} ms)",
1588 f.display(),
1589 rep.duration_ms
1590 );
1591 if let Some(e) = &rep.error {
1592 for line in e.lines().skip(1) {
1593 eprintln!(" {line}");
1594 }
1595 }
1596 }
1597 for tr in &rep.tests {
1598 let slow = flags.slow.is_some_and(|ms| tr.ms >= ms);
1599 if !flags.json && (flags.verbose || slow) {
1600 if flags.quiet && !show_file {
1601 eprintln!("slow {} {} ({:.1} ms)", f.display(), tr.name, tr.ms);
1603 continue;
1604 }
1605 let mark = if tr.ok { "ok " } else { "FAIL" };
1606 let note = if slow && !flags.verbose {
1607 " [slow]"
1608 } else {
1609 ""
1610 };
1611 eprintln!(" {mark} {} ({:.1} ms){note}", tr.name, tr.ms);
1612 }
1613 }
1614 if !flags.json {
1615 for m in &rep.failures {
1616 eprintln!(" - {m}");
1617 }
1618 for p in &rep.snapshots_written {
1620 eprintln!("snapshot written: {p}");
1621 }
1622 for p in &rep.snapshots_updated {
1623 eprintln!("snapshot updated: {p}");
1624 }
1625 }
1626 })?;
1627
1628 if let Some(out) = &flags.junit {
1629 std::fs::write(out, junit::document(&junit_suites, rep.duration_ms))
1632 .with_context(|| format!("writing {}", out.display()))?;
1633 }
1634 if let (Some(out), Some(cov)) = (&flags.lcov, &rep.coverage) {
1635 let root = match &cfg {
1638 Some((dir, _, _)) => dir.clone(),
1639 None => std::env::current_dir()?,
1640 };
1641 let root = std::fs::canonicalize(&root).unwrap_or(root);
1642 std::fs::write(out, cov.lcov(&root))
1643 .with_context(|| format!("writing {}", out.display()))?;
1644 }
1645 let ok = rep.ok();
1646 if flags.json {
1647 let summary = report::TestSummary {
1648 files: rep.files.len(),
1649 files_run: rep.ran,
1650 passed: rep.passed,
1651 failed: rep.failed,
1652 files_with_errors: rep.files_with_errors,
1653 replayed: rep.replayed,
1654 duration_ms: rep.duration_ms,
1655 ok,
1656 seed: rep.seed,
1657 };
1658 report::emit(&report::TestReport {
1659 files: json_files,
1660 summary,
1661 coverage: rep.coverage,
1662 })?;
1663 } else {
1664 if let Some(cov) = &rep.coverage {
1665 print_coverage(cov, flags.coverage_lines);
1666 if let Some(out) = &flags.lcov {
1667 eprintln!("coverage: lcov written to {}", out.display());
1668 }
1669 }
1670 eprintln!(
1671 "htl test: {} file(s), {} passed, {} failed, {} file(s) with errors{}{} ({:.0} ms)",
1672 rep.ran,
1673 rep.passed,
1674 rep.failed,
1675 rep.files_with_errors,
1676 if rep.skipped() > 0 {
1677 format!(", {} file(s) not run (--fail-fast)", rep.skipped())
1678 } else {
1679 String::new()
1680 },
1681 if rep.replayed > 0 {
1683 format!(", {} checked from cache", rep.replayed)
1684 } else {
1685 String::new()
1686 },
1687 rep.duration_ms
1688 );
1689 eprintln!(
1692 "htl test: seed {} (repeat with --seed {})",
1693 rep.seed, rep.seed
1694 );
1695 }
1696 Ok(if ok {
1697 ExitCode::SUCCESS
1698 } else {
1699 ExitCode::FAILURE
1700 })
1701}
1702
1703fn report_patched(paths: &[PathBuf]) {
1709 let roots: Vec<PathBuf> = paths
1710 .iter()
1711 .filter_map(|p| std::fs::canonicalize(p).ok())
1712 .collect();
1713 let cwd = std::env::current_dir().unwrap_or_default();
1714 let Some(project) = paths.first().and_then(|p| htl::pkg::Project::find(p)) else {
1715 return;
1716 };
1717 for p in &project.patches {
1718 let canon = std::fs::canonicalize(&p.dir).unwrap_or_else(|_| p.dir.clone());
1719 if !roots.iter().any(|r| canon.starts_with(r)) {
1720 continue;
1721 }
1722 let shown = p.dir.strip_prefix(&cwd).unwrap_or(&p.dir);
1723 eprintln!(" patched {} ({})", shown.display(), p.name);
1724 }
1725}
1726
1727fn load_config(first: &Path) -> Result<project::Config> {
1739 let cfg = project::config_of(first)?;
1740 if let Some((_, path, c)) = &cfg {
1741 htl::config::check_toolchain(c, path, env!("CARGO_PKG_VERSION"))?;
1742 }
1743 Ok(cfg)
1744}
1745
1746fn warn_cargo_htl_mismatch(first: &Path) {
1773 let Some(root) = htl::dts::find_cargo_package_root(first) else {
1774 return;
1775 };
1776 let Ok(text) = fs::read_to_string(root.join("Cargo.toml")) else {
1777 return;
1778 };
1779 let Ok(manifest) = text.parse::<toml::Table>() else {
1780 return;
1781 };
1782 let Some(dep) = manifest.get("dependencies").and_then(|d| d.get("htl")) else {
1783 return;
1784 };
1785 let req_text = match dep {
1786 toml::Value::String(s) => s.as_str(),
1787 toml::Value::Table(t) => match t.get("version").and_then(toml::Value::as_str) {
1788 Some(s) => s,
1789 None => return,
1790 },
1791 _ => return,
1792 };
1793 let running = env!("CARGO_PKG_VERSION");
1794 let (Ok(req), Ok(version)) = (
1795 semver::VersionReq::parse(req_text),
1796 semver::Version::parse(running),
1797 ) else {
1798 return;
1799 };
1800 if req.matches(&version) {
1801 return;
1802 }
1803 eprintln!(
1806 "htl {running}; Cargo.toml asks for htl {req_text} — the crate and the CLI are \
1807 meant to move together (cargo install htl-cli --version {req_text}, or bump the \
1808 dependency)"
1809 );
1810}
1811
1812fn cmd_fmt(paths: &[PathBuf], check: bool, indent: Option<usize>) -> Result<ExitCode> {
1813 let paths = if paths.is_empty() {
1814 vec![PathBuf::from(".")]
1815 } else {
1816 paths.to_vec()
1817 };
1818 let cfg = load_config(&paths[0])?;
1819 let indent = indent
1820 .or_else(|| cfg.as_ref().and_then(|(_, _, c)| c.fmt.indent))
1821 .unwrap_or(3);
1822 let h = Htl::new()?;
1823 let files = htl::collect_tl_skipping(&paths, &project::patched(&paths))?;
1827 let (mut changed, mut failed) = (0usize, 0usize);
1828 for f in &files {
1829 let before = fs::read_to_string(f).with_context(|| format!("reading {}", f.display()))?;
1830 let after = match h.format_file(f, indent) {
1831 Ok(s) => s,
1832 Err(e) => {
1833 eprintln!("error: {e}");
1834 failed += 1;
1835 continue;
1836 }
1837 };
1838 if after != before {
1839 changed += 1;
1840 if check {
1841 eprintln!("would reformat: {}", f.display());
1842 } else {
1843 fs::write(f, after).with_context(|| format!("writing {}", f.display()))?;
1844 eprintln!("reformatted: {}", f.display());
1845 }
1846 }
1847 }
1848 eprintln!(
1849 "htl fmt: {} file(s), {} {}, {} failed",
1850 files.len(),
1851 changed,
1852 if check { "would change" } else { "reformatted" },
1853 failed
1854 );
1855 let fail = failed > 0 || (check && changed > 0);
1856 Ok(if fail {
1857 ExitCode::FAILURE
1858 } else {
1859 ExitCode::SUCCESS
1860 })
1861}
1862
1863struct FixFlags {
1864 rule: Vec<String>,
1865 unsafe_fixes: bool,
1866 dry_run: bool,
1867 diff: bool,
1868 allow_dirty: bool,
1869 allow_no_vcs: bool,
1870 exit_non_zero_on_fix: bool,
1871 json: bool,
1872}
1873
1874fn cmd_fix(paths: &[PathBuf], flags: FixFlags) -> Result<ExitCode> {
1875 use htl::fix::{FixOptions, fix_file, git_dirty, unified_diff};
1876 let paths = if paths.is_empty() {
1877 vec![PathBuf::from(".")]
1878 } else {
1879 paths.to_vec()
1880 };
1881 let h = Htl::new()?;
1882 let cfg = load_config(&paths[0])?;
1883 let file_spec = cfg
1884 .as_ref()
1885 .map(|(_, _, c)| c.lint_spec())
1886 .unwrap_or_default();
1887 if !file_spec.is_empty() {
1888 h.configure_lints(&file_spec)?;
1889 }
1890 if let Some(first) = paths.first() {
1891 auto_dts(first)?;
1892 apply_project(&h, first)?;
1893 }
1894 if let Some((root, _, c)) = &cfg {
1895 h.apply_config(root, c)?;
1896 }
1897 h.install_test_lib()?;
1898 h.install_std()?;
1899 let opts = FixOptions {
1900 unsafe_fixes: flags.unsafe_fixes,
1901 promoted: cfg
1902 .as_ref()
1903 .map(|(_, _, c)| c.fix.unsafe_.clone())
1904 .unwrap_or_default(),
1905 disabled: cfg
1906 .as_ref()
1907 .map(|(_, _, c)| c.fix.disable.clone())
1908 .unwrap_or_default(),
1909 only: flags.rule.clone(),
1910 dry_run: flags.dry_run,
1911 };
1912 opts.validate()?;
1915 let files = htl::collect_tl(&paths)?;
1916
1917 if !flags.dry_run {
1919 let mut dirty = Vec::new();
1920 let mut no_vcs = Vec::new();
1921 for f in &files {
1922 match git_dirty(f)? {
1923 Some(true) => dirty.push(f.clone()),
1924 Some(false) => {}
1925 None => no_vcs.push(f.clone()),
1926 }
1927 }
1928 if !dirty.is_empty() && !flags.allow_dirty {
1929 bail!(
1930 "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",
1931 dirty
1932 .iter()
1933 .map(|p| p.display().to_string())
1934 .collect::<Vec<_>>()
1935 .join("\n ")
1936 );
1937 }
1938 if !no_vcs.is_empty() && !flags.allow_no_vcs {
1939 bail!(
1940 "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",
1941 no_vcs
1942 .iter()
1943 .map(|p| p.display().to_string())
1944 .collect::<Vec<_>>()
1945 .join("\n ")
1946 );
1947 }
1948 }
1949
1950 let mut sink = project::Sink::new(report::Out::new(flags.json));
1951 let fix_root = cfg
1955 .as_ref()
1956 .map(|(r, _, _)| r.clone())
1957 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
1958 let contracts = match &cfg {
1959 Some((r, _, c)) => htl::contract::resolve(r, c).0,
1960 None => Vec::new(),
1961 };
1962 let origins = project::Origins::new(&paths[0], &fix_root, &cfg, &contracts);
1963 sink.walking(&files);
1964 let (mut applied, mut skipped, mut json_files) = (Vec::new(), Vec::new(), Vec::new());
1965 let (mut changed, mut deferred, mut reverted, mut errors_remaining) =
1966 (0usize, 0usize, 0usize, 0usize);
1967 for f in &files {
1968 h.add_layout_paths(f)?;
1969 let before = if flags.diff {
1970 std::fs::read_to_string(f).ok()
1971 } else {
1972 None
1973 };
1974 let out = fix_file(&h, f, &opts)?;
1975 if out.contents.is_some() {
1976 changed += 1;
1977 }
1978 deferred += out.deferred;
1979 if out.reverted.is_some() {
1980 reverted += 1;
1981 }
1982 errors_remaining += out.check.errors.len();
1983 if !flags.json {
1984 for a in &out.applied {
1985 eprintln!(
1986 "fixed: {}:{}: {} ({}{})",
1987 f.display(),
1988 a.line,
1989 a.rule,
1990 a.applicability.as_str(),
1991 if flags.dry_run { ", not written" } else { "" }
1992 );
1993 }
1994 for s in &out.skipped {
1995 eprintln!(
1996 "skipped: {}:{}: {} — {}",
1997 f.display(),
1998 s.line,
1999 s.rule,
2000 s.reason
2001 );
2002 }
2003 if let Some(r) = &out.reverted {
2004 eprintln!("reverted: {}: {r}", f.display());
2005 }
2006 if let Some(o) = &out.oscillation {
2007 eprintln!("stopped: {}: fixes of {o} undo each other", f.display());
2008 }
2009 if out.deferred > 0 {
2010 eprintln!(
2011 "deferred: {}: {} edit(s) overlapped applied ones; run htl fix again",
2012 f.display(),
2013 out.deferred
2014 );
2015 }
2016 if flags.diff
2017 && let (Some(b), Some(a)) = (&before, &out.contents)
2018 {
2019 print!("{}", unified_diff(&f.display().to_string(), b, a));
2020 }
2021 if flags.diff
2024 && let (Some(b), Some(s)) = (
2025 out.contents.as_ref().or(before.as_ref()),
2026 out.suggested.as_ref(),
2027 )
2028 {
2029 print!(
2030 "{}",
2031 unified_diff(&format!("{} (suggested)", f.display()), b, s)
2032 );
2033 }
2034 }
2035 sink.checkinfo(&out.check);
2036 sink.dependency_errors(&out.check, &|p| origins.of(p));
2037 if flags.json {
2038 applied.extend(out.applied.iter().map(|a| report::FixApplied {
2039 file: f.display().to_string(),
2040 line: a.line,
2041 rule: a.rule.clone(),
2042 applicability: a.applicability.as_str(),
2043 pass: a.pass,
2044 }));
2045 skipped.extend(out.skipped.iter().map(|s| report::FixSkipped {
2046 file: f.display().to_string(),
2047 line: s.line,
2048 rule: s.rule.clone(),
2049 reason: s.reason.clone(),
2050 }));
2051 json_files.push(report::FixFile {
2052 path: f.display().to_string(),
2053 changed: out.contents.is_some(),
2054 deferred: out.deferred,
2055 reverted: out.reverted.clone(),
2056 oscillation: out.oscillation.clone(),
2057 diagnostics: sink.out().take(),
2058 });
2059 }
2060 }
2061 errors_remaining += sink.dependency_error_count();
2064 let n_applied = if flags.json { applied.len() } else { 0 };
2065 let fail = errors_remaining > 0 || (flags.exit_non_zero_on_fix && changed > 0);
2066 if flags.json {
2067 let n_skipped = skipped.len();
2068 report::emit(&report::FixReport {
2069 dry_run: flags.dry_run,
2070 applied,
2071 skipped,
2072 files: json_files,
2073 summary: report::FixSummary {
2074 files: files.len(),
2075 files_changed: changed,
2076 applied: n_applied,
2077 skipped: n_skipped,
2078 deferred,
2079 reverted,
2080 errors_remaining,
2081 ok: !fail,
2082 },
2083 })?;
2084 } else {
2085 eprintln!(
2086 "htl fix: {} file(s), {} changed{}, {} error(s) remaining{}",
2087 files.len(),
2088 changed,
2089 if flags.dry_run {
2090 " (dry run, nothing written)"
2091 } else {
2092 ""
2093 },
2094 errors_remaining,
2095 if deferred > 0 {
2096 format!(", {deferred} deferred")
2097 } else {
2098 String::new()
2099 }
2100 );
2101 }
2102 Ok(if fail {
2103 ExitCode::FAILURE
2104 } else {
2105 ExitCode::SUCCESS
2106 })
2107}
2108
2109fn cmd_check(paths: &[PathBuf], lint: Option<&str>, flags: CheckFlags) -> Result<ExitCode> {
2121 let CheckFlags {
2122 list_lints,
2123 json,
2124 use_cache,
2125 cache_mode,
2126 explain,
2127 ..
2128 } = flags;
2129 let mut sink = project::Sink::new(report::Out::new(json));
2130 let paths = if paths.is_empty() {
2131 vec![PathBuf::from(".")]
2132 } else {
2133 paths.to_vec()
2134 };
2135 if list_lints {
2140 let width = htl::lint::rule_names()
2145 .iter()
2146 .map(|r| r.len())
2147 .max()
2148 .unwrap_or(0);
2149 for (name, level) in htl::lint::rule_defaults() {
2150 println!("{name:width$} {level}");
2151 }
2152 return Ok(ExitCode::SUCCESS);
2153 }
2154 let cfg = load_config(&paths[0])?;
2156 warn_cargo_htl_mismatch(&paths[0]);
2157 let strict = flags.strict
2158 || cfg
2159 .as_ref()
2160 .and_then(|(_, _, c)| c.lint.strict)
2161 .unwrap_or(false);
2162 if let Some(first) = paths.first() {
2166 auto_dts(first)?;
2167 }
2168 let files = htl::collect_tl(&paths)?;
2173 if !json {
2174 report_patched(&paths);
2175 }
2176
2177 let rep = project::check(
2181 &mut sink,
2182 &files,
2183 &project::Options {
2184 paths: &paths,
2185 config: &cfg,
2186 lint,
2187 cache: project::cache_options(use_cache, cache_mode, &cfg, explain),
2188 },
2189 )?;
2190 let fail = report_check(
2191 sink.out(),
2192 json,
2193 &rep,
2194 strict,
2195 patched_files(&paths, &rep.files),
2196 )?;
2197 Ok(if fail {
2198 ExitCode::FAILURE
2199 } else {
2200 ExitCode::SUCCESS
2201 })
2202}
2203
2204fn cmd_unused(paths: &[PathBuf], flags: UnusedFlags) -> Result<ExitCode> {
2211 let UnusedFlags {
2212 json,
2213 fail_on_unused,
2214 use_cache,
2215 explain,
2216 } = flags;
2217 let paths = if paths.is_empty() {
2218 vec![PathBuf::from(".")]
2219 } else {
2220 paths.to_vec()
2221 };
2222 let cfg = load_config(&paths[0])?;
2223 auto_dts(&paths[0])?;
2226 let rep = htl::unused::unused(&htl::unused::Options {
2227 paths: &paths,
2228 config: &cfg,
2229 cache: project::cache_options(use_cache, None, &cfg, explain),
2230 })?;
2231 let s = &rep.summary;
2232 if json {
2233 report::emit(&rep)?;
2234 } else if s.no_entry {
2235 eprintln!(
2236 "htl unused: nothing to start from, so nothing is reported. An entry is \
2237 src/main.tl, a test file, a module under a [[contract]] directory, or a name \
2238 in [build] extra / host"
2239 );
2240 } else {
2241 if s.check_errors > 0 {
2242 eprintln!(
2243 "htl unused: {} error(s) in the check this graph comes from — what those \
2244 files require is missing from it (htl check)",
2245 s.check_errors
2246 );
2247 }
2248 for m in &rep.modules {
2249 match &m.module {
2250 Some(n) => eprintln!("module: {} ({n})", m.path),
2251 None => eprintln!("module: {}", m.path),
2252 }
2253 }
2254 for d in &rep.dependencies {
2255 eprintln!("dependency: {}", d.name);
2256 }
2257 eprintln!(
2258 "htl unused: {}, {} [{} considered, {} reached, {}]",
2259 count(s.modules, "module", "modules"),
2260 count(s.dependencies, "dependency", "dependencies"),
2261 s.considered,
2262 s.reached,
2263 count(s.entries, "entry", "entries"),
2264 );
2265 }
2266 Ok(if fail_on_unused && !s.ok {
2267 ExitCode::FAILURE
2268 } else {
2269 ExitCode::SUCCESS
2270 })
2271}
2272
2273fn cmd_resolve(module: &str, path: Option<&Path>, json: bool) -> Result<ExitCode> {
2282 let start = path.unwrap_or(Path::new("."));
2283 let cfg = load_config(start)?;
2284 auto_dts(start)?;
2288 let h = Htl::new()?;
2289 h.install_std()?;
2292 let project = apply_project(&h, start)?;
2293 if let Some((root, _, c)) = &cfg {
2294 h.apply_config(root, c)?;
2295 }
2296 let rep = htl::resolve::resolve(
2297 &h,
2298 module,
2299 cfg.as_ref().map(|(r, _, _)| r.as_path()),
2300 project.as_ref(),
2301 )?;
2302 if json {
2303 report::emit(&rep)?;
2304 } else {
2305 print_resolution(&rep);
2306 }
2307 Ok(if rep.summary.ok {
2308 ExitCode::SUCCESS
2309 } else {
2310 ExitCode::FAILURE
2311 })
2312}
2313
2314fn print_resolution(r: &htl::resolve::Resolution) {
2318 match &r.read {
2319 Some(read) => println!("htl resolve {}: {read}", r.module),
2320 None => println!(
2321 "htl resolve {}: nothing on the search path answers require(\"{}\")",
2322 r.module, r.module
2323 ),
2324 }
2325 if !r.candidates.is_empty() {
2326 let w = |f: fn(&htl::resolve::Candidate) -> usize, head: usize| {
2327 r.candidates.iter().map(f).max().unwrap_or(0).max(head)
2328 };
2329 let file = w(|c| c.path.len(), 4);
2330 let kind = w(|c| c.kind.as_str().len(), 4);
2331 let read_at = r
2332 .candidates
2333 .iter()
2334 .find(|c| c.status == htl::resolve::Status::Read)
2335 .map(|c| c.order);
2336 println!();
2337 println!(" order {:file$} {:kind$} status", "file", "kind");
2338 for c in &r.candidates {
2339 let status = match (c.status, c.shadowed_by, read_at) {
2340 (htl::resolve::Status::Shadowed, Some(by), _) => format!("shadowed by {by}"),
2341 (htl::resolve::Status::Runtime, _, Some(by)) => format!("runtime, typed by {by}"),
2343 (s, _, _) => s.as_str().to_string(),
2344 };
2345 let origin = match &c.origin {
2346 Some(o) => format!(" ({})", o.describe()),
2347 None => String::new(),
2348 };
2349 println!(
2350 " {:<5} {:file$} {:kind$} {status}{origin}",
2351 c.order,
2352 c.path,
2353 c.kind.as_str()
2354 );
2355 }
2356 }
2357 println!();
2358 println!(" searched, in order: {}", r.searched.join(", "));
2359}
2360
2361fn count(n: usize, one: &str, many: &str) -> String {
2364 format!("{n} {}", if n == 1 { one } else { many })
2365}
2366
2367fn cmd_cache_clear(path: Option<&Path>) -> Result<ExitCode> {
2377 let start = path.unwrap_or(Path::new("."));
2378 let root = load_config(start)?
2379 .map(|(r, _, _)| r)
2380 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
2381 let dir = root.join(".htl").join("cache");
2382 if !dir.is_dir() {
2383 eprintln!("htl cache: nothing stored at {}", dir.display());
2384 return Ok(ExitCode::SUCCESS);
2385 }
2386 let n = fs::read_dir(&dir)
2387 .map(|rd| {
2388 rd.flatten()
2389 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
2390 .count()
2391 })
2392 .unwrap_or(0);
2393 fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
2394 eprintln!(
2395 "htl cache: removed {n} {} from {}",
2396 if n == 1 { "entry" } else { "entries" },
2397 dir.display()
2398 );
2399 Ok(ExitCode::SUCCESS)
2400}
2401
2402fn cache_root(path: Option<&Path>) -> Result<PathBuf> {
2404 let start = path.unwrap_or(Path::new("."));
2405 Ok(cache::root_for(start)
2406 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))))
2407}
2408
2409fn cmd_cache_status(path: Option<&Path>, json: bool, list_entries: bool) -> Result<ExitCode> {
2415 let c = cache::describe(&cache_root(path)?);
2416 if json {
2417 report::emit(&c)?;
2418 return Ok(ExitCode::SUCCESS);
2419 }
2420
2421 if c.entries.is_empty() {
2422 println!("htl cache: empty ({})", c.dir);
2423 return Ok(ExitCode::SUCCESS);
2424 }
2425 let mut by_kind: std::collections::BTreeMap<&str, (usize, u64)> = Default::default();
2426 for e in &c.entries {
2427 let slot = by_kind.entry(e.kind.as_str()).or_default();
2428 slot.0 += 1;
2429 slot.1 += e.bytes;
2430 }
2431 println!(
2432 "htl cache: {} entries, {} at {}",
2433 c.entries.len(),
2434 human_bytes(c.bytes),
2435 c.dir
2436 );
2437 for (kind, (n, bytes)) in &by_kind {
2438 let what = match *kind {
2439 cache::CHECK => "checked modules",
2440 cache::GEN => "checked and generated test files (htl test)",
2441 cache::MODULE => "generated modules (htl test / build, include_bundle!)",
2442 cache::RUN => "whole runs",
2443 _ => "entries this build cannot read",
2444 };
2445 println!(" {n:>5} {what} ({})", human_bytes(*bytes));
2446 }
2447 if let (Some(min), Some(max)) = (
2448 c.entries.iter().map(|e| e.age_secs).min(),
2449 c.entries.iter().map(|e| e.age_secs).max(),
2450 ) {
2451 println!(
2452 " last used between {} and {} ago",
2453 human_age(min),
2454 human_age(max)
2455 );
2456 }
2457 if list_entries {
2458 println!();
2459 for e in &c.entries {
2460 println!(
2461 " {:<6} {:>8} {}",
2462 e.kind,
2463 human_bytes(e.bytes),
2464 e.subjects.join(", ")
2465 );
2466 }
2467 }
2468 Ok(ExitCode::SUCCESS)
2469}
2470
2471fn human_bytes(n: u64) -> String {
2472 if n >= 1 << 20 {
2473 format!("{:.1} MB", n as f64 / (1u64 << 20) as f64)
2474 } else if n >= 1 << 10 {
2475 format!("{:.0} KB", n as f64 / (1u64 << 10) as f64)
2476 } else {
2477 format!("{n} B")
2478 }
2479}
2480
2481fn human_age(secs: u64) -> String {
2482 match secs {
2483 s if s < 90 => format!("{s}s"),
2484 s if s < 5400 => format!("{}m", s / 60),
2485 s if s < 172_800 => format!("{}h", s / 3600),
2486 s => format!("{}d", s / 86_400),
2487 }
2488}
2489
2490fn patched_files(paths: &[PathBuf], files: &[PathBuf]) -> usize {
2499 let dirs: Vec<PathBuf> = project::patched(paths)
2500 .into_iter()
2501 .map(|d| fs::canonicalize(&d).unwrap_or(d))
2502 .collect();
2503 if dirs.is_empty() {
2504 return 0;
2505 }
2506 files
2507 .iter()
2508 .filter(|f| {
2509 let f = fs::canonicalize(f).unwrap_or_else(|_| (*f).to_path_buf());
2510 dirs.iter().any(|d| f.starts_with(d))
2511 })
2512 .count()
2513}
2514
2515fn report_check(
2524 out: &mut report::Out,
2525 json: bool,
2526 rep: &project::Report,
2527 strict: bool,
2528 patched: usize,
2529) -> Result<bool> {
2530 let (files, replayed) = (rep.files.len(), rep.replayed);
2531 let (errors, warnings, lints) = (rep.errors, rep.warnings, rep.lints);
2532 let fail = rep.failed(strict);
2533 let all_cached = rep.all_cached();
2534 if json {
2535 report::emit(&report::CheckReport {
2536 files,
2537 patched,
2538 diagnostics: out.take(),
2539 summary: report::CheckSummary {
2540 errors,
2541 warnings,
2542 lints,
2543 denied: rep.denied,
2544 strict,
2545 ok: !fail,
2546 cached: all_cached,
2547 replayed,
2548 },
2549 })?;
2550 } else {
2551 let cached = if all_cached {
2553 " [cached]".to_string()
2554 } else if replayed > 0 {
2555 format!(" [{replayed}/{files} cached]")
2556 } else {
2557 String::new()
2558 };
2559 let denied = match rep.denied {
2564 0 => String::new(),
2565 n => format!(", {n} at deny"),
2566 };
2567 let counted = match patched {
2571 0 => format!("{files} file(s)"),
2572 n => format!("{} file(s) + {n} in patched dependencies", files - n),
2573 };
2574 eprintln!(
2575 "htl check: {counted}, {errors} error(s), {warnings} warning(s), {lints} lint(s){denied}{}{cached}",
2576 if strict { " [strict]" } else { "" }
2577 );
2578 }
2579 Ok(fail)
2580}
2581
2582fn cmd_gen(file: &Path, out: Option<&Path>) -> Result<ExitCode> {
2583 let h = Htl::new()?;
2584 h.add_layout_paths(file)?;
2585 auto_dts(file)?;
2586 apply_project(&h, file)?;
2587 h.install_std()?;
2588 let (code, c) = h.gen_lua(file)?;
2589 text_sink().checkinfo(&c);
2590 let Some(mut code) = code else {
2591 return Ok(ExitCode::FAILURE);
2592 };
2593 if !code.ends_with('\n') {
2594 code.push('\n');
2595 }
2596 match out {
2597 Some(p) => fs::write(p, code).with_context(|| format!("writing {}", p.display()))?,
2598 None => print!("{code}"),
2599 }
2600 Ok(ExitCode::SUCCESS)
2601}
2602
2603fn cmd_run(file: &Path, args: &[String]) -> Result<ExitCode> {
2604 let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
2605 let h = Htl::new()?;
2606 auto_dts(file)?;
2607 apply_project(&h, file)?;
2608 h.install_test_lib()?;
2609 h.install_std()?;
2610 if Bundle::is_bundle(&bytes) {
2611 let b = Bundle::decode(&bytes)?;
2612 return Ok(match h.run_bundle(&b, args) {
2613 Ok(()) => ExitCode::SUCCESS,
2614 Err(e) => {
2615 eprintln!("{}", htl::developer_message(&e));
2618 ExitCode::FAILURE
2619 }
2620 });
2621 }
2622 h.add_layout_paths(file)?;
2624 h.install_searcher()?;
2625 h.set_arg(&file.to_string_lossy(), args)?;
2626 let (code, c) = h.gen_lua(file)?;
2627 text_sink().checkinfo(&c);
2628 let Some(code) = code else {
2629 return Ok(ExitCode::FAILURE);
2630 };
2631 match h.exec(&code, &format!("@{}", file.display()), args) {
2632 Ok(()) => Ok(ExitCode::SUCCESS),
2633 Err(e) => {
2634 eprintln!("{}", htl::developer_message(&e));
2638 Ok(ExitCode::FAILURE)
2639 }
2640 }
2641}
2642
2643struct BuildCache {
2648 use_cache: bool,
2649 explain: bool,
2650}
2651
2652fn cmd_build(
2653 entry: &Path,
2654 out: &Path,
2655 main: &str,
2656 mut opts: htl::link::LinkOptions,
2657 cache_flags: BuildCache,
2658) -> Result<ExitCode> {
2659 let h = Htl::new()?;
2660 auto_dts(entry)?;
2661 apply_project(&h, entry)?;
2662 h.install_std()?;
2666 let cfg = load_config(entry)?;
2667 if let Some((root, _, cfg)) = &cfg {
2668 h.apply_config(root, cfg)?;
2669 opts.extra.extend(cfg.build.extra.iter().cloned());
2670 opts.host.extend(cfg.build.host.iter().cloned());
2671 if let Some(t) = cfg.build.target.filter(|t| *t != BuildTarget::Hb) {
2677 eprintln!(
2678 "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.",
2679 t.name(),
2680 t.runs_it()
2681 );
2682 return Ok(ExitCode::FAILURE);
2683 }
2684 }
2685 if entry.is_dir() {
2686 if cache_flags.explain {
2687 eprintln!("htl cache: the directory form of `htl build` is not cached");
2688 }
2689 return cmd_build_dir(&h, entry, out, main, &opts);
2690 }
2691 h.add_layout_paths(entry)?;
2692 let root = cache::root_for(entry)
2698 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
2699 let spec = cfg
2700 .as_ref()
2701 .map(|(_, _, c)| c.lint_spec())
2702 .unwrap_or_default();
2703 let lint = (!spec.is_empty()).then_some(spec.as_str());
2704 let cache_opts = project::cache_options(
2705 cache_flags.use_cache,
2706 Some(cache::Mode::PerModule),
2707 &cfg,
2708 cache_flags.explain,
2709 );
2710 let store = project::store(&root, cache_opts, None, "htl build");
2711 let link_store = store.as_ref().map(|c| htl::link::LinkStore {
2712 cache: c,
2713 lint,
2714 root: &root,
2715 config: cfg.as_ref().map(|(_, p, c)| (p.as_path(), c)),
2716 });
2717 let linked = htl::link::link_with(&h, entry, &opts, link_store)?;
2718 project::explain_cache(store.as_ref(), cache_opts);
2719 let mut sink = text_sink();
2722 for (_, c) in &linked.checks {
2723 sink.checkinfo(c);
2724 }
2725 let n_err = linked.errors.len();
2726 for e in linked
2727 .errors
2728 .iter()
2729 .filter(|e| e.contains("is not on the search path"))
2730 {
2731 eprintln!("error: {e}");
2732 }
2733 if n_err > 0 {
2734 eprintln!("htl build: {n_err} error(s), bundle not written");
2735 return Ok(ExitCode::FAILURE);
2736 }
2737 let buf = linked.bundle()?.encode();
2738 fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
2739 let typed = linked.modules.iter().filter(|m| m.typed).count();
2740 let cached = if typed > 0 && linked.cached == typed {
2743 " [cached]".to_string()
2744 } else if linked.cached > 0 {
2745 format!(" [{}/{typed} cached]", linked.cached)
2746 } else {
2747 String::new()
2748 };
2749 eprintln!(
2750 "htl build: {} module(s) ({typed} typed, {} lua) -> {} ({} bytes{}{}){cached}",
2751 linked.modules.len(),
2752 linked.modules.len() - typed,
2753 out.display(),
2754 buf.len(),
2755 if opts.source {
2756 ", source"
2757 } else {
2758 ", bytecode"
2759 },
2760 if opts.debug { " with debug info" } else { "" }
2761 );
2762 if !linked.host_modules.is_empty() {
2763 eprintln!(
2764 "htl build: host must provide: {}",
2765 linked.host_modules.join(", ")
2766 );
2767 }
2768 Ok(ExitCode::SUCCESS)
2769}
2770
2771fn cmd_build_dir(
2773 h: &Htl,
2774 dir: &Path,
2775 out: &Path,
2776 entry: &str,
2777 opts: &htl::link::LinkOptions,
2778) -> Result<ExitCode> {
2779 h.add_path(dir)?;
2780 let files = htl::collect_tl(&[dir.to_path_buf()])?;
2781 let mut b = Bundle {
2782 entry: entry.to_string(),
2783 htl_version: env!("CARGO_PKG_VERSION").into(),
2784 ..Default::default()
2785 };
2786 let mut n_err = 0usize;
2787 let mut sink = text_sink();
2788 for f in &files {
2789 let name = htl::module_name(dir, f)?;
2790 let (code, c) = h.gen_lua(f)?;
2791 sink.checkinfo(&c);
2792 n_err += c.errors.len();
2793 let Some(code) = code else { continue };
2794 let (kind, payload) = if opts.source {
2795 (htl::bundle::Kind::Source, code.into_bytes())
2796 } else {
2797 (
2798 htl::bundle::Kind::Bytecode,
2799 h.compile_with(&name, &code, !opts.debug)?,
2800 )
2801 };
2802 b.modules.push(htl::bundle::Module {
2803 name,
2804 kind,
2805 payload,
2806 });
2807 }
2808 if n_err > 0 {
2809 eprintln!("htl build: {n_err} error(s), bundle not written");
2810 return Ok(ExitCode::FAILURE);
2811 }
2812 if b.module(entry).is_none() {
2813 bail!(
2814 "entry module '{entry}' not found among {} module(s)",
2815 b.modules.len()
2816 );
2817 }
2818 if !opts.source {
2819 b.fingerprint = h.fingerprint()?;
2820 }
2821 let buf = b.encode();
2822 fs::write(out, &buf).with_context(|| format!("writing {}", out.display()))?;
2823 eprintln!(
2824 "htl build: {} module(s) -> {} ({} bytes)",
2825 b.modules.len(),
2826 out.display(),
2827 buf.len()
2828 );
2829 Ok(ExitCode::SUCCESS)
2830}
2831
2832#[derive(serde::Serialize)]
2837struct BundleInfo {
2838 file: String,
2839 format: u8,
2840 htl_version: Option<String>,
2841 payload: &'static str,
2843 lua: Option<htl::bundle::LuaHeader>,
2844 entry: String,
2845 modules: Vec<BundleModuleInfo>,
2846 host_modules: Vec<String>,
2847}
2848
2849#[derive(serde::Serialize)]
2850struct BundleModuleInfo {
2851 name: String,
2852 kind: &'static str,
2853 bytes: usize,
2854}
2855
2856fn cmd_bundle_info(file: &Path, json: bool) -> Result<ExitCode> {
2857 let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
2858 let Some(format) = htl::bundle::format_version(&bytes) else {
2859 bail!("{} is not an htl bundle (bad magic)", file.display());
2860 };
2861 let b = Bundle::decode(&bytes)?;
2862 let kind_name = |k: htl::bundle::Kind| match k {
2863 htl::bundle::Kind::Bytecode => "bytecode",
2864 htl::bundle::Kind::Source => "source",
2865 };
2866 let payload = match (
2867 b.modules
2868 .iter()
2869 .any(|m| m.kind == htl::bundle::Kind::Bytecode),
2870 b.modules
2871 .iter()
2872 .any(|m| m.kind == htl::bundle::Kind::Source),
2873 ) {
2874 (true, true) => "mixed",
2875 (false, true) => "source",
2876 _ => "bytecode",
2878 };
2879 let info = BundleInfo {
2880 file: file.display().to_string(),
2881 format,
2882 htl_version: (!b.htl_version.is_empty()).then(|| b.htl_version.clone()),
2883 payload,
2884 lua: htl::bundle::LuaHeader::parse(&b.fingerprint),
2885 entry: b.entry.clone(),
2886 modules: b
2887 .modules
2888 .iter()
2889 .map(|m| BundleModuleInfo {
2890 name: m.name.clone(),
2891 kind: kind_name(m.kind),
2892 bytes: m.payload.len(),
2893 })
2894 .collect(),
2895 host_modules: b.host_modules.clone(),
2896 };
2897 if json {
2898 report::emit(&info)?;
2899 return Ok(ExitCode::SUCCESS);
2900 }
2901
2902 println!(
2903 "{}: htl bundle, format {}, built by {}",
2904 info.file,
2905 info.format,
2906 match &info.htl_version {
2907 Some(v) => format!("htl {v}"),
2908 None => "htl (version not recorded)".to_string(),
2909 }
2910 );
2911 println!(" payload: {}", info.payload);
2912 let lua = match &info.lua {
2913 Some(h) => h.to_string(),
2914 None if !b.fingerprint.is_empty() => {
2915 format!("unreadable fingerprint ({} bytes)", b.fingerprint.len())
2916 }
2917 None if info.format == 1 => {
2918 "not recorded (a format 1 bundle carries no fingerprint)".into()
2919 }
2920 None => "any (source payload, no bytecode to bind)".into(),
2921 };
2922 println!(" lua: {lua}");
2923 println!(" entry: {}", info.entry);
2924 let modules: Vec<String> = info
2925 .modules
2926 .iter()
2927 .map(|m| {
2928 if info.payload == "mixed" {
2929 format!("{} ({})", m.name, m.kind)
2930 } else {
2931 m.name.clone()
2932 }
2933 })
2934 .collect();
2935 println!(
2936 " modules: {}",
2937 if modules.is_empty() {
2938 "(none)".to_string()
2939 } else {
2940 modules.join(", ")
2941 }
2942 );
2943 println!(
2944 " host: {}",
2945 if info.host_modules.is_empty() {
2946 "(none)".to_string()
2947 } else {
2948 info.host_modules.join(", ")
2949 }
2950 );
2951 Ok(ExitCode::SUCCESS)
2952}