mds-cli 0.5.1

MDS (Markdown Script) compiler — command-line interface
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
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
mod common;
use common::{fixture, make_symlink, mds_bin};

#[test]
fn check_stdin_valid() {
    let mut child = mds_bin()
        .args(["check", "-"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    use std::io::Write;
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"---\nname: World\n---\nHello {{name}}!\n")
        .unwrap();

    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "check stdin should succeed for valid input"
    );
}

#[test]
fn check_stdin_with_root_cwd_succeeds() {
    // #371: `mds check -` with no explicit base_dir resolves it from cwd. A
    // process whose cwd IS the filesystem root must not fail to check.
    let mut child = mds_bin()
        .args(["check", "-"])
        .current_dir("/")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    use std::io::Write;
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"---\nname: World\n---\nHello {{name}}!\n")
        .unwrap();

    let output = child.wait_with_output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    assert!(
        output.status.success(),
        "check stdin with cwd=/ should succeed for valid input; stderr: {stderr}"
    );
}

#[test]
fn check_invalid_exits_nonzero() {
    let output = mds_bin()
        .args(["check", fixture("undefined_var.mds").to_str().unwrap()])
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "check on invalid file should exit non-zero"
    );
}

#[test]
fn check_auto_detects_single_mds_file_in_directory() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let mds_path = dir.path().join("valid.mds");
    std::fs::write(&mds_path, "---\nname: World\n---\nHello {{name}}!\n").expect("write fixture");

    let output = mds_bin()
        .current_dir(dir.path())
        .arg("check")
        .output()
        .expect("run mds check");

    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        output.status.success(),
        "check auto-detect should succeed; stderr: {stderr}"
    );
    assert!(
        stderr.contains("OK"),
        "check should print OK message, got stderr: {stderr}"
    );
}

#[test]
fn init_creates_compilable_file() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("test.mds");

    // Create the file
    let init_output = mds_bin()
        .args(["init", target.to_str().unwrap()])
        .output()
        .unwrap();
    assert!(init_output.status.success(), "init should succeed");
    assert!(target.exists(), "init should create the file");

    // Compile the created file
    let build_output = mds_bin()
        .args(["build", target.to_str().unwrap()])
        .output()
        .unwrap();
    assert!(
        build_output.status.success(),
        "init-created file should compile successfully; stderr: {}",
        String::from_utf8_lossy(&build_output.stderr)
    );
}

#[test]
fn init_force_overwrites() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("test.mds");
    std::fs::write(&target, "original content").unwrap();

    let output = mds_bin()
        .args(["init", target.to_str().unwrap(), "--force"])
        .output()
        .unwrap();

    assert!(output.status.success(), "init --force should succeed");
    let content = std::fs::read_to_string(&target).unwrap();
    assert!(
        content != "original content",
        "init --force should overwrite the file"
    );
    assert!(
        content.contains("Hello"),
        "overwritten file should contain template content"
    );
}

#[test]
fn init_does_not_overwrite_existing_file() {
    let dir = tempfile::tempdir().unwrap();
    let existing = dir.path().join("existing.mds");
    std::fs::write(&existing, "original content").unwrap();

    // Try to init over existing file - should fail
    let output = mds_bin()
        .args(["init", existing.to_str().unwrap()])
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "init should fail on existing file without --force"
    );

    // Verify original content preserved
    let content = std::fs::read_to_string(&existing).unwrap();
    assert_eq!(content, "original content");
}

/// T-D1-1 (#386): `mds init --force` at a live symlink is refused; the link and its
/// target survive untouched. Without `--force` the link is refused as a file already there
/// (#160). Positive control in the same test: `mds init` on a plain (non-symlink) path
/// still succeeds normally.
#[test]
fn init_force_symlink_target_refused_plain_path_created() {
    let dir = tempfile::tempdir().unwrap();
    let real = dir.path().join("real.txt");
    std::fs::write(&real, "REAL").unwrap();
    let link = dir.path().join("link.mds");
    if !make_symlink(&real, &link) {
        return;
    }

    let refused = mds_bin()
        .args(["init", link.to_str().unwrap(), "--force"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert_eq!(
        refused.status.code(),
        Some(2),
        "init --force onto a symlink is a refused write, exit 2 (#157); stderr: {stderr}"
    );
    assert!(
        stderr.contains("mds::io") && stderr.contains("refusing to replace a symlink"),
        "the refusal must be mds::io and say why; got: {stderr}"
    );
    assert_eq!(
        std::fs::read_to_string(&real).unwrap(),
        "REAL",
        "the symlink target must not be written through"
    );
    assert!(
        std::fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink(),
        "the symlink itself must survive the refusal"
    );

    // Without `--force` the same live link is a file already there (#160): refused as
    // one, exit 1 with no error code, and nothing is written through it.
    let found = mds_bin()
        .current_dir(dir.path())
        .args(["init", "link.mds"])
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&found.stderr);
    assert_eq!(
        found.status.code(),
        Some(1),
        "init onto a live symlink without --force; stderr: {stderr}"
    );
    assert!(
        stderr.contains("link.mds already exists (use --force to overwrite)")
            && !stderr.contains("mds::"),
        "refused as a file already there, with no error code; got: {stderr}"
    );
    assert_eq!(
        std::fs::read_to_string(&real).unwrap(),
        "REAL",
        "nothing is written through the link without --force"
    );

    // Positive control: init on a plain (non-symlink) path still succeeds.
    let plain = dir.path().join("plain.mds");
    let ok = mds_bin()
        .args(["init", plain.to_str().unwrap()])
        .output()
        .unwrap();
    assert_eq!(
        ok.status.code(),
        Some(0),
        "init on a plain path must still succeed; stderr: {}",
        String::from_utf8_lossy(&ok.stderr)
    );
    assert!(
        std::fs::read_to_string(&plain)
            .unwrap()
            .contains("Hello {{name}}!"),
        "init must write the starter template"
    );
}

/// T-D1-2 (#386): `mds init` (no `--force`) at a dangling symlink is refused; the
/// target is never created and the link survives. Positive control in the same test:
/// `mds init` on a plain (non-symlink) path still succeeds normally.
#[test]
fn init_dangling_symlink_refused_without_force() {
    let dir = tempfile::tempdir().unwrap();
    let victim = dir.path().join("victim.txt");
    let link = dir.path().join("link.mds");
    if !make_symlink(&victim, &link) {
        return;
    }

    let refused = mds_bin()
        .args(["init", link.to_str().unwrap()])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert_eq!(
        refused.status.code(),
        Some(2),
        "init onto a dangling symlink is a refused write, exit 2 (#157); stderr: {stderr}"
    );
    assert!(
        stderr.contains("mds::io") && stderr.contains("refusing to replace a symlink"),
        "the refusal must be mds::io and say why; got: {stderr}"
    );
    assert_eq!(
        victim.symlink_metadata().unwrap_err().kind(),
        std::io::ErrorKind::NotFound,
        "the dangling link's target must not be created"
    );
    assert!(
        std::fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink(),
        "the symlink itself must survive the refusal"
    );

    // Positive control: init on a plain (non-symlink) path still succeeds.
    let plain = dir.path().join("plain.mds");
    let ok = mds_bin()
        .args(["init", plain.to_str().unwrap()])
        .output()
        .unwrap();
    assert_eq!(
        ok.status.code(),
        Some(0),
        "init on a plain path must still succeed; stderr: {}",
        String::from_utf8_lossy(&ok.stderr)
    );
    assert!(
        std::fs::read_to_string(&plain)
            .unwrap()
            .contains("Hello {{name}}!"),
        "init must write the starter template"
    );
}

/// T-D1-3 (#386, pin): `mds init --force` on a regular file replaces it atomically via
/// rename, preserving its permission bits, and leaves no `.mds-tmp-` temp file behind.
/// Already green on `main` before this PR — this test pins the contract stated in the
/// PR body so a future regression is caught.
///
/// `#[cfg(unix)]`: Unix permission mode bits have no Windows equivalent (#147).
#[cfg(unix)]
#[test]
fn init_force_regular_file_replaced_atomically_mode_preserved() {
    use std::os::unix::fs::PermissionsExt as _;

    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("keep.mds");
    std::fs::write(&target, "original content").unwrap();
    std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)).unwrap();

    let output = mds_bin()
        .args(["init", target.to_str().unwrap(), "--force"])
        .output()
        .unwrap();

    assert_eq!(
        output.status.code(),
        Some(0),
        "init --force on a regular file must succeed; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let content = std::fs::read_to_string(&target).unwrap();
    assert!(
        content.contains("Hello {{name}}!"),
        "the overwritten file must contain the starter template; got: {content:?}"
    );
    let mode = std::fs::metadata(&target).unwrap().permissions().mode();
    assert_eq!(
        mode & 0o777,
        0o600,
        "the replaced file must preserve the original permission bits"
    );
    let leftover_tmp = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .any(|e| e.file_name().to_string_lossy().starts_with(".mds-tmp-"));
    assert!(
        !leftover_tmp,
        "no .mds-tmp- temp file should remain in the directory"
    );
}

#[test]
fn set_flag_cli_overrides() {
    // --set name=Test should override the frontmatter variable 'name'
    let output = mds_bin()
        .args([
            "build",
            fixture("simple.mds").to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "name=Test",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(output.status.success(), "build with --set should succeed");
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("Hello Test!"),
        "expected '--set name=Test' to override frontmatter, got: {stdout}"
    );
}

#[test]
fn set_flag_boolean_coercion() {
    // --set premium=false must coerce the string "false" to boolean false,
    // so @if premium: evaluates as falsy and the @else branch is rendered.
    let output = mds_bin()
        .args([
            "build",
            fixture("set_flag_false.mds").to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "premium=false",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build with --set premium=false should succeed"
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("Upgrade for premium features."),
        "expected falsy branch when --set premium=false, got: {stdout}"
    );
    assert!(
        !stdout.contains("Thanks for being premium!"),
        "truthy branch must not appear when --set premium=false, got: {stdout}"
    );
}

#[test]
fn set_flag_boolean_true_coercion() {
    // --set premium=true must coerce to boolean true (truthy branch rendered).
    let output = mds_bin()
        .args([
            "build",
            fixture("set_flag_false.mds").to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "premium=true",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build with --set premium=true should succeed"
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("Thanks for being premium!"),
        "expected truthy branch when --set premium=true, got: {stdout}"
    );
}

#[test]
fn set_flag_numeric_coercion() {
    // --set count=3 must coerce the string "3" to a number so {count} renders as "3".
    let output = mds_bin()
        .args([
            "build",
            fixture("set_count.mds").to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "count=3",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build with --set count=3 should succeed"
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("Count is 3."),
        "expected numeric value from --set count=3, got: {stdout}"
    );
}

#[test]
fn set_flag_null_coercion() {
    // --set premium=null must coerce to Value::Null (falsy), so @else branch renders.
    let output = mds_bin()
        .args([
            "build",
            fixture("set_flag_false.mds").to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "premium=null",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build with --set premium=null should succeed"
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("Upgrade for premium features."),
        "expected falsy branch when --set premium=null, got: {stdout}"
    );
}

#[test]
fn set_flag_empty_array() {
    // --set items=[] must produce Value::Array(vec![]) — not [String("")].
    // The empty array is falsy, so the @else branch should render.
    let output = mds_bin()
        .args([
            "build",
            fixture("set_items_empty.mds").to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "items=[]",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build with --set items=[] should succeed"
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("empty"),
        "expected falsy branch when --set items=[], got: {stdout}"
    );
}

#[test]
fn set_flag_duplicate_key_last_wins() {
    // Passing --set name=First --set name=Second should use "Second" (last wins).
    let output = mds_bin()
        .args([
            "build",
            fixture("simple.mds").to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "name=First",
            "--set",
            "name=Second",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build with duplicate --set should succeed"
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("Hello Second!"),
        "last --set value should win when key repeated, got: {stdout}"
    );
    assert!(
        !stdout.contains("Hello First!"),
        "first --set value should be overridden by second, got: {stdout}"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains(
            "warning: variable 'name' is set more than once by --set; the last value wins"
        ),
        "duplicate --set key should produce a warning on stderr, got: {stderr}"
    );
}

// ── --set-string e2e tests (#152) ─────────────────────────────────────────────

#[test]
fn set_string_forces_string_type() {
    // --set-string count=3 must keep "3" as a String, not coerce to a Number.
    // The template compares count == "3" (a string literal); this only succeeds
    // when count is a String — a Number would raise mds::type_mismatch.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("set_string.mds");
    std::fs::write(&src, "@if count == \"3\":\nstring\n@end\n").unwrap();
    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--set-string",
            "count=3",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "build with --set-string should succeed; stderr: {}",
        String::from_utf8(output.stderr).unwrap()
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("string"),
        "expected string branch when --set-string count=3, got: {stdout}"
    );
}

#[test]
fn set_string_cross_flag_duplicate_key_is_error() {
    // --set x=1 --set-string x=2 must exit non-zero — supplying the same key
    // through both flags is a hard error (#152).
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("conflict.mds");
    std::fs::write(&src, "{{x}}\n").unwrap();
    let output = mds_bin()
        .args([
            "build",
            src.to_str().unwrap(),
            "-o",
            "-",
            "--set",
            "x=1",
            "--set-string",
            "x=2",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();
    assert!(
        !output.status.success(),
        "build with --set and --set-string for the same key must exit non-zero"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains('x'),
        "error must name the duplicate key; got: {stderr}"
    );
}

#[test]
fn exit_code_success() {
    // Use a temp directory to avoid writing simple.md into tests/fixtures/.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("simple.mds");
    std::fs::write(&src, "---\nname: Alice\n---\nHello {{name}}!\n").unwrap();
    let status = mds_bin()
        .arg("build")
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert!(
        status.success(),
        "expected exit code 0 for successful build"
    );
}

#[test]
fn exit_code_file_not_found() {
    let status = mds_bin()
        .args(["build", "/tmp/no_such_file_12345.mds"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert_eq!(
        status.code(),
        Some(2),
        "expected exit code 2 for file-not-found"
    );
}

#[test]
fn exit_code_syntax_error() {
    // A file with an undefined variable produces a logical/syntax error → exit code 1.
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bad.mds");
    std::fs::write(&path, "{{undefined_var}}").unwrap();
    let status = mds_bin()
        .args(["build"])
        .arg(&path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert_eq!(
        status.code(),
        Some(1),
        "expected exit code 1 for undefined-variable error"
    );
}

// ── mds fmt exit codes (issue #60) ────────────────────────────────────────────

#[test]
fn exit_code_fmt_success() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("clean.mds");
    std::fs::write(&src, "Hello!\n").unwrap();
    let status = mds_bin()
        .arg("fmt")
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert!(
        status.success(),
        "expected exit code 0 for an already-clean file"
    );
}

#[test]
fn exit_code_fmt_check_dirty() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("dirty.mds");
    std::fs::write(&src, "Hello!\r\n\r\n\r\n\r\nBye.\r\n").unwrap();
    let status = mds_bin()
        .args(["fmt", "--check"])
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert_eq!(
        status.code(),
        Some(1),
        "expected exit code 1 when --check finds a file that would change"
    );
}

#[test]
fn exit_code_fmt_syntax_error() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bad.mds");
    std::fs::write(&path, "```\nunclosed fence\n").unwrap();
    let status = mds_bin()
        .arg("fmt")
        .arg(&path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert_eq!(
        status.code(),
        Some(1),
        "expected exit code 1 for a syntax error"
    );
}

#[test]
fn exit_code_fmt_file_not_found() {
    let status = mds_bin()
        .args(["fmt", "/tmp/no_such_fmt_file_98765.mds"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert_eq!(
        status.code(),
        Some(2),
        "expected exit code 2 for file-not-found"
    );
}

#[test]
fn exit_code_fmt_not_mds_extension() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("notes.txt");
    std::fs::write(&path, "plain text\n").unwrap();
    let status = mds_bin()
        .arg("fmt")
        .arg(&path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert_eq!(
        status.code(),
        Some(2),
        "expected exit code 2 for a non-.mds explicit file"
    );
}

#[test]
fn exit_code_fmt_oversized() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("huge.mds");
    std::fs::write(&path, "x".repeat(10 * 1024 * 1024 + 1)).unwrap();
    let status = mds_bin()
        .arg("fmt")
        .arg(&path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");
    assert_eq!(
        status.code(),
        Some(3),
        "expected exit code 3 for oversized source"
    );
}

// #204 reversal: until v0.4.3 this test was `cli_build_directory_empty_exits_zero`
// and pinned exit 0 for an empty directory.
// Directory input: an empty directory exits 1 (#204) — "nothing to build" is an
// error, as it already was for bare auto-detect
// (cli_build.rs::build_errors_when_no_mds_files_in_directory). A missing path is NOT
// a directory and takes the single-file path → exit 2.
#[test]
fn cli_build_directory_empty_exits_one_missing_root_exits_two() {
    let dir = tempfile::tempdir().unwrap();

    let output = mds_bin()
        .arg("build")
        .arg(dir.path())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(1),
        "build on an empty directory must exit 1; stderr: {stderr}"
    );
    assert!(
        stderr.contains("no .mds files found in"),
        "stderr must carry the empty-tree diagnostic; got: {stderr:?}"
    );

    // A path that does not exist is not a directory: it takes the single-file path
    // and reports mds::file_not_found (exit 2), never the empty-tree diagnostic.
    let missing = dir.path().join("does-not-exist");
    let output_missing = mds_bin()
        .arg("build")
        .arg(&missing)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    let stderr_missing = String::from_utf8_lossy(&output_missing.stderr);
    assert_eq!(
        output_missing.status.code(),
        Some(2),
        "build on a missing path must exit 2; stderr: {stderr_missing}"
    );
    assert!(
        !stderr_missing.contains("no .mds files found in"),
        "a missing path must NOT produce the empty-tree diagnostic; got: {stderr_missing:?}"
    );
}

#[test]
fn cli_init_rejects_path_traversal() {
    let output = mds_bin()
        .arg("init")
        .arg("../escaped.mds")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "init with path traversal must fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("..") || stderr.contains("traversal") || stderr.contains("components"),
        "error should mention path traversal, got: {stderr}"
    );
}

// ── ESC injection regression — mds check (issue #176 / ESC-INJECTION) ────────

/// Regression gate: `mds check <file>` (single-file mode) must not emit raw
/// ESC bytes to stderr when the source file contains a raw ESC byte that reaches
/// `MdsError::Syntax`.
///
/// Single-file check errors propagate to `main()` via `?`, which is the
/// last-resort sanitizer boundary at `main.rs`.  This test validates that
/// boundary for the check subcommand specifically.
#[test]
fn check_single_file_esc_byte_in_syntax_error_is_sanitized_on_stderr() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("esc_check.mds");
    std::fs::write(&path, b"@define \x1bfoo:\nhello\n").unwrap();

    let out = mds_bin()
        .args(["check"])
        .arg(&path)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert_ne!(
        out.status.code(),
        Some(0),
        "check with syntax error should fail; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must be sanitized before writing to stderr (check single-file); \
         got (hex): {:02x?}",
        &out.stderr[..out.stderr.len().min(512)]
    );
    assert!(
        !out.stdout.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not appear in stdout (check single-file); \
         got (hex): {:02x?}",
        &out.stdout[..out.stdout.len().min(512)]
    );
}

/// Regression gate: `mds check <dir>` (directory mode) must not emit raw ESC bytes
/// to stderr when a source file contains a raw ESC byte that reaches `MdsError::Syntax`.
///
/// Directory check errors are handled in `run_check_directory` (main.rs) which
/// explicitly calls `mds::sanitize_control_chars` at the per-file render site.
/// This test validates that boundary for the check directory path.
#[test]
fn check_directory_esc_byte_in_syntax_error_is_sanitized_on_stderr() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("esc_check.mds"),
        b"@define \x1bfoo:\nhello\n",
    )
    .unwrap();

    let out = mds_bin()
        .args(["check"])
        .arg(dir.path())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert_ne!(
        out.status.code(),
        Some(0),
        "check dir with syntax error should fail; stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must be sanitized before writing to stderr (check directory); \
         got (hex): {:02x?}",
        &out.stderr[..out.stderr.len().min(512)]
    );
    assert!(
        !out.stdout.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not appear in stdout (check directory); \
         got (hex): {:02x?}",
        &out.stdout[..out.stdout.len().min(512)]
    );
}

// ── R4 (v0.4.0 dogfood): --set/--set-string collision → mds::var_conflict, exit 1 ──
//
// The cross-flag collision was a bare `miette::miette!()` string: no diagnostic
// code anywhere, and `mds lint` blanket-exited 2 (analysis-failure code) for what
// is a runtime-variable usage error — while build/check/watch exited 1 via the
// untyped-error fall-through.  R4 types it as `MdsError::VarConflict` (code
// `mds::var_conflict`) and pins exit 1 on every subcommand; the message text is
// byte-identical to the old one so message-substring pins stay green.

/// Write a minimal template that uses {{x}} and return (tempdir, path-string).
fn var_conflict_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("conflict.mds");
    std::fs::write(&src, "{{x}}\n").unwrap();
    (dir, src)
}

const VAR_CONFLICT_ARGS: [&str; 4] = ["--set", "x=1", "--set-string", "x=2"];
const VAR_CONFLICT_MSG: &str = "variable 'x' is set by both --set and --set-string; use only one";

#[test]
fn d4_build_var_conflict_exits_1_with_code() {
    let (_dir, src) = var_conflict_fixture();
    let output = mds_bin()
        .arg("build")
        .arg(&src)
        .args(["-o", "-"])
        .args(VAR_CONFLICT_ARGS)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(1),
        "R4: build var conflict must exit 1; stderr: {stderr}"
    );
    assert!(
        stderr.contains("mds::var_conflict"),
        "R4: stderr must carry the diagnostic code; got: {stderr}"
    );
    assert!(
        stderr.contains(VAR_CONFLICT_MSG),
        "message must stay byte-identical; got: {stderr}"
    );
}

#[test]
fn d4_check_var_conflict_exits_1_with_code() {
    let (_dir, src) = var_conflict_fixture();
    let output = mds_bin()
        .arg("check")
        .arg(&src)
        .args(VAR_CONFLICT_ARGS)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(1),
        "R4: check var conflict must exit 1; stderr: {stderr}"
    );
    assert!(
        stderr.contains("mds::var_conflict"),
        "R4: stderr must carry the diagnostic code; got: {stderr}"
    );
}

#[test]
fn d4_lint_var_conflict_exits_1_with_code() {
    // THE regression: lint blanket-exited 2 for the same usage error that
    // build/check/watch report as exit 1.
    let (_dir, src) = var_conflict_fixture();
    let output = mds_bin()
        .arg("lint")
        .arg(&src)
        .args(VAR_CONFLICT_ARGS)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(1),
        "R4: lint var conflict must exit 1 (was 2); stderr: {stderr}"
    );
    assert!(
        stderr.contains("mds::var_conflict"),
        "R4: stderr must carry the diagnostic code; got: {stderr}"
    );
    assert!(
        stderr.contains(VAR_CONFLICT_MSG),
        "message must stay byte-identical; got: {stderr}"
    );
}

#[test]
fn d4_lint_json_var_conflict_emits_error_envelope() {
    // JSON consumers must see the structured code, not an empty stdout with a
    // stderr-only report: the collision routes through the analysis-failure
    // envelope ({"version":1,"error":{...}}) like every other lint-level failure.
    let (_dir, src) = var_conflict_fixture();
    let output = mds_bin()
        .arg("lint")
        .arg(&src)
        .args(["--format", "json"])
        .args(VAR_CONFLICT_ARGS)
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let json: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
        panic!(
            "R4: lint --format json must emit the error envelope on stdout ({e}); \
             stdout: {stdout:?}; stderr: {stderr}"
        )
    });
    assert_eq!(
        json["error"]["code"].as_str(),
        Some("mds::var_conflict"),
        "R4: envelope must carry the typed code; got: {json}"
    );
    assert_eq!(
        output.status.code(),
        Some(1),
        "R4: lint --format json var conflict must exit 1; stderr: {stderr}"
    );
}

#[test]
fn d4_watch_var_conflict_exits_1_with_code() {
    // The conflict is detected at watch startup, before any watcher is armed —
    // the process exits on its own (no readiness handshake needed).
    let (_dir, src) = var_conflict_fixture();
    let output = mds_bin()
        .arg("watch")
        .arg(&src)
        .args(VAR_CONFLICT_ARGS)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(1),
        "R4: watch var conflict must exit 1 at startup; stderr: {stderr}"
    );
    assert!(
        stderr.contains("mds::var_conflict"),
        "R4: stderr must carry the diagnostic code; got: {stderr}"
    );
}