adotenv-lint 0.4.0

Opt-in lint rules, schema checks and verified fixes for adotenv documents.
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
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
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
//! End-to-end tests for the report-only linter command.

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

static NEXT: AtomicU64 = AtomicU64::new(0);

struct TempDir(PathBuf);

impl TempDir {
    fn new() -> Self {
        let path = std::env::temp_dir().join(format!(
            "adotenv-lint-cli-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        fs::create_dir_all(&path).unwrap();
        Self(path)
    }
    fn file(&self, name: &str, source: &str) -> PathBuf {
        let path = self.0.join(name);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, source).unwrap();
        path
    }
    fn file_at(&self, relative: &str, source: &str) -> PathBuf {
        let path = self.0.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, source).unwrap();
        path
    }
    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

fn run(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
        .args(args)
        .output()
        .unwrap()
}

fn run_in(directory: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
        .current_dir(directory)
        .args(args)
        .output()
        .unwrap()
}

#[test]
fn reports_findings_and_exit_code_one() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "A=1\nA=2\n");
    let output = run(&[file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("duplicate-key"), "{text}");
    assert!(text.contains('A'), "{text}");
}

#[test]
fn clean_file_exits_zero() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "A=1\nB=2\n");
    let output = run(&[file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(output.stdout.len(), 0);
}

#[test]
fn key_order_and_json_output_work() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "B=2\nA=1\n");
    let output = run(&["--format=json", "--key-order", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.starts_with('['), "{text}");
    assert!(text.contains("\"rule\":\"key-order\""), "{text}");
    assert!(text.contains("\"path\":"), "{text}");
}

#[test]
fn recursive_discovery_finds_env_cascades() {
    let dir = TempDir::new();
    dir.file("nested/.env", "A=1\n");
    dir.file("nested/.env.production", "B=2\n");
    dir.file("nested/ignored.txt", "A=1\nA=2\n");
    let output = run(&["--recursive", dir.path().to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
}

#[test]
fn parse_and_usage_failures_exit_two() {
    let dir = TempDir::new();
    let bad = dir.file("bad.env", "BAD KEY=value\n");
    let output = run(&[bad.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(2));

    let output = run(&["--unknown"]);
    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn double_dash_allows_a_dash_prefixed_path() {
    let dir = TempDir::new();
    let file = dir.file("--dash.env", "A=1\nA=2\n");
    let output = run(&["--", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(1));
}

#[test]
fn fix_applies_verified_key_order_and_exits_zero() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "B=2\nA=1\n");
    let output = run(&["--fix", "--key-order", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nB=2\n");
}

#[test]
fn fix_reports_unfixable_findings_without_rewriting() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "A=1\nA=2\n");
    let output = run(&["--fix", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(1));
    assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nA=2\n");
}

#[test]
fn fix_applies_quote_style() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "A='one'\nC='two'\n");
    let output = run(&["--fix", "--quote-style=double", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(fs::read_to_string(&file).unwrap(), "A=\"one\"\nC=\"two\"\n");
}

#[test]
fn config_controls_rules_and_cli_overrides_format() {
    let dir = TempDir::new();
    let config = dir.file(
        ".adotenv-lint.toml",
        "key_order = true\nformat = \"json\"\n",
    );
    let file = dir.file("app.env", "B=2\nA=1\n");

    let output = run(&["--config", config.to_str().unwrap(), file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.trim_start().starts_with('['), "{text}");
    assert!(text.contains("key-order"), "{text}");

    let output = run(&[
        "--config",
        config.to_str().unwrap(),
        "--format=human",
        file.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(!text.trim_start().starts_with('['), "{text}");
    assert!(text.contains("key-order"), "{text}");
}

#[test]
fn default_config_is_read_from_the_working_directory() {
    let dir = TempDir::new();
    dir.file(".adotenv-lint.toml", "key_order = true\n");
    dir.file("app.env", "B=2\nA=1\n");
    let output = run_in(dir.path(), &["app.env"]);
    assert_eq!(output.status.code(), Some(1));
    assert!(String::from_utf8(output.stdout)
        .unwrap()
        .contains("key-order"));
}

#[test]
fn invalid_config_is_a_usage_failure() {
    let dir = TempDir::new();
    let config = dir.file(".adotenv-lint.toml", "unknown = true\n");
    let file = dir.file("app.env", "A=1\n");
    let output = run(&["--config", config.to_str().unwrap(), file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(2));
    assert!(String::from_utf8(output.stderr)
        .unwrap()
        .contains("unknown field"));
}

#[cfg(windows)]
#[test]
fn recursive_discovery_is_case_insensitive_on_windows() {
    let dir = TempDir::new();
    dir.file(".ENV", "A=1\nA=2\n");
    dir.file(".ENV.production", "B=2\nB=3\n");
    dir.file_at(".GIT/ignored.env", "C=1\nC=2\n");
    let output = run(&["--recursive", dir.path().to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains(".ENV"), "{text}");
    assert!(text.contains(".ENV.production"), "{text}");
    assert!(!text.contains("ignored.env"), "{text}");
}

#[test]
fn fix_batches_multiple_key_case_renames() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "a=1\nb=2\n");
    let output = run(&["--fix", "--key-case=upper", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nB=2\n");
}

#[test]
fn rule_severity_and_ignore_patterns_are_honored() {
    let dir = TempDir::new();
    dir.file(
        ".adotenv-lint.toml",
        "ignore = [\".env.skip\"]\n[rules]\nduplicate-key = \"error\"\n",
    );
    dir.file(".env.skip", "A=1\nA=2\n");
    dir.file(".env", "B=1\nB=2\n");

    let output = run_in(dir.path(), &["--format=json", ".env"]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("\"severity\":\"error\""), "{text}");

    let output = run_in(dir.path(), &["--format=github", ".env"]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.starts_with("::error "), "{text}");

    let output = run_in(dir.path(), &[".env"]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("error[duplicate-key]"), "{text}");

    let output = run_in(dir.path(), &["--recursive", "."]);
    assert_eq!(output.status.code(), Some(1));
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains(".env"), "{text}");
    assert!(!text.contains(".env.skip"), "{text}");

    let output = run_in(
        dir.path(),
        &["--recursive", "--exclude=.env", "--exclude=.env.skip", "."],
    );
    assert_eq!(output.status.code(), Some(0));
}

#[test]
fn config_is_discovered_from_an_ancestor_directory() {
    let dir = TempDir::new();
    dir.file(".adotenv-lint.toml", "key_order = true\n");
    dir.file_at("nested/app.env", "B=2\nA=1\n");
    let nested = dir.path().join("nested");
    let output = run_in(&nested, &["app.env"]);
    assert_eq!(output.status.code(), Some(1));
    assert!(String::from_utf8(output.stdout)
        .unwrap()
        .contains("key-order"));
}

#[test]
fn fix_batches_renames_sorting_and_quote_style() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "b='two'\na='one'\n");
    let output = run(&[
        "--fix",
        "--key-case=upper",
        "--key-order",
        "--quote-style=double",
        file.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(fs::read_to_string(&file).unwrap(), "A=\"one\"\nB=\"two\"\n");
}

#[test]
fn exclude_matches_an_explicit_file_by_basename() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "A=1\nA=2\n");
    let output = run(&["--exclude=app.env", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(output.stdout.len(), 0);
}

#[test]
fn fix_handles_a_long_target_file_name() {
    let dir = TempDir::new();
    let name = format!("{}.env", "x".repeat(180));
    let file = dir.file(&name, "B=2\nA=1\n");
    let output = run(&["--fix", "--key-order", file.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nB=2\n");
}

#[test]
fn rules_table_can_enable_and_disable_rules() {
    let dir = TempDir::new();
    dir.file(".adotenv-lint.toml", "[rules]\nkey-order = \"error\"\n");
    dir.file(".env", "B=2\nA=1\n");
    let output = run_in(dir.path(), &[".env"]);
    assert_eq!(output.status.code(), Some(1));
    assert!(String::from_utf8(output.stdout)
        .unwrap()
        .contains("key-order"));

    dir.file(".adotenv-lint.toml", "[rules]\nduplicate-key = \"off\"\n");
    dir.file(".env", "A=1\nA=2\n");
    let output = run_in(dir.path(), &[".env"]);
    assert_eq!(output.status.code(), Some(0));
}

#[test]
fn parse_limit_flags_bound_input_bytes_and_lines() {
    let dir = TempDir::new();
    let file = dir.file("app.env", "A=1\nB=2\nC=3\n");

    let too_many_lines = run(&["--max-lines", "2", file.to_str().unwrap()]);
    assert_eq!(too_many_lines.status.code(), Some(2));
    assert!(String::from_utf8(too_many_lines.stderr)
        .unwrap()
        .contains("line"));

    let too_many_bytes = run(&["--max-input-bytes=6", file.to_str().unwrap()]);
    assert_eq!(too_many_bytes.status.code(), Some(2));
    assert!(String::from_utf8(too_many_bytes.stderr)
        .unwrap()
        .contains("limit"));

    let within_limits = run(&[
        "--max-input-bytes",
        "64",
        "--max-lines=3",
        file.to_str().unwrap(),
    ]);
    assert_eq!(within_limits.status.code(), Some(0));

    let bad_val = run(&["--max-lines=abc", file.to_str().unwrap()]);
    assert_eq!(bad_val.status.code(), Some(2));
    let missing_val = run(&["--max-input-bytes"]);
    assert_eq!(missing_val.status.code(), Some(2));
}

#[test]
fn help_version_default_scan_multi_json_and_dir_without_recursive() {
    let help = run(&["--help"]);
    assert_eq!(help.status.code(), Some(0));
    assert!(String::from_utf8(help.stdout)
        .unwrap()
        .contains("--max-lines"));

    let version = run(&["--version"]);
    assert_eq!(version.status.code(), Some(0));
    assert!(String::from_utf8(version.stdout)
        .unwrap()
        .starts_with("adotenv-lint "));

    let dir = TempDir::new();
    let file = dir.file(".env", "A=1\nA=2\nB=3\nB=4\n");

    // Passing a directory without --recursive fails with exit code 2.
    let dir_err = run(&[dir.path().to_str().unwrap()]);
    assert_eq!(dir_err.status.code(), Some(2));
    assert!(String::from_utf8(dir_err.stderr)
        .unwrap()
        .contains("--recursive"));

    // No path argument searches the current directory recursively.
    let default_scan = run_in(dir.path(), &["--format=json"]);
    assert_eq!(default_scan.status.code(), Some(1));
    let json = String::from_utf8(default_scan.stdout).unwrap();
    assert!(json.starts_with("[{") && json.trim_end().ends_with("}]"));
    assert!(json.contains("},{"));

    // Recursive walk enters normal directories and skips ignored directories.
    let walk_dir = TempDir::new();
    walk_dir.file_at("nested/.env", "A=1\nA=2\n");
    walk_dir.file_at(".git/.env", "X=1\nX=2\n");
    walk_dir.file_at("target/.env", "Y=1\nY=2\n");
    let walk_out = run(&["--recursive", walk_dir.path().to_str().unwrap()]);
    assert_eq!(walk_out.status.code(), Some(1));
    let walk_text = String::from_utf8(walk_out.stdout).unwrap();
    assert!(walk_text.contains("nested"));
    assert!(!walk_text.contains(".git"));
    assert!(!walk_text.contains("target"));

    // --fix handles a >160-byte filename whose byte 160 falls inside a UTF-8 char.
    let utf8_name = format!("{}é.env", "a".repeat(159));
    let utf8_file = dir.file(&utf8_name, "B=2\nA=1\n");
    let utf8_fix = run(&["--fix", "--key-order", utf8_file.to_str().unwrap()]);
    assert_eq!(utf8_fix.status.code(), Some(0));
    assert_eq!(fs::read_to_string(&utf8_file).unwrap(), "A=1\nB=2\n");

    // --fix respects --max-lines.
    let fix_limited = run(&["--fix", "--max-lines=2", file.to_str().unwrap()]);
    assert_eq!(fix_limited.status.code(), Some(2));

    // Multiple failing files report every error instead of overwriting earlier ones.
    let bad1 = dir.file("bad1.env", "BAD KEY=1\n");
    let bad2 = dir.file("bad2.env", "ALSO BAD=2\n");
    let multi = run(&[bad1.to_str().unwrap(), bad2.to_str().unwrap()]);
    assert_eq!(multi.status.code(), Some(2));
    let multi_err = String::from_utf8(multi.stderr).unwrap();
    assert!(multi_err.contains("bad1.env"), "{multi_err}");
    assert!(multi_err.contains("bad2.env"), "{multi_err}");

    // --config --help passes "--help" as the config path instead of printing help.
    let opt_help = run(&["--config", "--help", file.to_str().unwrap()]);
    assert_eq!(opt_help.status.code(), Some(2));
    let opt_err = String::from_utf8(opt_help.stderr).unwrap();
    assert!(opt_err.contains("--help"), "{opt_err}");

    // Duplicate path spellings (.env and ./subdir/../.env) are deduplicated.
    let dedup_dir = TempDir::new();
    let target = dedup_dir.file(".env", "A=1\nA=2\n");
    let alt = dedup_dir.path().join(".").join(".env");
    let dedup = run(&[target.to_str().unwrap(), alt.to_str().unwrap()]);
    assert_eq!(dedup.status.code(), Some(1));
    let dedup_out = String::from_utf8(dedup.stdout).unwrap();
    assert_eq!(dedup_out.lines().count(), 1, "{dedup_out}");

    // --max-input-bytes rejects oversized files on both lint and --fix.
    let bytes_lint = run(&["--max-input-bytes=4", file.to_str().unwrap()]);
    assert_eq!(bytes_lint.status.code(), Some(2));
    assert!(String::from_utf8(bytes_lint.stderr)
        .unwrap()
        .contains("limit"));
    let bytes_fix = run(&["--fix", "--max-input-bytes=4", file.to_str().unwrap()]);
    assert_eq!(bytes_fix.status.code(), Some(2));

    // Explicit symlinked directory roots (with and without trailing slash) are refused.
    #[cfg(unix)]
    {
        use std::os::unix::fs::symlink;
        let sym_root = TempDir::new();
        let outside = TempDir::new();
        outside.file(".env", "A=1\nA=2\n");
        let link = sym_root.path().join("linked");
        symlink(outside.path(), &link).unwrap();

        let no_slash = run(&["--recursive", link.to_str().unwrap()]);
        assert_eq!(no_slash.status.code(), Some(2));
        assert!(String::from_utf8(no_slash.stderr)
            .unwrap()
            .contains("symbolic link directory"));

        let with_slash = run(&["--recursive", &format!("{}/", link.display())]);
        assert_eq!(with_slash.status.code(), Some(2));
        assert!(String::from_utf8(with_slash.stderr)
            .unwrap()
            .contains("symbolic link directory"));
    }
}

#[cfg(unix)]
#[test]
fn closed_stdout_pipe_and_stdout_write_errors_report_cleanly() {
    use std::process::Stdio;

    let dir = TempDir::new();
    let many = "K=v\n".repeat(10_000);
    let big = dir.file("big.env", &many);

    // Closed stdout pipe (BrokenPipe) must not report a spurious stdout error or exit 2.
    let mut child = Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
        .arg(&big)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    drop(child.stdout.take());
    let pipe_out = child.wait_with_output().unwrap();
    assert_eq!(
        pipe_out.status.code(),
        Some(1),
        "{}",
        String::from_utf8_lossy(&pipe_out.stderr)
    );
    assert_eq!(String::from_utf8_lossy(&pipe_out.stderr), "");

    // Real stdout write/flush error (/dev/full on Linux) must report stdout error once and exit 2.
    #[cfg(target_os = "linux")]
    if let Ok(full) = fs::OpenOptions::new().write(true).open("/dev/full") {
        let help_out = Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
            .arg("--help")
            .stdout(full)
            .output()
            .unwrap();
        assert_eq!(help_out.status.code(), Some(2));
        let err = String::from_utf8(help_out.stderr).unwrap();
        assert!(err.contains("stdout error"), "{err}");
        assert_eq!(err.matches("stdout error").count(), 1, "{err}");

        let full2 = fs::OpenOptions::new()
            .write(true)
            .open("/dev/full")
            .unwrap();
        let small = dir.file("small.env", "A=1\nA=2\n");
        let lint_out = Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
            .arg(&small)
            .stdout(full2)
            .output()
            .unwrap();
        assert_eq!(lint_out.status.code(), Some(2));
        let err2 = String::from_utf8(lint_out.stderr).unwrap();
        assert!(err2.contains("stdout error"), "{err2}");
        assert_eq!(err2.matches("stdout error").count(), 1, "{err2}");
    }
}

#[test]
fn schema_example_and_config_flags_validate_end_to_end() {
    let dir = TempDir::new();
    let example = dir.file(".env.example", "HOST=localhost\nPORT=8080\nSECRET=\n");
    let env_file = dir.file(".env", "HOST=localhost\nSECRET=\nEXTRA=top-secret-val\n");

    // Basic --example flags missing PORT, allows empty SECRET and extra EXTRA.
    let basic = run(&[
        "--example",
        example.to_str().unwrap(),
        env_file.to_str().unwrap(),
    ]);
    assert_eq!(basic.status.code(), Some(1));
    let basic_out = String::from_utf8(basic.stdout).unwrap();
    assert!(basic_out.contains("missing-key"), "{basic_out}");
    assert!(basic_out.contains("[PORT]"), "{basic_out}");
    assert!(!basic_out.contains("unknown-key"), "{basic_out}");
    assert!(!basic_out.contains("empty-value"), "{basic_out}");

    // Strict --no-unknown-keys and --no-empty-values catch all three without leaking values.
    let strict = run(&[
        "--format=json",
        "--example",
        example.to_str().unwrap(),
        "--no-unknown-keys",
        "--no-empty-values",
        env_file.to_str().unwrap(),
    ]);
    assert_eq!(strict.status.code(), Some(1));
    let strict_out = String::from_utf8(strict.stdout).unwrap();
    assert!(
        strict_out.contains("\"rule\":\"missing-key\""),
        "{strict_out}"
    );
    assert!(
        strict_out.contains("\"rule\":\"unknown-key\""),
        "{strict_out}"
    );
    assert!(
        strict_out.contains("\"rule\":\"empty-value\""),
        "{strict_out}"
    );
    assert!(!strict_out.contains("top-secret-val"), "{strict_out}");

    // Recursive scan skips the --example file itself; explicit positional arg still lints it.
    let rec_dir = TempDir::new();
    rec_dir.file(".env.example", "HOST=\nPORT=\n");
    rec_dir.file(".env", "HOST=localhost\nPORT=8080\n");
    let rec_ok = run_in(
        rec_dir.path(),
        &[
            "--example",
            ".env.example",
            "--no-unknown-keys",
            "--no-empty-values",
        ],
    );
    assert_eq!(
        rec_ok.status.code(),
        Some(0),
        "stdout={} stderr={}",
        String::from_utf8_lossy(&rec_ok.stdout),
        String::from_utf8_lossy(&rec_ok.stderr)
    );
    let explicit_example = run_in(
        rec_dir.path(),
        &[
            "--example=.env.example",
            "--no-empty-values",
            ".env.example",
        ],
    );
    assert_eq!(explicit_example.status.code(), Some(1));
    assert!(String::from_utf8(explicit_example.stdout)
        .unwrap()
        .contains("empty-value"));

    // Standalone --no-empty-values works without --example.
    let empty_only = dir.file("empty.env", "EMPTY=\nBARE\nOK=1\n");
    let standalone_empty = run(&["--no-empty-values", empty_only.to_str().unwrap()]);
    assert_eq!(standalone_empty.status.code(), Some(1));
    let standalone_out = String::from_utf8(standalone_empty.stdout).unwrap();
    assert_eq!(
        standalone_out.matches("empty-value").count(),
        2,
        "{standalone_out}"
    );

    // Bare --no-unknown-keys without --example or [schema.keys] is a usage error (exit 2).
    let bad_unknown = run(&["--no-unknown-keys", empty_only.to_str().unwrap()]);
    assert_eq!(bad_unknown.status.code(), Some(2));
    assert!(String::from_utf8(bad_unknown.stderr)
        .unwrap()
        .contains("--no-unknown-keys"));
}

#[test]
fn discovered_schema_config_resolves_relative_example_and_shapes() {
    // Discovered ancestor .adotenv-lint.toml resolves relative schema.example against config dir.
    let cfg_dir = TempDir::new();
    cfg_dir.file(".env.example", "HOST=localhost\nPORT=8080\nAPP_ENV=prod\n");
    cfg_dir.file(
        ".adotenv-lint.toml",
        r#"[rules]
invalid-value = "error"
missing-key = "error"

[schema]
example = ".env.example"
allow_unknown = false

[schema.keys.PORT]
shape = "port"

[schema.keys.APP_ENV]
one_of = ["dev", "staging", "prod"]
"#,
    );
    cfg_dir.file_at(
        "nested/.env",
        "HOST=localhost\nPORT=secret-bad\nAPP_ENV=prod\n",
    );
    let nested = cfg_dir.path().join("nested");
    let cfg_out = run_in(&nested, &["--format=github", ".env"]);
    assert_eq!(cfg_out.status.code(), Some(1));
    let cfg_text = String::from_utf8(cfg_out.stdout).unwrap();
    assert!(cfg_text.contains("::error "), "{cfg_text}");
    assert!(cfg_text.contains("invalid-value"), "{cfg_text}");
    assert!(!cfg_text.contains("secret-bad"), "{cfg_text}");
}

#[test]
fn bounded_fix_and_two_pass_unquoted_cli_options_work_end_to_end() {
    let dir = TempDir::new();

    // Two-pass unquoted + equals-spacing + trailing whitespace converges cleanly in one --fix run.
    let unquote = dir.file("unquote.env", "b = \"two\"   \na = \"one\"\n");
    let fixed = run(&[
        "--fix",
        "--key-case=upper",
        "--key-order",
        "--quote-style=unquoted",
        "--equals-spacing=none",
        "--trim-trailing-whitespace",
        unquote.to_str().unwrap(),
    ]);
    assert_eq!(
        fixed.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&fixed.stderr)
    );
    assert_eq!(fs::read_to_string(&unquote).unwrap(), "A=one\nB=two\n");

    // --max-output-bytes rejects an expanding --fix and leaves the file untouched.
    let expand = dir.file("expand.env", "A=1\n");
    let byte_capped = run(&[
        "--fix",
        "--equals-spacing=spaces",
        "--max-output-bytes=4",
        expand.to_str().unwrap(),
    ]);
    assert_eq!(byte_capped.status.code(), Some(2));
    assert!(String::from_utf8(byte_capped.stderr)
        .unwrap()
        .contains("output"));
    assert_eq!(fs::read_to_string(&expand).unwrap(), "A=1\n");

    // --max-output-lines rejects --fix when output lines exceed the cap.
    let lines = dir.file("lines.env", "B=2\nA=1\n");
    let line_capped = run(&[
        "--fix",
        "--equals-spacing=spaces",
        "--max-output-lines=1",
        lines.to_str().unwrap(),
    ]);
    assert_eq!(line_capped.status.code(), Some(2));
    assert_eq!(fs::read_to_string(&lines).unwrap(), "B=2\nA=1\n");

    // --max-references=0 reports unsorted key-order without sorting when references exist,
    // while --max-references=2 allows sorting the group.
    let refs = dir.file("refs.env", "C=3\nB=$A\nA=1\n");
    let ref_capped = run(&[
        "--fix",
        "--key-order",
        "--max-references=0",
        refs.to_str().unwrap(),
    ]);
    assert_eq!(ref_capped.status.code(), Some(1));
    assert!(String::from_utf8(ref_capped.stdout)
        .unwrap()
        .contains("key-order"));
    assert_eq!(fs::read_to_string(&refs).unwrap(), "C=3\nB=$A\nA=1\n");

    let ref_allowed = run(&[
        "--fix",
        "--key-order",
        "--max-references=2",
        refs.to_str().unwrap(),
    ]);
    assert_eq!(ref_allowed.status.code(), Some(1));
    assert_eq!(fs::read_to_string(&refs).unwrap(), "B=$A\nA=1\nC=3\n");

    // --max-items and --max-diagnostics reject exceeding inputs with exit 2.
    let items_capped = run(&["--max-items=1", lines.to_str().unwrap()]);
    assert_eq!(items_capped.status.code(), Some(2));
    let dup = dir.file("dup.env", "A=1\nA=2\n");
    let diag_capped = run(&["--max-diagnostics=0", dup.to_str().unwrap()]);
    assert_eq!(diag_capped.status.code(), Some(2));

    // --fix fixes auto-fixable findings while still reporting unfixable schema findings (exit 1).
    let example = dir.file("mix.example", "A=1\nB=2\nC=3\n");
    let mixed = dir.file("mixed.env", "B=2\nA=1\n");
    let mix_out = run(&[
        "--fix",
        "--key-order",
        "--example",
        example.to_str().unwrap(),
        mixed.to_str().unwrap(),
    ]);
    assert_eq!(mix_out.status.code(), Some(1));
    assert_eq!(fs::read_to_string(&mixed).unwrap(), "A=1\nB=2\n");
    assert!(String::from_utf8(mix_out.stdout)
        .unwrap()
        .contains("missing-key"));
}

#[test]
fn sort_output_limits_diagnostics_budget_github_keys_and_compose_example() {
    let dir = TempDir::new();
    let dup = dir.file("dup.env", "A=1\nA=2\n");
    let example = dir.file("mix.example", "A=1\nB=2\nC=3\n");
    let mixed = dir.file("mixed.env", "A=1\nB=2\n");

    // --fix --key-order honors --max-output-bytes and --max-output-lines with exit 2.
    let sort_bytes = dir.file("sort_bytes.env", "B=2\nA=1\n");
    let sort_bytes_out = run(&[
        "--fix",
        "--key-order",
        "--max-output-bytes=4",
        sort_bytes.to_str().unwrap(),
    ]);
    assert_eq!(sort_bytes_out.status.code(), Some(2));
    assert_eq!(fs::read_to_string(&sort_bytes).unwrap(), "B=2\nA=1\n");

    let sort_lines_out = run(&[
        "--fix",
        "--key-order",
        "--max-output-lines=1",
        sort_bytes.to_str().unwrap(),
    ]);
    assert_eq!(sort_lines_out.status.code(), Some(2));
    assert_eq!(fs::read_to_string(&sort_bytes).unwrap(), "B=2\nA=1\n");

    // --max-diagnostics=10 permits warnings (exit 1) while still rejecting parse errors (exit 2).
    let warn_ok = run(&["--max-diagnostics=10", dup.to_str().unwrap()]);
    assert_eq!(warn_ok.status.code(), Some(1));
    let parse_err = dir.file("bad_diag.env", "BAD KEY=1\n");
    let err_with_budget = run(&["--max-diagnostics=10", parse_err.to_str().unwrap()]);
    assert_eq!(err_with_budget.status.code(), Some(2));

    // --format=github includes [KEY] for missing-key annotations.
    let gh_missing = run(&[
        "--format=github",
        "--example",
        example.to_str().unwrap(),
        mixed.to_str().unwrap(),
    ]);
    assert_eq!(gh_missing.status.code(), Some(1));
    let gh_text = String::from_utf8(gh_missing.stdout).unwrap();
    assert!(
        gh_text.contains("missing-key::required key is missing [C]"),
        "{gh_text}"
    );

    // Compose bare key in --example works cleanly with --no-unknown-keys, and
    // CLI --example overrides [rules] missing-key = "off" in config.
    let compose_dir = TempDir::new();
    compose_dir.file(".adotenv-lint.toml", "[rules]\nmissing-key = \"off\"\n");
    compose_dir.file(".env.example", "AWS_PROFILE\nHOST=localhost\n");
    compose_dir.file(".env", "HOST=localhost\n");
    let compose_out = run_in(
        compose_dir.path(),
        &[
            "--dialect=compose",
            "--example=.env.example",
            "--no-unknown-keys",
            ".env",
        ],
    );
    assert_eq!(compose_out.status.code(), Some(1));
    let compose_text = String::from_utf8(compose_out.stdout).unwrap();
    assert!(compose_text.contains("missing-key"), "{compose_text}");
    assert!(compose_text.contains("[AWS_PROFILE]"), "{compose_text}");

    // Config `[schema] allow_unknown = false` without example or keys fails with exit 2.
    let closed_cfg_dir = TempDir::new();
    closed_cfg_dir.file(".adotenv-lint.toml", "[schema]\nallow_unknown = false\n");
    closed_cfg_dir.file(".env", "A=1\n");
    let closed_err = run_in(closed_cfg_dir.path(), &[".env"]);
    assert_eq!(closed_err.status.code(), Some(2));
    assert!(String::from_utf8(closed_err.stderr)
        .unwrap()
        .contains("allow_unknown = false"));

    // --max-input-bytes bounds .adotenv-lint.toml loading as well as .env files.
    let cfg_cap = run_in(closed_cfg_dir.path(), &["--max-input-bytes=4", ".env"]);
    assert_eq!(cfg_cap.status.code(), Some(2));
    assert!(String::from_utf8(cfg_cap.stderr)
        .unwrap()
        .contains("max_input_bytes"));

    // Human output escapes control characters / newlines in keys (Python quoted keys).
    let ctrl_file = dir.file("ctrl.env", "'A\nB'=1\n'A\nB'=2\n");
    let ctrl_out = run(&["--dialect=python", ctrl_file.to_str().unwrap()]);
    assert_eq!(ctrl_out.status.code(), Some(1));
    let ctrl_text = String::from_utf8(ctrl_out.stdout).unwrap();
    assert_eq!(ctrl_text.lines().count(), 1, "{ctrl_text:?}");
    assert!(ctrl_text.contains("[A\\nB]"), "{ctrl_text:?}");
}

#[test]
fn github_key_escaping_and_config_four_mib_cap() {
    // --format=github escapes ANSI, LS/PS, and Bidi control characters in keys.
    let bidi_dir = TempDir::new();
    bidi_dir.file(
        ".env",
        "'A\x1b[31m\u{202e}\u{2028}B'=1\n'A\x1b[31m\u{202e}\u{2028}B'=2\n",
    );
    let gh_bidi = run_in(
        bidi_dir.path(),
        &["--dialect=python", "--format=github", ".env"],
    );
    assert_eq!(gh_bidi.status.code(), Some(1));
    let gh_bidi_text = String::from_utf8(gh_bidi.stdout).unwrap();
    assert!(
        gh_bidi_text.contains("\\u{1b}")
            && gh_bidi_text.contains("\\u{202e}")
            && gh_bidi_text.contains("\\u{2028}")
            && !gh_bidi_text.contains('\x1b')
            && !gh_bidi_text.contains('\u{202e}')
            && !gh_bidi_text.contains('\u{2028}'),
        "{gh_bidi_text}"
    );

    // Exact 4 MiB config succeeds when `--max-input-bytes` >= 4 MiB, while 4 MiB + 1 fails.
    let exact_cfg_dir = TempDir::new();
    let exact_cfg = format!("# {}\n", "x".repeat(4 * 1024 * 1024 - 3));
    assert_eq!(exact_cfg.len(), 4 * 1024 * 1024);
    exact_cfg_dir.file(".adotenv-lint.toml", &exact_cfg);
    exact_cfg_dir.file(".env", "A=1\n");
    let exact_ok = run_in(exact_cfg_dir.path(), &["--max-input-bytes=8388608", ".env"]);
    assert_eq!(exact_ok.status.code(), Some(0));

    let big_cfg_dir = TempDir::new();
    let oversized_cfg = format!("# {}\n", "x".repeat(4 * 1024 * 1024 - 2));
    assert_eq!(oversized_cfg.len(), 4 * 1024 * 1024 + 1);
    big_cfg_dir.file(".adotenv-lint.toml", &oversized_cfg);
    big_cfg_dir.file(".env", "A=1\n");
    let big_cfg_err = run_in(big_cfg_dir.path(), &["--max-input-bytes=8388608", ".env"]);
    assert_eq!(big_cfg_err.status.code(), Some(2));
    let big_cfg_stderr = String::from_utf8(big_cfg_err.stderr).unwrap();
    assert!(
        big_cfg_stderr.contains("4194304"),
        "expected 4 MiB cap error: {big_cfg_stderr}"
    );
}

#[derive(Debug, PartialEq)]
enum JsonVal {
    Null,
    Bool(bool),
    Number(i64),
    String(String),
    Array(Vec<JsonVal>),
    Object(Vec<(String, JsonVal)>),
}

impl JsonVal {
    fn field(&self, name: &str) -> &JsonVal {
        let Self::Object(entries) = self else {
            panic!("expected JSON object, got {self:?}");
        };
        entries
            .iter()
            .find_map(|(k, v)| (k == name).then_some(v))
            .unwrap_or_else(|| panic!("missing JSON field {name:?} in {self:?}"))
    }

    fn get_field(&self, name: &str) -> Option<&JsonVal> {
        let Self::Object(entries) = self else {
            return None;
        };
        entries.iter().find_map(|(k, v)| (k == name).then_some(v))
    }

    fn as_str(&self) -> &str {
        let Self::String(s) = self else {
            panic!("expected JSON string, got {self:?}");
        };
        s
    }

    fn as_i64(&self) -> i64 {
        let Self::Number(n) = self else {
            panic!("expected JSON number, got {self:?}");
        };
        *n
    }

    fn as_array(&self) -> &[JsonVal] {
        let Self::Array(items) = self else {
            panic!("expected JSON array, got {self:?}");
        };
        items
    }
}

struct JsonParser<'a> {
    bytes: &'a [u8],
    pos: usize,
}

impl JsonParser<'_> {
    fn skip_ws(&mut self) {
        while self.pos < self.bytes.len()
            && matches!(self.bytes[self.pos], b' ' | b'\n' | b'\r' | b'\t')
        {
            self.pos += 1;
        }
    }
    fn peek(&mut self) -> Option<u8> {
        self.skip_ws();
        self.bytes.get(self.pos).copied()
    }
    fn expect(&mut self, ch: u8) {
        self.skip_ws();
        assert_eq!(self.bytes.get(self.pos).copied(), Some(ch));
        self.pos += 1;
    }
    fn parse_value(&mut self) -> JsonVal {
        match self.peek().expect("unexpected EOF") {
            b'{' => self.parse_object(),
            b'[' => self.parse_array(),
            b'"' => JsonVal::String(self.parse_string()),
            b't' => {
                assert!(self.bytes[self.pos..].starts_with(b"true"));
                self.pos += 4;
                JsonVal::Bool(true)
            }
            b'f' => {
                assert!(self.bytes[self.pos..].starts_with(b"false"));
                self.pos += 5;
                JsonVal::Bool(false)
            }
            b'n' => {
                assert!(self.bytes[self.pos..].starts_with(b"null"));
                self.pos += 4;
                JsonVal::Null
            }
            b'-' | b'0'..=b'9' => self.parse_number(),
            other => panic!("unexpected JSON byte {other:?} at {}", self.pos),
        }
    }
    fn parse_object(&mut self) -> JsonVal {
        self.expect(b'{');
        let mut entries = Vec::new();
        if self.peek() == Some(b'}') {
            self.pos += 1;
            return JsonVal::Object(entries);
        }
        loop {
            let key = self.parse_string();
            self.expect(b':');
            let val = self.parse_value();
            entries.push((key, val));
            match self.peek() {
                Some(b',') => self.pos += 1,
                Some(b'}') => {
                    self.pos += 1;
                    return JsonVal::Object(entries);
                }
                other => panic!("expected ',' or '}}', got {other:?}"),
            }
        }
    }
    fn parse_array(&mut self) -> JsonVal {
        self.expect(b'[');
        let mut items = Vec::new();
        if self.peek() == Some(b']') {
            self.pos += 1;
            return JsonVal::Array(items);
        }
        loop {
            items.push(self.parse_value());
            match self.peek() {
                Some(b',') => self.pos += 1,
                Some(b']') => {
                    self.pos += 1;
                    return JsonVal::Array(items);
                }
                other => panic!("expected ',' or ']', got {other:?}"),
            }
        }
    }
    fn parse_string(&mut self) -> String {
        self.expect(b'"');
        let mut out = String::new();
        while self.pos < self.bytes.len() {
            let b = self.bytes[self.pos];
            self.pos += 1;
            match b {
                b'"' => return out,
                b'\\' => {
                    let esc = self.bytes[self.pos];
                    self.pos += 1;
                    match esc {
                        b'"' => out.push('"'),
                        b'\\' => out.push('\\'),
                        b'/' => out.push('/'),
                        b'b' => out.push('\u{0008}'),
                        b'f' => out.push('\u{000c}'),
                        b'n' => out.push('\n'),
                        b'r' => out.push('\r'),
                        b't' => out.push('\t'),
                        b'u' => {
                            let hex =
                                std::str::from_utf8(&self.bytes[self.pos..self.pos + 4]).unwrap();
                            let code = u32::from_str_radix(hex, 16).unwrap();
                            self.pos += 4;
                            out.push(char::from_u32(code).unwrap());
                        }
                        other => panic!("invalid JSON escape \\{other:?}"),
                    }
                }
                _ => {
                    let start = self.pos - 1;
                    let s = std::str::from_utf8(&self.bytes[start..]).unwrap();
                    let ch = s.chars().next().unwrap();
                    self.pos = start + ch.len_utf8();
                    out.push(ch);
                }
            }
        }
        panic!("unterminated JSON string");
    }
    fn parse_number(&mut self) -> JsonVal {
        self.skip_ws();
        let start = self.pos;
        if self.bytes[self.pos] == b'-' {
            self.pos += 1;
        }
        while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
            self.pos += 1;
        }
        let text = std::str::from_utf8(&self.bytes[start..self.pos]).unwrap();
        JsonVal::Number(text.parse::<i64>().unwrap())
    }
}

fn parse_json(input: &str) -> JsonVal {
    let mut parser = JsonParser {
        bytes: input.as_bytes(),
        pos: 0,
    };
    let val = parser.parse_value();
    parser.skip_ws();
    assert_eq!(parser.pos, parser.bytes.len(), "trailing JSON data");
    val
}

#[test]
fn list_rules_and_explain_flags_cover_all_rules_and_reject_invalid() {
    let list_out = run(&["--list-rules"]);
    assert_eq!(list_out.status.code(), Some(0));
    let list_text = String::from_utf8(list_out.stdout).unwrap();
    let expected_rules = [
        "duplicate-key",
        "key-order",
        "key-case",
        "quote-style",
        "whitespace",
        "missing-key",
        "unknown-key",
        "empty-value",
        "invalid-value",
        "deprecated-key",
    ];
    assert_eq!(list_text.lines().count(), expected_rules.len());
    for rule in expected_rules {
        assert!(list_text.contains(rule), "missing {rule} in:\n{list_text}");
        let exp = run(&["--explain", rule]);
        assert_eq!(exp.status.code(), Some(0), "rule={rule}");
        let exp_text = String::from_utf8(exp.stdout).unwrap();
        assert!(
            exp_text.contains(&format!("Rule:      {rule}")),
            "{exp_text}"
        );
        assert!(exp_text.contains("Summary:   "), "{exp_text}");
        assert!(exp_text.contains("Default:   "), "{exp_text}");
        assert!(exp_text.contains("Autofix:   "), "{exp_text}");
        assert!(exp_text.contains("Config:    "), "{exp_text}");
        assert!(exp_text.contains("Rationale: "), "{exp_text}");
    }

    let eq_exp = run(&["--explain=deprecated-key"]);
    assert_eq!(eq_exp.status.code(), Some(0));
    assert!(String::from_utf8(eq_exp.stdout)
        .unwrap()
        .contains("Rule:      deprecated-key"));

    let kc_exp = run(&["--explain=key-case"]);
    assert_eq!(kc_exp.status.code(), Some(0));
    let kc_text = String::from_utf8(kc_exp.stdout).unwrap();
    assert!(
        !kc_text.contains("key_case = \"upper\" | \"lower\" | \"off\""),
        "{kc_text}"
    );

    for bad_args in [
        &["--explain"][..],
        &["--explain="][..],
        &["--explain", "no-such-rule"][..],
        &["--explain=no-such-rule"][..],
    ] {
        let bad = run(bad_args);
        assert_eq!(bad.status.code(), Some(2), "{bad_args:?}");
    }
}

#[test]
fn fix_missing_is_opt_in_and_never_copies_example_values() {
    let dir = TempDir::new();
    dir.file(
        ".env.example",
        "API_KEY=example-secret-never-copy\nHOST=localhost\nPORT=8080\n",
    );
    let env_file = dir.file(".env", "port=8080\n");

    // --fix-missing without --fix is a usage error (exit 2).
    let usage_err = run_in(
        dir.path(),
        &["--example=.env.example", "--fix-missing", ".env"],
    );
    assert_eq!(usage_err.status.code(), Some(2));
    assert!(String::from_utf8(usage_err.stderr)
        .unwrap()
        .contains("--fix-missing requires --fix"));

    // Plain --fix fixes style (key_case) without injecting missing KEY= stubs.
    let style_only = run_in(
        dir.path(),
        &[
            "--example=.env.example",
            "--key-case=upper",
            "--fix",
            ".env",
        ],
    );
    assert_eq!(style_only.status.code(), Some(1));
    assert_eq!(fs::read_to_string(&env_file).unwrap(), "PORT=8080\n");
    let style_stdout = String::from_utf8(style_only.stdout).unwrap();
    assert!(style_stdout.contains("missing-key"), "{style_stdout}");
    assert!(style_stdout.contains("[API_KEY]"), "{style_stdout}");
    assert!(style_stdout.contains("[HOST]"), "{style_stdout}");

    // --fix --fix-missing inserts empty KEY= placeholders, sorts them, and NEVER copies values.
    let scaffold = run_in(
        dir.path(),
        &[
            "--example=.env.example",
            "--key-case=upper",
            "--key-order",
            "--fix",
            "--fix-missing",
            ".env",
        ],
    );
    assert_eq!(scaffold.status.code(), Some(0));
    let fixed_content = fs::read_to_string(&env_file).unwrap();
    assert_eq!(fixed_content, "API_KEY=\nHOST=\nPORT=8080\n");
    assert!(!fixed_content.contains("example-secret-never-copy"));
    assert!(!fixed_content.contains("localhost"));

    // When a schema also requires non-empty values, --fix --fix-missing still writes
    // empty stubs and exits 1 with empty-value reminders.
    let strict_dir = TempDir::new();
    strict_dir.file(
        ".adotenv-lint.toml",
        "[schema]\nallow_empty = false\n[schema.keys.HOST]\nshape = \"host\"\n[schema.keys.PORT]\nshape = \"port\"\n",
    );
    let strict_env = strict_dir.file(".env", "PORT=8080\n");
    let strict_out = run_in(strict_dir.path(), &["--fix", "--fix-missing", ".env"]);
    assert_eq!(strict_out.status.code(), Some(1));
    assert_eq!(
        fs::read_to_string(&strict_env).unwrap(),
        "PORT=8080\nHOST=\n"
    );
    let strict_text = String::from_utf8(strict_out.stdout).unwrap();
    assert!(strict_text.contains("empty-value"), "{strict_text}");
    assert!(strict_text.contains("[HOST]"), "{strict_text}");
}

#[test]
fn sarif_clean_file_emits_valid_empty_results() {
    let clean_dir = TempDir::new();
    clean_dir.file(".env", "A=1\n");
    let clean_out = run_in(clean_dir.path(), &["--format=sarif", ".env"]);
    assert_eq!(clean_out.status.code(), Some(0));
    let clean_sarif = parse_json(&String::from_utf8(clean_out.stdout).unwrap());
    assert_eq!(clean_sarif.field("version").as_str(), "2.1.0");
    assert_eq!(
        clean_sarif.field("$schema").as_str(),
        "https://json.schemastore.org/sarif-2.1.0.json"
    );
    let clean_run = &clean_sarif.field("runs").as_array()[0];
    assert_eq!(clean_run.field("columnKind").as_str(), "unicodeCodePoints");
    assert_eq!(
        clean_run.field("invocations").as_array()[0].field("executionSuccessful"),
        &JsonVal::Bool(true)
    );
    let driver = clean_run.field("tool").field("driver");
    assert_eq!(driver.field("name").as_str(), "adotenv-lint");
    assert_eq!(driver.field("version").as_str(), env!("CARGO_PKG_VERSION"));
    assert_eq!(
        driver.field("informationUri").as_str(),
        "https://zeropier.com/adotenv/"
    );
    assert_eq!(driver.field("rules").as_array().len(), 10);
    assert_eq!(clean_run.field("results").as_array().len(), 0);

    // Parse error sets invocations[0].executionSuccessful = false and exits 2,
    // while key-order trims the trailing newline and absolute paths use file:///.
    let err_dir = TempDir::new();
    let bad_path = err_dir.file("bad.env", "NOT VALID\n");
    let unsorted_path = err_dir.file("order.env", "B=2\nA=1\n");
    let partial_out = run(&[
        "--format=sarif",
        "--key-order",
        bad_path.to_str().unwrap(),
        unsorted_path.to_str().unwrap(),
    ]);
    assert_eq!(partial_out.status.code(), Some(2));
    let partial_sarif = parse_json(&String::from_utf8(partial_out.stdout).unwrap());
    let partial_run = &partial_sarif.field("runs").as_array()[0];
    assert_eq!(
        partial_run.field("invocations").as_array()[0].field("executionSuccessful"),
        &JsonVal::Bool(false)
    );
    let order_res = &partial_run.field("results").as_array()[0];
    let order_loc = &order_res.field("locations").as_array()[0].field("physicalLocation");
    assert!(
        order_loc
            .field("artifactLocation")
            .field("uri")
            .as_str()
            .starts_with("file:///"),
        "{order_loc:?}"
    );
    let region = order_loc.field("region");
    assert_eq!(region.field("startLine").as_i64(), 1);
    assert_eq!(region.field("startColumn").as_i64(), 1);
    assert_eq!(region.field("endLine").as_i64(), 2);
    assert_eq!(region.field("endColumn").as_i64(), 4);
    assert_eq!(region.field("byteOffset").as_i64(), 0);
    assert_eq!(region.field("byteLength").as_i64(), 7);
}

#[test]
fn sarif_handles_compose_crlf_eof_cr_and_double_slash_relative_paths() {
    let dir = TempDir::new();
    dir.file("crlf.env", "B=2\r\nA=1\r\n");
    dir.file("eofcr.env", "B=2\nA=1\r");

    let crlf_out = run_in(
        dir.path(),
        &[
            "--dialect=compose",
            "--key-order",
            "--format=sarif",
            ".//crlf.env",
        ],
    );
    assert_eq!(crlf_out.status.code(), Some(1));
    let crlf_sarif = parse_json(&String::from_utf8(crlf_out.stdout).unwrap());
    let crlf_loc = &crlf_sarif.field("runs").as_array()[0]
        .field("results")
        .as_array()[0]
        .field("locations")
        .as_array()[0]
        .field("physicalLocation");
    assert_eq!(
        crlf_loc.field("artifactLocation").field("uri").as_str(),
        "crlf.env"
    );
    let crlf_reg = crlf_loc.field("region");
    assert_eq!(crlf_reg.field("startLine").as_i64(), 1);
    assert_eq!(crlf_reg.field("startColumn").as_i64(), 1);
    assert_eq!(crlf_reg.field("endLine").as_i64(), 2);
    assert_eq!(crlf_reg.field("endColumn").as_i64(), 4);
    assert_eq!(crlf_reg.field("byteOffset").as_i64(), 0);
    assert_eq!(crlf_reg.field("byteLength").as_i64(), 8);

    let eofcr_out = run_in(
        dir.path(),
        &[
            "--dialect=docker",
            "--key-order",
            "--format=sarif",
            ".///eofcr.env",
        ],
    );
    assert_eq!(eofcr_out.status.code(), Some(1));
    let eofcr_sarif = parse_json(&String::from_utf8(eofcr_out.stdout).unwrap());
    let eofcr_loc = &eofcr_sarif.field("runs").as_array()[0]
        .field("results")
        .as_array()[0]
        .field("locations")
        .as_array()[0]
        .field("physicalLocation");
    assert_eq!(
        eofcr_loc.field("artifactLocation").field("uri").as_str(),
        "eofcr.env"
    );
    let eofcr_reg = eofcr_loc.field("region");
    assert_eq!(eofcr_reg.field("startLine").as_i64(), 1);
    assert_eq!(eofcr_reg.field("startColumn").as_i64(), 1);
    assert_eq!(eofcr_reg.field("endLine").as_i64(), 2);
    assert_eq!(eofcr_reg.field("endColumn").as_i64(), 4);
    assert_eq!(eofcr_reg.field("byteOffset").as_i64(), 0);
    assert_eq!(eofcr_reg.field("byteLength").as_i64(), 7);
}

#[test]
fn sarif_and_detail_outputs_are_spec_compliant_value_free_and_post_fix_accurate() {
    let dir = TempDir::new();
    dir.file(
        ".adotenv-lint.toml",
        r#"
[rules]
deprecated-key = "error"
invalid-value = "warning"
missing-key = "error"

[schema.keys.REQ_HOST]
shape = "host"

[schema.keys.OLD_VAR]
required = false
deprecated = "use NEW_VAR\u001b[31m\u202e"

[schema.keys.TOKEN]
prefix = "sk_"
min_len = 8

[schema.keys.BIND]
shape = "socket-addr"

[schema.keys.ADMIN]
shape = "email"
"#,
    );

    // Multi-finding file with BOM, space in filename, deprecated note with Bidi/ANSI,
    // literal bound failure, new shapes, and style fix that reorders lines before SARIF emission.
    dir.file(
        "app env.env",
        "\u{feff}TOKEN=super-secret-bad\nOLD_VAR=secret-legacy\nBIND=127.0.0.1:8080\nADMIN=ops@example.com\n",
    );
    let sarif_out = run_in(
        dir.path(),
        &["--format=sarif", "--key-order", "--fix", "./app env.env"],
    );
    assert_eq!(sarif_out.status.code(), Some(1));
    let sarif_raw = String::from_utf8(sarif_out.stdout).unwrap();
    assert!(!sarif_raw.contains("super-secret-bad"), "{sarif_raw}");
    assert!(!sarif_raw.contains("secret-legacy"), "{sarif_raw}");
    assert!(!sarif_raw.contains('\u{202e}'), "{sarif_raw}");
    assert!(!sarif_raw.contains('\x1b'), "{sarif_raw}");

    let sarif = parse_json(&sarif_raw);
    let run_obj = &sarif.field("runs").as_array()[0];
    let rules = run_obj
        .field("tool")
        .field("driver")
        .field("rules")
        .as_array();
    let results = run_obj.field("results").as_array();
    // After --fix --key-order, order is ADMIN (1), BIND (2), OLD_VAR (3), TOKEN (4).
    assert_eq!(results.len(), 3, "{sarif_raw}");

    // 1. MissingKey (line 1, col 1 after BOM, zero-width insertion point).
    let r0 = &results[0];
    assert_eq!(r0.field("ruleId").as_str(), "missing-key");
    let idx0 = usize::try_from(r0.field("ruleIndex").as_i64()).unwrap();
    assert_eq!(rules[idx0].field("id").as_str(), "missing-key");
    assert_eq!(r0.field("level").as_str(), "error");
    let loc0 = &r0.field("locations").as_array()[0].field("physicalLocation");
    assert_eq!(
        loc0.field("artifactLocation").field("uri").as_str(),
        "app%20env.env"
    );
    let reg0 = loc0.field("region");
    assert_eq!(reg0.field("startLine").as_i64(), 1);
    assert_eq!(reg0.field("startColumn").as_i64(), 1);
    assert_eq!(reg0.field("endLine").as_i64(), 1);
    assert_eq!(reg0.field("endColumn").as_i64(), 1);
    assert_eq!(reg0.field("byteOffset").as_i64(), 3);
    assert_eq!(reg0.field("byteLength").as_i64(), 0);

    // 2. DeprecatedKey moved to line 3 by --key-order fix!
    let r1 = &results[1];
    assert_eq!(r1.field("ruleId").as_str(), "deprecated-key");
    let idx1 = usize::try_from(r1.field("ruleIndex").as_i64()).unwrap();
    assert_eq!(rules[idx1].field("id").as_str(), "deprecated-key");
    assert_eq!(r1.field("level").as_str(), "error");
    let msg1 = r1.field("message").field("text").as_str();
    assert!(msg1.contains("use NEW_VAR"), "{msg1}");
    assert!(
        msg1.contains("\\u{1b}") && msg1.contains("\\u{202e}"),
        "{msg1}"
    );
    let reg1 = r1.field("locations").as_array()[0]
        .field("physicalLocation")
        .field("region");
    assert_eq!(reg1.field("startLine").as_i64(), 3);
    assert_eq!(reg1.field("startColumn").as_i64(), 1);
    assert_eq!(reg1.field("endLine").as_i64(), 3);
    assert_eq!(reg1.field("endColumn").as_i64(), 8);

    // 3. InvalidValue on TOKEN moved to line 4 by --key-order fix!
    let r2 = &results[2];
    assert_eq!(r2.field("ruleId").as_str(), "invalid-value");
    assert_eq!(r2.field("level").as_str(), "warning");
    assert!(
        r2.field("message")
            .field("text")
            .as_str()
            .contains("expected prefix \"sk_\""),
        "{r2:?}"
    );
    let reg2 = r2.field("locations").as_array()[0]
        .field("physicalLocation")
        .field("region");
    assert_eq!(reg2.field("startLine").as_i64(), 4);
    assert_eq!(reg2.field("startColumn").as_i64(), 7);
}

#[test]
fn json_human_and_github_outputs_emit_escaped_details_value_free() {
    let dir = TempDir::new();
    dir.file(
        ".adotenv-lint.toml",
        r#"
[rules]
deprecated-key = "error"
missing-key = "error"

[schema.keys.REQ_HOST]
shape = "host"

[schema.keys.OLD_VAR]
required = false
deprecated = "use NEW_VAR\u001b[31m\u202e"

[schema.keys.TOKEN]
prefix = "sk_"
"#,
    );
    dir.file(
        "app env.env",
        "OLD_VAR=secret-legacy\nTOKEN=super-secret-bad\n",
    );

    // Check JSON, Human, and GitHub output also include detail cleanly and omit detail when absent.
    let json_out = run_in(dir.path(), &["--format=json", "./app env.env"]);
    assert_eq!(json_out.status.code(), Some(1));
    let json_raw = String::from_utf8(json_out.stdout).unwrap();
    assert!(!json_raw.contains("super-secret-bad"));
    assert!(!json_raw.contains("secret-legacy"));
    let json_arr = parse_json(&json_raw);
    let items = json_arr.as_array();
    assert_eq!(items.len(), 3);
    assert_eq!(items[0].field("rule").as_str(), "deprecated-key");
    assert!(items[0].field("detail").as_str().starts_with("use NEW_VAR"));
    assert_eq!(items[1].field("rule").as_str(), "missing-key");
    assert!(items[1].get_field("detail").is_none());
    assert_eq!(items[2].field("rule").as_str(), "invalid-value");
    assert_eq!(items[2].field("detail").as_str(), "expected prefix \"sk_\"");

    let human_out = run_in(dir.path(), &["./app env.env"]);
    assert_eq!(human_out.status.code(), Some(1));
    let human_raw = String::from_utf8(human_out.stdout).unwrap();
    assert!(human_raw.contains("error[deprecated-key]: key is deprecated: use NEW_VAR"));
    assert!(human_raw.contains("expected prefix \"sk_\" [TOKEN]"));
    assert!(!human_raw.contains('\u{202e}'));

    let gh_out = run_in(dir.path(), &["--format=github", "./app env.env"]);
    assert_eq!(gh_out.status.code(), Some(1));
    let gh_raw = String::from_utf8(gh_out.stdout).unwrap();
    assert!(gh_raw.contains("title=deprecated-key::key is deprecated: use NEW_VAR"));
    assert!(gh_raw.contains("expected prefix \"sk_\" [TOKEN]"));
    assert!(!gh_raw.contains('\u{202e}'));
}