htl-cli 0.19.0

htl command line (also `cargo htl`): check / run / test / fmt / build / pkg / new for Teal projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! `htl rs`, driven through the binary on a temp project: what it writes and where, what it
//! says on stderr, when it exits non-zero, and that the file it writes compiles and carries
//! a Lua table to a struct and back.
//!
//! The file of the first acceptance case is committed as `tests/fixtures/rs/teal_types.rs`:
//! one test compiles it (`include!`) and round-trips a table through it, and another runs
//! the binary and holds its output to it, so the file that is compiled is the file that is
//! written.

use std::path::Path;
use std::process::{Command, Output};
use std::time::{Duration, SystemTime};

mod common;

/// The file of the first acceptance case, compiled in place: `pub mod ev`.
mod generated {
    include!("fixtures/rs/teal_types.rs");
}

fn write(path: &Path, text: &str) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, text).unwrap();
}

fn read(path: &Path) -> String {
    std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
}

fn htl(root: &Path, args: &[&str]) -> Output {
    Command::new(common::htl_bin())
        .args(args)
        .current_dir(root)
        .output()
        .unwrap()
}

fn stderr(out: &Output) -> String {
    String::from_utf8_lossy(&out.stderr).into_owned()
}

/// The module of acceptance 1: `Event` with three fields, and the enum `Kind`.
const EV: &str = "local record M
   record Event
      kind: Kind
      at: integer
      note: string
   end
   enum Kind
      \"open\"
      \"close\"
   end
end
return M
";

const MODULES_EV: &str = "[rust]\nmodules = [\"ev\"]\n";

/// A project whose `src/ev/init.tl` is [`EV`], listed in `[rust] modules`.
fn project(name: &str) -> common::TempDir {
    project_with(name, MODULES_EV, EV)
}

fn project_with(name: &str, toml: &str, ev: &str) -> common::TempDir {
    let root = common::tempdir("htl-cli-rs", name);
    write(&root.join("htl.toml"), toml);
    write(&root.join("src/ev/init.tl"), ev);
    root
}

/// Acceptance 1: exit 0, the line, and the file with the `struct` and the `enum`.
#[test]
fn a_record_and_an_enum_are_written_as_a_struct_and_an_enum() {
    let root = project("acceptance-1");
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stderr(&out), "htl rs: wrote src/teal_types.rs\n");
    let file = read(&root.join("src/teal_types.rs"));
    assert!(file.starts_with("// Generated by htl rs"), "{file}");
    assert!(file.contains("pub mod ev {"), "{file}");
    assert!(
        file.contains(
            "    #[derive(Debug, Clone, PartialEq, ::htl::TealRecord)]
    #[teal(name = \"Event\")]
    pub struct Event {
        pub kind: ::core::option::Option<Kind>,
        pub at: ::core::option::Option<i64>,
        pub note: ::core::option::Option<::std::string::String>,
    }"
        ),
        "{file}"
    );
    assert!(
        file.contains(
            "    pub enum Kind {
        #[teal(name = \"close\")]
        Close,
        #[teal(name = \"open\")]
        Open,
    }"
        ),
        "{file}"
    );
}

/// The project of `htl-core/tests/fixtures/client`: `[rust] exports` next to `modules`, and
/// the file `htl rs` writes for it, which `teal_types!()` expands to as well (the test of
/// `htl-macros`) and which the `htl` crate compiles against `htl::run`.
#[test]
fn an_exported_module_is_written_as_the_client_the_macro_expands_to() {
    let root = common::tempdir("htl-cli-rs", "client");
    write(
        &root.join("htl.toml"),
        include_str!("../../htl-core/tests/fixtures/client/htl.toml"),
    );
    write(
        &root.join("src/shop/types.tl"),
        include_str!("../../htl-core/tests/fixtures/client/src/shop/types.tl"),
    );
    write(
        &root.join("src/shop/app.tl"),
        include_str!("../../htl-core/tests/fixtures/client/src/shop/app.tl"),
    );
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stderr(&out), "htl rs: wrote src/teal_types.rs\n");
    assert_eq!(
        read(&root.join("src/teal_types.rs")),
        include_str!("../../htl-core/tests/fixtures/client/teal_types.rs")
    );
}

/// `exports` without `modules` is something to write, and a note about a function the
/// client does not have is said without failing the run.
#[test]
fn exports_alone_are_written_and_a_function_outside_the_body_is_a_note() {
    let app = "local record app\n   add: function(integer, integer): integer\nend\n\
               function app.add(a: integer, b: integer): integer\n   return a + b\nend\n\
               function app.helper()\nend\nreturn app\n";
    let root = project_with("exports-alone", "[rust]\nexports = [\"app\"]\n", EV);
    write(&root.join("src/app.tl"), app);
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(
        stderr(&out).contains(
            "src/app.tl:7:1: `app.helper` is defined outside the body of the record, so it is not in the client; declare `helper: function(..)` in the body to add it"
        ),
        "{}",
        stderr(&out)
    );
    let file = read(&root.join("src/teal_types.rs"));
    assert!(file.contains("pub struct App {"), "{file}");
    assert!(!file.contains("helper"), "{file}");
}

/// Acceptance 2: `---@struct` makes a field required unless it is `---@optional`.
#[test]
fn a_struct_record_requires_the_fields_that_are_not_optional() {
    let marked = EV
        .replace("record Event\n", "record Event   ---@struct\n")
        .replace("note: string\n", "note: string   ---@optional\n");
    let root = project_with("acceptance-2", MODULES_EV, &marked);
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    let file = read(&root.join("src/teal_types.rs"));
    assert!(
        file.contains(
            "    pub struct Event {
        pub kind: Kind,
        pub at: i64,
        pub note: ::core::option::Option<::std::string::String>,
    }"
        ),
        "{file}"
    );
}

/// Acceptance 3: `[rust.types]` sets a field's type; a key that is no field is refused by
/// name, and nothing is written.
#[test]
fn a_types_entry_sets_a_field_and_a_key_that_matches_nothing_is_refused() {
    let toml = format!("{MODULES_EV}[rust.types]\n\"ev.Event.at\" = \"u32\"\n");
    let root = project_with("acceptance-3", &toml, EV);
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    let file = read(&root.join("src/teal_types.rs"));
    assert!(file.contains("        pub at: u32,\n"), "{file}");

    let bad = format!("{MODULES_EV}[rust.types]\n\"ev.Event.nope\" = \"u32\"\n");
    let root = project_with("acceptance-3-nope", &bad, EV);
    let out = htl(&root, &["rs"]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    let err = stderr(&out);
    assert!(err.contains("\"ev.Event.nope\" matches no field"), "{err}");
    assert!(
        err.ends_with("htl rs: src/teal_types.rs not written\n"),
        "{err}"
    );
    assert!(!root.join("src/teal_types.rs").exists());
}

/// Acceptance 4: a second run with no change says so and does not rewrite the file.
#[test]
fn a_second_run_is_current_and_leaves_the_file_alone() {
    let root = project("acceptance-4");
    assert!(htl(&root, &["rs"]).status.success());
    let path = root.join("src/teal_types.rs");
    // A modification time a rewrite would move.
    let long_ago = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
    std::fs::File::options()
        .write(true)
        .open(&path)
        .unwrap()
        .set_modified(long_ago)
        .unwrap();

    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stderr(&out), "htl rs: src/teal_types.rs is current\n");
    assert_eq!(
        std::fs::metadata(&path).unwrap().modified().unwrap(),
        long_ago
    );
}

/// Acceptance 5: a function field is refused at its line, naming `M.Event.f`, and no file
/// is written.
#[test]
fn a_function_field_is_refused_and_nothing_is_written() {
    let with_fn = EV.replace(
        "note: string\n",
        "note: string\n      f: function(): integer\n",
    );
    let root = project_with("acceptance-5", MODULES_EV, &with_fn);
    let out = htl(&root, &["rs"]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    assert_eq!(
        stderr(&out),
        "error: src/ev/init.tl:6:7: `M.Event.f`: a function or method field has no Rust type\n\
         htl rs: src/teal_types.rs not written\n"
    );
    assert!(!root.join("src/teal_types.rs").exists());
}

/// Acceptance 6: with `modules` empty it says so and removes the file it wrote.
#[test]
fn an_empty_modules_removes_the_file_it_wrote() {
    let root = project("acceptance-6");
    assert!(htl(&root, &["rs"]).status.success());
    assert!(root.join("src/teal_types.rs").exists());

    write(&root.join("htl.toml"), "[rust]\nmodules = []\n");
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(
        stderr(&out),
        "htl rs: nothing to write ([rust] modules and exports are empty)\n\
         htl rs: removed src/teal_types.rs\n"
    );
    assert!(!root.join("src/teal_types.rs").exists());
}

/// Acceptance 7: a file without the header is not touched, and the run fails saying why.
#[test]
fn a_file_that_htl_rs_did_not_write_is_left_alone() {
    let root = project("acceptance-7");
    write(
        &root.join("src/teal_types.rs"),
        "// mine\npub struct Mine;\n",
    );
    let out = htl(&root, &["rs"]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    assert_eq!(
        stderr(&out),
        "htl rs: src/teal_types.rs is not written by htl rs; move it, or set [rust] out\n"
    );
    assert_eq!(
        read(&root.join("src/teal_types.rs")),
        "// mine\npub struct Mine;\n"
    );

    // `--check` says the same and also leaves it.
    let out = htl(&root, &["rs", "--check"]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    assert!(stderr(&out).contains("is not written by htl rs"));
    assert_eq!(
        read(&root.join("src/teal_types.rs")),
        "// mine\npub struct Mine;\n"
    );
}

/// Acceptance 8: `--check` exits 1 once a field is added, and 0 after `htl rs`.
#[test]
fn check_finds_a_file_that_has_fallen_behind() {
    let root = project("acceptance-8");
    let out = htl(&root, &["rs", "--check"]);
    assert_eq!(out.status.code(), Some(1), "no file yet: {}", stderr(&out));
    assert_eq!(
        stderr(&out),
        "htl rs: src/teal_types.rs is stale; run htl rs\n"
    );
    assert!(
        !root.join("src/teal_types.rs").exists(),
        "--check wrote the file"
    );

    assert!(htl(&root, &["rs"]).status.success());
    let out = htl(&root, &["rs", "--check"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stderr(&out), "htl rs: src/teal_types.rs is current\n");

    write(
        &root.join("src/ev/init.tl"),
        &EV.replace("note: string\n", "note: string\n      by: string\n"),
    );
    let out = htl(&root, &["rs", "--check"]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    assert_eq!(
        stderr(&out),
        "htl rs: src/teal_types.rs is stale; run htl rs\n"
    );

    assert!(htl(&root, &["rs"]).status.success());
    let out = htl(&root, &["rs", "--check"]);
    assert!(out.status.success(), "{}", stderr(&out));
}

/// `--check` writes nothing at all: not the Rust file, and not the `.d.tl` of a contract
/// type, which every command that reads the project publishes first and `htl rs` writing
/// does too. A CI step that runs `--check` leaves the checkout as it found it.
#[test]
fn check_writes_no_declaration_either() {
    let root = project_with(
        "check-writes-nothing",
        &format!("{MODULES_EV}\n[[contract]]\ndir = \"mods\"\n"),
        EV,
    );
    write(
        &root.join("src/defs.tl"),
        "local record defs\n   record Mod   ---@contract\n      name: string   ---@required\n   \
         end\nend\nreturn defs\n",
    );
    write(&root.join("mods/good.tl"), "return { name = \"g\" }\n");

    let out = htl(&root, &["rs", "--check"]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    assert!(
        !root.join("types/defs.d.tl").exists(),
        "--check published a declaration: {}",
        stderr(&out)
    );

    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(
        root.join("types/defs.d.tl").exists(),
        "htl rs without --check publishes it, as every command does: {}",
        stderr(&out)
    );
}

/// A type error in a file the project owns, listed or not, is reported and nothing is
/// written.
#[test]
fn a_type_error_in_any_own_file_stops_the_run() {
    let root = project("type-error");
    write(
        &root.join("src/other.tl"),
        "local x: integer = \"not an integer\"\nreturn x\n",
    );
    let out = htl(&root, &["rs"]);
    assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
    let err = stderr(&out);
    assert!(err.contains("src/other.tl:1:"), "{err}");
    assert!(
        err.ends_with("htl rs: src/teal_types.rs not written\n"),
        "{err}"
    );
    assert!(!root.join("src/teal_types.rs").exists());
}

/// `[rust] out` says where the file goes, relative to `htl.toml`.
#[test]
fn out_sets_the_file() {
    let toml = "[rust]\nmodules = [\"ev\"]\nout = \"gen/types.rs\"\n";
    let root = project_with("out", toml, EV);
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stderr(&out), "htl rs: wrote gen/types.rs\n");
    assert!(root.join("gen/types.rs").exists());
    assert!(!root.join("src/teal_types.rs").exists());
}

/// Acceptance 9, the compiled half: the file of acceptance 1 is `include!`d above, and a
/// Lua table read as an `ev::Event` and written back is the same table.
#[test]
fn the_generated_file_carries_a_table_to_a_struct_and_back() {
    use generated::ev::{Event, Kind};
    use htl::mlua::{FromLua, IntoLua};

    let h = htl::Htl::new().unwrap();
    let lua = h.lua();
    let table: htl::mlua::Value = lua
        .load(r#"return { kind = "open", at = 3 }"#)
        .eval()
        .unwrap();

    let event = Event::from_lua(table, lua).unwrap();
    assert_eq!(
        event,
        Event {
            kind: Some(Kind::Open),
            at: Some(3),
            note: None,
        }
    );

    let back = event.into_lua(lua).unwrap();
    lua.globals().set("back", back).unwrap();
    let same: bool = lua
        .load(
            r#"
            local n = 0
            for _ in pairs(back) do n = n + 1 end
            return n == 2 and back.kind == "open" and back.at == 3 and back.note == nil
            "#,
        )
        .eval()
        .unwrap();
    assert!(same, "the table that came back is not the one that went in");
}

/// Acceptance 9, the written half: the binary writes the file that is compiled above.
#[test]
fn the_binary_writes_the_committed_file() {
    let root = project("fixture");
    assert!(htl(&root, &["rs"]).status.success());
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/rs/teal_types.rs");
    assert_eq!(read(&root.join("src/teal_types.rs")), read(&fixture));
}

/// #540: a field typed with an alias from a listed module that declares no record or enum of
/// its own is lowered through both `htl rs` and `htl shapes`.
#[test]
fn an_alias_in_a_listed_module_with_no_record_or_enum_is_lowered() {
    let root = project_with(
        "alias-only-module",
        "[rust]\nmodules = [\"ev\", \"geom\"]\n",
        "local geom = require(\"geom\")
local record M
   record Event
      pts: geom.Pts
   end
end
return M
",
    );
    write(
        &root.join("src/geom/init.tl"),
        "local record M
   type Pts = {integer}
end
return M
",
    );
    let out = htl(&root, &["rs"]);
    assert!(out.status.success(), "{}", stderr(&out));
    let file = read(&root.join("src/teal_types.rs"));
    assert!(
        file.contains("        pub pts: ::core::option::Option<::std::vec::Vec<i64>>,\n"),
        "{file}"
    );
}