argenv-resolve 0.4.0

Resolve an argenv contract against a real invocation - argv and envp, with precedence, defaults, and linting. Depends on argenv for the declared data; argenv depends on nothing here.
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
//! The generators: what they derive from a contract, that they treat it as untrusted, and that
//! the output works in real shells.
//!
//! The shell tests run bash, fish, zsh and nushell when they are installed. Set
//! `ARGENV_REQUIRE_SHELLS=1` (CI does) to turn "not installed" into a failure, so a missing shell
//! cannot make a test silently vacuous.

use argenv_resolve::generate::{
    bash, completions, fish, man_page, nushell, zsh, Asked, Command, GenerateError, Program, Shell,
};
use argenv_resolve::*;
use std::path::{Path, PathBuf};
use std::process::Command as Process;

/// A summary built to break anything that quotes carelessly.
const HOSTILE: &str = "Names; it's `x` [y]: $(touch PWNED) \"q\" \\ \n done; touch PWNED2 #";

fn records() -> Vec<Record> {
    let help: Input<bool, &'static str> = Input {
        key: "help",
        ty: Type::Bool,
        default: Some(false),
        arg: Some(Arg::pair("help", 'h')),
        group: "general",
        summary: "Show this help and exit.",
        ..Input::EMPTY
    };
    let log: Input<String, &'static str> = Input {
        key: "log",
        ty: Type::Enum,
        allowed: &["off", "text", "json"],
        default: Some("off".to_string()),
        env: Some(Env::new("APP_LOG")),
        arg: Some(Arg {
            value_name: "FORMAT",
            ..Arg::long("log")
        }),
        group: "logging",
        summary: "What to log.",
        ..Input::EMPTY
    };
    let log_file: Input<PathBuf, &'static str> = Input {
        key: "log_file",
        ty: Type::Path,
        env: Some(Env::new("APP_LOG_FILE")),
        arg: Some(Arg {
            value_name: "PATH",
            ..Arg::long("log-file")
        }),
        group: "logging",
        summary: "Where to log.",
        ..Input::EMPTY
    };
    let color: Input<bool, &'static str> = Input {
        key: "color",
        ty: Type::Bool,
        arg: Some(Arg {
            negatable: true,
            ..Arg::long("color")
        }),
        group: "general",
        summary: "Use colour.",
        ..Input::EMPTY
    };
    let only: Input<String, &'static str> = Input {
        key: "only",
        ty: Type::String,
        subcommands: &["create"],
        env: Some(Env::new("APP_ONLY")),
        arg: Some(Arg {
            value_name: "CONFIGS",
            ..Arg::long("only")
        }),
        group: "create",
        summary: HOSTILE,
        ..Input::EMPTY
    };
    let dry_run: Input<bool, &'static str> = Input {
        key: "dry_run",
        ty: Type::Bool,
        default: Some(false),
        subcommands: &["create"],
        arg: Some(Arg::pair("dry-run", 'n')),
        group: "create",
        summary: "Show what would happen.",
        ..Input::EMPTY
    };
    let mode: Input<String, &'static str> = Input {
        key: "mode",
        ty: Type::Enum,
        allowed: &["fast", "slow"],
        subcommands: &["create"],
        arg: Some(Arg {
            value_name: "MODE",
            ..Arg::long("mode")
        }),
        group: "create",
        summary: "How to snapshot.",
        ..Input::EMPTY
    };
    let description: Input<String, &'static str> = Input {
        key: "description",
        ty: Type::String,
        subcommands: &["create"],
        arg: Some(Arg {
            value_name: "DESCRIPTION",
            ..Arg::positional(0)
        }),
        group: "create",
        summary: "Text stored with each snapshot.",
        ..Input::EMPTY
    };
    let shell: Input<String, &'static str> = Input {
        key: "shell",
        ty: Type::Enum,
        allowed: &["bash", "zsh", "fish", "nushell"],
        required: true,
        subcommands: &["completions"],
        arg: Some(Arg {
            value_name: "SHELL",
            ..Arg::positional(0)
        }),
        group: "completions",
        summary: "Which shell.",
        ..Input::EMPTY
    };
    let target: Input<PathBuf, &'static str> = Input {
        key: "target",
        ty: Type::Path,
        subcommands: &["export"],
        arg: Some(Arg {
            value_name: "FILE",
            ..Arg::positional(0)
        }),
        group: "export",
        summary: "Where to write.",
        ..Input::EMPTY
    };
    vec![
        help.to_record(),
        log.to_record(),
        log_file.to_record(),
        color.to_record(),
        only.to_record(),
        dry_run.to_record(),
        mode.to_record(),
        description.to_record(),
        shell.to_record(),
        target.to_record(),
    ]
}

const COMMANDS: &[Command<'static>] = &[
    Command {
        name: "create",
        summary: "Take a snapshot",
    },
    Command {
        name: "list",
        summary: "List the configs",
    },
    Command {
        name: "completions",
        summary: "Print shell completions",
    },
    Command {
        name: "export",
        summary: "Write a file",
    },
];

fn program() -> Program<'static> {
    Program {
        name: "app",
        version: "1.2.3",
        about: "Snapshot every config",
        commands: COMMANDS,
        exit_status: &[("0", "done"), ("2", "the invocation is wrong")],
        see_also: &["snapper(8)"],
        date: "2026-10-23",
        asked: &[],
    }
}

// ---- finding shells ---------------------------------------------------------------------

fn tool(name: &str) -> Option<PathBuf> {
    let found = std::env::var_os("PATH").and_then(|paths| {
        std::env::split_paths(&paths)
            .map(|dir| dir.join(name))
            .find(|candidate| candidate.is_file())
    });
    if found.is_none() && std::env::var_os("ARGENV_REQUIRE_SHELLS").is_some() {
        panic!("{name} is required (ARGENV_REQUIRE_SHELLS is set) but is not installed");
    }
    found
}

fn scratch(label: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("argenv-generate-{label}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("create scratch dir");
    dir
}

fn write(dir: &Path, name: &str, text: &str) -> PathBuf {
    let path = dir.join(name);
    std::fs::write(&path, text).expect("write file");
    path
}

fn run(process: &mut Process) -> (bool, String, String) {
    let out = process.output().expect("run");
    (
        out.status.success(),
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
    )
}

// ---- what is derived --------------------------------------------------------------------

#[test]
fn every_shell_mentions_every_spelling_of_every_flag() {
    let all: Vec<(Shell, String)> = Shell::ALL
        .iter()
        .map(|s| (*s, completions(*s, &program(), &records()).unwrap()))
        .collect();
    for (shell, text) in &all {
        for needle in ["help", "log", "log-file", "color", "only", "dry-run"] {
            assert!(text.contains(needle), "{shell:?} lacks `{needle}`:\n{text}");
        }
    }
    // short spellings are completed too (bash lists them; the others declare them)
    let (_, bash_text) = &all[0];
    assert!(
        bash_text.contains("-h") && bash_text.contains("-n"),
        "{bash_text}"
    );
}

#[test]
fn a_negatable_flag_also_offers_its_negation() {
    for shell in Shell::ALL {
        let text = completions(shell, &program(), &records()).unwrap();
        assert!(text.contains("no-color"), "{shell:?}: {text}");
    }
}

#[test]
fn enumerated_values_and_commands_are_offered() {
    for shell in Shell::ALL {
        let text = completions(shell, &program(), &records()).unwrap();
        for value in ["off", "text", "json", "bash", "zsh", "fish", "nushell"] {
            assert!(text.contains(value), "{shell:?} lacks value `{value}`");
        }
        for command in ["create", "list", "completions", "export"] {
            assert!(
                text.contains(command),
                "{shell:?} lacks command `{command}`"
            );
        }
    }
}

#[test]
fn a_flag_scoped_to_a_command_is_only_offered_for_that_command() {
    // bash: the flag list for `list` must not contain --dry-run, the one for `create` must.
    let text = bash(&program(), &records()).unwrap();
    let line = |command: &str| {
        text.lines()
            .find(|l| l.trim_start().starts_with(&format!("{command}) flags=")))
            .unwrap_or_else(|| panic!("no flags line for {command}:\n{text}"))
            .to_string()
    };
    assert!(line("create").contains("--dry-run"));
    assert!(!line("list").contains("--dry-run") && !line("list").contains("--only"));
    assert!(
        line("list").contains("--log"),
        "unscoped flags are offered everywhere"
    );

    // fish: the dry-run line carries the condition.
    let text = fish(&program(), &records()).unwrap();
    let dry = text.lines().find(|l| l.contains("-l dry-run")).unwrap();
    assert!(dry.contains("__fish_seen_subcommand_from create"), "{dry}");
    let log = text.lines().find(|l| l.contains("-l log ")).unwrap();
    assert!(!log.contains("__fish_seen_subcommand_from"), "{log}");

    // zsh: --dry-run only appears inside the create branch.
    let text = zsh(&program(), &records()).unwrap();
    let create = text.find("        create)").unwrap();
    let after = &text[create..];
    let end = after.find(";;").unwrap();
    assert!(after[..end].contains("--dry-run"));
    let before_create = &text[..create];
    assert!(
        !before_create.contains("dry-run"),
        "not in the top-level flags:\n{before_create}"
    );

    // nushell: the `app list` extern has no --dry-run.
    let text = nushell(&program(), &records()).unwrap();
    let block = |name: &str| {
        let start = text.find(&format!("export extern \"{name}\"")).unwrap();
        let rest = &text[start..];
        rest[..rest.find("  ]").unwrap()].to_string()
    };
    assert!(block("app create").contains("--dry-run"));
    assert!(!block("app list").contains("--dry-run"));
    assert!(block("app list").contains("--log"));
}

#[test]
fn output_is_deterministic() {
    for shell in Shell::ALL {
        assert_eq!(
            completions(shell, &program(), &records()).unwrap(),
            completions(shell, &program(), &records()).unwrap()
        );
    }
    assert_eq!(
        man_page(&program(), &records()).unwrap(),
        man_page(&program(), &records()).unwrap()
    );
}

#[test]
fn a_program_without_subcommands_still_gets_completions() {
    let bare = Program {
        commands: &[],
        ..program()
    };
    let flags_only: Vec<Record> = records()
        .into_iter()
        .filter(|r| r.subcommands.is_empty())
        .collect();
    for shell in Shell::ALL {
        let text = completions(shell, &bare, &flags_only).unwrap();
        assert!(text.contains("log"), "{shell:?}");
    }
}

// ---- the contract is untrusted ----------------------------------------------------------

#[test]
fn a_program_or_command_name_that_is_not_a_plain_name_is_refused() {
    for bad in ["my app", "a;b", "$(x)", "-x", "", "a'b", "a\"b", "a`b"] {
        let p = Program {
            name: bad,
            ..program()
        };
        for shell in Shell::ALL {
            assert_eq!(
                completions(shell, &p, &records()),
                Err(GenerateError::InvalidName(bad.to_string())),
                "{shell:?} {bad:?}"
            );
        }
        assert!(man_page(&p, &records()).is_err());
    }
    let commands = [
        Command {
            name: "ok",
            summary: "",
        },
        Command {
            name: "b ad",
            summary: "",
        },
    ];
    let p = Program {
        commands: &commands,
        ..program()
    };
    assert!(bash(&p, &records()).is_err());
}

#[test]
fn flag_names_and_values_that_are_not_plain_tokens_are_left_out_not_emitted() {
    let evil: Input<String, &'static str> = Input {
        key: "evil",
        ty: Type::Enum,
        allowed: &["fine", "x; rm -rf PWNEDVALUE", "$(id)", "has space"],
        arg: Some(Arg {
            value_name: "V",
            ..Arg::long("evil")
        }),
        ..Input::EMPTY
    };
    let mut recs = records();
    recs.push(evil.to_record());
    let mut weird = records()[1].clone();
    weird.key = "weird".into();
    weird.arg.as_mut().unwrap().long = Some("x;touch PWNEDFLAG".into());
    weird.arg.as_mut().unwrap().short = None;
    recs.push(weird);
    for shell in Shell::ALL {
        let text = completions(shell, &program(), &recs).unwrap();
        assert!(text.contains("fine"), "{shell:?}: the safe value stays");
        for forbidden in ["PWNEDVALUE", "PWNEDFLAG", "$(id)", "has space"] {
            assert!(
                !text.contains(forbidden),
                "{shell:?} emitted `{forbidden}`:\n{text}"
            );
        }
    }
}

#[test]
fn hostile_free_text_is_quoted_in_the_man_page_too() {
    let text = man_page(&program(), &records()).unwrap();
    assert!(!text.contains("\n done"), "newlines are flattened");
    for line in text.lines() {
        assert!(
            !(line.starts_with('.') && line.contains("touch PWNED")),
            "text must not become a roff request: {line}"
        );
    }
}

fn assert_nothing_ran(dir: &Path) {
    for marker in ["PWNED", "PWNED2"] {
        assert!(
            !dir.join(marker).exists(),
            "hostile text was executed ({marker})"
        );
    }
}

#[test]
fn bash_output_is_valid_and_inert() {
    let Some(bash_path) = tool("bash") else {
        return;
    };
    let dir = scratch("bash-inert");
    let script = write(&dir, "app.bash", &bash(&program(), &records()).unwrap());
    let (ok, _, stderr) = run(Process::new(&bash_path).arg("-n").arg(&script));
    assert!(ok, "syntax: {stderr}");
    let (ok, _, stderr) = run(Process::new(&bash_path)
        .current_dir(&dir)
        .arg("-c")
        .arg(format!("source {}; type _app >/dev/null", script.display())));
    assert!(ok, "{stderr}");
    assert_nothing_ran(&dir);
}

fn bash_complete(script: &Path, dir: &Path, words: &[&str]) -> Vec<String> {
    let quoted: Vec<String> = words.iter().map(|w| format!("'{w}'")).collect();
    let program = format!(
        "source {}; COMP_WORDS=({}); COMP_CWORD={}; COMPREPLY=(); _app; printf '%s\\n' \"${{COMPREPLY[@]}}\"",
        script.display(),
        quoted.join(" "),
        words.len() - 1
    );
    let (ok, stdout, stderr) = run(Process::new("bash").current_dir(dir).arg("-c").arg(program));
    assert!(ok, "{stderr}");
    stdout
        .lines()
        .filter(|l| !l.is_empty())
        .map(str::to_string)
        .collect()
}

#[test]
fn bash_completes_commands_flags_values_and_files_the_way_a_user_would_type_them() {
    if tool("bash").is_none() {
        return;
    }
    let dir = scratch("bash-complete");
    std::fs::write(dir.join("alpha.txt"), "").unwrap();
    let script = write(&dir, "app.bash", &bash(&program(), &records()).unwrap());
    let complete = |words: &[&str]| bash_complete(&script, &dir, words);

    let mut commands = complete(&["app", ""]);
    commands.sort();
    assert_eq!(commands, ["completions", "create", "export", "list"]);
    assert_eq!(complete(&["app", "cr"]), ["create"]);

    assert_eq!(complete(&["app", "create", "--d"]), ["--dry-run"]);
    assert!(
        complete(&["app", "list", "--d"]).is_empty(),
        "scoped to create"
    );
    assert!(complete(&["app", "create", "-"]).contains(&"-n".to_string()));
    assert!(
        complete(&["app", "list", "-"]).contains(&"--log".to_string()),
        "unscoped everywhere"
    );
    assert!(complete(&["app", "--"]).contains(&"--color".to_string()));
    assert!(
        !complete(&["app", "--"]).contains(&"--dry-run".to_string()),
        "no command yet"
    );

    let mut formats = complete(&["app", "--log", ""]);
    formats.sort();
    assert_eq!(formats, ["json", "off", "text"]);
    assert_eq!(complete(&["app", "--log", "t"]), ["text"]);
    assert_eq!(
        complete(&["app", "--log", "=", "j"]),
        ["json"],
        "the --flag=value form"
    );
    assert!(
        complete(&["app", "create", "--only", ""]).is_empty(),
        "a free-text value: nothing to suggest"
    );

    // The values of a flag that belongs to `create` are completed after `create`, and only there.
    let mut modes = complete(&["app", "create", "--mode", ""]);
    modes.sort();
    assert_eq!(modes, ["fast", "slow"]);
    let before_a_command = complete(&["app", "--mode", ""]);
    assert!(
        !before_a_command.iter().any(|w| w == "fast" || w == "slow"),
        "no command yet: --mode is not in play, so its values are not offered: {before_a_command:?}"
    );
    assert!(
        complete(&["app", "list", "--mode", ""]).is_empty(),
        "list has no --mode"
    );
    assert_eq!(
        complete(&["app", "create", "--mode", "=", "s"]),
        ["slow"],
        "the --flag=value form too"
    );

    let mut shells = complete(&["app", "completions", ""]);
    shells.sort();
    assert_eq!(shells, ["bash", "fish", "nushell", "zsh"]);
    assert_eq!(
        complete(&["app", "export", "al"]),
        ["alpha.txt"],
        "a path positional completes files"
    );
    assert_eq!(
        complete(&["app", "--log-file", "al"]),
        ["alpha.txt"],
        "a path flag completes files"
    );
}

#[test]
fn fish_output_is_valid_inert_and_completes() {
    let Some(fish_path) = tool("fish") else {
        return;
    };
    let dir = scratch("fish");
    let script = write(&dir, "app.fish", &fish(&program(), &records()).unwrap());
    let ask = |line: &str| {
        let (ok, stdout, stderr) = run(Process::new(&fish_path)
            .current_dir(&dir)
            .arg("--no-config")
            .arg("-c")
            .arg(format!("source {}; complete -C '{line}'", script.display())));
        assert!(ok, "{stderr}");
        stdout
    };
    let flags = ask("app create --d");
    assert!(flags.contains("--dry-run"), "{flags}");
    assert!(!ask("app list --d").contains("--dry-run"));
    let values = ask("app --log ");
    assert!(
        values.contains("off") && values.contains("text") && values.contains("json"),
        "{values}"
    );
    let commands = ask("app ");
    for command in ["create", "list", "completions", "export"] {
        assert!(commands.contains(command), "{commands}");
    }
    assert!(ask("app completions ").contains("nushell"));
    assert_nothing_ran(&dir);
}

#[test]
fn zsh_output_is_valid_and_inert() {
    let Some(zsh_path) = tool("zsh") else { return };
    let dir = scratch("zsh");
    let script = write(&dir, "_app", &zsh(&program(), &records()).unwrap());
    let (ok, _, stderr) = run(Process::new(&zsh_path).arg("-n").arg(&script));
    assert!(ok, "syntax: {stderr}");
    // Loading the function (not running the completer) must execute nothing.
    let (ok, _, stderr) = run(Process::new(&zsh_path).current_dir(&dir).arg("-fc").arg(format!("autoload -Uz compinit && compinit -u -d {}/zcomp && fpath=({} $fpath) && autoload -Uz _app && whence -w _app", dir.display(), dir.display())));
    assert!(ok, "{stderr}");
    assert_nothing_ran(&dir);
}

/// Drives an interactive zsh through a pseudo-terminal: types `typed`, presses Tab, returns what
/// the terminal showed. This is the only honest test of an `_arguments` spec: a wrong one does not
/// fail, it silently completes nothing.
const ZSH_DRIVER: &str = r#"
zmodload zsh/zpty || exit 3
dir=$1; typed=$2
zpty zt 'zsh -f -i' || exit 4
zpty -w zt "fpath=($dir \$fpath); autoload -Uz compinit; compinit -u -d $dir/.zcompdump; autoload -Uz _app; compdef _app app; PS1='READY> '; setopt no_beep; zstyle ':completion:*' list-prompt ''; zstyle ':completion:*' menu no"
sleep 1; zpty -r -t zt junk 2>/dev/null
zpty -w -n zt "$typed"
sleep 0.3
zpty -w -n zt $'\t'
sleep 2
out=""; while zpty -r -t zt chunk 2>/dev/null; do out+=$chunk; done
print -r -- "$out"
zpty -d zt
"#;

#[test]
fn zsh_completes_for_real_in_a_terminal() {
    let Some(zsh_path) = tool("zsh") else { return };
    let dir = scratch("zsh-real");
    write(&dir, "_app", &zsh(&program(), &records()).unwrap());
    let driver = write(&dir, "driver.zsh", ZSH_DRIVER);
    let tab = |typed: &str| -> String {
        let (ok, stdout, stderr) = run(Process::new("timeout")
            .arg("40")
            .arg(&zsh_path)
            .current_dir(&dir)
            .arg("-f")
            .arg(&driver)
            .arg(&dir)
            .arg(typed));
        assert!(ok, "zsh driver failed: {stderr}\n{stdout}");
        stdout.replace('\r', "")
    };

    let completed = tab("app create --d");
    assert!(
        completed.contains("--dry-run") && completed.contains("Show what would happen."),
        "the flag and its description are offered:\n{completed}"
    );
    let listed = tab("app create -");
    for flag in [
        "--color",
        "--dry-run",
        "--log",
        "--log-file",
        "--no-color",
        "--only",
        "--help",
    ] {
        assert!(listed.contains(flag), "{flag} missing:\n{listed}");
    }
    let list_flags = tab("app list --d");
    assert!(
        !list_flags.contains("dry-run"),
        "--dry-run is scoped to create:\n{list_flags}"
    );
    let values = tab("app --log ");
    assert!(
        values.contains("off") && values.contains("text") && values.contains("json"),
        "{values}"
    );
    assert!(tab("app completions ").contains("nushell"));
    assert!(
        tab("app cr").contains("app create"),
        "a command completes by prefix"
    );
    assert_nothing_ran(&dir);
}

#[test]
fn nushell_output_loads_and_defines_every_command() {
    let Some(nu) = tool("nu") else { return };
    let dir = scratch("nu");
    let script = write(&dir, "app.nu", &nushell(&program(), &records()).unwrap());
    let (ok, stdout, stderr) = run(Process::new(&nu)
        .current_dir(&dir)
        .arg("--no-config-file")
        .arg("-c")
        .arg(format!(
            "source {}; scope externs | where name =~ '^app' | get name | to json",
            script.display()
        )));
    assert!(ok, "{stderr}\n{stdout}");
    let names: Vec<String> = serde_json::from_str(&stdout).expect("nu prints a JSON list");
    for expected in [
        "app",
        "app create",
        "app list",
        "app completions",
        "app export",
    ] {
        assert!(
            names.iter().any(|n| n == expected),
            "{expected} missing from {names:?}"
        );
    }
    assert_nothing_ran(&dir);
}

// ---- the man page -----------------------------------------------------------------------

#[test]
fn the_man_page_has_its_sections_and_escapes_hyphens() {
    let text = man_page(&program(), &records()).unwrap();
    assert!(
        text.starts_with(".TH APP 1 \"2026-10-23\" \"app 1.2.3\" \"User Commands\"\n"),
        "{text}"
    );
    for section in [
        "NAME",
        "SYNOPSIS",
        "COMMANDS",
        "OPTIONS",
        "ARGUMENTS",
        "ENVIRONMENT",
        "EXIT STATUS",
        "SEE ALSO",
    ] {
        assert!(
            text.contains(&format!(".SH {section}\n")),
            "{section}:\n{text}"
        );
    }
    assert!(
        text.contains("\\fB\\-\\-dry\\-run\\fR"),
        "hyphens are escaped:\n{text}"
    );
    assert!(text.contains("Applies to: \\fBcreate\\fR."));
    assert!(text.contains("One of: \\fBoff\\fR, \\fBtext\\fR, \\fBjson\\fR."));
    assert!(text.contains("Default: \\fBoff\\fR."));
    assert!(
        text.contains("\\fBAPP_LOG\\fR"),
        "environment variables are listed"
    );
    assert!(text.contains("snapper(8)"));
    assert!(text.contains("app create") || text.contains("\\fBcreate\\fR"));
}

#[test]
fn the_man_page_passes_a_roff_syntax_check_when_groff_is_installed() {
    let Some(groff) = tool("groff") else { return };
    let dir = scratch("man");
    let page = write(&dir, "app.1", &man_page(&program(), &records()).unwrap());
    let (ok, _, stderr) = run(Process::new(&groff)
        .arg("-man")
        .arg("-z")
        .arg("-ww")
        .arg(&page));
    assert!(ok && stderr.trim().is_empty(), "groff complained: {stderr}");
}

#[test]
fn shell_tokens_round_trip() {
    for shell in Shell::ALL {
        assert_eq!(Shell::parse(shell.token()), Some(shell));
    }
    assert_eq!(Shell::parse("nu"), Some(Shell::Nushell));
    assert_eq!(Shell::parse("powershell"), None);
}

// ---- values the program lists itself, asked at completion time ---------------------------

/// `create`'s description and `completions`' shell are asked of the program: the first has no
/// values of its own, the second has enumerated ones the asked values replace.
const ASKED: &[Asked<'static>] = &[
    Asked {
        command: "create",
        position: 0,
        ask: &["names", "create"],
    },
    Asked {
        command: "completions",
        position: 0,
        ask: &["names", "shells"],
    },
];

fn asked_program() -> Program<'static> {
    Program {
        asked: ASKED,
        ..program()
    }
}

/// A fake `app` on `PATH` that prints its candidates when asked, and fails (noisily) for
/// `names shells` when `APP_FAIL` is set.
const FAKE_APP: &str = r#"#!/bin/sh
if [ "$1 $2" = "names create" ]; then
    printf 'first-name\nsecond-name\n'
elif [ "$1 $2" = "names shells" ]; then
    if [ -n "$APP_FAIL" ]; then echo "app: broken" >&2; exit 1; fi
    printf 'ksh\n'
else
    echo "app: asked something unexpected: $*" >&2
    exit 2
fi
"#;

/// A directory holding the fake `app`, and a `PATH` with it in front.
fn fake_app(dir: &Path) -> std::ffi::OsString {
    let bin = dir.join("bin");
    std::fs::create_dir_all(&bin).unwrap();
    let app = write(&bin, "app", FAKE_APP);
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(&app, std::fs::Permissions::from_mode(0o755)).unwrap();
    let mut paths = vec![bin];
    if let Some(old) = std::env::var_os("PATH") {
        paths.extend(std::env::split_paths(&old));
    }
    std::env::join_paths(paths).unwrap()
}

#[test]
fn an_asked_positional_runs_the_program_in_every_shell() {
    for shell in Shell::ALL {
        let text = completions(shell, &asked_program(), &records()).unwrap();
        let bare = text.replace(['\'', '"'], "");
        assert!(bare.contains("app names create"), "{shell:?}:\n{text}");
        assert!(
            text.contains("2>/dev/null") || shell == Shell::Nushell,
            "{shell:?}"
        );
    }
    // Asked values take precedence over the enumerated ones for that slot (bash, the one arm).
    let text = bash(&asked_program(), &records()).unwrap();
    let arm = text
        .lines()
        .find(|l| l.trim_start().starts_with("completions:0)"))
        .unwrap();
    assert!(arm.contains("names") && !arm.contains("nushell"), "{arm}");
}

#[test]
fn an_ask_that_is_not_plain_tokens_is_refused() {
    for (command, ask) in [
        ("create", &["names", "$(touch PWNED)"][..]),
        ("create", &["a b"][..]),
        ("create", &["x;y"][..]),
        ("create", &[][..]),
        ("cr eate", &["names"][..]),
    ] {
        let asked = [Asked {
            command,
            position: 0,
            ask,
        }];
        let p = Program {
            asked: &asked,
            ..program()
        };
        for shell in Shell::ALL {
            assert!(
                matches!(
                    completions(shell, &p, &records()),
                    Err(GenerateError::InvalidName(_))
                ),
                "{shell:?} {command:?} {ask:?}"
            );
        }
    }
}

#[test]
fn bash_completes_what_the_program_prints_when_asked() {
    if tool("bash").is_none() {
        return;
    }
    let dir = scratch("bash-asked");
    let path = fake_app(&dir);
    let script = write(
        &dir,
        "app.bash",
        &bash(&asked_program(), &records()).unwrap(),
    );
    let complete = |words: &[&str], fail: bool| {
        let quoted: Vec<String> = words.iter().map(|w| format!("'{w}'")).collect();
        let line = format!(
            "source {}; COMP_WORDS=({}); COMP_CWORD={}; COMPREPLY=(); _app; printf '%s\\n' \"${{COMPREPLY[@]}}\"",
            script.display(),
            quoted.join(" "),
            words.len() - 1
        );
        let mut process = Process::new("bash");
        process
            .current_dir(&dir)
            .env("PATH", &path)
            .arg("-c")
            .arg(line);
        if fail {
            process.env("APP_FAIL", "1");
        }
        let (ok, stdout, stderr) = run(&mut process);
        assert!(ok, "{stderr}");
        assert!(
            stderr.is_empty(),
            "the program's errors are not shown: {stderr}"
        );
        stdout
            .lines()
            .filter(|l| !l.is_empty())
            .map(str::to_string)
            .collect::<Vec<_>>()
    };
    assert_eq!(
        complete(&["app", "create", ""], false),
        ["first-name", "second-name"]
    );
    assert_eq!(complete(&["app", "create", "s"], false), ["second-name"]);
    assert_eq!(
        complete(&["app", "completions", ""], false),
        ["ksh"],
        "the asked values replace the enumerated ones"
    );
    assert!(
        complete(&["app", "completions", ""], true).is_empty(),
        "a failing program offers nothing"
    );
    assert_nothing_ran(&dir);
}

#[test]
fn fish_completes_what_the_program_prints_when_asked() {
    let Some(fish_path) = tool("fish") else {
        return;
    };
    let dir = scratch("fish-asked");
    let path = fake_app(&dir);
    let script = write(
        &dir,
        "app.fish",
        &fish(&asked_program(), &records()).unwrap(),
    );
    let ask = |line: &str, fail: bool| {
        let mut process = Process::new(&fish_path);
        process
            .current_dir(&dir)
            .env("PATH", &path)
            .arg("--no-config")
            .arg("-c")
            .arg(format!("source {}; complete -C '{line}'", script.display()));
        if fail {
            process.env("APP_FAIL", "1");
        }
        let (ok, stdout, stderr) = run(&mut process);
        assert!(ok, "{stderr}");
        assert!(
            stderr.is_empty(),
            "the program's errors are not shown: {stderr}"
        );
        stdout
    };
    let names = ask("app create ", false);
    assert!(
        names.contains("first-name") && names.contains("second-name"),
        "{names}"
    );
    let shells = ask("app completions ", false);
    assert!(
        shells.contains("ksh") && !shells.contains("nushell"),
        "{shells}"
    );
    assert!(!ask("app completions ", true).contains("ksh"));
    assert_nothing_ran(&dir);
}

#[test]
fn zsh_completes_what_the_program_prints_when_asked() {
    let Some(zsh_path) = tool("zsh") else { return };
    let dir = scratch("zsh-asked");
    let path = fake_app(&dir);
    write(&dir, "_app", &zsh(&asked_program(), &records()).unwrap());
    let driver = write(&dir, "driver.zsh", ZSH_DRIVER);
    let tab = |typed: &str| -> String {
        let (ok, stdout, stderr) = run(Process::new("timeout")
            .arg("40")
            .arg(&zsh_path)
            .current_dir(&dir)
            .env("PATH", &path)
            .arg("-f")
            .arg(&driver)
            .arg(&dir)
            .arg(typed));
        assert!(ok, "zsh driver failed: {stderr}\n{stdout}");
        stdout.replace('\r', "")
    };
    let names = tab("app create ");
    assert!(
        names.contains("first-name") && names.contains("second-name"),
        "{names}"
    );
    assert!(
        tab("app create s").contains("app create second-name"),
        "a single candidate is completed in place"
    );
    let shells = tab("app completions ");
    assert!(
        shells.contains("app completions ksh") && !shells.contains("nushell"),
        "{shells}"
    );
    assert_nothing_ran(&dir);
}

#[test]
fn nushell_completes_what_the_program_prints_when_asked() {
    let Some(nu) = tool("nu") else { return };
    let dir = scratch("nu-asked");
    let path = fake_app(&dir);
    let text = nushell(&asked_program(), &records()).unwrap();
    write(&dir, "app.nu", &text);
    // The completers are private to the module, so each is lifted out and run on its own.
    let body = |completer: &str| -> String {
        let head = format!("  def \"nu-complete app {completer}\" [] {{ ");
        let line = text
            .lines()
            .find(|l| l.starts_with(&head))
            .unwrap_or_else(|| panic!("no completer {completer}:\n{text}"));
        line[head.len()..line.len() - 2].to_string()
    };
    let call = |completer: &str, fail: bool| -> Vec<String> {
        let mut process = Process::new(&nu);
        process
            .current_dir(&dir)
            .env("PATH", &path)
            .arg("--no-config-file")
            .arg("-c")
            .arg(format!("def f [] {{ {} }}; f | to json", body(completer)));
        if fail {
            process.env("APP_FAIL", "1");
        }
        let (ok, stdout, stderr) = run(&mut process);
        assert!(ok, "{stderr}\n{stdout}");
        serde_json::from_str(&stdout).expect("nu prints a JSON list")
    };
    assert_eq!(call("create 0", false), ["first-name", "second-name"]);
    assert_eq!(call("completions 0", false), ["ksh"]);
    assert!(call("completions 0", true).is_empty());
    // And the whole file still loads, with the completer attached to the positional.
    let (ok, stdout, stderr) = run(Process::new(&nu)
        .current_dir(&dir)
        .arg("--no-config-file")
        .arg("-c")
        .arg(format!(
            "source {}; scope externs | where name == 'app create' | length",
            dir.join("app.nu").display()
        )));
    assert!(ok && stdout.trim() == "1", "{stderr}\n{stdout}");
    assert!(
        text.contains("string@\"nu-complete app create 0\""),
        "{text}"
    );
    assert_nothing_ran(&dir);
}