mds-cli 0.7.0

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
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
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
//! How a stream or I/O failure sets an `mds` exit code (#157):
//!
//! - A closed stdout or stderr never changes the exit code.
//! - Any other I/O failure — a stdout that fails for another reason, an output file or
//!   directory that cannot be written, stdin that cannot be read or is not UTF-8 — is
//!   one `mds::io` error, and the run exits at least 2.
//! - Stdin over the 10 MiB cap is `mds::resource_limit`, exit 3; exactly the cap passes.
//!
//! # The closed-stream vector
//!
//! A pipe whose read end is already gone: [`closed_pipe`] drops the reader BEFORE the
//! child is spawned, so no process holds it and the child's first write to that stream
//! fails deterministically with a broken pipe (EPIPE on unix, the pipe-is-closing
//! error on Windows). The two tempting alternatives do not test this:
//!
//! - Dropping `child.stderr` / `child.stdout` AFTER spawn races the child's writes — a
//!   short run can finish before the drop.
//! - Closing the descriptor outright (`2>&-`) never reaches the writer at all: the Rust
//!   runtime reopens a closed standard descriptor as `/dev/null` at startup.
//!
//! # What each row proves
//!
//! Every row closes one stream, stdout or stderr, and runs the same command twice, in
//! fresh directories:
//!
//! 1. **Open stream (positive control).** It must exit with the row's verdict AND print
//!    the row's expected text on the stream the row closes. That proves the command
//!    really writes to the stream the closed run loses — without it, a command that
//!    printed nothing would pass the closed run vacuously.
//! 2. **Closed stream.** It must exit with the SAME verdict and leave the other stream
//!    and every output file exactly as the open run did.
//!
//! The assertion is the exit code (`status.code() == Some(verdict)`). With stderr
//! closed a panic message has nowhere to go, so an absence-of-`panicked` check would
//! pass whether or not the command panicked; a panic shows up here as `Some(101)`.
//! With stdout closed, stderr stays open and must match the open run's byte for byte,
//! so a panic or an error report about the closed pipe fails the row as well.
//!
//! A command that writes nothing to the stream a row closes — `mds check` and `mds init`
//! report on stderr only — has a row whose control asserts the open run's stream is
//! empty instead: the row then pins that the stream stays unused.
//!
//! # The subcommand × closed-stream table
//!
//! [`TABLE`] names one row for every subcommand and closed stream, and
//! `every_subcommand_has_a_row_for_each_closed_stream` fails for a subcommand `mds --help`
//! lists without both rows, for a row whose subcommand is gone, and for a row that names
//! no test. `mds watch` keeps running, so its two rows are in `cli_watch.rs`.
//!
//! # The other failures
//!
//! - An output that cannot be written: a directory at mode `0o555` (unix). Root ignores
//!   the mode, so each such test first checks that it really cannot create a file there
//!   and skips with a printed reason when it can. A source that cannot be read, in
//!   directory mode: a file at mode `0o000` (unix), skipped the same way.
//! - Stdin that cannot be read: a directory handle on unix (reading it fails with
//!   "is a directory"), a write-only file handle on Windows. A write-only handle cannot
//!   stand in on unix: the Rust runtime reads EBADF on a standard stream as end of input.
//! - A stdout that fails for another reason: `/dev/full` on Linux ("no space left on
//!   device"); on every unix a regular file the child may not grow — its file-size limit
//!   is 0 and it ignores SIGXFSZ, so each write fails with "file too large"; and on
//!   Windows a file handle opened to read alone, which each write fails through with
//!   "access is denied". A handle opened to read alone cannot stand in on unix: a write
//!   through it fails with EBADF, which the Rust runtime takes for a closed standard
//!   stream and reports as written.

mod common;
use common::{closed_pipe, mds_bin};

use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

/// Failure bound for one `mds` run. Every row finishes in milliseconds; this only stops
/// a hung child from hanging the suite.
const RUN_TIMEOUT: Duration = Duration::from_secs(60);

/// How often [`wait_bounded`] polls the child for exit.
const POLL: Duration = Duration::from_millis(5);

/// One of the child's output streams.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stream {
    Stdout,
    Stderr,
}

impl Stream {
    fn other(self) -> Self {
        match self {
            Self::Stdout => Self::Stderr,
            Self::Stderr => Self::Stdout,
        }
    }
}

/// What one run left behind.
struct Run {
    code: Option<i32>,
    /// Empty when stdout was closed.
    stdout: String,
    /// Empty when stderr was closed.
    stderr: String,
}

impl Run {
    fn text(&self, stream: Stream) -> &str {
        match stream {
            Stream::Stdout => &self.stdout,
            Stream::Stderr => &self.stderr,
        }
    }
}

/// Drain one child pipe on its own thread so neither pipe can fill and stall the child.
fn drain<R: Read + Send + 'static>(pipe: Option<R>) -> Option<JoinHandle<Vec<u8>>> {
    pipe.map(|mut pipe| {
        std::thread::spawn(move || {
            let mut bytes = Vec::new();
            let _ = pipe.read_to_end(&mut bytes);
            bytes
        })
    })
}

fn joined(handle: Option<JoinHandle<Vec<u8>>>) -> String {
    let bytes = handle
        .map(|h| h.join().expect("pipe drain thread"))
        .unwrap_or_default();
    String::from_utf8_lossy(&bytes).into_owned()
}

/// Wait for `child` to exit, killing it if [`RUN_TIMEOUT`] passes first.
fn wait_bounded(child: &mut Child, what: &str) -> Option<i32> {
    let deadline = Instant::now() + RUN_TIMEOUT;
    loop {
        if let Some(status) = child.try_wait().expect("poll the mds child") {
            return status.code();
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            panic!("`mds {what}` did not exit within {RUN_TIMEOUT:?}");
        }
        std::thread::sleep(POLL);
    }
}

/// What the child reads on stdin.
enum Input {
    /// These bytes, written into a pipe.
    Bytes(Vec<u8>),
    /// This handle, as it is.
    Handle(Stdio),
}

/// Run `mds <args>` in `dir`, feeding `stdin`, with the stream `closed` (if any) a closed
/// pipe from the start.
fn run(dir: &Path, args: &[&str], stdin: &str, closed: Option<Stream>) -> Run {
    let stdout = match closed {
        Some(Stream::Stdout) => Stdio::from(closed_pipe()),
        _ => Stdio::piped(),
    };
    let stderr = match closed {
        Some(Stream::Stderr) => Stdio::from(closed_pipe()),
        _ => Stdio::piped(),
    };
    run_with(
        dir,
        args,
        Input::Bytes(stdin.as_bytes().to_vec()),
        stdout,
        stderr,
    )
}

/// Run `mds <args>` in `dir` with the given stdin, stdout and stderr.
fn run_with(dir: &Path, args: &[&str], stdin: Input, stdout: Stdio, stderr: Stdio) -> Run {
    run_command(mds_bin(), dir, args, stdin, stdout, stderr)
}

/// [`run_with`] on an `mds` command the caller has already prepared.
fn run_command(
    mut cmd: Command,
    dir: &Path,
    args: &[&str],
    stdin: Input,
    stdout: Stdio,
    stderr: Stdio,
) -> Run {
    let what = args.join(" ");
    cmd.args(args)
        .current_dir(dir)
        .stdout(stdout)
        .stderr(stderr);
    let bytes = match stdin {
        Input::Bytes(bytes) => {
            cmd.stdin(Stdio::piped());
            Some(bytes)
        }
        Input::Handle(handle) => {
            cmd.stdin(handle);
            None
        }
    };
    let mut child = cmd.spawn().expect("spawn mds");

    // A child that exits without reading stdin closes it first; on Linux that makes
    // this write fail with a broken pipe, which says nothing about the child.
    let writer = bytes.map(|bytes| {
        let mut child_stdin = child.stdin.take().expect("stdin is piped");
        std::thread::spawn(move || {
            let _ = child_stdin.write_all(&bytes);
        })
    });
    let out = drain(child.stdout.take());
    let err = drain(child.stderr.take());

    let code = wait_bounded(&mut child, &what);
    if let Some(writer) = writer {
        writer.join().expect("stdin writer thread");
    }
    Run {
        code,
        stdout: joined(out),
        stderr: joined(err),
    }
}

/// A template `mds lint` warns about (an unused frontmatter key), exit 1.
const LINT_WARN_SOURCE: &str =
    "---\ngreeting: Hello\nunused_key: never referenced in the body\n---\n\n{{greeting}}, world!\n";

/// A template `mds lint --fix` fixes to `Hello\n` (a branch that can never be taken).
const LINT_FIXABLE_SOURCE: &str = "@if \"x\" == \"y\":\nhidden\n@end\nHello\n";

/// A fresh working directory holding every fixture a row may name.
///
/// - `ok.mds` compiles, and `mds lint` finds nothing in it; `bad.mds` does not compile
///   (an unterminated `@if`).
/// - `d/` holds one of each; `good/` holds two that compile, so a run that stops after
///   the first output shows up as a missing second one.
/// - `messy.mds` and `m/messy.mds` lack the final newline `mds fmt` adds; so do both
///   files in `two/`, so `mds fmt --diff two` writes two diffs.
/// - `warn.mds` and `lints/` (a clean file and a warning one) lint with warnings, exit 1;
///   `fix.mds` and both files in `fixes/` hold a fix, so `mds lint --fix --diff fixes`
///   writes two diffs.
fn fixture_dir() -> tempfile::TempDir {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    let files: [(&str, &str); 15] = [
        ("ok.mds", "Hello\n"),
        ("bad.mds", "@if flag:\nunterminated\n"),
        ("d/ok.mds", "Hello\n"),
        ("d/bad.mds", "@if flag:\nunterminated\n"),
        ("good/a.mds", "A\n"),
        ("good/b.mds", "B\n"),
        ("messy.mds", "Hello"),
        ("two/a.mds", "A"),
        ("two/b.mds", "B"),
        ("warn.mds", LINT_WARN_SOURCE),
        ("fix.mds", LINT_FIXABLE_SOURCE),
        ("lints/ok.mds", "Hello\n"),
        ("lints/warn.mds", LINT_WARN_SOURCE),
        ("fixes/a.mds", LINT_FIXABLE_SOURCE),
        ("fixes/b.mds", LINT_FIXABLE_SOURCE),
    ];
    for dir_name in ["d", "good", "m", "two", "lints", "fixes"] {
        std::fs::create_dir(root.join(dir_name)).expect("create a fixture dir");
    }
    for (name, text) in files {
        std::fs::write(root.join(name), text).expect("write a fixture file");
    }
    std::fs::write(root.join("m/messy.mds"), "Hello").expect("write m/messy.mds");
    dir
}

/// Every file under `dir` with its bytes, sorted — what a run left on disk.
fn files_under(dir: &Path) -> Vec<(PathBuf, Vec<u8>)> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    // Bounded: the fixture tree is two levels deep and holds a handful of files.
    for _ in 0..64 {
        let Some(d) = stack.pop() else { break };
        for entry in std::fs::read_dir(&d).expect("read fixture dir").flatten() {
            let path = entry.path();
            let file_type = entry.file_type().expect("file type");
            if file_type.is_dir() {
                stack.push(path);
            } else {
                let bytes = std::fs::read(&path).expect("read fixture file");
                let rel = path.strip_prefix(dir).expect("under dir").to_path_buf();
                out.push((rel, bytes));
            }
        }
    }
    assert!(stack.is_empty(), "fixture tree deeper than the walk bound");
    out.sort();
    out
}

/// `path`, written with `/`, in the platform's separator. A path `mds` builds by joining
/// components — `ok.mds`'s output `./ok.md`, a directory walk's `fixes/b.mds` — is
/// printed that way (`.\ok.md` on Windows), so an expected text naming one is built
/// with this and stays exact on each OS.
fn native(path: &str) -> String {
    path.replace('/', std::path::MAIN_SEPARATOR_STR)
}

/// The `+++` line that opens the new side of a unified diff of `path` (written with `/`,
/// printed through [`native`]).
fn diff_header(path: &str) -> String {
    format!("+++ {}\n", native(path))
}

/// One command, its verdict with open streams, the stream it closes, and what the open
/// run must print on that stream.
struct Row<'a> {
    args: &'static [&'static str],
    stdin: &'static str,
    verdict: i32,
    closed: Stream,
    open_contains: &'a str,
}

/// Run `row` with every stream open and then with `row.closed` closed, asserting both
/// arms (see the module doc).
///
/// Returns the file listing both runs left, for rows that also check what was written.
fn assert_closing_keeps_the_verdict(row: &Row<'_>) -> Vec<(PathBuf, Vec<u8>)> {
    let what = row.args.join(" ");
    let closed_name = format!("{:?}", row.closed).to_lowercase();

    let open_dir = fixture_dir();
    let open = run(open_dir.path(), row.args, row.stdin, None);
    assert_eq!(
        open.code,
        Some(row.verdict),
        "control: `mds {what}` with open streams must exit with its verdict; stderr: {:?}",
        open.stderr
    );
    assert!(
        open.text(row.closed).contains(row.open_contains),
        "control: `mds {what}` must print {:?} on {closed_name}, or the closed-{closed_name} \
         run would prove nothing; {closed_name}: {:?}",
        row.open_contains,
        open.text(row.closed)
    );
    assert_the_closed_run_matches(row, &open, open_dir.path())
}

/// [`assert_closing_keeps_the_verdict`] for a command that writes nothing to the stream
/// it closes. The control asserts the open run's stream is empty, so the row pins that
/// the command keeps not using it: closing it changes neither the verdict, nor the other
/// stream, nor what is written to disk.
fn assert_closing_an_unused_stream_changes_nothing(
    args: &'static [&'static str],
    verdict: i32,
    closed: Stream,
) -> Vec<(PathBuf, Vec<u8>)> {
    let what = args.join(" ");
    let open_dir = fixture_dir();
    let open = run(open_dir.path(), args, "", None);
    assert_eq!(
        open.code,
        Some(verdict),
        "control: `mds {what}` with open streams must exit with its verdict; stderr: {:?}",
        open.stderr
    );
    assert_eq!(
        open.text(closed),
        "",
        "control: `mds {what}` must write nothing to {closed:?} for this row"
    );
    let row = Row {
        args,
        stdin: "",
        verdict,
        closed,
        open_contains: "",
    };
    assert_the_closed_run_matches(&row, &open, open_dir.path())
}

/// The closed arm of a row: run it with `row.closed` closed in a fresh fixture directory
/// and compare it with `open`, the open run made in `open_dir` (see the module doc).
fn assert_the_closed_run_matches(
    row: &Row<'_>,
    open: &Run,
    open_dir: &Path,
) -> Vec<(PathBuf, Vec<u8>)> {
    let what = row.args.join(" ");
    let closed_name = format!("{:?}", row.closed).to_lowercase();
    let kept = row.closed.other();

    let closed_dir = fixture_dir();
    let closed = run(closed_dir.path(), row.args, row.stdin, Some(row.closed));
    assert_eq!(
        closed.code,
        Some(row.verdict),
        "`mds {what}` with {closed_name} closed must exit with the verdict it has with open \
         streams ({}), not a panic (101) or a signal (None); open-run stderr: {:?}; \
         closed-run stdout: {:?}; closed-run stderr: {:?}",
        row.verdict,
        open.stderr,
        closed.stdout,
        closed.stderr
    );
    assert_eq!(
        closed.text(kept),
        open.text(kept),
        "`mds {what}`: closing {closed_name} must not change {:?}",
        kept
    );

    let open_files = files_under(open_dir);
    let closed_files = files_under(closed_dir.path());
    assert_eq!(
        closed_files, open_files,
        "`mds {what}`: closing {closed_name} must not change what is written to disk"
    );
    closed_files
}

/// The bytes a run left at `path` (relative to its working directory), if any.
fn written<'a>(files: &'a [(PathBuf, Vec<u8>)], path: &str) -> Option<&'a [u8]> {
    files
        .iter()
        .find(|(p, _)| p == Path::new(path))
        .map(|(_, bytes)| bytes.as_slice())
}

// ── check, init, lint ────────────────────────────────────────────────────────

#[test]
fn check_a_file_with_stderr_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["check", "ok.mds"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: "OK: ok.mds\n",
    });
}

#[test]
fn check_a_broken_file_with_stderr_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["check", "bad.mds"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "mds::syntax",
    });
}

#[test]
fn check_stdin_with_stderr_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["check", "-"],
        stdin: "Hello\n",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: "OK: <stdin>\n",
    });
}

#[test]
fn check_a_directory_with_stderr_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["check", "d"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "1 passed, 1 failed\n",
    });
}

#[test]
fn init_with_stderr_closed_exits_0_and_writes_the_file() {
    let files = assert_closing_keeps_the_verdict(&Row {
        args: &["init"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: "Created hello.mds",
    });
    let starter = written(&files, "hello.mds").map(String::from_utf8_lossy);
    assert!(
        starter
            .as_deref()
            .is_some_and(|s| s.contains("Hello {{name}}!")),
        "`mds init` with stderr closed must still write the starter file; got {starter:?}"
    );
}

/// `mds check` reports on stderr only; closing its stdout changes nothing.
#[test]
fn check_a_file_with_stdout_closed_exits_0() {
    assert_closing_an_unused_stream_changes_nothing(&["check", "ok.mds"], 0, Stream::Stdout);
}

/// `mds init` reports on stderr only; closing its stdout changes nothing, and the
/// starter file is written.
#[test]
fn init_with_stdout_closed_exits_0_and_writes_the_file() {
    let files = assert_closing_an_unused_stream_changes_nothing(&["init"], 0, Stream::Stdout);
    assert!(
        written(&files, "hello.mds").is_some(),
        "`mds init` with stdout closed must still write the starter file"
    );
}

#[test]
fn lint_with_an_unknown_format_and_stderr_closed_exits_2() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--format", "yaml", "ok.mds"],
        stdin: "",
        verdict: 2,
        closed: Stream::Stderr,
        open_contains: "unknown --format value",
    });
}

// ── build ────────────────────────────────────────────────────────────────────

#[test]
fn build_to_stdout_with_stdout_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["build", "ok.mds", "-o", "-"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stdout,
        open_contains: "Hello\n",
    });
}

#[test]
fn build_stdin_to_stdout_with_stdout_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["build", "-"],
        stdin: "Hello\n",
        verdict: 0,
        closed: Stream::Stdout,
        open_contains: "Hello\n",
    });
}

#[test]
fn build_a_file_with_stderr_closed_exits_0_and_writes_the_output() {
    let files = assert_closing_keeps_the_verdict(&Row {
        args: &["build", "ok.mds"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: &format!("Compiled to {}\n", native("./ok.md")),
    });
    assert_eq!(
        written(&files, "ok.md"),
        Some(&b"Hello\n"[..]),
        "`mds build ok.mds` with stderr closed must still write ok.md"
    );
}

#[test]
fn build_with_a_source_map_and_stderr_closed_exits_0_and_writes_both_files() {
    let files = assert_closing_keeps_the_verdict(&Row {
        args: &["build", "ok.mds", "--source-map"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: &format!("Source map written to {}\n", native("./ok.md.map")),
    });
    assert!(
        written(&files, "ok.md").is_some() && written(&files, "ok.md.map").is_some(),
        "`mds build ok.mds --source-map` with stderr closed must still write the output \
         and its map; files: {:?}",
        files.iter().map(|(p, _)| p).collect::<Vec<_>>()
    );
}

#[test]
fn build_a_directory_with_stderr_closed_exits_0_and_writes_every_output() {
    let files = assert_closing_keeps_the_verdict(&Row {
        args: &["build", "good"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: "2 built, 0 failed\n",
    });
    assert_eq!(
        (written(&files, "good/a.md"), written(&files, "good/b.md")),
        (Some(&b"A\n"[..]), Some(&b"B\n"[..])),
        "`mds build good` with stderr closed must still write both outputs"
    );
}

#[test]
fn build_a_directory_with_a_broken_file_and_stderr_closed_exits_1() {
    let files = assert_closing_keeps_the_verdict(&Row {
        args: &["build", "d"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "1 built, 1 failed\n",
    });
    assert_eq!(
        written(&files, "d/ok.md"),
        Some(&b"Hello\n"[..]),
        "`mds build d` with stderr closed must still write the file that compiles"
    );
}

// ── fmt ──────────────────────────────────────────────────────────────────────

#[test]
fn fmt_a_file_with_stderr_closed_exits_0_and_rewrites_it() {
    let files = assert_closing_keeps_the_verdict(&Row {
        args: &["fmt", "messy.mds"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: "Formatted: messy.mds\n",
    });
    assert_eq!(
        written(&files, "messy.mds"),
        Some(&b"Hello\n"[..]),
        "`mds fmt messy.mds` with stderr closed must still rewrite the file"
    );
}

#[test]
fn fmt_check_with_stderr_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["fmt", "--check", "messy.mds"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "Would reformat: messy.mds\n",
    });
}

#[test]
fn fmt_stdin_with_stdout_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["fmt", "-"],
        stdin: "Hello",
        verdict: 0,
        closed: Stream::Stdout,
        open_contains: "Hello\n",
    });
}

#[test]
fn fmt_diff_with_stdout_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["fmt", "--diff", "messy.mds"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stdout,
        open_contains: "+++ messy.mds\n",
    });
}

#[test]
fn fmt_check_diff_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["fmt", "--check", "--diff", "messy.mds"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: "+++ messy.mds\n",
    });
}

#[test]
fn fmt_check_diff_on_a_directory_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["fmt", "--check", "--diff", "m"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: &diff_header("m/messy.mds"),
    });
}

// ── lint ─────────────────────────────────────────────────────────────────────

#[test]
fn lint_a_file_with_warnings_and_stderr_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "warn.mds"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "[unused-variable]",
    });
}

#[test]
fn lint_a_clean_file_with_stderr_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "ok.mds"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: "Clean: ok.mds\n",
    });
}

#[test]
fn lint_a_directory_with_warnings_and_stderr_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "lints"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "1 clean, 1 with warnings, 0 with errors, 0 resource-limited\n",
    });
}

#[test]
fn lint_stdin_with_warnings_and_stderr_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "-"],
        stdin: LINT_WARN_SOURCE,
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "[unused-variable]",
    });
}

#[test]
fn lint_fix_check_of_stdin_with_stderr_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--fix", "--check", "-"],
        stdin: LINT_FIXABLE_SOURCE,
        verdict: 1,
        closed: Stream::Stderr,
        open_contains: "Would fix: <stdin>\n",
    });
}

#[test]
fn lint_fix_of_a_file_with_stderr_closed_exits_0_and_rewrites_it() {
    let files = assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--fix", "fix.mds"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stderr,
        open_contains: "Fixed: fix.mds\n",
    });
    assert_eq!(
        written(&files, "fix.mds"),
        Some(&b"Hello\n"[..]),
        "`mds lint --fix fix.mds` with stderr closed must still rewrite the file"
    );
}

#[test]
fn lint_json_on_a_file_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--format", "json", "warn.mds"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: "\"file\":\"warn.mds\"",
    });
}

#[test]
fn lint_json_on_a_directory_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--format", "json", "lints"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: "\"file\":\"warn.mds\"",
    });
}

#[test]
fn lint_json_on_stdin_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--format", "json", "-"],
        stdin: LINT_WARN_SOURCE,
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: "\"file\":\"<stdin>\"",
    });
}

#[test]
fn lint_fix_of_stdin_with_stdout_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--fix", "-"],
        stdin: LINT_FIXABLE_SOURCE,
        verdict: 0,
        closed: Stream::Stdout,
        open_contains: "Hello\n",
    });
}

#[test]
fn lint_fix_diff_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--fix", "--diff", "fix.mds"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: "+++ fix.mds\n",
    });
}

/// Two diffs into a closed stdout: neither file is counted as failed — stderr, the
/// summary line included, is the open run's byte for byte (#157).
#[test]
fn lint_fix_diff_of_a_directory_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--fix", "--diff", "fixes"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: &diff_header("fixes/b.mds"),
    });
}

/// The `--format json` directory emitter is a separate one; the same holds for it.
#[test]
fn lint_json_fix_diff_of_a_directory_with_stdout_closed_exits_1() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["lint", "--format", "json", "--fix", "--diff", "fixes"],
        stdin: "",
        verdict: 1,
        closed: Stream::Stdout,
        open_contains: &diff_header("fixes/b.mds"),
    });
}

// ── The subcommand × closed-stream table ─────────────────────────────────────

/// One cell of the table: the test that closes `stream` under `subcommand`, in `file`
/// (under `tests/`), with an open-stream control.
struct Cell {
    subcommand: &'static str,
    stream: Stream,
    file: &'static str,
    test: &'static str,
}

/// One named row per subcommand and closed stream. Most subcommands have more rows above;
/// this names the one each cell rests on. `mds watch` keeps running, so its rows live
/// with the other watch tests: stdout closed ends its session with exit 0, stderr closed
/// leaves it watching.
const TABLE: &[Cell] = &[
    Cell {
        subcommand: "build",
        stream: Stream::Stdout,
        file: "broken_pipe.rs",
        test: "build_to_stdout_with_stdout_closed_exits_0",
    },
    Cell {
        subcommand: "build",
        stream: Stream::Stderr,
        file: "broken_pipe.rs",
        test: "build_a_file_with_stderr_closed_exits_0_and_writes_the_output",
    },
    Cell {
        subcommand: "check",
        stream: Stream::Stdout,
        file: "broken_pipe.rs",
        test: "check_a_file_with_stdout_closed_exits_0",
    },
    Cell {
        subcommand: "check",
        stream: Stream::Stderr,
        file: "broken_pipe.rs",
        test: "check_a_file_with_stderr_closed_exits_0",
    },
    Cell {
        subcommand: "fmt",
        stream: Stream::Stdout,
        file: "broken_pipe.rs",
        test: "fmt_stdin_with_stdout_closed_exits_0",
    },
    Cell {
        subcommand: "fmt",
        stream: Stream::Stderr,
        file: "broken_pipe.rs",
        test: "fmt_a_file_with_stderr_closed_exits_0_and_rewrites_it",
    },
    Cell {
        subcommand: "lint",
        stream: Stream::Stdout,
        file: "broken_pipe.rs",
        test: "lint_json_on_a_file_with_stdout_closed_exits_1",
    },
    Cell {
        subcommand: "lint",
        stream: Stream::Stderr,
        file: "broken_pipe.rs",
        test: "lint_a_file_with_warnings_and_stderr_closed_exits_1",
    },
    Cell {
        subcommand: "init",
        stream: Stream::Stdout,
        file: "broken_pipe.rs",
        test: "init_with_stdout_closed_exits_0_and_writes_the_file",
    },
    Cell {
        subcommand: "init",
        stream: Stream::Stderr,
        file: "broken_pipe.rs",
        test: "init_with_stderr_closed_exits_0_and_writes_the_file",
    },
    Cell {
        subcommand: "watch",
        stream: Stream::Stdout,
        file: "cli_watch.rs",
        test: "watch_to_stdout_whose_reader_is_gone_stops_and_exits_0",
    },
    Cell {
        subcommand: "watch",
        stream: Stream::Stderr,
        file: "cli_watch.rs",
        test: "watch_with_stderr_closed_keeps_watching",
    },
];

/// The subcommands `mds --help` lists, clap's own `help` aside.
fn subcommands() -> Vec<String> {
    let mut cmd = mds_bin();
    cmd.arg("--help")
        .stdout(Stdio::piped())
        .stderr(Stdio::null());
    let mut child = cmd.spawn().expect("spawn mds --help");
    let out = drain(child.stdout.take());
    let code = wait_bounded(&mut child, "--help");
    assert_eq!(code, Some(0), "`mds --help` exits 0");
    commands_in_help(&joined(out))
}

/// The command names under `Commands:` in clap's help text, `help` aside.
fn commands_in_help(help: &str) -> Vec<String> {
    help.lines()
        .skip_while(|line| line.trim() != "Commands:")
        .skip(1)
        .take_while(|line| line.starts_with(' '))
        .filter_map(|line| line.split_whitespace().next())
        .filter(|name| *name != "help")
        .map(str::to_string)
        .collect()
}

/// What `table` lacks for `subcommands`: every subcommand × stream with no cell, and every
/// cell for a subcommand that no longer exists.
fn table_gaps(subcommands: &[String], table: &[Cell]) -> Vec<String> {
    let mut gaps = Vec::new();
    for subcommand in subcommands {
        for stream in [Stream::Stdout, Stream::Stderr] {
            if !table
                .iter()
                .any(|cell| cell.subcommand == subcommand && cell.stream == stream)
            {
                gaps.push(format!("mds {subcommand} × {stream:?} closed: no row"));
            }
        }
    }
    for cell in table {
        if !subcommands.iter().any(|s| s == cell.subcommand) {
            gaps.push(format!(
                "mds {} is not a subcommand, but has a row: {}",
                cell.subcommand, cell.test
            ));
        }
    }
    gaps
}

/// Does `tests/<file>` define a function named `test` with `#[test]` among the attributes
/// right above it?
fn defines_test(file: &str, test: &str) -> bool {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join(file);
    let src = std::fs::read_to_string(&path).expect("read a test file");
    let lines: Vec<&str> = src.lines().map(str::trim).collect();
    let signature = format!("fn {test}() {{");
    lines
        .iter()
        .enumerate()
        .filter(|(_, line)| **line == signature)
        .any(|(at, _)| {
            lines[..at]
                .iter()
                .rev()
                .take_while(|line| line.starts_with("#[") || line.starts_with("///"))
                .any(|line| *line == "#[test]")
        })
}

/// Every subcommand has a row for a closed stdout and one for a closed stderr, each a
/// test that exists (#157). A new subcommand without its rows fails here.
#[test]
fn every_subcommand_has_a_row_for_each_closed_stream() {
    let subcommands = subcommands();
    assert!(
        subcommands.len() >= 6,
        "non-vacuity: expected at least 6 subcommands in `mds --help`, found {subcommands:?}"
    );
    let gaps = table_gaps(&subcommands, TABLE);
    assert!(
        gaps.is_empty(),
        "the closed-stream table has gaps:\n{gaps:#?}"
    );
    let missing: Vec<&str> = TABLE
        .iter()
        .filter(|cell| !defines_test(cell.file, cell.test))
        .map(|cell| cell.test)
        .collect();
    assert!(
        missing.is_empty(),
        "these rows name no #[test] fn in their file: {missing:?}"
    );
}

/// The table check finds a gap for a new subcommand and a stale cell for a removed one,
/// and a row that names no test (positive controls).
#[test]
fn the_table_check_reports_a_missing_row_a_stale_cell_and_an_unknown_test() {
    let help = "Usage: mds <COMMAND>\n\nCommands:\n  build  Compile\n  serve  Serve\n  \
                help   Print this message\n\nOptions:\n  -q  Quiet\n";
    let subcommands = commands_in_help(help);
    assert_eq!(subcommands, ["build", "serve"]);

    let gaps = table_gaps(&subcommands, TABLE);
    for want in [
        "mds serve × Stdout closed: no row",
        "mds serve × Stderr closed: no row",
        "mds watch is not a subcommand, but has a row: watch_with_stderr_closed_keeps_watching",
    ] {
        assert!(
            gaps.iter().any(|gap| gap == want),
            "want {want:?} among {gaps:#?}"
        );
    }
    assert!(
        !gaps.iter().any(|gap| gap.starts_with("mds build ×")),
        "build has both rows; gaps: {gaps:#?}"
    );

    assert!(defines_test(
        "broken_pipe.rs",
        "check_a_file_with_stderr_closed_exits_0"
    ));
    assert!(!defines_test(
        "broken_pipe.rs",
        "check_a_file_with_stdout_closed_exits_42"
    ));
}

// ── A stdout that fails for another reason than a closed pipe ────────────────

/// Run `mds <args>` in `dir` with stdout on `/dev/full`, where every write fails with "no
/// space left on device" — a failure that is not a closed pipe (#157).
#[cfg(target_os = "linux")]
fn run_into_dev_full_in(dir: &Path, args: &[&str], stdin: &str) -> Run {
    let full = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/full")
        .expect("open /dev/full");
    run_with(
        dir,
        args,
        Input::Bytes(stdin.as_bytes().to_vec()),
        Stdio::from(full),
        Stdio::piped(),
    )
}

/// Run `mds <args>` in `dir` with stdout on a regular file the child may not grow: its
/// file-size limit is 0 and it ignores SIGXFSZ, so every write to stdout fails with
/// "file too large" (EFBIG) — a failure that is not a closed pipe, on every unix, where
/// `/dev/full` is Linux only. Stderr stays a pipe, which the limit does not cover (#157).
#[cfg(unix)]
fn run_into_a_file_it_may_not_grow_in(dir: &Path, args: &[&str], stdin: &str) -> Run {
    let out = tempfile::tempfile().expect("create the stdout file");
    let mut cmd = mds_bin();
    common::limit_file_growth(&mut cmd, 0);
    run_command(
        cmd,
        dir,
        args,
        Input::Bytes(stdin.as_bytes().to_vec()),
        Stdio::from(out),
        Stdio::piped(),
    )
}

/// Run `mds <args>` in `dir` with stdout a file handle opened to read alone: every write
/// through it fails with "access is denied" (ERROR_ACCESS_DENIED) — a failure that is
/// not a closed pipe, on Windows, where the Rust runtime passes on every write error but
/// an invalid handle's. Stderr stays a pipe (#157).
#[cfg(windows)]
fn run_into_a_read_only_handle_in(dir: &Path, args: &[&str], stdin: &str) -> Run {
    let holder = tempfile::tempdir().expect("create the stdout file's directory");
    let path = holder.path().join("stdout");
    std::fs::write(&path, "").expect("create the stdout file");
    let read_only = std::fs::File::open(&path).expect("open the stdout file to read");
    run_with(
        dir,
        args,
        Input::Bytes(stdin.as_bytes().to_vec()),
        Stdio::from(read_only),
        Stdio::piped(),
    )
}

/// One way to fail stdout for another reason than a closed pipe.
struct FailingStdout {
    /// What stdout is, for the messages.
    how: &'static str,
    /// The end of the operating system's text for the error every write fails with, as
    /// the `mds::io` report carries it: the failure is this way's, not another.
    cause: &'static str,
    /// Run `mds <args>` in a directory, feeding it stdin, with stdout failing this way.
    run: fn(&Path, &[&str], &str) -> Run,
}

/// Every way this platform has to fail stdout for another reason than a closed pipe:
/// `/dev/full` on Linux, a file the child may not grow on every unix, and a handle opened
/// to read alone on Windows; none elsewhere, where the rows that use them are ignored.
fn failing_stdouts() -> Vec<FailingStdout> {
    [
        #[cfg(target_os = "linux")]
        FailingStdout {
            how: "/dev/full",
            cause: "(os error 28)",
            run: run_into_dev_full_in,
        },
        #[cfg(unix)]
        FailingStdout {
            how: "a file it may not grow",
            cause: "(os error 27)",
            run: run_into_a_file_it_may_not_grow_in,
        },
        #[cfg(windows)]
        FailingStdout {
            how: "a handle opened to read alone",
            cause: "(os error 5)",
            run: run_into_a_read_only_handle_in,
        },
    ]
    .into_iter()
    .collect()
}

/// An `mds` run whose stdout fails for another reason than a closed pipe.
struct FullRow<'a> {
    args: &'static [&'static str],
    stdin: &'static str,
    /// The exit code with stdout on an open pipe.
    verdict: i32,
    /// What the open run prints on stdout: the writes a failing stdout loses.
    open_contains: &'a [&'a str],
    /// Run on each fresh fixture dir before `mds` is.
    prepare: fn(&Path),
}

/// Run `row` into an open pipe, then with stdout failing in each of the platform's
/// [`failing_stdouts`] (#157).
///
/// The open run is the control: it must exit with the row's verdict, report nothing
/// about stdout, and print every `open_contains` text there — so a failing stdout really
/// loses those writes. Each failing run must exit `max(verdict, 2)` and report the
/// failure exactly once, as one `mds::io` error naming stdout and the way's own cause,
/// however many writes it lost. Returns the open run and the failing runs.
fn assert_a_failing_stdout_lifts_the_verdict(row: &FullRow<'_>) -> (Run, Vec<Run>) {
    let what = row.args.join(" ");
    let ways = failing_stdouts();
    assert!(
        !ways.is_empty(),
        "no way to fail stdout on this platform: ignore the row here"
    );

    let open_dir = fixture_dir();
    (row.prepare)(open_dir.path());
    let open = run(open_dir.path(), row.args, row.stdin, None);
    assert_eq!(
        open.code,
        Some(row.verdict),
        "control: `mds {what}` into an open pipe must exit with its verdict; stderr: {:?}",
        open.stderr
    );
    assert!(
        !open.stderr.contains("cannot write to stdout"),
        "control: `mds {what}` into an open pipe must not report stdout; stderr: {:?}",
        open.stderr
    );
    for text in row.open_contains {
        assert!(
            open.stdout.contains(text),
            "control: `mds {what}` must print {text:?} on stdout, or a failing stdout would \
             lose nothing; stdout: {:?}",
            open.stdout
        );
    }

    let want = row.verdict.max(2);
    let mut failing = Vec::with_capacity(ways.len());
    for FailingStdout {
        how,
        cause,
        run: run_failing,
    } in ways
    {
        let dir = fixture_dir();
        (row.prepare)(dir.path());
        let run = run_failing(dir.path(), row.args, row.stdin);
        assert_eq!(
            run.code,
            Some(want),
            "`mds {what}` into {how} must exit {want}, its verdict {} lifted to at least 2; \
             stderr: {:?}",
            row.verdict,
            run.stderr
        );
        assert_eq!(
            (
                run.stderr.matches("mds::io").count(),
                run.stderr.matches("cannot write to stdout").count()
            ),
            (1, 1),
            "`mds {what}` into {how} must report the failure exactly once, as one mds::io \
             error naming stdout; stderr: {:?}",
            run.stderr
        );
        assert!(
            run.stderr.contains(cause),
            "`mds {what}` into {how} must fail for that reason, {cause}; stderr: {:?}",
            run.stderr
        );
        failing.push(run);
    }
    (open, failing)
}

/// Write `big.mds`, one byte over the 10 MiB source cap.
fn write_an_oversized_source(dir: &Path) {
    std::fs::write(dir.join("big.mds"), vec![b'x'; STDIN_CAP + 1]).expect("write big.mds");
}

/// A build to stdout whose output is lost exits 2, not 0 (#157).
#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn build_to_stdout_into_a_failing_stdout_exits_2() {
    assert_a_failing_stdout_lifts_the_verdict(&FullRow {
        args: &["build", "ok.mds", "-o", "-"],
        stdin: "",
        verdict: 0,
        open_contains: &["Hello\n"],
        prepare: |_| {},
    });
}

#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn fmt_stdin_into_a_failing_stdout_exits_2() {
    assert_a_failing_stdout_lifts_the_verdict(&FullRow {
        args: &["fmt", "-"],
        stdin: "Hello",
        verdict: 0,
        open_contains: &["Hello\n"],
        prepare: |_| {},
    });
}

/// clap's own output follows the rule as well.
#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn help_into_a_failing_stdout_exits_2() {
    assert_a_failing_stdout_lifts_the_verdict(&FullRow {
        args: &["--help"],
        stdin: "",
        verdict: 0,
        open_contains: &["Usage: mds"],
        prepare: |_| {},
    });
}

/// A clean JSON report into a failing stdout exits 2, not 0: the lost report is the
/// run's only output (#157).
#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn lint_json_on_a_clean_file_into_a_failing_stdout_exits_2() {
    assert_a_failing_stdout_lifts_the_verdict(&FullRow {
        args: &["lint", "--format", "json", "ok.mds"],
        stdin: "",
        verdict: 0,
        open_contains: &["{\"files\":[],\"truncated\":false,\"version\":1}\n"],
        prepare: |_| {},
    });
}

#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn lint_json_on_a_clean_directory_into_a_failing_stdout_exits_2() {
    assert_a_failing_stdout_lifts_the_verdict(&FullRow {
        args: &["lint", "--format", "json", "good"],
        stdin: "",
        verdict: 0,
        open_contains: &["{\"files\":[],\"truncated\":false,\"version\":1}\n"],
        prepare: |_| {},
    });
}

/// The fixed source has no final newline, so it waits in stdout's buffer and only the
/// flush fails.
#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn lint_fix_of_stdin_without_a_final_newline_into_a_failing_stdout_exits_2() {
    let (open, _) = assert_a_failing_stdout_lifts_the_verdict(&FullRow {
        args: &["lint", "--fix", "-"],
        stdin: "Hello",
        verdict: 0,
        open_contains: &["Hello"],
        prepare: |_| {},
    });
    assert_eq!(
        open.stdout, "Hello",
        "control: the source must be written back without a final newline"
    );
}

/// A resource limit keeps its 3 when the report of it is lost as well.
#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn lint_json_on_a_file_over_the_size_limit_into_a_failing_stdout_exits_3() {
    assert_a_failing_stdout_lifts_the_verdict(&FullRow {
        args: &["lint", "--format", "json", "big.mds"],
        stdin: "",
        verdict: 3,
        open_contains: &["\"code\":\"mds::resource_limit\""],
        prepare: write_an_oversized_source,
    });
}

/// Run `row`, a directory run whose files each write a diff, as
/// [`assert_a_failing_stdout_lifts_the_verdict`] does, and check its summary line on
/// stderr: `open_summary` with every diff written, `lost_summary` once a failing stdout
/// has lost them all.
///
/// One rule for `mds fmt <dir>` and `mds lint <dir>` (#157): a file whose own diff a
/// failing stdout lost counts as failed — `N failed` for `mds fmt`, `with errors` for
/// `mds lint` — as a file whose rewrite fails does, while the failure is reported once
/// for the run. A closed stdout loses nothing: its rows above keep the open run's
/// summary.
fn assert_each_lost_diff_counts_as_failed(
    row: &FullRow<'_>,
    open_summary: &str,
    lost_summary: &str,
) {
    let what = row.args.join(" ");
    let (open, failing) = assert_a_failing_stdout_lifts_the_verdict(row);
    assert!(
        open.stderr.contains(open_summary),
        "control: `mds {what}` into an open pipe must print {open_summary:?}; stderr: {:?}",
        open.stderr
    );
    for run in &failing {
        assert!(
            run.stderr.contains(lost_summary),
            "`mds {what}` must count each file whose diff a failing stdout lost as failed, \
             {lost_summary:?}; stderr: {:?}",
            run.stderr
        );
    }
}

#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn fmt_diff_of_a_directory_into_a_failing_stdout_counts_each_lost_diff_as_failed() {
    assert_each_lost_diff_counts_as_failed(
        &FullRow {
            args: &["fmt", "--diff", "two"],
            stdin: "",
            verdict: 0,
            open_contains: &[&diff_header("two/a.mds"), &diff_header("two/b.mds")],
            prepare: |_| {},
        },
        "2 would reformat, 0 unchanged, 0 failed\n",
        "0 would reformat, 0 unchanged, 2 failed\n",
    );
}

#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn lint_fix_diff_of_a_directory_into_a_failing_stdout_counts_each_lost_diff_under_errors() {
    assert_each_lost_diff_counts_as_failed(
        &FullRow {
            args: &["lint", "--fix", "--diff", "fixes"],
            stdin: "",
            verdict: 1,
            open_contains: &[&diff_header("fixes/a.mds"), &diff_header("fixes/b.mds")],
            prepare: |_| {},
        },
        "2 clean, 0 with warnings, 0 with errors, 0 resource-limited\n",
        "0 clean, 0 with warnings, 2 with errors, 0 resource-limited\n",
    );
}

/// The `--format json` directory emitter is a separate one; the same rule holds for it.
#[test]
#[cfg_attr(not(any(unix, windows)), ignore = "needs a way to fail stdout")]
fn lint_json_fix_diff_of_a_directory_into_a_failing_stdout_counts_each_lost_diff_under_errors() {
    assert_each_lost_diff_counts_as_failed(
        &FullRow {
            args: &["lint", "--format", "json", "--fix", "--diff", "fixes"],
            stdin: "",
            verdict: 1,
            open_contains: &[
                &diff_header("fixes/a.mds"),
                &diff_header("fixes/b.mds"),
                "\"version\":1}\n",
            ],
            prepare: |_| {},
        },
        "2 clean, 0 with warnings, 0 with errors, 0 resource-limited\n",
        "0 clean, 0 with warnings, 2 with errors, 0 resource-limited\n",
    );
}

// ── clap's own output: help, version and usage errors ────────────────────────

#[test]
fn help_with_stdout_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["--help"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stdout,
        open_contains: "Usage: mds",
    });
}

#[test]
fn version_with_stdout_closed_exits_0() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["--version"],
        stdin: "",
        verdict: 0,
        closed: Stream::Stdout,
        open_contains: "mds ",
    });
}

#[test]
fn a_usage_error_with_stderr_closed_exits_2() {
    assert_closing_keeps_the_verdict(&Row {
        args: &["build", "--no-such-flag"],
        stdin: "",
        verdict: 2,
        closed: Stream::Stderr,
        open_contains: "unexpected argument",
    });
}

// ── An output that cannot be written: mds::io, exit 2 ────────────────────────

/// Assert that `run` exited `code` and reported the error code `mds_code` on stderr.
fn assert_exit_and_code(run: &Run, what: &str, code: i32, mds_code: &str) {
    assert_eq!(
        run.code,
        Some(code),
        "`mds {what}` must exit {code}; stderr: {:?}",
        run.stderr
    );
    assert!(
        run.stderr.contains(mds_code),
        "`mds {what}` must report {mds_code}; stderr: {:?}",
        run.stderr
    );
}

/// A directory the test's user cannot create files in (mode `0o555`), made writable
/// again on drop so the tempdir can be removed.
#[cfg(unix)]
struct ReadOnlyDir(PathBuf);

#[cfg(unix)]
impl ReadOnlyDir {
    /// `None` when a file can still be created in `path` at mode `0o555` — root ignores
    /// the mode — after printing why the caller skips.
    fn new(path: &Path) -> Option<Self> {
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o555))
            .expect("chmod 0o555");
        let guard = Self(path.to_path_buf());
        let probe = path.join(".write-probe");
        if std::fs::write(&probe, b"").is_ok() {
            let _ = std::fs::remove_file(&probe);
            eprintln!(
                "skipped: a file can be created in {} at mode 0o555 (running as root?)",
                path.display()
            );
            return None;
        }
        Some(guard)
    }
}

#[cfg(unix)]
impl Drop for ReadOnlyDir {
    fn drop(&mut self) {
        use std::os::unix::fs::PermissionsExt as _;
        let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755));
    }
}

/// A fixture dir with `ro/` holding `files`, made read-only. `None` when the mode does
/// not stop writes (see [`ReadOnlyDir::new`]).
#[cfg(unix)]
fn fixture_with_read_only_dir(files: &[(&str, &str)]) -> Option<(tempfile::TempDir, ReadOnlyDir)> {
    let dir = fixture_dir();
    let ro = dir.path().join("ro");
    std::fs::create_dir(&ro).expect("create ro");
    for (name, text) in files {
        std::fs::write(ro.join(name), text).expect("write a file in ro");
    }
    let guard = ReadOnlyDir::new(&ro)?;
    Some((dir, guard))
}

/// Run `mds <args>` in `dir` with open pipes and no stdin.
#[cfg(unix)]
fn run_in(dir: &Path, args: &[&str]) -> Run {
    run(dir, args, "", None)
}

#[cfg(unix)]
#[test]
fn a_build_whose_output_cannot_be_written_exits_2() {
    let Some((dir, _ro)) = fixture_with_read_only_dir(&[]) else {
        return;
    };
    let run = run_in(dir.path(), &["build", "ok.mds", "-o", "ro/out.md"]);
    assert_exit_and_code(&run, "build ok.mds -o ro/out.md", 2, "mds::io");
    assert!(
        !dir.path().join("ro/out.md").exists(),
        "nothing may be written"
    );
}

#[cfg(unix)]
#[test]
fn a_directory_build_with_one_unwritable_output_exits_2_and_writes_the_others() {
    let dir = fixture_dir();
    let w = dir.path().join("w");
    std::fs::create_dir_all(w.join("ro")).expect("create w/ro");
    std::fs::write(w.join("a.mds"), "A\n").expect("write w/a.mds");
    std::fs::write(w.join("ro/b.mds"), "B\n").expect("write w/ro/b.mds");
    let Some(_ro) = ReadOnlyDir::new(&w.join("ro")) else {
        return;
    };
    let run = run_in(dir.path(), &["build", "w"]);
    assert_exit_and_code(&run, "build w", 2, "mds::io");
    assert!(
        run.stderr.contains("1 built, 1 failed"),
        "the summary must count the write failure; stderr: {:?}",
        run.stderr
    );
    assert_eq!(
        std::fs::read_to_string(w.join("a.md")).ok().as_deref(),
        Some("A\n"),
        "the output that can be written must still be written"
    );
}

#[cfg(unix)]
#[test]
fn fmt_of_a_file_it_cannot_rewrite_exits_2() {
    let Some((dir, _ro)) = fixture_with_read_only_dir(&[("messy.mds", "Hello")]) else {
        return;
    };
    let run = run_in(dir.path(), &["fmt", "ro/messy.mds"]);
    assert_exit_and_code(&run, "fmt ro/messy.mds", 2, "mds::io");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("ro/messy.mds"))
            .ok()
            .as_deref(),
        Some("Hello"),
        "the file must be left as it was"
    );
}

#[cfg(unix)]
#[test]
fn fmt_of_a_directory_with_a_file_it_cannot_rewrite_exits_2() {
    let Some((dir, _ro)) = fixture_with_read_only_dir(&[("messy.mds", "Hello")]) else {
        return;
    };
    let run = run_in(dir.path(), &["fmt", "ro"]);
    assert_exit_and_code(&run, "fmt ro", 2, "mds::io");
    assert!(
        run.stderr.contains("0 formatted, 0 unchanged, 1 failed"),
        "the summary must count the write failure; stderr: {:?}",
        run.stderr
    );
}

#[cfg(unix)]
#[test]
fn lint_fix_of_a_file_it_cannot_rewrite_exits_2_with_the_io_code() {
    let fixable = "@if \"x\" == \"y\":\nhidden\n@end\nHello\n";
    let Some((dir, _ro)) = fixture_with_read_only_dir(&[("fix.mds", fixable)]) else {
        return;
    };
    let run = run_in(dir.path(), &["lint", "--fix", "ro/fix.mds"]);
    assert_exit_and_code(&run, "lint --fix ro/fix.mds", 2, "mds::io");
}

#[cfg(unix)]
#[test]
fn init_in_a_directory_it_cannot_write_exits_2() {
    let Some((dir, _ro)) = fixture_with_read_only_dir(&[]) else {
        return;
    };
    let run = run_in(dir.path(), &["init", "ro/hello.mds"]);
    assert_exit_and_code(&run, "init ro/hello.mds", 2, "mds::io");
    assert!(
        !dir.path().join("ro/hello.mds").exists(),
        "nothing may be written"
    );
}

// ── A directory run whose file fails with an I/O or file-system error: exit 2 ─

/// A fixture dir with `u/a.mds`, which compiles but lacks the final newline `mds fmt`
/// adds, and `u/b.mds`, which the test's user cannot read (mode `0o000`). `None`, after
/// printing why, when the mode does not stop the read — root ignores it.
#[cfg(unix)]
fn fixture_with_unreadable_source() -> Option<tempfile::TempDir> {
    use std::os::unix::fs::PermissionsExt as _;
    let dir = fixture_dir();
    let u = dir.path().join("u");
    std::fs::create_dir(&u).expect("create u");
    std::fs::write(u.join("a.mds"), "A").expect("write u/a.mds");
    let b = u.join("b.mds");
    std::fs::write(&b, "B\n").expect("write u/b.mds");
    std::fs::set_permissions(&b, std::fs::Permissions::from_mode(0o000)).expect("chmod 0o000");
    if std::fs::read(&b).is_ok() {
        eprintln!(
            "skipped: {} can be read at mode 0o000 (running as root?)",
            b.display()
        );
        return None;
    }
    Some(dir)
}

/// Assert a directory run that could not read one of its sources: exit 2, the failure
/// reported as `mds::io`, and `summary` on stderr — the other file was processed.
#[cfg(unix)]
fn assert_unreadable_source_exits_2(run: &Run, what: &str, summary: &str) {
    assert_exit_and_code(run, what, 2, "mds::io");
    assert!(
        run.stderr.contains("b.mds"),
        "`mds {what}` must name the file it could not read; stderr: {:?}",
        run.stderr
    );
    assert!(
        run.stderr.contains(summary),
        "`mds {what}` must process the other file and count the failed one: {summary:?}; \
         stderr: {:?}",
        run.stderr
    );
}

#[cfg(unix)]
#[test]
fn a_directory_build_with_an_unreadable_source_exits_2() {
    let Some(dir) = fixture_with_unreadable_source() else {
        return;
    };
    let run = run_in(dir.path(), &["build", "u"]);
    assert_unreadable_source_exits_2(&run, "build u", "1 built, 1 failed");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("u/a.md"))
            .ok()
            .as_deref(),
        Some("A\n"),
        "the source that can be read must still be built"
    );
}

#[cfg(unix)]
#[test]
fn a_directory_check_with_an_unreadable_source_exits_2() {
    let Some(dir) = fixture_with_unreadable_source() else {
        return;
    };
    let run = run_in(dir.path(), &["check", "u"]);
    assert_unreadable_source_exits_2(&run, "check u", "1 passed, 1 failed");
}

#[cfg(unix)]
#[test]
fn a_directory_fmt_with_an_unreadable_source_exits_2() {
    let Some(dir) = fixture_with_unreadable_source() else {
        return;
    };
    let run = run_in(dir.path(), &["fmt", "u"]);
    assert_unreadable_source_exits_2(&run, "fmt u", "1 formatted, 0 unchanged, 1 failed");
    assert_eq!(
        std::fs::read_to_string(dir.path().join("u/a.mds"))
            .ok()
            .as_deref(),
        Some("A\n"),
        "the source that can be read must still be formatted"
    );
}

/// A directory build or check with a file that imports a file that does not exist
/// exits 2, as that file given alone does: `mds::file_not_found` is in the I/O and
/// file-system class (#157). Unlike the unreadable-source tests, this runs on every OS.
#[test]
fn a_directory_build_or_check_with_a_missing_import_exits_2() {
    for (args, summary) in [
        (&["build", "i"][..], "1 built, 1 failed"),
        (&["check", "i"][..], "1 passed, 1 failed"),
    ] {
        let what = args.join(" ");
        let dir = fixture_dir();
        let i = dir.path().join("i");
        std::fs::create_dir(&i).expect("create i");
        std::fs::write(i.join("a.mds"), "@import \"./nope.mds\" as n\n\nHi\n")
            .expect("write i/a.mds");
        std::fs::write(i.join("b.mds"), "Ok\n").expect("write i/b.mds");
        let run = run(dir.path(), args, "", None);
        assert_exit_and_code(&run, &what, 2, "mds::file_not_found");
        assert!(
            run.stderr.contains(summary),
            "`mds {what}` must process the other file and count the failed one: \
             {summary:?}; stderr: {:?}",
            run.stderr
        );
    }
}

/// A directory run whose only failures are a template error and a file over the size
/// cap exits 3, the file's own code alone, not the template error's 1; and it reports no
/// I/O failure, which would lift it to 2 (#157).
#[test]
fn a_directory_run_whose_failures_are_a_template_error_and_a_resource_limit_exits_3() {
    let over_cap = "x".repeat(STDIN_CAP + 1);
    for (args, summary) in [
        (&["build", "t"][..], "1 built, 2 failed"),
        (&["check", "t"][..], "1 passed, 2 failed"),
        (&["fmt", "t"][..], "0 formatted, 1 unchanged, 2 failed"),
    ] {
        let what = args.join(" ");
        let dir = fixture_dir();
        let t = dir.path().join("t");
        std::fs::create_dir(&t).expect("create t");
        std::fs::write(t.join("ok.mds"), "Hello\n").expect("write t/ok.mds");
        std::fs::write(t.join("bad.mds"), "@if flag:\nunterminated\n").expect("write t/bad.mds");
        std::fs::write(t.join("big.mds"), &over_cap).expect("write t/big.mds");
        let run = run(dir.path(), args, "", None);
        assert_exit_and_code(&run, &what, 3, "mds::resource_limit");
        assert!(
            run.stderr.contains("mds::syntax") && !run.stderr.contains("mds::io"),
            "`mds {what}` must report the template error and no I/O failure; stderr: {:?}",
            run.stderr
        );
        assert!(
            run.stderr.contains(summary),
            "`mds {what}` must count both failures: {summary:?}; stderr: {:?}",
            run.stderr
        );
    }
}

// ── Stdin that cannot be read, is not UTF-8, or is over the cap ──────────────

/// The four subcommands that read a source from stdin.
const STDIN_COMMANDS: [&[&str]; 4] = [
    &["build", "-"],
    &["check", "-"],
    &["fmt", "-"],
    &["lint", "-"],
];

/// A stdin handle every read of fails: a directory on unix, a write-only file on
/// Windows. Kept alive by the returned tempdir.
fn unreadable_stdin() -> (tempfile::TempDir, Stdio) {
    let dir = tempfile::tempdir().expect("tempdir");
    #[cfg(unix)]
    let handle = std::fs::File::open(dir.path()).expect("open a directory handle");
    #[cfg(windows)]
    let handle = std::fs::File::create(dir.path().join("stdin")).expect("create a write-only file");
    (dir, Stdio::from(handle))
}

#[test]
fn stdin_that_cannot_be_read_exits_2() {
    for args in STDIN_COMMANDS {
        let what = args.join(" ");
        let dir = fixture_dir();
        let (_keep, stdin) = unreadable_stdin();
        let run = run_with(
            dir.path(),
            args,
            Input::Handle(stdin),
            Stdio::piped(),
            Stdio::piped(),
        );
        assert_exit_and_code(&run, &what, 2, "mds::io");
        assert!(
            run.stderr.contains("cannot read stdin"),
            "`mds {what}` must say stdin could not be read; stderr: {:?}",
            run.stderr
        );
    }
}

#[test]
fn stdin_that_is_not_utf8_exits_2() {
    for args in STDIN_COMMANDS {
        let what = args.join(" ");
        let dir = fixture_dir();
        let run = run_with(
            dir.path(),
            args,
            Input::Bytes(b"Hello \xff\n".to_vec()),
            Stdio::piped(),
            Stdio::piped(),
        );
        assert_exit_and_code(&run, &what, 2, "mds::io");
        assert!(
            run.stderr.contains("valid UTF-8"),
            "`mds {what}` must say stdin was not UTF-8; stderr: {:?}",
            run.stderr
        );
    }
}

/// The per-source cap stdin is read against: 10 MiB.
const STDIN_CAP: usize = 10 * 1024 * 1024;

#[test]
fn stdin_over_the_cap_exits_3() {
    let lint_json: &[&str] = &["lint", "--format", "json", "-"];
    for args in STDIN_COMMANDS.into_iter().chain([lint_json]) {
        let what = args.join(" ");
        let dir = fixture_dir();
        let run = run_with(
            dir.path(),
            args,
            Input::Bytes(vec![b'x'; STDIN_CAP + 1]),
            Stdio::piped(),
            Stdio::piped(),
        );
        if args == lint_json {
            // Reported in its one document, the error document on stdout (#309).
            assert_eq!(run.code, Some(3), "`mds {what}`; stderr: {:?}", run.stderr);
            assert!(
                run.stdout.contains("\"code\":\"mds::resource_limit\""),
                "`mds {what}` must report mds::resource_limit; stdout: {:?}",
                run.stdout
            );
        } else {
            assert_exit_and_code(&run, &what, 3, "mds::resource_limit");
        }
    }
}

/// The source ends in a newline, so `mds fmt` has nothing to change and the run tests
/// the size gate alone.
#[test]
fn stdin_of_exactly_the_cap_passes_the_size_gate() {
    let mut at_cap = vec![b'x'; STDIN_CAP - 1];
    at_cap.push(b'\n');
    for args in STDIN_COMMANDS {
        let what = args.join(" ");
        let dir = fixture_dir();
        let run = run_with(
            dir.path(),
            args,
            Input::Bytes(at_cap.clone()),
            Stdio::piped(),
            Stdio::piped(),
        );
        assert_eq!(
            run.code,
            Some(0),
            "`mds {what}` must accept exactly the cap; stderr: {:?}",
            run.stderr
        );
    }
}