rustyfi 0.1.0

SATySFi command line interface: compile .saty documents to PDF
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Chimera CLI dispatch tests: drive the *built* binary under its three
//! personalities by overriding `argv[0]` (`Command::arg0` on unix, and via a
//! real hardlink alias for the `multicall install` helper), plus one
//! install→loader-resolves round trip proving the installer's materialised
//! layout matches `rustyfi_loader`'s `@require:` contract.

use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

fn bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_rustyfi"))
}

fn tmpdir(tag: &str) -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let p = std::env::temp_dir().join(format!(
        "rustyfi-dispatch-{tag}-{}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos(),
        n
    ));
    std::fs::create_dir_all(&p).unwrap();
    p
}

/// Run `bin()` with an overridden `argv[0]` basename (multicall dispatch key).
#[cfg(unix)]
fn run_as(arg0: &str, args: &[&str]) -> std::process::Output {
    use std::os::unix::process::CommandExt as _;
    Command::new(bin())
        .arg0(arg0)
        .args(args)
        .output()
        .expect("spawn binary")
}

#[cfg(unix)]
#[test]
fn argv0_rustyfi_is_compiler_and_package_manager() {
    let out = run_as("rustyfi", &["--help"]);
    assert!(out.status.success(), "rustyfi --help should succeed");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Compile a SATySFi"),
        "rustyfi --help should describe the compiler:\n{stdout}"
    );
    // One personality carrying both roles: the package commands are top-level,
    // so the compiler's own help lists them.
    assert!(
        stdout.contains("install") && stdout.contains("search"),
        "rustyfi --help should offer the package commands:\n{stdout}"
    );
}

#[cfg(unix)]
#[test]
fn argv0_satyrographos_is_package_manager() {
    let root = tmpdir("sg-personality");
    let out = run_as("satyrographos", &["list", "--dest", root.to_str().unwrap()]);
    assert!(
        out.status.success(),
        "satyrographos list should succeed on empty root"
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("(no packages installed)"),
        "expected empty-list message:\n{stdout}"
    );
}

#[cfg(unix)]
#[test]
fn package_commands_are_top_level() {
    let root = tmpdir("sg-subcommand");
    let out = run_as("rustyfi", &["list", "--dest", root.to_str().unwrap()]);
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("(no packages installed)"));

    let out = run_as(
        "rustyfi",
        &["satyrographos", "list", "--dest", root.to_str().unwrap()],
    );
    assert!(
        !out.status.success(),
        "`rustyfi satyrographos …` should no longer parse"
    );
}

#[cfg(unix)]
#[test]
fn bare_rustyfi_without_input_is_usage_error() {
    let out = run_as("rustyfi", &[]);
    assert!(!out.status.success(), "bare invocation must fail");
    assert_eq!(out.status.code(), Some(2), "clap usage error is exit 2");
}

#[cfg(unix)]
#[test]
fn multicall_install_creates_working_aliases() {
    use std::os::unix::process::CommandExt as _;

    let dir = tmpdir("aliases");
    let out = Command::new(bin())
        .args(["multicall", "install", "--dir", dir.to_str().unwrap()])
        .output()
        .expect("spawn");
    assert!(out.status.success(), "multicall install should succeed");

    let rustyfi_alias = dir.join("rustyfi");
    let satyro_alias = dir.join("satyrographos");
    assert!(rustyfi_alias.exists(), "rustyfi alias created");
    assert!(satyro_alias.exists(), "satyrographos alias created");

    // Invoking the real alias file (its own basename drives dispatch).
    let root = tmpdir("aliases-root");
    let out = Command::new(&satyro_alias)
        .arg0("satyrographos")
        .args(["list", "--dest", root.to_str().unwrap()])
        .output()
        .expect("spawn alias");
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("(no packages installed)"));

    let out = Command::new(bin())
        .args(["multicall", "install", "--dir", dir.to_str().unwrap()])
        .output()
        .expect("spawn");
    assert!(
        out.status.success(),
        "re-install of same aliases is idempotent"
    );
}

/// Manifest mode: `satyrographos install` with no PATH locates
/// `Satyristes` via upward search from cwd.
#[cfg(unix)]
#[test]
fn manifest_mode_install_reconciles_and_writes_lock() {
    use std::os::unix::process::CommandExt as _;
    let work = tmpdir("manifest-mode");

    let pkg = work.join("vendor/mylib");
    std::fs::create_dir_all(pkg.join("packages")).unwrap();
    std::fs::write(
        pkg.join("rustyfi-package.toml"),
        "[package]\n\
         name = \"mylib\"\n\
         version = \"1.0.0\"\n\
         rustyfi-version-compat = \">=0.0.6, <0.1\"\n\
         \n\
         [[files]]\n\
         kind = \"package-dir\"\n\
         src = \"packages\"\n",
    )
    .unwrap();
    std::fs::write(pkg.join("packages/mylib.satyh"), "let mylib = 1\n").unwrap();

    let proj = work.join("proj");
    std::fs::create_dir_all(&proj).unwrap();
    std::fs::write(
        proj.join("Satyristes"),
        "(version 0.0.2)\n\
         (library (name \"proj\") (version \"0.1.0\")\n\
           (sources ((packageDir \"src\")))\n\
           (dependencies ((mylib ((path \"../vendor/mylib\"))))))\n",
    )
    .unwrap();

    let root = work.join("root");
    let run = |extra_help: &str| {
        Command::new(bin())
            .arg0("satyrographos")
            .current_dir(&proj)
            .args(["install", "--dest", root.to_str().unwrap()])
            .output()
            .unwrap_or_else(|e| panic!("spawn ({extra_help}): {e}"))
    };

    let out = run("first");
    assert!(out.status.success(), "manifest install should succeed");
    assert!(root.join("dist/packages/mylib/mylib.satyh").is_file());
    assert!(proj.join("Satyristes.lock").is_file(), "lockfile written");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("installed mylib"), "{stdout}");

    let out = run("second");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("unchanged mylib"), "{stdout}");

    let _ = std::fs::remove_dir_all(&work);
}

/// Manifest mode with no discoverable `Satyristes` exits `3` (nothing to
/// operate on).
#[cfg(unix)]
#[test]
fn manifest_mode_without_a_manifest_exits_3() {
    use std::os::unix::process::CommandExt as _;
    let empty = tmpdir("no-satyrfile");
    let root = tmpdir("no-satyrfile-root");
    let out = Command::new(bin())
        .arg0("satyrographos")
        .current_dir(&empty)
        .args(["install", "--dest", root.to_str().unwrap()])
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    assert_eq!(out.status.code(), Some(3), "no Satyristes → exit 3");
}

/// A leading global flag (`--config`, before the subcommand) must behave
/// exactly like the same flag after it — the bug `dispatch::get_matches`
/// exists to fix. `--config` names a file that must exist to be read, so
/// give it a real, registry-less one; the point here is dispatch, not the
/// file's contents.
#[cfg(unix)]
#[test]
fn leading_global_flag_reaches_a_subcommand() {
    let work = tmpdir("leading-global");
    let config = work.join("config.toml");
    std::fs::write(&config, "").unwrap();
    let root = tmpdir("leading-global-root");

    // `search` needs a registry; a `list --dest` on an empty root is enough
    // to prove `--config` before the subcommand was consumed AND `list`
    // still dispatched (the pre-fix failure mode was "unexpected argument
    // '--dest' found", `input` having swallowed "list").
    let out = run_as(
        "rustyfi",
        &[
            "--config",
            config.to_str().unwrap(),
            "list",
            "--dest",
            root.to_str().unwrap(),
        ],
    );
    assert!(
        out.status.success(),
        "leading --config before `list` should parse and dispatch:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(String::from_utf8_lossy(&out.stdout).contains("(no packages installed)"));

    // Same argv, flag after the subcommand — must produce byte-identical
    // stdout, proving the two orders are truly equivalent, not just both
    // exit 0.
    let out_after = run_as(
        "rustyfi",
        &[
            "list",
            "--config",
            config.to_str().unwrap(),
            "--dest",
            root.to_str().unwrap(),
        ],
    );
    assert_eq!(out.stdout, out_after.stdout);
}

/// The narrower failure mode: with nothing else on the command line to
/// expose the mistake, `rustyfi --config F install` parses SUCCESSFULLY as
/// compile mode with `input = "install"` (a file literally named `install`)
/// instead of dispatching the `install` subcommand, because `--config` has
/// already matched before clap reaches the word `install`. `install` with no
/// PATH means "reconcile the nearest Satyristes"; a leading flag must resolve
/// the exact same ambiguity the exact same way.
#[cfg(unix)]
#[test]
fn leading_global_flag_does_not_swallow_a_bare_subcommand_name() {
    use std::os::unix::process::CommandExt as _;

    let empty = tmpdir("leading-global-bare");
    let config = empty.join("config.toml");
    std::fs::write(&config, "").unwrap();

    let with_leading_flag = Command::new(bin())
        .arg0("rustyfi")
        .current_dir(&empty)
        .args(["--config", config.to_str().unwrap(), "install"])
        .output()
        .expect("spawn");
    let bare = Command::new(bin())
        .arg0("rustyfi")
        .current_dir(&empty)
        .args(["install"])
        .output()
        .expect("spawn");

    // Both must mean "reconcile" (exit 3, no Satyristes here) — NOT a
    // compile-mode "install: No such file or directory".
    assert_eq!(
        with_leading_flag.status.code(),
        bare.status.code(),
        "leading --config must not change what bare `install` means:\n{}",
        String::from_utf8_lossy(&with_leading_flag.stderr)
    );
    assert_eq!(with_leading_flag.status.code(), Some(3));
    assert_eq!(with_leading_flag.stderr, bare.stderr);
}

/// The nesting closed off by `package_commands_are_top_level` must stay
/// closed even with a leading global flag in front of it — the hoist pre-pass
/// must not accidentally resurrect `rustyfi satyrographos list`.
#[cfg(unix)]
#[test]
fn leading_global_flag_does_not_revive_the_old_nesting() {
    let root = tmpdir("leading-global-old-nesting");
    let config_dir = tmpdir("leading-global-old-nesting-cfg");
    let config = config_dir.join("config.toml");
    std::fs::write(&config, "").unwrap();

    let out = run_as(
        "rustyfi",
        &[
            "--config",
            config.to_str().unwrap(),
            "satyrographos",
            "list",
            "--dest",
            root.to_str().unwrap(),
        ],
    );
    assert!(
        !out.status.success(),
        "`rustyfi --config F satyrographos list …` should still not parse"
    );
}

/// `--help` after a leading global flag must show the SUBCOMMAND's help
/// (what the user actually asked to run), not the compile personality's —
/// the hoist-and-retry fallback prefers a `DisplayHelp`/`DisplayVersion`
/// result over the original, less specific error.
#[cfg(unix)]
#[test]
fn leading_global_flag_help_is_subcommand_specific() {
    let config_dir = tmpdir("leading-global-help-cfg");
    let config = config_dir.join("config.toml");
    std::fs::write(&config, "").unwrap();

    let with_leading_flag = run_as(
        "rustyfi",
        &["--config", config.to_str().unwrap(), "install", "--help"],
    );
    let direct = run_as("rustyfi", &["install", "--help"]);
    assert!(with_leading_flag.status.success());
    assert_eq!(with_leading_flag.stdout, direct.stdout);
}

/// A flag VALUE that collides with a subcommand name (`--lib-root search
/// install PATH`, `search` being `--lib-root`'s value, not a subcommand)
/// must not be mistaken for the split point; the pre-pass must hoist at the
/// REAL subcommand (`install`). Proven by a lib-root directory literally
/// named `search` ending up holding the installed package.
#[cfg(unix)]
#[test]
fn leading_flag_value_matching_a_subcommand_name_is_not_the_split_point() {
    use std::os::unix::process::CommandExt as _;

    let work = tmpdir("value-aware-hoist");
    std::fs::create_dir_all(work.join("pkgsrc/packages")).unwrap();
    std::fs::write(
        work.join("pkgsrc/rustyfi-package.toml"),
        "[package]\n\
         name = \"mylib\"\n\
         version = \"1.0.0\"\n\
         rustyfi-version-compat = \">=0.0.6, <0.1\"\n\
         \n\
         [[files]]\n\
         kind = \"package-dir\"\n\
         src = \"packages\"\n",
    )
    .unwrap();
    std::fs::write(work.join("pkgsrc/packages/mylib.satyh"), "let mylib = 1\n").unwrap();

    let out = Command::new(bin())
        .arg0("rustyfi")
        .current_dir(&work)
        .args(["--lib-root", "search", "install", "pkgsrc"])
        .output()
        .expect("spawn");
    assert!(
        out.status.success(),
        "install should dispatch, with `search` consumed as --lib-root's value:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        work.join("search/dist/packages/mylib/mylib.satyh").is_file(),
        "package should land under the `search` lib-root, proving `search` was \
         --lib-root's VALUE and `install` was the dispatched subcommand"
    );

    let _ = std::fs::remove_dir_all(&work);
}

/// The `--flag=value` spelling must reach a subcommand exactly like the
/// space-separated form already proven by
/// `leading_global_flag_reaches_a_subcommand`.
#[cfg(unix)]
#[test]
fn leading_global_flag_equals_spelling_reaches_a_subcommand() {
    let work = tmpdir("leading-global-equals");
    let config = work.join("config.toml");
    std::fs::write(&config, "").unwrap();
    let root = tmpdir("leading-global-equals-root");

    let out = run_as(
        "rustyfi",
        &[
            &format!("--config={}", config.to_str().unwrap()),
            "list",
            "--dest",
            root.to_str().unwrap(),
        ],
    );
    assert!(
        out.status.success(),
        "leading --config=F before `list` should parse and dispatch:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(String::from_utf8_lossy(&out.stdout).contains("(no packages installed)"));
}

/// End-to-end contract: install a tiny package into a temp root
/// (through the library API the CLI calls into), then load a document that
/// `@require:`s it against that same root — proving the installer's nested
/// `dist/packages/<name>/<name>.satyh` layout is exactly what the loader's
/// third resolver candidate finds.
#[test]
fn install_then_loader_resolves_the_package() {
    let work = tmpdir("roundtrip");

    let src = work.join("src");
    std::fs::create_dir_all(src.join("packages")).unwrap();
    std::fs::write(
        src.join("rustyfi-package.toml"),
        "[package]\n\
         name = \"greetlib\"\n\
         version = \"1.0.0\"\n\
         rustyfi-version-compat = \">=0.0.6, <0.1\"\n\
         \n\
         [[files]]\n\
         kind = \"package-dir\"\n\
         src = \"packages\"\n",
    )
    .unwrap();
    // A library file: bindings only, no `in ...` body.
    std::fs::write(
        src.join("packages/greetlib.satyh"),
        "% library: bindings only\nlet greeting-word = `Hello`\n",
    )
    .unwrap();

    let root = work.join("root");
    rustyfi_satyrographos::install(
        &src,
        &rustyfi_satyrographos::InstallOptions {
            dest: Some(root.clone()),
            ..Default::default()
        },
    )
    .expect("install ok");

    assert!(root.join("dist/packages/greetlib/greetlib.satyh").is_file());

    let doc = work.join("doc.saty");
    std::fs::write(&doc, "@require: greetlib\ndocument (||) '<>\n").unwrap();

    let program = rustyfi_loader::load(
        &doc,
        &rustyfi_loader::LoadOptions {
            lib_root: Some(root.clone()),
            ..Default::default()
        },
    )
    .expect("loader must resolve @require: greetlib against the install root");

    let names: Vec<String> = program
        .files
        .iter()
        .map(|f| f.path.file_name().unwrap().to_string_lossy().into_owned())
        .collect();
    assert!(
        names.iter().any(|n| n == "greetlib.satyh"),
        "loaded files should include the installed library: {names:?}"
    );
    assert!(names.iter().any(|n| n == "doc.saty"));

    let _ = std::fs::remove_dir_all(&work);
}