use anyhow::{Context, Result, anyhow, bail};
use htl::BuildTarget;
use std::path::{Path, PathBuf};
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HtlPin {
Release(String),
Main,
Path(PathBuf),
}
const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
const HTLX_REPOSITORY: &str = "https://github.com/ynishi/htl-x";
pub const HTLX_TAG: &str = "v0.1.0";
const PIN_DEFAULT: &str = env!("HTL_PIN_DEFAULT");
const PIN_CHECKOUT: &str = env!("HTL_PIN_CHECKOUT");
impl Default for HtlPin {
fn default() -> Self {
match PIN_DEFAULT {
"release" => HtlPin::Release(env!("CARGO_PKG_VERSION").to_string()),
"main" => HtlPin::Main,
"path" => HtlPin::Path(PathBuf::from(PIN_CHECKOUT)),
other => unreachable!("build.rs wrote HTL_PIN_DEFAULT={other}"),
}
}
}
impl HtlPin {
pub fn parse(s: Option<&str>) -> Result<HtlPin> {
let Some(s) = s else {
return Ok(HtlPin::default());
};
if s == "main" {
return Ok(HtlPin::Main);
}
if let Some(dir) = s.strip_prefix("path:") {
if dir.is_empty() {
bail!("`path:` names no checkout directory; {}", accepted());
}
return Ok(HtlPin::Path(PathBuf::from(dir)));
}
bail!(
"unsupported htl `{s}`; {}. A project for a published release is written by that release's CLI: cargo install htl-cli --version {s}",
accepted()
);
}
#[allow(dead_code)]
pub fn requirement(&self) -> String {
dep_value(&self.keys(), &[])
}
fn keys(&self) -> Vec<(&'static str, String)> {
self.keys_for("htl")
}
fn keys_for(&self, crate_name: &str) -> Vec<(&'static str, String)> {
match self {
HtlPin::Release(v) => vec![("version", v.clone())],
HtlPin::Main => vec![
("git", REPOSITORY.to_string()),
("branch", "main".to_string()),
],
HtlPin::Path(root) => vec![(
"path",
format!(
"{}/crates/{crate_name}",
root.display()
.to_string()
.replace('\\', "/")
.trim_end_matches('/')
),
)],
}
}
}
fn accepted() -> String {
format!(
"--htl takes `main` or `path:<checkout>`, and without it a project pins the htl this CLI was built with ({})",
HtlPin::default().requirement()
)
}
pub struct Options {
pub lib: bool,
pub target: Option<&'static TargetProfile>,
pub htl: HtlPin,
pub no_x: bool,
}
impl Options {
pub fn writes_htlx(&self) -> bool {
!self.no_x
}
}
pub struct Ctx<'a> {
pub name: &'a str,
pub module: &'a str,
pub script: bool,
pub htlx: bool,
}
pub struct DepLine {
pub name: &'static str,
pub req: Dep,
pub features: &'static [&'static str],
}
impl DepLine {
const fn plain(name: &'static str, req: Dep) -> Self {
DepLine {
name,
req,
features: &[],
}
}
}
pub enum Dep {
Htl,
Sibling(&'static str),
Version(&'static str),
}
pub struct ScaffoldFile {
pub path: &'static str,
pub body: fn(&Ctx<'_>) -> String,
}
pub struct TealSample {
pub module: fn(&Ctx<'_>) -> String,
pub test: fn(&Ctx<'_>) -> String,
pub main: fn(&Ctx<'_>) -> String,
}
pub struct TargetProfile {
pub target: BuildTarget,
pub deps: &'static [DepLine],
pub lib: ScaffoldFile,
pub main: Option<ScaffoldFile>,
pub extra: &'static [ScaffoldFile],
pub ignore: &'static [&'static str],
pub teal: TealSample,
pub readme_commands: fn(&Ctx<'_>) -> String,
pub readme_prose: fn(&Ctx<'_>) -> String,
}
const BIN: TargetProfile = TargetProfile {
target: BuildTarget::Bin,
deps: &[
DepLine::plain("htl", Dep::Htl),
DepLine::plain("anyhow", Dep::Version("1")),
],
lib: ScaffoldFile {
path: "src/lib.rs",
body: rust_lib_rs,
},
main: Some(ScaffoldFile {
path: "src/main.rs",
body: rust_main_rs,
}),
extra: &[],
ignore: &["/target"],
teal: TealSample {
module: teal_module,
test: teal_test,
main: rust_main_tl,
},
readme_commands: rust_readme_commands,
readme_prose: rust_readme_prose,
};
const CDYLIB: TargetProfile = TargetProfile {
target: BuildTarget::Cdylib,
deps: &[
DepLine {
name: "htl",
req: Dep::Htl,
features: &["ffi"],
},
DepLine::plain("anyhow", Dep::Version("1")),
DepLine {
name: "serde",
req: Dep::Version("1"),
features: &["derive"],
},
],
lib: ScaffoldFile {
path: "src/lib.rs",
body: ffi_lib_rs,
},
main: None,
extra: &[
ScaffoldFile {
path: "examples/c/main.c",
body: ffi_example_c,
},
ScaffoldFile {
path: "examples/c/Makefile",
body: ffi_example_makefile,
},
ScaffoldFile {
path: "examples/python/run.py",
body: ffi_example_py,
},
],
ignore: &["/target", "examples/c/{{mod}}_c"],
teal: TealSample {
module: ffi_teal_module,
test: ffi_teal_test,
main: teal_main,
},
readme_commands: ffi_readme_commands,
readme_prose: ffi_readme_prose,
};
const WINDOW: TargetProfile = TargetProfile {
target: BuildTarget::Window,
deps: &[
DepLine::plain("htl", Dep::Htl),
DepLine::plain("htl-mq", Dep::Sibling("htl-mq")),
DepLine::plain("anyhow", Dep::Version("1")),
],
lib: ScaffoldFile {
path: "src/lib.rs",
body: window_lib_rs,
},
main: Some(ScaffoldFile {
path: "src/main.rs",
body: window_main_rs,
}),
extra: &[],
ignore: &["/target"],
teal: TealSample {
module: window_teal_module,
test: window_teal_test,
main: window_main_tl,
},
readme_commands: window_readme_commands,
readme_prose: window_readme_prose,
};
pub static PROFILES: &[TargetProfile] = &[BIN, CDYLIB, WINDOW];
pub const DEFAULT_TARGET: BuildTarget = BuildTarget::Bin;
static DEFAULT_TEAL: TealSample = TealSample {
module: teal_module,
test: teal_test,
main: teal_main,
};
const T_MANIFEST: &str = include_str!("../templates/mlua-pkg.toml");
const T_TEAL_MODULE: &str = include_str!("../templates/teal/init.tl");
const T_TEAL_TEST: &str = include_str!("../templates/teal/test.tl");
const T_TEAL_MAIN: &str = include_str!("../templates/teal/main.tl");
const T_RUST_MAIN_TL: &str = include_str!("../templates/rust/main.tl");
const T_RUST_LIB_RS: &str = include_str!("../templates/rust/lib.rs");
const T_RUST_MAIN_RS: &str = include_str!("../templates/rust/main.rs");
const T_FFI_LIB_RS: &str = include_str!("../templates/ffi/lib.rs");
const T_FFI_TEAL_MODULE: &str = include_str!("../templates/ffi/init.tl");
const T_FFI_TEAL_TEST: &str = include_str!("../templates/ffi/test.tl");
const T_FFI_MAIN_C: &str = include_str!("../templates/ffi/main.c");
const T_FFI_MAKEFILE: &str = include_str!("../templates/ffi/Makefile");
const T_FFI_RUN_PY: &str = include_str!("../templates/ffi/run.py");
const T_WINDOW_LIB_RS: &str = include_str!("../templates/window/lib.rs");
const T_WINDOW_MAIN_RS: &str = include_str!("../templates/window/main.rs");
const T_WINDOW_TEAL_MODULE: &str = include_str!("../templates/window/init.tl");
const T_WINDOW_TEAL_TEST: &str = include_str!("../templates/window/test.tl");
const T_WINDOW_MAIN_TL: &str = include_str!("../templates/window/main.tl");
pub fn module_ident(name: &str) -> String {
let mut s: String = name
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
if s.chars().next().is_some_and(|c| c.is_ascii_digit()) {
s.insert(0, '_');
}
s
}
const RUST_KEYWORDS: &[&str] = &[
"Self", "abstract", "as", "async", "await", "become", "box", "break", "const", "continue",
"crate", "do", "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "if", "impl",
"in", "let", "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref",
"return", "self", "static", "struct", "super", "trait", "true", "try", "type", "typeof",
"unsafe", "unsized", "use", "virtual", "where", "while", "yield",
];
const RUST_KEYWORDS_BEYOND_CARGO: &[&str] = &["gen"];
const LUA_KEYWORDS: &[&str] = &[
"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in",
"local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while",
];
const TEAL_TYPE_WORDS: &[&str] = &["record", "enum", "interface"];
fn refuse_reserved_name(name: &str, module: &str, writes_cargo: bool) -> Result<()> {
if writes_cargo {
if RUST_KEYWORDS.contains(&name) {
bail!("{}", rust_refusal(name, module, "it is a Rust keyword"));
}
if RUST_KEYWORDS_BEYOND_CARGO.contains(&name) {
bail!(
"{}",
rust_refusal(
name,
module,
"it is a keyword reserved by Rust's 2024 edition, which is the edition this scaffold writes"
)
);
}
if name.starts_with(|c: char| c.is_ascii_digit()) {
bail!(
"{}",
rust_refusal(name, module, "the name cannot start with a digit")
);
}
if let Some(ch) = name
.chars()
.find(|c| !(c.is_ascii_alphanumeric() || *c == '-' || *c == '_'))
{
bail!(
"{}",
rust_refusal(
name,
module,
&format!(
"invalid character `{ch}`: the name has to be ASCII letters, digits, `-` and `_`"
)
)
);
}
}
if LUA_KEYWORDS.contains(&module) {
bail!("{}", teal_refusal(name, module, "it is a Lua keyword"));
}
if TEAL_TYPE_WORDS.contains(&module) {
bail!(
"{}",
teal_refusal(name, module, "it is how Teal opens a type declaration")
);
}
Ok(())
}
fn rust_refusal(name: &str, module: &str, reason: &str) -> String {
format!(
"invalid project name `{name}`: {reason}; a project with a target is a crate named after it and a host that preloads its module through that name (`{module}::preload`), so what cargo or rustc refuses here is a project that does not build — scaffold it under another name"
)
}
fn teal_refusal(name: &str, module: &str, reason: &str) -> String {
format!(
"invalid project name `{name}`: {reason}; the scaffold binds the module to a local of that name (`local {module} = require(\"{module}\")`) and declares a record called it, so the project it would write does not check — scaffold it under another name"
)
}
pub fn target_names() -> Vec<&'static str> {
PROFILES.iter().map(|p| p.target.name()).collect()
}
pub fn profile(t: BuildTarget) -> Option<&'static TargetProfile> {
PROFILES.iter().find(|p| p.target == t)
}
pub fn resolve_target(
target: Option<&str>,
embed: bool,
lib: bool,
) -> Result<Option<&'static TargetProfile>> {
let t = match (target, embed) {
(None, false) => return Ok(None),
(None, true) => DEFAULT_TARGET,
(Some(n), true) if n != DEFAULT_TARGET.name() => bail!(
"--embed is the shorthand for --target {DEFAULT_TARGET}, so it cannot be given with --target {n}; drop one of them"
),
(Some(n), _) => BuildTarget::from_str(n).map_err(|e| anyhow!("{e}"))?,
};
let Some(p) = profile(t) else {
bail!(
"the `{t}` target is what plain `htl new` writes, so there is no scaffold to ask for; targets that scaffold: {}",
target_names().join(", ")
);
};
if !p.target.entry().accepts(lib) {
bail!("{}", script_mismatch(p, lib));
}
Ok(Some(p))
}
fn script_mismatch(p: &TargetProfile, lib: bool) -> String {
let fits: Vec<&str> = PROFILES
.iter()
.filter(|c| c.target.entry().accepts(lib))
.map(|c| c.target.name())
.collect();
let fits = if fits.is_empty() {
"none".to_string()
} else {
fits.join(", ")
};
if lib {
format!(
"the `{}` target runs an entry script, which --lib leaves out; targets that work with --lib: {fits}",
p.target
)
} else {
format!(
"the `{}` target writes no entry script, so it needs --lib; targets that write one: {fits}",
p.target
)
}
}
fn plan(dir: &Path, name: &str, module: &str, opts: &Options) -> Vec<(PathBuf, String)> {
let ctx = Ctx {
name,
module,
script: !opts.lib,
htlx: opts.writes_htlx(),
};
let target = opts.target;
let teal = target.map_or(&DEFAULT_TEAL, |t| &t.teal);
let mut files = vec![
(dir.join("mlua-pkg.toml"), t_manifest(&ctx)),
(dir.join("htl.toml"), t_htl_toml(target.map(|t| t.target))),
(dir.join("types").join("README.md"), t_types_readme()),
(
dir.join("src").join(module).join("init.tl"),
(teal.module)(&ctx),
),
(
dir.join("tests").join(format!("{module}_test.tl")),
(teal.test)(&ctx),
),
(dir.join(".gitignore"), t_gitignore(target, &ctx)),
(dir.join("README.md"), t_readme(&ctx, target)),
];
if let Some(m) = t_mise(&opts.htl) {
files.push((dir.join("mise.toml"), m));
}
if !opts.lib {
files.push((dir.join("src").join("main.tl"), (teal.main)(&ctx)));
}
if let Some(t) = target {
files.push((dir.join("Cargo.toml"), t_cargo(name, t, &opts.htl)));
files.push((dir.join(t.lib.path), (t.lib.body)(&ctx)));
if !opts.lib
&& let Some(m) = &t.main
{
files.push((dir.join(m.path), (m.body)(&ctx)));
}
for f in t.extra {
files.push((dir.join(f.path), (f.body)(&ctx)));
}
}
files
}
pub struct Scaffolded {
pub written: Vec<PathBuf>,
pub kept: Vec<PathBuf>,
}
pub fn scaffold(dir: &Path, name: &str, opts: &Options, must_be_new: bool) -> Result<Scaffolded> {
if must_be_new && dir.exists() && dir.read_dir()?.next().is_some() {
bail!(
"{} already exists and is not empty (use `htl init` to fill in a directory)",
dir.display()
);
}
let m = module_ident(name);
refuse_reserved_name(name, &m, opts.target.is_some())?;
let mut out = Scaffolded {
written: Vec::new(),
kept: Vec::new(),
};
for (path, text) in plan(dir, name, &m, opts) {
if path.exists() {
out.kept.push(path);
continue;
}
if let Some(p) = path.parent() {
std::fs::create_dir_all(p)?;
}
std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
out.written.push(path);
}
Ok(out)
}
fn fill(template: &str, ctx: &Ctx<'_>) -> String {
template
.replace("{{name}}", ctx.name)
.replace("{{mod}}", ctx.module)
.replace("{{MOD}}", &ctx.module.to_uppercase())
}
fn t_manifest(ctx: &Ctx<'_>) -> String {
let base = fill(T_MANIFEST, ctx);
if !ctx.htlx {
return base;
}
let line = format!("htlx = {{ git = \"{HTLX_REPOSITORY}\", tag = \"{HTLX_TAG}\" }}\n");
base.replace("[deps]\n", &format!("[deps]\n{line}"))
}
fn teal_module(ctx: &Ctx<'_>) -> String {
fill(T_TEAL_MODULE, ctx)
}
fn teal_test(ctx: &Ctx<'_>) -> String {
fill(T_TEAL_TEST, ctx)
}
fn teal_main(ctx: &Ctx<'_>) -> String {
fill(T_TEAL_MAIN, ctx)
}
fn rust_main_tl(ctx: &Ctx<'_>) -> String {
fill(T_RUST_MAIN_TL, ctx)
}
fn rust_lib_rs(ctx: &Ctx<'_>) -> String {
fill(T_RUST_LIB_RS, ctx)
}
fn rust_main_rs(ctx: &Ctx<'_>) -> String {
fill(T_RUST_MAIN_RS, ctx)
}
fn ffi_lib_rs(ctx: &Ctx<'_>) -> String {
fill(T_FFI_LIB_RS, ctx)
}
fn ffi_teal_module(ctx: &Ctx<'_>) -> String {
fill(T_FFI_TEAL_MODULE, ctx)
}
fn ffi_teal_test(ctx: &Ctx<'_>) -> String {
fill(T_FFI_TEAL_TEST, ctx)
}
fn ffi_example_c(ctx: &Ctx<'_>) -> String {
fill(T_FFI_MAIN_C, ctx)
}
fn ffi_example_makefile(ctx: &Ctx<'_>) -> String {
fill(T_FFI_MAKEFILE, ctx)
}
fn ffi_example_py(ctx: &Ctx<'_>) -> String {
fill(T_FFI_RUN_PY, ctx)
}
fn window_lib_rs(ctx: &Ctx<'_>) -> String {
fill(T_WINDOW_LIB_RS, ctx)
}
fn window_main_rs(ctx: &Ctx<'_>) -> String {
fill(T_WINDOW_MAIN_RS, ctx)
}
fn window_teal_module(ctx: &Ctx<'_>) -> String {
fill(T_WINDOW_TEAL_MODULE, ctx)
}
fn window_teal_test(ctx: &Ctx<'_>) -> String {
fill(T_WINDOW_TEAL_TEST, ctx)
}
fn window_main_tl(ctx: &Ctx<'_>) -> String {
fill(T_WINDOW_MAIN_TL, ctx)
}
fn t_types_readme() -> String {
"# types/\n\n\
Hand-written `.d.tl` declarations for modules the host provides at run time and\n\
that ship no declaration of their own (a Rust crate re-exported to Lua, a runtime\n\
SDK): `xlib.d.tl` here makes `require(\"xlib\")` typed in `htl check`, `htl test` and\n\
`include_tl!`. Consulted after the project root and `src/`, before `[check] paths`;\n\
a `.tl` source anywhere on the path beats a declaration, so nothing here can shadow\n\
an implementation, and a second declaration of the same module is reported\n\
(`duplicate-declaration`) rather than silently losing to one of them.\n\n\
Files htl writes here are the ones the project *publishes*: the module a\n\
`---@contract` type is declared in, for the authors of the modules that contract\n\
holds. Declarations generated from this crate's own Rust (`#[host_module]`) are\n\
written next to the scripts, not here. Both are committed.\n\n\
So is `<crate>/`, when there is one: a dependency that names its declarations in\n\
`[package.metadata.htl] dts` has them copied there by `htl dts` (and by check / run\n\
/ test). Edit the crate, not the copy — the next run writes it again.\n"
.to_string()
}
fn t_htl_toml(target: Option<BuildTarget>) -> String {
let mut s = String::from(
"# htl project settings (htl check / htl test / htl fmt / include_tl! all read this).\n\
# Command-line flags and HTL_LINTS / HTL_LINT override it.\n\n\
[lint]\n\
# strict = true # warnings and lints fail htl check (not htl test); lints fail\n\
# include_tl!; false makes the macro advisory\n\n\
# Per rule: htl check --list-lints names every rule with the level it has by\n\
# default, and the README's \"Lints\" section says how to change one.\n\n\
[fmt]\n\
indent = 3\n\n\
[check]\n\
# paths = [\"mods\"] # extra dirs require() resolves from while checking\n\
# (src/ and types/ are always searched; hand-written .d.tl go under types/)\n\n\
# Where this project accepts modules written outside it:\n\
# [[contract]]\n\
# dir = \"mods\" # relative to this file; \"sites/*\" = each subdirectory\n\
# module = \"Site\" # optional: only this module name in each dir\n\
#\n\
# The shape those modules must have is declared on the record itself, so the two\n\
# cannot drift apart:\n\
#\n\
# local record defs\n\
# record Mod ---@contract -- inherits `dir` above;\n\
# name: string ---@required -- ---@contract(\"other\") overrides it\n\
# monsters: {Monster} ---@required\n\
# factions: {Faction} -- unmarked: for the mods that want it\n\
# end\n\
# end\n\
#\n\
# The host must enforce it too: htl::pkg::contract_resolvers(root, &config).\n\
# `htl check` reports `contract-unenforced` when that call is not in the Rust sources.\n\
# enforced_by = \"mods/_validate.lua\" # ...or name where it is enforced instead,\n\
# # for a Lua-side validator, a sibling crate, generated\n\
# # code. The file has to exist; a missing one is reported.\n",
);
if let Some(t) = target {
s.push_str(&format!(
"\n[build]\n\
# What runs this project's output: hb (the htl binary, the default when absent), bin,\n\
# cdylib, window. Written by htl new --target; see README \"Build targets\".\n\
target = \"{t}\"\n"
));
}
s
}
fn t_mise(pin: &HtlPin) -> Option<String> {
let HtlPin::Release(v) = pin else {
return None;
};
Some(format!(
"# The htl this project was written by. mise (https://mise.jdx.dev) reads this file:\n\
# `mise install` puts that release on PATH here, whatever `htl` is elsewhere.\n\
[tools]\n\
\"cargo:htl-cli\" = \"{v}\"\n"
))
}
fn t_gitignore(target: Option<&'static TargetProfile>, ctx: &Ctx<'_>) -> String {
let mut s = String::from(".htl/\n*.hb\n");
for line in target.into_iter().flat_map(|t| t.ignore) {
s.push_str(&fill(line, ctx));
s.push('\n');
}
s
}
fn t_readme(ctx: &Ctx<'_>, target: Option<&'static TargetProfile>) -> String {
let (name, m) = (ctx.name, ctx.module);
let mut s = format!(
"# {name}\n\nTeal project managed with [htl](https://github.com/ynishi/htl).\n\n```sh\n"
);
if ctx.htlx {
s.push_str("htl pkg install # fetch [deps] from mlua-pkg.toml — first, htlx is one of them\n");
}
s.push_str("htl check . # type-check + lints\n");
if ctx.script && target.is_none() {
s.push_str("htl run src/main.tl # run the entry script\n");
}
s.push_str("htl test # tests/*_test.tl via htl.test\nhtl fmt . # whitespace formatter\n");
if !ctx.htlx {
s.push_str("htl pkg install # fetch [deps] from mlua-pkg.toml\n");
}
if let Some(t) = target {
s.push_str(&(t.readme_commands)(ctx));
}
s.push_str(&format!(
"```\n\nModule: `src/{m}/init.tl` (`require(\"{m}\")` from `src/` and `tests/`).\n\n"
));
if ctx.htlx {
s.push_str(&format!(
"`htlx` ([htl-x]({HTLX_REPOSITORY}) {HTLX_TAG}) is a dependency from the start: the collections\n\
Lua does not have — `htlx.list` over arrays, `htlx.tablex` over maps, `htlx.seq` over\n\
iterators, `htlx.ordered` for insertion-ordered maps and sets — as `require(\"htlx.list\")`\n\
and the rest, once `htl pkg install` has run. Drop the line from `mlua-pkg.toml` if it\n\
is not wanted (`htl new --no-x` writes the project without it).\n"
));
s.push('\n');
}
s.push_str(&format!(
"`mlua-pkg.toml` `entry = \"src/{m}\"` only matters to *consumers* that depend on this\n\
package through mlua-pkg: they get it as `require(\"{name}\")`. "
));
match target {
Some(t) => s.push_str(&(t.readme_prose)(ctx)),
None => s.push_str("Ignore it if nobody depends on this package.\n"),
}
s
}
fn rust_readme_commands(ctx: &Ctx<'_>) -> String {
let mut s = String::new();
if ctx.script {
s.push_str("cargo run # the binary: preload, then src/main.tl (type-checked at build)\n");
s.push_str(" # (src/main.tl requires the Rust `host`, so `htl run` cannot run it)\n");
}
s.push_str(
"cargo test # the library's Rust test: the module loaded through preload\n",
);
s
}
fn rust_readme_prose(ctx: &Ctx<'_>) -> String {
let mut s = String::from(
"The Rust host is a library:\n`src/lib.rs` holds the `#[host_module]`, embeds this module, and registers both in\n\
`preload(&Htl)`. ",
);
if ctx.script {
s.push_str(
"`src/main.rs` is a few lines on top of it — `preload`, then the entry\nscript. Grow the library, not the binary.\n\n",
);
} else {
s.push_str(
"There is no binary: call `preload` from whatever embeds this\ncrate, and grow the library.\n\n",
);
}
s.push_str(HOST_DTL);
s
}
const HOST_DTL: &str = "`src/host.d.tl` is generated from `#[host_module]` in `src/lib.rs`: `cargo build` writes it,\n\
and so does `htl dts` / `htl check` without building, so the Teal side always sees the\n\
current Rust signatures.\n";
fn ffi_readme_commands(ctx: &Ctx<'_>) -> String {
format!(
"cargo test # the library's Rust tests: preload, and the generated header\n\
cargo build # the library, and include/{}.h from #[c_export]\n\
make -C examples/c run # the C caller (after cargo build)\n\
python3 examples/python/run.py # the Python caller, the same round trip\n",
ctx.module
)
}
fn ffi_readme_prose(ctx: &Ctx<'_>) -> String {
let m = ctx.module;
let mut s = String::from(
"This project is a library with two boundaries:\n\
`src/lib.rs` holds the `#[host_module]` the *scripts* call and the `#[c_export]` block a\n\
*caller that is not written in Rust* calls. There is no binary — a C ABI library has no\n\
entry point of its own, which is why `--target cdylib` implies `--lib`.\n\n",
);
s.push_str(HOST_DTL);
s.push_str(&format!(
"\n## The C ABI\n\n\
`cargo build` writes `include/{m}.h` from the same `impl` block, and leaves\n\
`target/debug/lib{m}.{{so,dylib,dll}}` for a caller to load and `lib{m}.a` to link\n\
statically (Unity on iOS wants the latter). Commit the header: it is generated, and so is\n\
`src/host.d.tl`, and both are what someone reads without building this crate.\n\n\
Everything that crosses is an opaque `{m}_handle *`, a `char *` this library allocated,\n\
or an `int`. Three rules cover the whole ABI:\n\n\
- **Every `char *` returned is yours to free**, with `{m}_free()` and nothing else. The\n\
call that produced it is not finished until you do.\n\
- **An `int` is a status, never a value** (`{}_OK` and friends, in the header). A call\n\
that has both writes the value through an `int *out`.\n\
- **One handle, one thread.** Using it from another answers `WRONG_THREAD`; the exception\n\
is `{m}_interrupt()`, which any thread may call to stop a runaway script.\n\n\
A failed call answers `NULL` or a status, and `{m}_last_error()` is the message —\n\
a pointer valid until the next call *on that thread*, so copy it (or use\n\
`{m}_last_error_into()`) rather than keeping it.\n\n\
`examples/c/` and `examples/python/` are two callers doing the same round trip: open,\n\
a text call, a JSON call, the two error paths, `free`, close. Each is written the way its\n\
own language gets this wrong by default — see the comment at the top of both.\n",
m.to_uppercase()
));
s
}
fn window_readme_commands(_ctx: &Ctx<'_>) -> String {
String::from(
"cargo run # the window; Esc quits\n\
HTL_MQ_FRAMES=60 HTL_MQ_SHOT=out.png cargo run # sixty frames, then a PNG\n\
cargo test # the engine's Rust test: the module loaded through preload\n",
)
}
fn window_readme_prose(ctx: &Ctx<'_>) -> String {
let m = ctx.module;
let mut s = format!(
"This project is a library, a binary and an engine:\n\
`src/lib.rs` holds `fx` — the project's own `#[host_module]`, for what wants the GPU —\n\
embeds the Teal engine, and registers both (plus htl-mq's `mq`) in `preload(&Htl)`.\n\
`src/main.rs` opens the window and hands `htl_mq::run` the game table, and `src/main.tl`\n\
is that table: `update(dt)` says whether to go on, `draw()` draws.\n\n\
`src/{m}/init.tl` is the engine, and it is where the game goes. It takes its world as\n\
arguments and never opens anything, so `htl test` runs it with no display: `require(\"mq\")`\n\
resolves to the declaration, which declares and does nothing. `render` is the one function\n\
that draws, and nothing in the engine calls it — the loop does.\n\n\
Effects go into `fx`, beside `mq` rather than inside the engine: `mq` is macroquad's\n\
drawing and input as htl-mq ships it, and `fx` is this project's, drawing with the same\n\
macroquad through `htl_mq::macroquad`. A new one is a method on `Fx` and a line in\n\
`render`.\n\n"
);
s.push_str(
"`src/fx.d.tl` is generated from `#[host_module]` in `src/lib.rs`: `cargo build` writes it,\n\
and so does `htl dts` / `htl check` without building, so the Teal side always sees the\n\
current Rust signatures. `types/htl-mq/mq.d.tl` is the same file for the dependency's `mq`,\n\
copied in from the crate by `htl check`. Commit both; the next run writes them again.\n\n\
`cargo build` reads `types/htl-mq/mq.d.tl` — `include_bundle!` links `mq` against it — so\n\
`htl check .` comes first in a fresh clone.\n",
);
s
}
fn dep_value(keys: &[(&str, String)], features: &[&str]) -> String {
if features.is_empty()
&& let [("version", v)] = keys
{
return format!("\"{v}\"");
}
let mut parts: Vec<String> = keys.iter().map(|(k, v)| format!("{k} = \"{v}\"")).collect();
if !features.is_empty() {
let feats: Vec<String> = features.iter().map(|f| format!("\"{f}\"")).collect();
parts.push(format!("features = [{}]", feats.join(", ")));
}
format!("{{ {} }}", parts.join(", "))
}
fn t_cargo(name: &str, target: &TargetProfile, htl: &HtlPin) -> String {
let mut s = format!(
"[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n# authors / license / repository: fill in yourself\n\n"
);
if !target.target.crate_types().is_empty() {
let types: Vec<String> = target
.target
.crate_types()
.iter()
.map(|t| format!("\"{t}\""))
.collect();
s.push_str(&format!("[lib]\ncrate-type = [{}]\n\n", types.join(", ")));
}
s.push_str("[dependencies]\n");
for d in target.deps {
let keys = match d.req {
Dep::Htl => htl.keys_for("htl"),
Dep::Sibling(n) => htl.keys_for(n),
Dep::Version(v) => vec![("version", v.to_string())],
};
s.push_str(&format!("{} = {}\n", d.name, dep_value(&keys, d.features)));
}
s.push_str(
"\n# The Teal checker runs inside htl's proc macros; the dev profile would build it\n\
# unoptimised and make every `cargo build` that touches a .tl about 3x slower.\n\
[profile.dev.build-override]\nopt-level = 3\n",
);
s
}
#[cfg(test)]
mod tests {
use super::{
BuildTarget, Ctx, DEFAULT_TARGET, HTLX_REPOSITORY, HTLX_TAG, HtlPin, LUA_KEYWORDS, Options,
PIN_DEFAULT, Path, PathBuf, REPOSITORY, RUST_KEYWORDS, Result, dep_value, ffi_lib_rs,
module_ident, plan, profile, refuse_reserved_name, resolve_target, rust_lib_rs,
rust_main_rs, script_mismatch, t_cargo, t_htl_toml, t_manifest, t_mise, t_readme,
target_names, window_lib_rs, window_main_rs,
};
use htl::build_target::Script;
#[test]
fn the_default_pin_is_where_this_binary_was_built_from() {
match (PIN_DEFAULT, HtlPin::default()) {
("release", HtlPin::Release(v)) => assert_eq!(v, env!("CARGO_PKG_VERSION")),
("main", HtlPin::Main) => {}
("path", HtlPin::Path(root)) => {
assert!(root.is_absolute(), "{}", root.display());
assert!(
root.join("crates").join("htl").join("Cargo.toml").exists(),
"{} is not a checkout of this repository",
root.display()
);
let here = std::fs::canonicalize(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."),
)
.unwrap();
assert_eq!(std::fs::canonicalize(&root).unwrap(), here);
}
(kind, pin) => panic!("HTL_PIN_DEFAULT={kind} but the default is {pin:?}"),
}
}
#[test]
fn a_pin_is_the_default_main_or_a_checkout() {
assert_eq!(HtlPin::parse(None).unwrap(), HtlPin::default());
assert_eq!(HtlPin::parse(Some("main")).unwrap(), HtlPin::Main);
assert_eq!(
HtlPin::parse(Some("path:x")).unwrap(),
HtlPin::Path(PathBuf::from("x"))
);
}
#[test]
fn a_number_is_refused_with_the_release_cli_that_writes_for_it() {
let e = err(HtlPin::parse(Some("0.5")));
assert!(e.contains("unsupported htl `0.5`"), "{e}");
assert!(e.contains("`main` or `path:<checkout>`"), "{e}");
assert!(e.contains(&HtlPin::default().requirement()), "{e}");
assert!(e.contains("cargo install htl-cli --version 0.5"), "{e}");
assert!(err(HtlPin::parse(Some("nope"))).contains("unsupported htl `nope`"));
assert!(err(HtlPin::parse(Some("path:"))).contains("names no checkout directory"));
}
#[test]
fn each_pin_writes_its_own_dependency_line() {
let release = HtlPin::Release("0.6.0".into());
let path = HtlPin::Path(PathBuf::from("../co"));
assert_eq!(release.requirement(), "\"0.6.0\"");
assert_eq!(
HtlPin::Main.requirement(),
format!("{{ git = \"{REPOSITORY}\", branch = \"main\" }}")
);
assert_eq!(path.requirement(), "{ path = \"../co/crates/htl\" }");
assert!(REPOSITORY.contains("://"), "{REPOSITORY}");
let ffi = ["ffi"];
assert_eq!(
dep_value(&release.keys(), &ffi),
"{ version = \"0.6.0\", features = [\"ffi\"] }"
);
assert_eq!(
dep_value(&HtlPin::Main.keys(), &ffi),
format!("{{ git = \"{REPOSITORY}\", branch = \"main\", features = [\"ffi\"] }}")
);
assert_eq!(
dep_value(&path.keys(), &ffi),
"{ path = \"../co/crates/htl\", features = [\"ffi\"] }"
);
}
#[test]
fn the_rust_host_installs_std() {
let ctx = Ctx {
name: "sample",
module: "sample",
script: true,
htlx: false,
};
let lib = rust_lib_rs(&ctx);
assert!(
lib.contains(
" Host.htl_preload(h)?;\n // `std.*`: json, string, path and the rest"
),
"{lib}"
);
assert!(lib.contains(" h.install_std()?;\n"), "{lib}");
assert!(!lib.contains("{{"), "{lib}");
let ffi = ffi_lib_rs(&ctx);
assert!(ffi.contains(" h.install_std()?;\n"), "{ffi}");
}
#[test]
fn the_rust_host_embeds_its_module_as_a_bundle() {
let ctx = Ctx {
name: "sample",
module: "sample",
script: true,
htlx: true,
};
let lib = rust_lib_rs(&ctx);
assert!(
lib.contains("include_bundle!(\"src/sample/init.tl\", host = [\"host\"])"),
"{lib}"
);
assert!(
lib.contains("h.install_bundle(&htl::bundle::Bundle::decode(BUNDLE)?)?;"),
"{lib}"
);
assert!(
!lib.contains("include_tl_bytes") && !lib.contains("{{"),
"{lib}"
);
let ffi = ffi_lib_rs(&ctx);
assert!(
ffi.contains("include_bundle!(\"src/sample/init.tl\"") && !ffi.contains("{{"),
"{ffi}"
);
let main = rust_main_rs(&ctx);
assert!(
main.contains(
"include_bundle!(\"src/main.tl\", host = [\"host\", \"sample\"], debug = true)"
) && main.contains("h.run_bundle(&Bundle::decode(MAIN)?, &args)?;"),
"{main}"
);
assert!(
!main.contains("set_arg") && !main.contains("h.exec(") && !main.contains("{{"),
"{main}"
);
}
#[test]
fn the_manifest_names_htlx_unless_no_x_is_given() {
let opts = |htl: HtlPin, no_x: bool| Options {
lib: false,
target: None,
htl,
no_x,
};
let ctx = |o: &Options| Ctx {
name: "sample",
module: "sample",
script: true,
htlx: o.writes_htlx(),
};
let opted_out = opts(HtlPin::Release("0.6.0".into()), true);
let bare = t_manifest(&ctx(&opted_out));
assert!(!bare.contains("htlx"), "{bare}");
assert!(bare.contains("[deps]\n# lshape"), "{bare}");
let main = opts(HtlPin::Main, false);
let with = t_manifest(&ctx(&main));
let release = opts(HtlPin::Release("0.6.0".into()), false);
assert_eq!(t_manifest(&ctx(&release)), with);
let line = format!(
"[deps]\nhtlx = {{ git = \"{HTLX_REPOSITORY}\", tag = \"{HTLX_TAG}\" }}\n# lshape"
);
assert!(with.contains(&line), "{with}");
assert_eq!(with.replacen(&line, "[deps]\n# lshape", 1), bare);
let main_opted_out = opts(HtlPin::Main, true);
assert_eq!(t_manifest(&ctx(&main_opted_out)), bare);
let n: Vec<&str> = HTLX_TAG.trim_start_matches('v').split('.').collect();
assert!(
HTLX_TAG.starts_with('v') && n.len() == 3 && n.iter().all(|p| p.parse::<u64>().is_ok()),
"HTLX_TAG {HTLX_TAG} is not an exact vX.Y.Z tag"
);
}
#[test]
fn the_readme_puts_the_fetch_first_when_there_is_something_to_fetch() {
let ctx = |htlx| Ctx {
name: "sample",
module: "sample",
script: true,
htlx,
};
let with = t_readme(&ctx(true), None);
let block: Vec<&str> = with.lines().skip_while(|l| *l != "```sh").skip(1).collect();
assert!(block[0].starts_with("htl pkg install"), "{with}");
let fetches = block
.iter()
.take_while(|l| **l != "```")
.filter(|l| l.starts_with("htl pkg install"))
.count();
assert_eq!(fetches, 1, "{with}");
assert!(with.contains("`htlx` ([htl-x]("), "{with}");
assert!(with.contains("htl new --no-x"), "{with}");
let without = t_readme(&ctx(false), None);
let block: Vec<&str> = without
.lines()
.skip_while(|l| *l != "```sh")
.skip(1)
.collect();
assert!(block[0].starts_with("htl check ."), "{without}");
assert!(!without.contains("htlx"), "{without}");
}
#[test]
fn the_config_records_the_target() {
let block = |name: &str| {
format!(
"\n[build]\n\
# What runs this project's output: hb (the htl binary, the default when absent), bin,\n\
# cdylib, window. Written by htl new --target; see README \"Build targets\".\n\
target = \"{name}\"\n"
)
};
let plain = t_htl_toml(None);
assert!(!plain.contains("[build]"), "{plain}");
let bin = t_htl_toml(Some(BuildTarget::Bin));
assert_eq!(bin, format!("{plain}{}", block("bin")));
let cdylib = t_htl_toml(Some(BuildTarget::Cdylib));
assert_eq!(cdylib, format!("{plain}{}", block("cdylib")));
let window = t_htl_toml(Some(BuildTarget::Window));
assert_eq!(window, format!("{plain}{}", block("window")));
}
#[test]
fn the_registry_holds_the_target_embed_asks_for() {
assert!(target_names().contains(&DEFAULT_TARGET.name()));
let bin = profile(DEFAULT_TARGET).unwrap();
assert_eq!(bin.lib.path, "src/lib.rs");
assert_eq!(bin.main.as_ref().unwrap().path, "src/main.rs");
assert!(bin.target.entry().accepts(true) && bin.target.entry().accepts(false));
}
#[test]
fn the_default_build_target_has_no_profile_and_is_not_offered() {
assert!(profile(BuildTarget::Hb).is_none());
assert!(!target_names().contains(&"hb"));
let e = err(resolve_target(Some("hb"), false, false));
assert!(
e.contains("the `hb` target is what plain `htl new` writes"),
"{e}"
);
assert!(
e.contains("targets that scaffold: bin, cdylib, window"),
"{e}"
);
}
fn err<T>(r: Result<T>) -> String {
r.err().expect("expected a refusal").to_string()
}
#[test]
fn embed_and_target_bin_are_the_same_request() {
let by_flag = resolve_target(None, true, false).unwrap().unwrap();
let by_name = resolve_target(Some("bin"), false, false).unwrap().unwrap();
assert_eq!(by_flag.target, by_name.target);
assert!(resolve_target(Some("bin"), true, false).is_ok());
}
#[test]
fn an_unknown_target_is_refused_with_the_registered_names() {
let e = err(resolve_target(Some("nope"), false, false));
assert!(e.contains("unknown target `nope`"), "{e}");
for n in target_names() {
assert!(e.contains(n), "{e}");
}
}
#[test]
fn embed_disagreeing_with_target_is_refused() {
let e = err(resolve_target(Some("other"), true, false));
assert!(
e.contains("--embed is the shorthand for --target bin"),
"{e}"
);
}
#[test]
fn a_target_that_disagrees_with_lib_names_the_targets_that_do_not() {
assert!(Script::Requires.accepts(false) && !Script::Requires.accepts(true));
let msg = script_mismatch(profile(BuildTarget::Cdylib).unwrap(), false);
assert!(
msg.contains("the `cdylib` target writes no entry script"),
"{msg}"
);
assert!(msg.contains("targets that write one: bin, window"), "{msg}");
let msg = script_mismatch(profile(BuildTarget::Window).unwrap(), true);
assert!(
msg.contains("the `window` target runs an entry script, which --lib leaves out"),
"{msg}"
);
assert!(
msg.contains("targets that work with --lib: bin, cdylib"),
"{msg}"
);
}
#[test]
fn the_cdylib_target_is_refused_without_lib_and_taken_with_it() {
let e = err(resolve_target(Some("cdylib"), false, false));
assert!(e.contains("so it needs --lib"), "{e}");
let ffi = resolve_target(Some("cdylib"), false, true)
.unwrap()
.unwrap();
assert_eq!(ffi.target, BuildTarget::Cdylib);
assert!(ffi.main.is_none());
let paths: Vec<&str> = ffi.extra.iter().map(|f| f.path).collect();
assert_eq!(
paths,
vec![
"examples/c/main.c",
"examples/c/Makefile",
"examples/python/run.py"
]
);
}
#[test]
fn the_cdylib_cargo_toml_is_a_c_library_with_the_ffi_feature() {
let release = HtlPin::Release(env!("CARGO_PKG_VERSION").into());
let toml = t_cargo("sample", profile(BuildTarget::Cdylib).unwrap(), &release);
assert!(
toml.contains("[lib]\ncrate-type = [\"rlib\", \"cdylib\", \"staticlib\"]\n"),
"{toml}"
);
assert!(
toml.contains(&format!(
"htl = {{ version = \"{}\", features = [\"ffi\"] }}\n",
env!("CARGO_PKG_VERSION")
)),
"{toml}"
);
assert!(
toml.contains("serde = { version = \"1\", features = [\"derive\"] }\n"),
"{toml}"
);
}
#[test]
fn the_cdylib_feature_survives_every_pin_kind() {
let ffi = profile(BuildTarget::Cdylib).unwrap();
let toml = t_cargo("sample", ffi, &HtlPin::Main);
assert!(
toml.contains(&format!(
"\nhtl = {{ git = \"{REPOSITORY}\", branch = \"main\", features = [\"ffi\"] }}\n"
)),
"{toml}"
);
let toml = t_cargo("sample", ffi, &HtlPin::Path(PathBuf::from("../co")));
assert!(
toml.contains("\nhtl = { path = \"../co/crates/htl\", features = [\"ffi\"] }\n"),
"{toml}"
);
}
#[test]
fn a_sibling_crate_follows_the_htl_pin() {
let window = profile(BuildTarget::Window).unwrap();
for pin in [
HtlPin::Release("0.7.0".into()),
HtlPin::Main,
HtlPin::Path(PathBuf::from("../co")),
] {
let toml = t_cargo("sample", window, &pin);
let line = |name: &str| -> String {
toml.lines()
.find(|l| l.starts_with(&format!("{name} = ")))
.unwrap_or_else(|| panic!("no `{name}` dependency in:\n{toml}"))
.to_string()
};
let htl = line("htl");
let mq = line("htl-mq");
let want = match &pin {
HtlPin::Release(v) => (format!("htl = \"{v}\""), format!("htl-mq = \"{v}\"")),
HtlPin::Main => (
format!("htl = {{ git = \"{REPOSITORY}\", branch = \"main\" }}"),
format!("htl-mq = {{ git = \"{REPOSITORY}\", branch = \"main\" }}"),
),
HtlPin::Path(_) => (
"htl = { path = \"../co/crates/htl\" }".to_string(),
"htl-mq = { path = \"../co/crates/htl-mq\" }".to_string(),
),
};
assert_eq!(
(htl.as_str(), mq.as_str()),
(want.0.as_str(), want.1.as_str())
);
}
}
#[test]
fn the_window_target_is_a_binary_with_two_host_modules() {
let window = resolve_target(Some("window"), false, false)
.unwrap()
.unwrap();
assert_eq!(window.target, BuildTarget::Window);
assert_eq!(window.main.as_ref().unwrap().path, "src/main.rs");
assert!(window.extra.is_empty());
let release = HtlPin::Release(env!("CARGO_PKG_VERSION").into());
let toml = t_cargo("sample", window, &release);
assert!(!toml.contains("[lib]"), "{toml}");
assert!(toml.contains("anyhow = \"1\"\n"), "{toml}");
let ctx = Ctx {
name: "sample",
module: "sample",
script: true,
htlx: false,
};
let lib = window_lib_rs(&ctx);
assert!(
lib.contains("#[host_module(name = \"fx\", dts = \"src/fx.d.tl\""),
"{lib}"
);
assert!(
lib.contains("htl::include_bundle!(\"src/sample/init.tl\", host = [\"fx\", \"mq\"])"),
"{lib}"
);
assert!(
lib.contains("Fx.htl_preload(h)?;") && lib.contains("htl_mq::Mq.htl_preload(h)?;"),
"{lib}"
);
assert!(!lib.contains("{{"), "{lib}");
let main = window_main_rs(&ctx);
assert!(
main.contains(
"include_bundle!(\"src/main.tl\", host = [\"fx\", \"mq\", \"sample\"], debug = true)"
),
"{main}"
);
assert!(
main.contains("htl_mq::run(h, game, htl_mq::conf(\"sample\", 800, 600))"),
"{main}"
);
assert!(!main.contains("{{"), "{main}");
}
#[test]
fn the_window_target_is_refused_with_lib() {
let e = err(resolve_target(Some("window"), false, true));
assert!(
e.contains("the `window` target runs an entry script, which --lib leaves out"),
"{e}"
);
}
#[test]
fn the_readme_commands_come_from_the_target() {
let ctx = |script| Ctx {
name: "sample",
module: "sample",
script,
htlx: false,
};
let bin = profile(DEFAULT_TARGET).unwrap();
assert!((bin.readme_commands)(&ctx(true)).contains("cargo run"));
assert!(!(bin.readme_commands)(&ctx(false)).contains("cargo run"));
let ffi = (profile(BuildTarget::Cdylib).unwrap().readme_commands)(&ctx(false));
assert!(ffi.contains("make -C examples/c run"), "{ffi}");
assert!(ffi.contains("python3 examples/python/run.py"), "{ffi}");
assert!(ffi.contains("include/sample.h"), "{ffi}");
let win = (profile(BuildTarget::Window).unwrap().readme_commands)(&ctx(true));
assert!(win.contains("cargo run # the window"), "{win}");
assert!(
win.contains("HTL_MQ_FRAMES=60 HTL_MQ_SHOT=out.png cargo run"),
"{win}"
);
}
#[test]
fn cargo_toml_takes_the_crate_shape_from_the_target() {
let release = HtlPin::Release(env!("CARGO_PKG_VERSION").into());
let toml = t_cargo("sample", profile(DEFAULT_TARGET).unwrap(), &release);
assert!(!toml.contains("[lib]"), "{toml}");
assert!(toml.contains("anyhow = \"1\"\n"), "{toml}");
assert!(
toml.contains(&format!("htl = \"{}\"\n", env!("CARGO_PKG_VERSION"))),
"{toml}"
);
let toml = t_cargo("sample", profile(BuildTarget::Cdylib).unwrap(), &release);
assert!(
toml.contains("[lib]\ncrate-type = [\"rlib\", \"cdylib\", \"staticlib\"]\n"),
"{toml}"
);
}
fn refusal(name: &str, writes_cargo: bool) -> String {
match refuse_reserved_name(name, &module_ident(name), writes_cargo) {
Ok(()) => String::new(),
Err(e) => e.to_string(),
}
}
#[test]
fn a_rust_keyword_is_refused_by_a_target_and_taken_by_a_plain_project() {
let e = refusal("pub", true);
assert!(
e.starts_with("invalid project name `pub`: it is a Rust keyword"),
"{e}"
);
assert!(e.contains("`pub::preload`"), "what htl does with it:\n{e}");
assert!(e.contains("another name"), "the way out:\n{e}");
assert!(refusal("match", true).contains("it is a Rust keyword"));
assert_eq!(refusal("pub", false), "");
assert_eq!(refusal("match", false), "");
}
#[test]
fn a_2024_keyword_cargo_still_accepts_is_refused() {
let e = refusal("gen", true);
assert!(e.contains("reserved by Rust's 2024 edition"), "{e}");
assert_eq!(refusal("gen", false), "");
}
#[test]
fn the_names_cargo_refuses_for_their_spelling_are_refused_too() {
assert!(
refusal("123abc", true).contains("the name cannot start with a digit"),
"{}",
refusal("123abc", true)
);
let e = refusal("my lib", true);
assert!(e.contains("invalid character ` `"), "{e}");
assert_eq!(refusal("123abc", false), "");
assert_eq!(refusal("my lib", false), "");
}
#[test]
fn a_lua_keyword_is_refused_by_every_target() {
for name in ["end", "function", "local", "nil"] {
for writes_cargo in [false, true] {
let e = refusal(name, writes_cargo);
assert!(
e.contains(&format!(
"invalid project name `{name}`: it is a Lua keyword"
)),
"{e}"
);
}
}
let e = refusal("end", false);
assert!(e.contains("`local end = require(\"end\")`"), "{e}");
}
#[test]
fn the_teal_words_refused_are_the_three_that_break_a_scaffolded_project() {
for name in ["record", "enum", "interface"] {
let e = refusal(name, false);
assert!(
e.contains(&format!(
"invalid project name `{name}`: it is how Teal opens a type declaration"
)),
"{e}"
);
}
for name in ["type", "where", "is", "as", "global", "macroexp"] {
assert_eq!(refusal(name, false), "", "{name}");
}
}
#[test]
fn a_name_that_merely_contains_a_keyword_is_taken() {
for name in ["pubs", "my-lib", "matcher", "ending", "sample"] {
assert_eq!(refusal(name, true), "", "{name}");
assert_eq!(refusal(name, false), "", "{name}");
}
}
#[test]
fn the_keyword_lists_are_the_size_of_the_sets_they_copy() {
assert_eq!(RUST_KEYWORDS.len(), 51);
assert_eq!(LUA_KEYWORDS.len(), 22);
}
#[test]
fn mise_toml_pins_the_command_under_a_release_and_is_absent_otherwise() {
assert_eq!(
t_mise(&HtlPin::Release("0.7.0".into())).as_deref(),
Some(
"# The htl this project was written by. mise (https://mise.jdx.dev) reads this file:\n\
# `mise install` puts that release on PATH here, whatever `htl` is elsewhere.\n\
[tools]\n\
\"cargo:htl-cli\" = \"0.7.0\"\n"
)
);
assert_eq!(t_mise(&HtlPin::Main), None);
assert_eq!(t_mise(&HtlPin::Path(PathBuf::from("../co"))), None);
}
#[test]
fn the_plan_carries_mise_toml_exactly_when_the_pin_is_a_release() {
let planned = |htl: HtlPin| -> Vec<String> {
let opts = Options {
lib: false,
target: None,
htl,
no_x: false,
};
plan(Path::new("p"), "sample", "sample", &opts)
.into_iter()
.map(|(path, _)| path.display().to_string().replace('\\', "/"))
.collect()
};
assert!(planned(HtlPin::Release("0.7.0".into())).contains(&"p/mise.toml".to_string()));
assert!(!planned(HtlPin::Main).contains(&"p/mise.toml".to_string()));
assert!(
!planned(HtlPin::Path(PathBuf::from("../co"))).contains(&"p/mise.toml".to_string())
);
}
}