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
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
//! The lines of `mds build`, `mds check`, `mds fmt`, `mds lint`, `mds watch` and
//! `mds init` pinned here, each in the form spec.md §7.10 gives it (#390). Most name a
//! path as typed, or as the part below a directory the user named, as typed — the
//! directory argument, `--out-dir`, the directory `mds.json` was reached by, or the
//! entry's directory — never by a canonical or absolute spelling the user did not type;
//! `mds lint`'s rule findings name a file argument by its file name. The cause an error
//! pinned here gives after its path — the operating system's, the file watcher's or
//! tempfile's — names no path. The carve-outs are pinned as they stand: the file name of
//! `mds watch`'s output beside its entry is the one the volume holds, which differs from
//! the name as typed for an entry typed in another case on a case-insensitive volume, and
//! a directory `mds watch` watches for a dependency outside the entry's directory and the
//! directory argument has only the path the compile reported (one below either is named
//! below it as typed — only a refused watch prints it, so watch.rs's unit tests pin that).
//!
//! spec.md §7.10's table cites, row by row, the tests that pin each line it lists;
//! [`the_spec_s_path_label_table_cites_exactly_these_tests`] keeps the table and
//! [`LABEL_TABLE`] in step and checks that each test cited is defined.
//!
//! Each run starts in a scratch directory with relative arguments, so the scratch
//! directory's own absolute path has no business in a line pinned as typed: [`leak`] looks
//! for it in every spelling it can take. Every absence check sits beside a check that the
//! line it is about was printed, so no test passes on a run that printed nothing.
//!
//! An expected path is written with `/` and printed through [`native`], so it names the
//! path in the platform's separator, exactly as `mds` prints it. A path argument is typed
//! through [`typed_args`] the same way: `mds` prints a typed path exactly as typed, so an
//! argument typed with `/` keeps it on Windows while the components `mds` joins to it
//! take `\`.

mod common;

use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Output, Stdio};
use std::time::{Duration, Instant};

use common::{mds_bin, write_atomic};

/// A scratch directory whose name no output could carry by chance.
fn scratch() -> tempfile::TempDir {
    tempfile::Builder::new()
        .prefix("mds-path-labels-")
        .tempdir()
        .expect("create a scratch directory")
}

/// `path`, written with `/`, in the platform's separator.
fn native(path: &str) -> String {
    path.replace('/', std::path::MAIN_SEPARATOR_STR)
}

/// Write `contents` to `root/rel` (`rel` written with `/`), creating its directories.
fn put(root: &Path, rel: &str, contents: &str) -> PathBuf {
    let path = root.join(native(rel));
    let parent = path.parent().expect("a file below the root");
    std::fs::create_dir_all(parent).expect("create the fixture's directories");
    std::fs::write(&path, contents).expect("write a fixture file");
    path
}

/// `args` as a user of this platform types them: each `/` in the platform's separator.
/// No flag or value in these tests other than a path carries a `/`.
fn typed_args(args: &[&str]) -> Vec<String> {
    args.iter().map(|arg| native(arg)).collect()
}

/// `mds <args>` in `cwd`, stdin empty.
fn run(cwd: &Path, args: &[impl AsRef<OsStr>]) -> Output {
    mds_bin()
        .current_dir(cwd)
        .args(args)
        .stdin(Stdio::null())
        .output()
        .expect("run mds")
}

/// `mds <args>` in `cwd`, with `input` on stdin.
fn run_with_stdin(cwd: &Path, args: &[impl AsRef<OsStr>], input: &'static str) -> Output {
    let mut child = mds_bin()
        .current_dir(cwd)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn mds");
    let mut stdin = child.stdin.take().expect("stdin is piped");
    // A child that exits before reading all of stdin closes the pipe; that is not this
    // test's concern, so the write's result is ignored.
    let writer = std::thread::spawn(move || {
        let _ = stdin.write_all(input.as_bytes());
    });
    let output = child.wait_with_output().expect("wait for mds");
    writer.join().expect("the stdin writer does not panic");
    output
}

fn text(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).into_owned()
}

/// Every spelling of `dir`'s absolute path a leak could take: as created and canonical;
/// each with and without macOS's `/private`, with and without a Windows verbatim prefix;
/// each of those JSON-escaped; and `dir`'s own name, which every one of them ends with.
fn spellings(dir: &Path) -> Vec<String> {
    let created = dir.to_string_lossy().into_owned();
    let canonical = dir
        .canonicalize()
        .expect("the scratch directory resolves")
        .to_string_lossy()
        .into_owned();
    let mut forms = Vec::new();
    for form in [created, canonical] {
        let plain = form.strip_prefix(r"\\?\").unwrap_or(&form).to_owned();
        let public = plain.strip_prefix("/private").unwrap_or(&plain).to_owned();
        for spelling in [
            form.clone(),
            format!(r"\\?\{plain}"),
            format!("/private{public}"),
            plain,
            public,
        ] {
            forms.push(spelling.replace('\\', r"\\"));
            forms.push(spelling);
        }
    }
    forms.push(
        dir.file_name()
            .expect("the scratch directory has a name")
            .to_string_lossy()
            .into_owned(),
    );
    forms.sort();
    forms.dedup();
    forms
}

/// `s` without whitespace and without miette's frame gutter (U+2502): an error frame
/// wraps a long line, even inside a path, and continues it after the gutter.
fn squash(s: &str) -> String {
    s.chars()
        .filter(|c| !c.is_whitespace() && *c != '\u{2502}')
        .collect()
}

/// The first spelling of `dir` that `text` carries, as printed or wrapped across an
/// error frame's lines, if any.
fn leak(text: &str, dir: &Path) -> Option<String> {
    let squashed = squash(text);
    spellings(dir)
        .into_iter()
        .find(|spelling| text.contains(spelling.as_str()) || squashed.contains(&squash(spelling)))
}

/// The leak check itself finds the scratch directory in every spelling a line could
/// carry, JSON-escaped too, and finds nothing in a line that names a relative path.
#[test]
fn the_leak_check_finds_the_scratch_directory_in_every_spelling() {
    let dir = scratch();
    let canonical = dir.path().canonicalize().unwrap();
    let mut planted = vec![dir.path().to_path_buf(), canonical.clone()];
    // macOS: the temporary directory is `/var/…`, canonical `/private/var/…`.
    if let Ok(public) = canonical.strip_prefix("/private") {
        planted.push(Path::new("/").join(public));
    }
    for shown in planted {
        let line = format!("Compiled to {}\n", shown.join("page.md").display());
        assert!(
            leak(&line, dir.path()).is_some(),
            "the check must find {shown:?} in {line:?}"
        );
        let json = serde_json::to_string(&line).unwrap();
        assert!(
            leak(&json, dir.path()).is_some(),
            "the check must find {shown:?} JSON-escaped in {json:?}"
        );
        // An error frame wraps a long line inside the path, at a hyphen, and goes on
        // after its gutter.
        let text = shown.to_string_lossy().into_owned();
        let at = text
            .rfind('-')
            .expect("the scratch directory's name has a hyphen")
            + 1;
        let wrapped = format!(
            "  \u{d7} cannot create output directory {}\n  \u{2502} {}/out: File exists\n",
            &text[..at],
            &text[at..]
        );
        assert!(
            leak(&wrapped, dir.path()).is_some(),
            "the check must find {shown:?} wrapped in {wrapped:?}"
        );
    }
    assert_eq!(
        leak(
            &format!("Compiled to {}\n", native("out/page.md")),
            dir.path()
        ),
        None,
        "a relative path is no leak"
    );
}

// ── `Compiled to` under `--out-dir` ──────────────────────────────────────────

/// A directory build under a relative `--out-dir` names each output below the out-dir as
/// typed, never below its canonical absolute path.
#[test]
fn compiled_to_under_a_relative_out_dir_names_the_out_dir_as_typed() {
    let dir = scratch();
    put(dir.path(), "src/sub/page.mds", "Page\n");

    let out = run(dir.path(), &["build", "src", "--out-dir", "out"]);
    let stderr = text(&out.stderr);

    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Compiled to {}\n1 built, 0 failed\n",
            native("out/sub/page.md")
        ),
        "the output is named below the out-dir as typed"
    );
    assert!(
        dir.path().join("out/sub/page.md").is_file(),
        "the output was written"
    );
    assert_eq!(leak(&stderr, dir.path()), None, "stderr: {stderr}");
    assert_eq!(leak(&text(&out.stdout), dir.path()), None);
}

/// An out-dir reached through a symlink is named by the link, as typed — relative or
/// absolute — never by the directory the link resolves to.
///
/// Runs on every OS; each name is written in the platform's separator.
#[test]
fn compiled_to_under_a_symlinked_out_dir_names_the_link_not_its_target() {
    let dir = scratch();
    put(dir.path(), "src/sub/page.mds", "Page\n");
    std::fs::create_dir(dir.path().join("real-target")).unwrap();
    if !common::make_symlink(
        &dir.path().join("real-target"),
        &dir.path().join("alias-link"),
    ) {
        return;
    }

    // Relative, as typed.
    let out = run(dir.path(), &["build", "src", "--out-dir", "alias-link"]);
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Compiled to {}\n1 built, 0 failed\n",
            native("alias-link/sub/page.md")
        ),
        "the output is named below the link as typed"
    );
    assert!(
        dir.path().join(native("real-target/sub/page.md")).is_file(),
        "the output was written through the link"
    );
    assert!(
        !stderr.contains("real-target"),
        "never by the link's target; stderr: {stderr}"
    );
    assert_eq!(leak(&stderr, dir.path()), None, "stderr: {stderr}");

    // Absolute, as typed: the same spelling, never the canonical one.
    let typed = dir.path().join("alias-link");
    let out = run(
        dir.path(),
        &["build", "src", "--out-dir", typed.to_str().unwrap()],
    );
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Compiled to {}\n1 built, 0 failed\n",
            typed.join("sub").join("page.md").display()
        ),
        "an absolute out-dir is named exactly as typed"
    );
    assert!(
        !stderr.contains("real-target"),
        "never by the link's target; stderr: {stderr}"
    );
}

/// The `Source map written` lines under a relative `--out-dir` name each map below the
/// out-dir as typed.
#[test]
fn source_map_lines_under_an_out_dir_name_the_out_dir_as_typed() {
    let dir = scratch();
    put(dir.path(), "src/sub/page.mds", "Page\n");

    let out = run(
        dir.path(),
        &["build", "src", "--out-dir", "out", "--source-map"],
    );
    let stderr = text(&out.stderr);

    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Compiled to {}\nSource map written to {}\n1 built, 0 failed\n",
            native("out/sub/page.md"),
            native("out/sub/page.md.map")
        ),
    );
    assert!(
        dir.path().join("out/sub/page.md.map").is_file(),
        "the map was written"
    );
    assert_eq!(leak(&stderr, dir.path()), None, "stderr: {stderr}");
}

/// An output whose directory cannot be created is named as its `Compiled to` line would
/// name it, in the one wording of a failed write (#160): below `--out-dir` as typed, and
/// below the directory `mds.json` was reached by.
#[test]
fn an_output_directory_that_cannot_be_created_is_named_as_its_output_is() {
    let dir = scratch();
    put(dir.path(), "src/sub/page.mds", "Page\n");
    // A file where the output's directory would go.
    put(dir.path(), "out/sub", "not a directory\n");
    let proj = dir.path().join("proj");
    put(&proj, "mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(&proj, "page.mds", "Page\n");
    put(&proj, "dist", "not a directory\n");

    for (cwd, args, shown) in [
        (
            dir.path(),
            &["build", "src", "--out-dir", "out"][..],
            "out/sub/page.md",
        ),
        (proj.as_path(), &["build", "page.mds"][..], "./dist/page.md"),
    ] {
        let out = run(cwd, args);
        let stderr = text(&out.stderr);
        assert_eq!(out.status.code(), Some(2), "{args:?}: stderr: {stderr}");
        let expected = format!("cannot write {}: ", native(shown));
        assert!(
            stderr.contains(&expected),
            "{args:?}: stderr must hold {expected:?}; got: {stderr}"
        );
        assert_eq!(
            leak(&stderr, dir.path()),
            None,
            "{args:?}: stderr: {stderr}"
        );
    }
}

// ── `mds.json` `build.output_dir` and `build.source_map` ─────────────────────

/// An output under `mds.json` `build.output_dir` is named through the directory the
/// argument reached `mds.json` by — `./`, `src/../`, one `..` per step up — exactly as a
/// config error names `mds.json` itself, never by the canonical config directory.
#[test]
fn a_config_output_dir_is_named_through_the_directory_mds_json_was_reached_by() {
    let dir = scratch();
    let proj = dir.path().join("proj");
    put(&proj, "mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(&proj, "page.mds", "Page\n");
    put(&proj, "src/sub/deep.mds", "Deep\n");

    let cases: [(&[&str], String, &str); 3] = [
        (
            &["build", "page.mds"],
            format!("Compiled to {}\n", native("./dist/page.md")),
            "dist/page.md",
        ),
        (
            &["build", "src"],
            format!(
                "Compiled to {}\n1 built, 0 failed\n",
                native("src/../dist/sub/deep.md")
            ),
            "dist/sub/deep.md",
        ),
        (
            &["build", "src/sub/deep.mds"],
            format!("Compiled to {}\n", native("src/sub/../../dist/deep.md")),
            "dist/deep.md",
        ),
    ];
    for (args, expected, written) in cases {
        let out = run(&proj, &typed_args(args));
        let stderr = text(&out.stderr);
        assert_eq!(out.status.code(), Some(0), "{args:?}: stderr: {stderr}");
        assert_eq!(stderr, expected, "{args:?}");
        assert!(
            proj.join(written).is_file(),
            "{args:?}: {written} was written"
        );
        assert_eq!(
            leak(&stderr, dir.path()),
            None,
            "{args:?}: stderr: {stderr}"
        );
    }
}

/// Under `mds.json` `build.output_dir`, the source map a build writes and the stale map
/// a later build without one removes are both named as the output is.
#[test]
fn a_config_output_dir_names_the_map_written_and_the_stale_map_removed() {
    let dir = scratch();
    let proj = dir.path().join("proj");
    put(&proj, "mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(&proj, "page.mds", "Page\n");

    let out = run(&proj, &["build", "page.mds", "--source-map"]);
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Compiled to {}\nSource map written to {}\n",
            native("./dist/page.md"),
            native("./dist/page.md.map")
        ),
    );
    assert!(
        proj.join("dist/page.md.map").is_file(),
        "the map was written"
    );
    assert_eq!(leak(&stderr, dir.path()), None, "stderr: {stderr}");

    let out = run(&proj, &["build", "page.mds"]);
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Compiled to {}\nRemoved stale map {}\n",
            native("./dist/page.md"),
            native("./dist/page.md.map")
        ),
    );
    assert!(
        !proj.join("dist/page.md.map").exists(),
        "the stale map was removed"
    );
    assert_eq!(leak(&stderr, dir.path()), None, "stderr: {stderr}");
}

/// The warning that `mds.json` `build.source_map` has no effect on stdout names the
/// `mds.json` it came from as the argument reached it, as a config error does — never
/// the canonical config directory.
#[test]
fn the_config_source_map_warning_names_mds_json_as_reached() {
    let dir = scratch();
    let proj = dir.path().join("proj");
    put(&proj, "mds.json", r#"{"build":{"source_map":true}}"#);
    put(&proj, "page.mds", "Page\n");
    put(&proj, "src/deep.mds", "Deep\n");

    for (args, config, stdout) in [
        (["build", "page.mds", "-o", "-"], "./mds.json", "Page\n"),
        (
            ["build", "src/deep.mds", "-o", "-"],
            "src/../mds.json",
            "Deep\n",
        ),
    ] {
        let out = run(&proj, &typed_args(&args));
        let stderr = text(&out.stderr);
        assert_eq!(out.status.code(), Some(0), "{args:?}: stderr: {stderr}");
        assert_eq!(
            stderr,
            format!(
                "warning: source_map in {} has no effect when writing to stdout (sidecar \
                 requires -o <file> or --out-dir); use --inline to embed the map, or \
                 --no-source-map to silence this warning\n",
                native(config)
            ),
            "{args:?}"
        );
        assert_eq!(
            text(&out.stdout),
            stdout,
            "{args:?}: the output went to stdout"
        );
        assert_eq!(
            leak(&stderr, dir.path()),
            None,
            "{args:?}: stderr: {stderr}"
        );
    }
}

// ── lint `Clean:` ────────────────────────────────────────────────────────────

/// `Clean:` names a file argument as typed — its directory part and an absolute path
/// included — as `Fixed:` and `Would fix:` already do, not by its file name alone.
#[test]
fn clean_names_a_file_argument_as_typed() {
    let dir = scratch();
    let file = put(
        dir.path(),
        "sub/page.mds",
        "---\ngreeting: Hello\n---\n\n{{greeting}}, world!\n",
    );

    let out = run(dir.path(), &typed_args(&["lint", "sub/page.mds"]));
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(stderr, format!("Clean: {}\n", native("sub/page.mds")));

    let out = run(&dir.path().join("sub"), &["lint", "page.mds"]);
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(stderr, "Clean: page.mds\n", "a bare name stays bare");

    let typed = file.to_str().unwrap();
    let out = run(dir.path(), &["lint", typed]);
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!("Clean: {typed}\n"),
        "an absolute argument is named as typed"
    );
}

/// The two lines that open a unified diff of `path` (written with `/`, printed through
/// [`native`]).
fn diff_header(path: &str) -> String {
    let path = native(path);
    format!("--- {path}\n+++ {path}\n")
}

/// Runs `mds` with `args` (each passed through [`typed_args`]) against `root`, feeding
/// `stdin` when given: the exit code, stdout, stderr — each checked for no leaked
/// scratch-directory path — and a label naming the invocation.
fn run_typed(
    root: &Path,
    args: &[&str],
    stdin: Option<&'static str>,
) -> (Option<i32>, String, String, String) {
    let args = typed_args(args);
    let out = match stdin {
        Some(input) => run_with_stdin(root, &args, input),
        None => run(root, &args),
    };
    let (stdout, stderr) = (text(&out.stdout), text(&out.stderr));
    assert_eq!(leak(&stdout, root), None, "{args:?}: stdout: {stdout}");
    assert_eq!(leak(&stderr, root), None, "{args:?}: stderr: {stderr}");
    (
        out.status.code(),
        stdout,
        stderr,
        format!("mds {}", args.join(" ")),
    )
}

/// `mds lint` names a file argument as typed in `Fixed:`, `Would fix:` and the header of a
/// `--fix --diff`, a directory's entry below the directory argument as typed, and stdin as
/// `<stdin>`. The source frame of a rule's finding and the JSON `file` key name a file
/// argument by its file name and a directory's entry by its path relative to the directory
/// argument, `/`-separated on every OS.
#[test]
fn lint_names_a_file_argument_as_typed_and_its_findings_by_its_file_name() {
    const WARN: &str = "---\ngreeting: Hello\nunused_key: x\n---\n\n{{greeting}}, world!\n";
    const FIXABLE: &str = "@if \"x\" == \"y\":\nhidden\n@end\nHello\n";
    let dir = scratch();
    let root = dir.path();
    put(root, "sub/warn.mds", WARN);
    put(root, "lints/deep/warn.mds", WARN);
    put(root, "sub/f.mds", FIXABLE);
    put(root, "fix/deep/f.mds", FIXABLE);
    let lint = |args: &[&str], stdin: Option<&'static str>| run_typed(root, args, stdin);

    // (the input, stdin, the source frame's header, the JSON `file` key)
    for (input, stdin, frame, key) in [
        ("sub/warn.mds", None, "[warn.mds:3:1]", "warn.mds"),
        ("lints", None, "[deep/warn.mds:3:1]", "deep/warn.mds"),
        ("-", Some(WARN), "[<stdin>:3:1]", "<stdin>"),
    ] {
        let (code, _, stderr, label) = lint(&["lint", input], stdin);
        assert_eq!(code, Some(1), "{label}: stderr: {stderr}");
        assert!(
            stderr.contains(frame),
            "{label}: the finding's frame names the input as {frame:?}; stderr: {stderr}"
        );
        assert!(
            !stderr.contains(&format!("[{}", native(input))) || input == "-",
            "{label}: never by the path as typed; stderr: {stderr}"
        );
        let (code, stdout, _, label) = lint(&["lint", input, "--format", "json"], stdin);
        assert_eq!(code, Some(1), "{label}: stdout: {stdout}");
        let key = format!("\"file\":\"{key}\"");
        assert!(stdout.contains(&key), "{label}: {key}; stdout: {stdout}");
    }

    // Read-only first, then the fixes.
    let (code, _, stderr, label) = lint(&["lint", "--fix", "--check", "sub/f.mds"], None);
    assert_eq!(code, Some(1), "{label}: stderr: {stderr}");
    let would = format!("Would fix: {}", native("sub/f.mds"));
    assert!(
        stderr.lines().any(|line| line == would),
        "{label}: {would:?}; stderr: {stderr}"
    );
    let (code, _, stderr, label) = lint(&["lint", "--fix", "--check", "-"], Some(FIXABLE));
    assert_eq!(code, Some(1), "{label}: stderr: {stderr}");
    assert!(
        stderr.lines().any(|line| line == "Would fix: <stdin>"),
        "{label}: stderr: {stderr}"
    );
    for (input, shown) in [("sub/f.mds", "sub/f.mds"), ("fix", "fix/deep/f.mds")] {
        let (code, stdout, stderr, label) = lint(&["lint", "--fix", "--diff", input], None);
        assert_eq!(code, Some(1), "{label}: stderr: {stderr}");
        assert!(
            stdout.starts_with(&diff_header(shown)),
            "{label}: the diff names the input as {shown:?}; stdout: {stdout}"
        );
    }
    let (code, _, stderr, label) = lint(&["lint", "--fix", "sub/f.mds"], None);
    assert_eq!(code, Some(0), "{label}: stderr: {stderr}");
    assert_eq!(
        stderr,
        format!("Fixed: {}\n", native("sub/f.mds")),
        "{label}"
    );
    let (code, _, stderr, label) = lint(&["lint", "--fix", "fix"], None);
    assert_eq!(code, Some(0), "{label}: stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Fixed: {}\n1 clean, 0 with warnings, 0 with errors, 0 resource-limited\n",
            native("fix/deep/f.mds")
        ),
        "{label}"
    );
}

// ── `mds fmt` and `mds init` ─────────────────────────────────────────────────

/// `mds fmt` names a file argument as typed, a directory's entry below the directory
/// argument as typed and stdin as `<stdin>`, in `Formatted:`, `Unchanged:` and
/// `Would reformat:` and in the header of a `--diff`.
#[test]
fn fmt_names_a_file_argument_as_typed_and_a_directory_s_entries_below_it() {
    let dir = scratch();
    let root = dir.path();
    // Without a final newline each of these reformats; `fine.mds` does not.
    put(root, "sub/messy.mds", "Hello");
    put(root, "sub/fine.mds", "Fine\n");
    put(root, "src/a.mds", "A");
    put(root, "src/inner/b.mds", "B");
    let fmt = |args: &[&str], stdin: Option<&'static str>| run_typed(root, args, stdin);

    // Read-only first: (arguments, stdin, exit, the start of stdout, all of stderr).
    let cases = [
        (
            &["fmt", "--check", "sub/messy.mds"][..],
            None,
            1,
            String::new(),
            format!("Would reformat: {}\n", native("sub/messy.mds")),
        ),
        (
            &["fmt", "--check", "sub/fine.mds"][..],
            None,
            0,
            String::new(),
            format!("Unchanged: {}\n", native("sub/fine.mds")),
        ),
        (
            &["fmt", "--diff", "sub/messy.mds"][..],
            None,
            0,
            diff_header("sub/messy.mds"),
            String::new(),
        ),
        (
            &["fmt", "--check", "-"][..],
            Some("Q"),
            1,
            String::new(),
            "Would reformat: <stdin>\n".to_owned(),
        ),
        (
            &["fmt", "--diff", "-"][..],
            Some("Q"),
            0,
            diff_header("<stdin>"),
            String::new(),
        ),
    ];
    for (args, stdin, exit, stdout_start, expected_stderr) in cases {
        let (code, stdout, stderr, label) = fmt(args, stdin);
        assert_eq!(code, Some(exit), "{label}: stderr: {stderr}");
        assert!(
            stdout.starts_with(&stdout_start),
            "{label}: stdout starts {stdout_start:?}; stdout: {stdout}"
        );
        assert_eq!(stderr, expected_stderr, "{label}");
    }
    // A directory's entries come in the order the walk finds them.
    let (code, stdout, stderr, label) = fmt(&["fmt", "--diff", "src"], None);
    assert_eq!(code, Some(0), "{label}: stderr: {stderr}");
    for entry in ["src/a.mds", "src/inner/b.mds"] {
        assert!(
            stdout.contains(&diff_header(entry)),
            "{label}: {entry} is named below the directory as typed; stdout: {stdout}"
        );
    }
    assert_eq!(
        stderr, "2 would reformat, 0 unchanged, 0 failed\n",
        "{label}"
    );

    let (code, _, stderr, label) = fmt(&["fmt", "sub/messy.mds"], None);
    assert_eq!(code, Some(0), "{label}: stderr: {stderr}");
    assert_eq!(
        stderr,
        format!("Formatted: {}\n", native("sub/messy.mds")),
        "{label}"
    );
    let (code, _, stderr, label) = fmt(&["fmt", "src"], None);
    assert_eq!(code, Some(0), "{label}: stderr: {stderr}");
    assert_eq!(
        lines_starting(&stderr, "Formatted: "),
        [
            format!("Formatted: {}", native("src/a.mds")),
            format!("Formatted: {}", native("src/inner/b.mds")),
        ],
        "{label}: stderr: {stderr}"
    );
    assert!(
        stderr.ends_with("2 formatted, 0 unchanged, 0 failed\n"),
        "{label}: stderr: {stderr}"
    );
}

/// `mds init` names the file it creates as typed, in `Created` and in its `Try:` hint, and
/// in its refusal to overwrite the file; with no argument the file is `hello.mds`.
#[test]
fn init_names_the_file_it_creates_as_typed() {
    let dir = scratch();
    let root = dir.path();
    std::fs::create_dir_all(root.join("sub")).unwrap();
    std::fs::create_dir_all(root.join("bare")).unwrap();
    let typed = native("sub/new.mds");

    let out = run(root, &typed_args(&["init", "sub/new.mds"]));
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!("Created {typed}\n  Try: mds build {typed}\n")
    );
    assert!(root.join("sub/new.mds").is_file(), "the file was created");
    assert_eq!(leak(&stderr, root), None, "stderr: {stderr}");

    let out = run(root, &typed_args(&["init", "sub/new.mds"]));
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(1), "stderr: {stderr}");
    let refusal = format!("{typed} already exists (use --force to overwrite)");
    assert!(stderr.contains(&refusal), "{refusal:?}; stderr: {stderr}");
    assert_eq!(leak(&stderr, root), None, "stderr: {stderr}");

    let out = run(&root.join("bare"), &["init"]);
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(stderr, "Created hello.mds\n  Try: mds build hello.mds\n");
    assert_eq!(leak(&stderr, root), None, "stderr: {stderr}");
}

// ── The build, check and lint runs listed in `ROWS` ──────────────────────────

/// One run of the sweep below: where it runs, what it runs, what it reads on stdin, its
/// exit code, and a line it must print — proof that the sink the absence check looks at
/// fired.
struct Row {
    cwd: &'static str,
    args: &'static [&'static str],
    stdin: Option<&'static str>,
    exit: i32,
    stdout: Option<&'static str>,
    stderr: Option<&'static str>,
}

const ROWS: &[Row] = &[
    Row {
        cwd: ".",
        args: &["build", "x.mds"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Compiled to ./x.md\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "src/a.mds"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Compiled to src/a.md\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "x.mds", "--source-map"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Source map written to ./x.md.map\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "x.mds", "--out-dir", "o1"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Compiled to o1/x.md\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "x.mds", "-o", "o2/y.md"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Compiled to o2/y.md\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "-", "--out-dir", "o3"],
        stdin: Some("Hi\n"),
        exit: 0,
        stdout: None,
        stderr: Some("Compiled to o3/output.md\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "src"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Compiled to src/sub/b.md\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "src", "--out-dir", "o4", "--source-map"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Source map written to o4/sub/b.md.map\n"),
    },
    Row {
        cwd: ".",
        args: &["build", "bad", "--out-dir", "o5"],
        stdin: None,
        exit: 1,
        stdout: None,
        stderr: Some("undefined variable 'nope'"),
    },
    Row {
        cwd: "proj",
        args: &["build", "p.mds"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Compiled to ./dist/p.md\n"),
    },
    Row {
        cwd: "proj",
        args: &["build", "src", "--source-map"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Source map written to src/../dist/q.md.map\n"),
    },
    Row {
        cwd: "smap",
        args: &["build", "s.mds", "-o", "-"],
        stdin: None,
        exit: 0,
        stdout: Some("S\n"),
        stderr: Some("warning: source_map in ./mds.json has no effect"),
    },
    Row {
        cwd: ".",
        args: &["check", "x.mds"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("OK: x.mds\n"),
    },
    Row {
        cwd: ".",
        args: &["check", "src/a.mds"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("OK: src/a.mds\n"),
    },
    Row {
        cwd: ".",
        args: &["check", "-"],
        stdin: Some("Hi\n"),
        exit: 0,
        stdout: None,
        stderr: Some("OK: <stdin>\n"),
    },
    Row {
        cwd: ".",
        args: &["check", "src"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("2 passed, 0 failed\n"),
    },
    Row {
        cwd: ".",
        args: &["check", "bad"],
        stdin: None,
        exit: 1,
        stdout: None,
        stderr: Some("undefined variable 'nope'"),
    },
    Row {
        cwd: ".",
        args: &["lint", "lint/clean.mds"],
        stdin: None,
        exit: 0,
        stdout: None,
        stderr: Some("Clean: lint/clean.mds\n"),
    },
    Row {
        cwd: ".",
        args: &["lint", "lint/warn.mds"],
        stdin: None,
        exit: 1,
        stdout: None,
        stderr: Some("unused_key"),
    },
    Row {
        cwd: ".",
        args: &["lint", "lint"],
        stdin: None,
        exit: 1,
        stdout: None,
        stderr: Some("1 clean, 1 with warnings, 0 with errors, 0 resource-limited\n"),
    },
    Row {
        cwd: ".",
        args: &["lint", "lint", "--format", "json"],
        stdin: None,
        exit: 1,
        stdout: Some("\"file\":\"warn.mds\""),
        stderr: None,
    },
    Row {
        cwd: ".",
        args: &["lint", "fix", "--fix", "--check"],
        stdin: None,
        exit: 1,
        stdout: None,
        stderr: Some("Would fix: fix/f.mds\n"),
    },
];

/// Each build, check and lint run in [`ROWS`], run from the scratch directory with
/// relative arguments, names no spelling of the scratch directory on stdout or stderr —
/// and printed the line that shows its sink ran.
#[test]
fn no_listed_build_check_or_lint_run_names_the_working_directory() {
    let dir = scratch();
    let root = dir.path();
    put(root, "x.mds", "Hello\n");
    put(root, "src/a.mds", "A\n");
    put(root, "src/sub/b.mds", "B\n");
    put(root, "bad/undef.mds", "Hi {{nope}}\n");
    put(root, "proj/mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(root, "proj/p.mds", "P\n");
    put(root, "proj/src/q.mds", "Q\n");
    put(root, "smap/mds.json", r#"{"build":{"source_map":true}}"#);
    put(root, "smap/s.mds", "S\n");
    put(
        root,
        "lint/clean.mds",
        "---\ngreeting: Hello\n---\n\n{{greeting}}, world!\n",
    );
    put(
        root,
        "lint/warn.mds",
        "---\ngreeting: Hello\nunused_key: never referenced in the body\n---\n\n{{greeting}}, world!\n",
    );
    put(
        root,
        "fix/f.mds",
        "@if \"x\" == \"y\":\nhidden\n@end\nHello\n",
    );

    for row in ROWS {
        let cwd = root.join(row.cwd);
        let args = typed_args(row.args);
        let out = match row.stdin {
            Some(input) => run_with_stdin(&cwd, &args, input),
            None => run(&cwd, &args),
        };
        let (stdout, stderr) = (text(&out.stdout), text(&out.stderr));
        let label = format!("(in {}) mds {}", row.cwd, args.join(" "));
        assert_eq!(
            out.status.code(),
            Some(row.exit),
            "{label}: stdout: {stdout}; stderr: {stderr}"
        );
        if let Some(line) = row.stdout {
            assert!(
                stdout.contains(&native(line)),
                "{label}: stdout must hold {line:?}; got: {stdout}"
            );
        }
        if let Some(line) = row.stderr {
            assert!(
                stderr.contains(&native(line)),
                "{label}: stderr must hold {line:?}; got: {stderr}"
            );
        }
        assert_eq!(leak(&stdout, root), None, "{label}: stdout: {stdout}");
        assert_eq!(leak(&stderr, root), None, "{label}: stderr: {stderr}");
    }
}

// ── `mds watch`, where it shares build's output lines ─────────────────────────

/// `mds watch` announces its startup outputs through build's `Compiled to` line, so an
/// output under `--out-dir` (directory mode) or under `mds.json` `build.output_dir`
/// (both modes) is named as `mds build` names it — for an entry typed as the volume
/// spells it (see `an_entry_typed_in_another_case_names_its_output_by_the_name_on_disk`).
/// Watch's own lines are pinned in the section below.
#[test]
fn watch_startup_names_an_out_dir_and_a_config_output_dir_as_build_does() {
    let dir = scratch();
    put(dir.path(), "src/sub/page.mds", "Page\n");
    let proj = dir.path().join("proj");
    put(&proj, "mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(&proj, "p.mds", "P\n");
    put(&proj, "src/q.mds", "Q\n");

    let cases: [(&Path, &[&str], String); 3] = [
        (
            dir.path(),
            &["watch", "src", "--out-dir", "out"],
            format!("Compiled to {}\n", native("out/sub/page.md")),
        ),
        (
            &proj,
            &["watch", "src"],
            format!("Compiled to {}\n", native("src/../dist/q.md")),
        ),
        (
            &proj,
            &["watch", "p.mds"],
            format!("Compiled to {}\n", native("./dist/p.md")),
        ),
    ];
    for (cwd, args, expected) in cases {
        let (child, tap, _) = common::spawn_watch_ready(
            mds_bin()
                .current_dir(cwd)
                .args(args)
                .args(["--debounce", "0"])
                .stdout(Stdio::null()),
        );
        let mut child = common::ChildGuard(child);
        let stderr = tap.finish_text(&mut child);
        assert!(
            stderr.contains(&expected),
            "{args:?}: stderr must hold {expected:?}; got: {stderr}"
        );
        let canonical = cwd.canonicalize().unwrap();
        assert!(
            !stderr.contains(&format!("Compiled to {}", canonical.display())),
            "{args:?}: never below the canonical directory; got: {stderr}"
        );
    }
}

// ── `mds watch`'s own lines ──────────────────────────────────────────────────

/// Bound for one step of a watch session — a rebuild, a deletion. A failure bound only:
/// each wait returns as soon as its line is on stderr.
const WATCH_STEP: Duration = Duration::from_secs(10);

/// `mds watch <args> --debounce 0` in `cwd`, live — every watch armed, its startup output
/// printed. stdout is tapped when `tap_stdout` (`-o -`), discarded otherwise.
fn watch_live(
    cwd: &Path,
    args: &[impl AsRef<OsStr>],
    tap_stdout: bool,
) -> (
    common::ChildGuard,
    common::StderrTap,
    Option<common::StdoutTap>,
) {
    let stdout = if tap_stdout {
        Stdio::piped()
    } else {
        Stdio::null()
    };
    let (child, stderr, stdout) = common::spawn_watch_ready(
        mds_bin()
            .current_dir(cwd)
            .args(args)
            .args(["--debounce", "0"])
            .stdout(stdout),
    );
    (common::ChildGuard(child), stderr, stdout)
}

/// Makes a directory writable again on drop, so the scratch directory can go.
///
/// Unix-only: it sets unix mode bits, for the read-only fixtures, which are unix's.
#[cfg(unix)]
struct Writable(PathBuf);

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

/// The lines of `text` that start with `prefix`, sorted: a directory's sources are
/// compiled in the order the walk finds them, which the filesystem decides.
fn lines_starting(text: &str, prefix: &str) -> Vec<String> {
    let mut lines: Vec<String> = text
        .lines()
        .filter(|line| line.starts_with(prefix))
        .map(str::to_owned)
        .collect();
    lines.sort();
    lines
}

/// `Watching` names the entry as typed — below a subdirectory, through `..` uncollapsed,
/// and by its bare name when auto-detection found it — and `Watching directory` names the
/// directory argument as typed, `.` included; never by the canonical absolute path the
/// session matches events against. Each session's startup output is compared whole, the
/// `Compiled to` beside each source included, so every line the absence check covers is
/// proven printed.
#[test]
fn watching_names_the_entry_and_the_directory_as_typed() {
    let dir = scratch();
    let root = dir.path();
    put(root, "sub/page.mds", "Page\n");
    put(root, "solo/x.mds", "X\n");
    put(root, "src/a.mds", "A\n");
    put(root, "src/sub/b.mds", "B\n");

    // (working directory, arguments, the banner, the startup `Compiled to` names)
    let cases: [(&str, &[&str], &str, &[&str]); 6] = [
        (
            ".",
            &["watch", "sub/page.mds"],
            "Watching sub/page.mds",
            &["sub/page.md"],
        ),
        (
            ".",
            &["watch", "sub/../sub/page.mds"],
            "Watching sub/../sub/page.mds",
            &["sub/../sub/page.md"],
        ),
        ("solo", &["watch"], "Watching x.mds", &["./x.md"]),
        (
            ".",
            &["watch", "src"],
            "Watching directory src",
            &["src/a.md", "src/sub/b.md"],
        ),
        (
            "src",
            &["watch", "."],
            "Watching directory .",
            &["./a.md", "./sub/b.md"],
        ),
        (
            ".",
            &["watch", "src/sub/.."],
            "Watching directory src/sub/..",
            &["src/sub/../a.md", "src/sub/../sub/b.md"],
        ),
    ];
    for (cwd, args, banner, compiled) in cases {
        let args = typed_args(args);
        let label = format!("(in {cwd}) mds {}", args.join(" "));
        let (mut child, tap, _) = watch_live(&root.join(cwd), &args, false);
        let stderr = tap.finish_text(&mut child);

        let mut expected: Vec<String> = compiled
            .iter()
            .map(|name| format!("Compiled to {}", native(name)))
            .collect();
        expected.sort();
        assert_eq!(
            stderr.lines().next(),
            Some(native(banner).as_str()),
            "{label}: the banner names the argument as typed; stderr: {stderr}"
        );
        assert_eq!(
            lines_starting(&stderr, "Compiled to "),
            expected,
            "{label}: stderr: {stderr}"
        );
        assert_eq!(
            stderr.lines().count(),
            1 + compiled.len(),
            "{label}: nothing but the banner and the startup outputs; stderr: {stderr}"
        );
        assert_eq!(leak(&stderr, root), None, "{label}: stderr: {stderr}");
    }
}

/// An entry, and a directory argument, reached through a symlinked directory are named by
/// the link, as typed — in the banner, the startup `Compiled to` and a rebuild's
/// `Recompiled` — never by the directory the link resolves to, which is what the session
/// watches.
///
/// Runs on every OS; each path is typed, and each name expected, in the platform's
/// separator.
#[test]
fn watching_names_a_path_reached_through_a_symlink_by_the_link() {
    let dir = scratch();
    let root = dir.path();
    put(root, "real-target/page.mds", "Page\n");
    put(root, "real-target/sub/b.mds", "B\n");
    if !common::make_symlink(&root.join("real-target"), &root.join("alias-link")) {
        return;
    }

    // (arguments, the banner, the output's name, the source edited, the output written)
    let cases: [(&[&str], &str, &str, &str, &str); 2] = [
        (
            &["watch", "alias-link/page.mds"],
            "Watching alias-link/page.mds",
            "alias-link/page.md",
            "real-target/page.mds",
            "real-target/page.md",
        ),
        (
            &["watch", "alias-link/sub"],
            "Watching directory alias-link/sub",
            "alias-link/sub/b.md",
            "real-target/sub/b.mds",
            "real-target/sub/b.md",
        ),
    ];
    for (args, banner, output, edit, written) in cases {
        let args = typed_args(args);
        let (banner, output) = (native(banner), native(output));
        let (mut child, tap, _) = watch_live(root, &args, false);
        write_atomic(&root.join(native(edit)), "Edited\n");
        common::wait_for_tap(&tap, "Recompiled ", WATCH_STEP);
        let stderr = tap.finish_text(&mut child);

        assert_eq!(
            stderr.lines().next(),
            Some(banner.as_str()),
            "{args:?}: stderr: {stderr}"
        );
        assert_eq!(
            lines_starting(&stderr, "Compiled to "),
            [format!("Compiled to {output}")],
            "{args:?}: stderr: {stderr}"
        );
        let recompiled = lines_starting(&stderr, "Recompiled ");
        assert!(
            !recompiled.is_empty()
                && recompiled
                    .iter()
                    .all(|line| line.starts_with(&format!("Recompiled {output} ("))),
            "{args:?}: every rebuild names the output by the link; stderr: {stderr}"
        );
        assert_eq!(
            std::fs::read_to_string(root.join(native(written))).unwrap(),
            "Edited\n",
            "{args:?}: the rebuild was written through the link"
        );
        assert!(
            !stderr.contains("real-target"),
            "{args:?}: never by the link's target; stderr: {stderr}"
        );
        assert_eq!(leak(&stderr, root), None, "{args:?}: stderr: {stderr}");
    }
}

/// One `mds watch` session of [`SESSIONS`]: where it runs and what it runs, the outputs
/// its startup names, the source it edits once live and the name the rebuild's
/// `Recompiled` line gives, and — in directory mode — the source it deletes after that
/// and the name the `Removed` line gives its output. Every path is written with `/`,
/// relative to `cwd`.
struct Session {
    cwd: &'static str,
    args: &'static [&'static str],
    /// `-o -`: stdout is the session's product and is checked as well.
    stdout: bool,
    compiled: &'static [&'static str],
    edit: &'static str,
    recompiled: &'static str,
    removed: Option<(&'static str, &'static str)>,
}

const SESSIONS: &[Session] = &[
    Session {
        cwd: ".",
        args: &["watch", "w1/page.mds"],
        stdout: false,
        compiled: &["w1/page.md"],
        edit: "w1/page.mds",
        recompiled: "w1/page.md",
        removed: None,
    },
    Session {
        cwd: ".",
        args: &["watch", "w2/page.mds", "--out-dir", "o2"],
        stdout: false,
        compiled: &["o2/page.md"],
        edit: "w2/page.mds",
        recompiled: "o2/page.md",
        removed: None,
    },
    Session {
        cwd: ".",
        args: &["watch", "w3/page.mds", "-o", "o3/y.md"],
        stdout: false,
        compiled: &["o3/y.md"],
        edit: "w3/page.mds",
        recompiled: "o3/y.md",
        removed: None,
    },
    Session {
        cwd: ".",
        args: &["watch", "w4/page.mds", "-o", "-"],
        stdout: true,
        compiled: &[],
        edit: "w4/page.mds",
        recompiled: "<stdout>",
        removed: None,
    },
    Session {
        cwd: "w5",
        args: &["watch"],
        stdout: false,
        compiled: &["./x.md"],
        edit: "x.mds",
        recompiled: "./x.md",
        removed: None,
    },
    Session {
        cwd: "p6",
        args: &["watch", "p.mds"],
        stdout: false,
        compiled: &["./dist/p.md"],
        edit: "p.mds",
        recompiled: "./dist/p.md",
        removed: None,
    },
    Session {
        cwd: ".",
        args: &["watch", "d7"],
        stdout: false,
        compiled: &["d7/a.md", "d7/sub/b.md"],
        edit: "d7/sub/b.mds",
        recompiled: "d7/sub/b.md",
        removed: Some(("d7/sub/b.mds", "d7/sub/b.md")),
    },
    Session {
        cwd: ".",
        args: &["watch", "d8", "--out-dir", "o8"],
        stdout: false,
        compiled: &["o8/a.md", "o8/sub/b.md"],
        edit: "d8/sub/b.mds",
        recompiled: "o8/sub/b.md",
        removed: Some(("d8/sub/b.mds", "o8/sub/b.md")),
    },
    Session {
        cwd: "d9",
        args: &["watch", "."],
        stdout: false,
        compiled: &["./a.md", "./sub/b.md"],
        edit: "sub/b.mds",
        recompiled: "./sub/b.md",
        removed: Some(("sub/b.mds", "./sub/b.md")),
    },
    Session {
        cwd: "p10",
        args: &["watch", "src"],
        stdout: false,
        compiled: &["src/../dist/q.md", "src/../dist/sub/r.md"],
        edit: "src/sub/r.mds",
        recompiled: "src/../dist/sub/r.md",
        removed: Some(("src/sub/r.mds", "src/../dist/sub/r.md")),
    },
];

/// Every `mds watch` session in [`SESSIONS`] names each output as typed, in every line
/// that names one — the startup `Compiled to`, a rebuild's `Recompiled` and, in directory
/// mode, the `Removed … (source deleted)` of a deleted source's output — and so never
/// mixes a typed `Compiled to` with an absolute `Recompiled`. Run from the scratch
/// directory with relative arguments, no session names any spelling of it on stdout or
/// stderr; each line the absence check covers is proven printed first.
#[test]
fn recompiled_and_removed_name_each_output_as_typed() {
    let dir = scratch();
    let root = dir.path();
    for src in ["w1", "w2", "w3", "w4"] {
        put(root, &format!("{src}/page.mds"), "Page\n");
    }
    put(root, "w5/x.mds", "X\n");
    put(root, "p6/mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(root, "p6/p.mds", "P\n");
    for src in ["d7", "d8", "d9"] {
        put(root, &format!("{src}/a.mds"), "A\n");
        put(root, &format!("{src}/sub/b.mds"), "B\n");
    }
    put(root, "p10/mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(root, "p10/src/q.mds", "Q\n");
    put(root, "p10/src/sub/r.mds", "R\n");

    for session in SESSIONS {
        let cwd = root.join(session.cwd);
        let args = typed_args(session.args);
        let label = format!("(in {}) mds {}", session.cwd, args.join(" "));
        let (mut child, tap, stdout_tap) = watch_live(&cwd, &args, session.stdout);

        write_atomic(&cwd.join(native(session.edit)), "Edited\n");
        common::wait_for_tap(&tap, "Recompiled ", WATCH_STEP);
        if let Some((source, _)) = session.removed {
            std::fs::remove_file(cwd.join(native(source))).expect("delete the source");
            common::wait_for_tap(&tap, "(source deleted)", WATCH_STEP);
        }
        let stderr = tap.finish_text(&mut child);
        let stdout = stdout_tap.map_or_else(String::new, |tap| tap.finish_text(&mut child));

        let mut compiled: Vec<String> = session
            .compiled
            .iter()
            .map(|name| format!("Compiled to {}", native(name)))
            .collect();
        compiled.sort();
        assert_eq!(
            lines_starting(&stderr, "Compiled to "),
            compiled,
            "{label}: stderr: {stderr}"
        );
        let recompiled = lines_starting(&stderr, "Recompiled ");
        let prefix = format!("Recompiled {} (", native(session.recompiled));
        assert!(
            !recompiled.is_empty() && recompiled.iter().all(|line| line.starts_with(&prefix)),
            "{label}: every rebuild names the output as {prefix:?}; stderr: {stderr}"
        );
        let removed: Vec<String> = session
            .removed
            .iter()
            .map(|(_, output)| format!("Removed {} (source deleted)", native(output)))
            .collect();
        assert_eq!(
            lines_starting(&stderr, "Removed "),
            removed,
            "{label}: stderr: {stderr}"
        );
        if session.stdout {
            assert_eq!(
                stdout, "Page\nEdited\n",
                "{label}: the startup output and the rebuild went to stdout"
            );
        }
        assert_eq!(leak(&stderr, root), None, "{label}: stderr: {stderr}");
        assert_eq!(leak(&stdout, root), None, "{label}: stdout: {stdout}");
    }
}

/// `Wrote an empty output: <output>` — what a rebuild prints when it writes an output
/// empty over the non-empty one the session wrote there, as it does once a source emptied
/// and closed stays empty past its hold (#380) — names the output as its `Recompiled`
/// line does: beside the entry as typed, below `--out-dir` as typed, below the directory
/// argument as typed. Run from the scratch directory with relative arguments, it names no
/// spelling of it; each session first proves the line printed.
#[test]
fn an_emptied_output_is_named_as_its_recompiled_line_names_it() {
    let dir = scratch();
    let root = dir.path();
    put(root, "e1/page.mds", "Page\n");
    put(root, "e2/page.mds", "Page\n");
    put(root, "e3/sub/a.mds", "A\n");
    put(root, "e4/sub/a.mds", "A\n");

    // (cwd, args, the source emptied, the output as named)
    let sessions: [(&str, &[&str], &str, &str); 4] = [
        (".", &["watch", "e1/page.mds"], "e1/page.mds", "e1/page.md"),
        ("e2", &["watch", "page.mds"], "page.mds", "./page.md"),
        (
            ".",
            &["watch", "e3", "--out-dir", "o3"],
            "e3/sub/a.mds",
            "o3/sub/a.md",
        ),
        ("e4", &["watch", "."], "sub/a.mds", "./sub/a.md"),
    ];
    for (rel, args, emptied, output) in sessions {
        let cwd = root.join(rel);
        let args = typed_args(args);
        let label = format!("(in {rel}) mds {}", args.join(" "));
        let (mut child, tap, _) = watch_live(&cwd, &args, false);

        // Truncate and close: the source stays empty, so its hold runs out and the empty
        // output is written.
        drop(std::fs::File::create(cwd.join(native(emptied))).expect("empty the source"));
        common::wait_for_tap(&tap, "Wrote an empty output: ", WATCH_STEP);
        let stderr = tap.finish_text(&mut child);

        assert_eq!(
            lines_starting(&stderr, "Wrote an empty output: "),
            [format!("Wrote an empty output: {}", native(output))],
            "{label}: stderr: {stderr}"
        );
        assert_eq!(leak(&stderr, root), None, "{label}: stderr: {stderr}");
    }
}

/// A source deleted in the same batch as an edit to the `--vars` file — the batch that
/// recompiles every source — has its output named as typed in the `Removed … (source
/// deleted)` line, as a deletion alone does.
#[test]
fn removed_names_the_output_as_typed_when_the_vars_file_changes_in_the_same_batch() {
    let dir = scratch();
    let root = dir.path();
    put(root, "d/a.mds", "A {{name}}\n");
    put(root, "d/sub/b.mds", "B\n");
    put(root, "vars.json", r#"{"name": "one"}"#);

    // A debounce window long enough to take both changes into one batch.
    let (child, tap, _) = common::spawn_watch_ready(
        mds_bin()
            .current_dir(root)
            .args(typed_args(&["watch", "d", "--vars", "vars.json"]))
            .args(["--debounce", "500"])
            .stdout(Stdio::null()),
    );
    let mut child = common::ChildGuard(child);
    std::fs::remove_file(root.join(native("d/sub/b.mds"))).expect("delete the source");
    write_atomic(&root.join("vars.json"), r#"{"name": "two"}"#);
    common::wait_for_tap(&tap, "(source deleted)", WATCH_STEP);
    common::wait_for_tap(&tap, "Recompiled ", WATCH_STEP);
    let stderr = tap.finish_text(&mut child);

    assert_eq!(
        lines_starting(&stderr, "Removed "),
        [format!("Removed {} (source deleted)", native("d/sub/b.md"))],
        "stderr: {stderr}"
    );
    let prefix = format!("Recompiled {} (", native("d/a.md"));
    let recompiled = lines_starting(&stderr, "Recompiled ");
    assert!(
        !recompiled.is_empty() && recompiled.iter().all(|line| line.starts_with(&prefix)),
        "the vars change rebuilt the other source, named as {prefix:?}; stderr: {stderr}"
    );
    assert_eq!(leak(&stderr, root), None, "stderr: {stderr}");
}

/// `mds watch d --out-dir o <extra>` in `cwd`, over the one source `d/sub/b.mds`: once the
/// session has written its output `o/sub/b.md`, `block` is given `o/sub` to keep that
/// output from being removed — it returns `false` where it cannot — then the source is
/// deleted, the `--vars` file `vars.json` edited too when `edit_vars`, and the session's
/// stderr given back once it says it could not remove the output. `None` when `block`
/// could not keep the output.
fn retire_a_kept_output(
    cwd: &Path,
    extra: &[&str],
    edit_vars: bool,
    block: impl FnOnce(&Path) -> bool,
) -> Option<String> {
    put(cwd, "d/sub/b.mds", "B\n");
    put(cwd, "vars.json", r#"{"name": "one"}"#);
    let (child, tap, _) = common::spawn_watch_ready(
        mds_bin()
            .current_dir(cwd)
            .args(["watch", "d", "--out-dir", "o"])
            .args(extra)
            .stdout(Stdio::null()),
    );
    let mut child = common::ChildGuard(child);
    if !block(&cwd.join("o").join("sub")) {
        return None;
    }
    std::fs::remove_file(cwd.join(native("d/sub/b.mds"))).expect("delete the source");
    if edit_vars {
        write_atomic(&cwd.join("vars.json"), r#"{"name": "two"}"#);
    }
    common::wait_for_tap(&tap, "could not remove", WATCH_STEP);
    Some(tap.finish_text(&mut child))
}

/// A deleted source's output that cannot be removed is named as typed in the warning that
/// says so, as a removed one is in `Removed`: after a deletion alone, and after one in the
/// same batch as an edit to the `--vars` file. What keeps it is a directory put at its path
/// after the session wrote it — refused as no regular file — or its directory made
/// read-only.
///
/// The directory arm runs on every platform. The read-only arm is unix-only, and skipped
/// with a reason where the mode does not stop a removal (running as root).
#[test]
fn an_output_that_cannot_be_removed_is_named_as_typed() {
    let dir = scratch();
    let root = dir.path();
    let shown = native("o/sub/b.md");
    // (fixture directory, the extra arguments, whether the `--vars` file is edited too)
    for (fixture, extra, edit_vars) in [
        ("alone", &["--debounce", "0"][..], false),
        (
            "with-vars",
            &["--vars", "vars.json", "--debounce", "500"][..],
            true,
        ),
    ] {
        let cwd = root.join(fixture).join("directory");
        let stderr = retire_a_kept_output(&cwd, extra, edit_vars, |sub| {
            std::fs::remove_file(sub.join("b.md")).expect("remove the session's output");
            std::fs::create_dir(sub.join("b.md")).expect("put a directory in its place");
            true
        })
        .expect("a directory always keeps the output");
        let warning = format!("warning: could not remove {shown}: not a regular file\n");
        assert!(
            stderr.contains(&warning),
            "{fixture}: the output is named below the out-dir as typed, {warning:?}; \
             stderr: {stderr}"
        );
        assert!(
            cwd.join(&shown).is_dir(),
            "{fixture}: the directory is still there"
        );
        assert_eq!(leak(&stderr, root), None, "{fixture}: stderr: {stderr}");

        // Unix-only: it sets a directory's mode bits, which Windows has no counterpart of.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;

            let cwd = root.join(fixture).join("read-only");
            let _writable = Writable(cwd.join("o").join("sub"));
            let stderr = retire_a_kept_output(&cwd, extra, edit_vars, |sub| {
                std::fs::set_permissions(sub, std::fs::Permissions::from_mode(0o555)).unwrap();
                if std::fs::write(sub.join(".write-probe"), b"").is_ok() {
                    let _ = std::fs::remove_file(sub.join(".write-probe"));
                    eprintln!(
                        "skipped the read-only arm: {} is writable at mode 0o555 (running as \
                         root?)",
                        sub.display()
                    );
                    return false;
                }
                true
            });
            if let Some(stderr) = stderr {
                assert!(
                    stderr.contains(&format!("warning: could not remove {shown}: ")),
                    "{fixture}: the output is named below the out-dir as typed; stderr: {stderr}"
                );
                assert!(
                    cwd.join(&shown).is_file(),
                    "{fixture}: the output is still there"
                );
                assert_eq!(leak(&stderr, root), None, "{fixture}: stderr: {stderr}");
            }
        }
    }
}

/// Say that `test` was skipped, and why, where a passing run cannot hide it: a `SKIPPED`
/// line on stderr and, under GitHub Actions, a warning in the job summary, as the lint
/// goldens do. The summary write is best effort.
fn announce_skip(test: &str, reason: &str) {
    eprintln!("SKIPPED {test}: {reason}");
    if let Some(path) = std::env::var_os("GITHUB_STEP_SUMMARY") {
        if let Ok(mut summary) = std::fs::OpenOptions::new()
            .append(true)
            .create(true)
            .open(path)
        {
            let _ = writeln!(summary, ":warning: path labels: skipped {test}: {reason}");
        }
    }
}

/// An entry typed in another case than its name on a case-insensitive volume: `mds watch`
/// derives its output's file name from the name the volume holds — the file it resolves
/// the entry to — and writes and names the output by it, beside the entry as typed or
/// below `--out-dir` as typed; `mds build` keeps the case as typed.
///
/// Runs on every platform, but means something only where the volume folds case: NTFS —
/// the Windows CI job runs it — and a default macOS volume. Where the volume tells case
/// apart (Linux, a case-sensitive macOS volume) it is skipped, and says so where a passing
/// run cannot hide it ([`announce_skip`]).
#[test]
fn an_entry_typed_in_another_case_names_its_output_by_the_name_on_disk() {
    let dir = scratch();
    let root = dir.path();
    put(root, "b/page.mds", "Page\n");
    if !root.join(native("b/PAGE.mds")).exists() {
        announce_skip(
            "an_entry_typed_in_another_case_names_its_output_by_the_name_on_disk",
            "the volume of the temporary directory tells case apart",
        );
        return;
    }

    let build = run(&root.join("b"), &["build", "PAGE.mds"]);
    let built = String::from_utf8_lossy(&build.stderr);
    let control = format!("Compiled to {}", native("./PAGE.md"));
    assert!(
        built.lines().any(|line| line == control),
        "control: mds build names the output by the case typed, {control:?}; stderr: {built}"
    );

    // (the session's directory, its arguments, the output as named, where it is written)
    for (cwd, args, output, written) in [
        ("w", &["watch", "PAGE.mds"][..], "./page.md", "w"),
        (
            "o",
            &["watch", "PAGE.mds", "--out-dir", "out"],
            "out/page.md",
            "o/out",
        ),
    ] {
        let output = native(output);
        put(root, &format!("{cwd}/page.mds"), "Page\n");
        let (mut child, tap, _) = watch_live(&root.join(cwd), args, false);
        write_atomic(&root.join(cwd).join("page.mds"), "Edited\n");
        common::wait_for_tap(&tap, "Recompiled ", WATCH_STEP);
        let stderr = tap.finish_text(&mut child);

        assert_eq!(
            stderr.lines().next(),
            Some("Watching PAGE.mds"),
            "{args:?}: stderr: {stderr}"
        );
        assert_eq!(
            lines_starting(&stderr, "Compiled to "),
            [format!("Compiled to {output}")],
            "{args:?}: stderr: {stderr}"
        );
        let recompiled = lines_starting(&stderr, "Recompiled ");
        assert!(
            !recompiled.is_empty()
                && recompiled
                    .iter()
                    .all(|line| line.starts_with(&format!("Recompiled {output} ("))),
            "{args:?}: every rebuild names the output by the name on disk; stderr: {stderr}"
        );
        let names: Vec<String> = std::fs::read_dir(root.join(native(written)))
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .filter(|name| name.ends_with(".md"))
            .collect();
        assert_eq!(names, ["page.md"], "{args:?}: written under that name");
        assert_eq!(leak(&stderr, root), None, "{args:?}: stderr: {stderr}");
    }
}

/// `failed to watch vars directory` names the directory as the `--vars` file was typed:
/// a directory that does not exist, and — for a bare file name — the working directory,
/// which the session asks the watcher for as the empty path. The cause after it is the
/// watcher's, without the path notify lists, so no line of the run names the scratch
/// directory. Neither file exists, so each session then ends at startup, refusing the
/// `--vars` file.
///
/// The bare name runs on macOS only: its watcher refuses the empty path, while the Linux
/// and Windows watchers resolve it against the working directory, which exists, and watch
/// that, so nothing is printed there.
#[test]
fn a_vars_directory_that_cannot_be_watched_is_named_as_typed() {
    let dir = scratch();
    let root = dir.path();
    put(root, "d/a.mds", "A\n");

    // (the `--vars` argument, the directory the warning names)
    let mut cases = vec![("nodir/v.json", "nodir")];
    if cfg!(target_os = "macos") {
        cases.push(("v.json", "."));
    }
    for (vars, shown) in cases {
        let args = typed_args(&["watch", "d", "--vars", vars]);
        let label = format!("mds {}", args.join(" "));
        let (child, tap, _) = common::spawn_watch_unsynchronized(
            mds_bin()
                .current_dir(root)
                .args(&args)
                .stdout(Stdio::null()),
        );
        let mut child = common::ChildGuard(child);
        // Bounded: the session ends at startup on its own.
        let deadline = Instant::now() + WATCH_STEP;
        let status = loop {
            if let Some(status) = child.0.try_wait().expect("wait for mds watch") {
                break status;
            }
            assert!(
                Instant::now() < deadline,
                "{label}: the session did not end within {WATCH_STEP:?}"
            );
            std::thread::sleep(Duration::from_millis(10));
        };
        let stderr = tap.finish_text(&mut child);

        assert!(
            !status.success(),
            "{label}: a missing --vars file ends the session at startup; stderr: {stderr}"
        );
        let warning = format!(
            "warning: failed to watch vars directory {}: {WATCHER_REFUSAL}\n",
            native(shown)
        );
        assert!(
            stderr.contains(&warning),
            "{label}: the directory is named as the --vars file was typed, and the watcher's \
             cause names no path; stderr: {stderr}"
        );
        assert_eq!(leak(&stderr, root), None, "{label}: stderr: {stderr}");
    }
}

/// The cause the file watcher gives for a directory that does not exist, once `mds`
/// drops the paths notify lists after it (#390). Windows' watcher words its own refusal;
/// FSEvents and inotify report notify's "path not found".
const WATCHER_REFUSAL: &str = if cfg!(windows) {
    "Input watch path is neither a file nor a directory."
} else {
    "No path was found."
};

// ── The text of an error writing an output ───────────────────────────────────

/// `path`'s refusal as a symlink at an output's path.
fn refused(path: &str) -> String {
    format!("cannot write {path}: refusing to replace a symlink")
}

/// Plant a symlink at `root/rel` (`rel` written with `/`) to a regular file, creating
/// `rel`'s directories: `false` where this platform lets no test make one
/// (`common::make_symlink`).
#[must_use]
fn plant_symlink(root: &Path, rel: &str) -> bool {
    let target = root.join("target.md");
    if !target.exists() {
        put(root, "target.md", "T\n");
    }
    let at = root.join(native(rel));
    std::fs::create_dir_all(at.parent().expect("a path below the root")).unwrap();
    common::make_symlink(&target, &at)
}

/// The text of an error writing an output names it as its `Compiled to` line does, and
/// the cause after it names no path (#390): below a directory argument's `--out-dir` and
/// below `mds.json` `build.output_dir`, where the write goes to the directory's canonical
/// path, as well as under `-o`, below a file argument's `--out-dir` and beside the source
/// — in `cannot write …`, whichever step of the write failed (#160), and in the warning
/// that keeps a stale output of the other kind, `kept stale output …`; the cause is the
/// operating system's, which names no file, the temporary one included. Each line's
/// presence is the control for the absence of the scratch directory from the run's
/// output.
///
/// Unix-only: it plants symlinks and makes a directory read-only; the read-only arm is
/// skipped with a reason where the mode does not stop a write (running as root).
#[cfg(unix)]
#[test]
fn an_error_writing_an_output_names_it_as_its_status_line_does() {
    use std::os::unix::fs::PermissionsExt as _;

    let dir = scratch();
    let root = dir.path();
    put(root, "src/a.mds", "A\n");
    assert!(plant_symlink(root, "out/a.md"));
    put(root, "proj/mds.json", r#"{"build":{"output_dir":"dist"}}"#);
    put(root, "proj/p.mds", "P\n");
    put(root, "proj/src/q.mds", "Q\n");
    assert!(plant_symlink(root, "proj/dist/p.md"));
    assert!(plant_symlink(root, "proj/dist/q.md"));
    put(root, "nts/n.mds", "N\n");
    assert!(plant_symlink(root, "nts/n.md"));
    assert!(plant_symlink(root, "o4/a.md"));
    assert!(plant_symlink(root, "o5/y.md"));

    // (working directory, arguments, the output as its status line names it)
    for (cwd, args, shown) in [
        (".", &["build", "src", "--out-dir", "out"][..], "out/a.md"),
        ("proj", &["build", "p.mds"][..], "./dist/p.md"),
        ("proj", &["build", "src"][..], "src/../dist/q.md"),
        (".", &["build", "src/a.mds", "-o", "o5/y.md"][..], "o5/y.md"),
        (
            ".",
            &["build", "src/a.mds", "--out-dir", "o4"][..],
            "o4/a.md",
        ),
        (".", &["build", "nts/n.mds"][..], "nts/n.md"),
        (".", &["build", "nts"][..], "nts/n.md"),
    ] {
        let out = run(&root.join(cwd), args);
        let stderr = text(&out.stderr);
        assert_eq!(out.status.code(), Some(2), "{args:?}: stderr: {stderr}");
        assert!(
            squash(&stderr).contains(&squash(&refused(shown))),
            "{args:?}: the error names the output as {shown:?}; stderr: {stderr}"
        );
        assert_eq!(leak(&stderr, root), None, "{args:?}: stderr: {stderr}");
    }

    // A stale `x.md` that is a directory beside the `x.json` a messages template writes
    // now, below `--out-dir` and below `build.output_dir`: kept, with a warning that names
    // it as the status line names the output (#160).
    put(root, "msrc/x.mds", "@message user:\nHi\n@end\n");
    put(root, "stale/x.md/keep", "keep\n");
    put(root, "proj/msrc/x.mds", "@message user:\nHi\n@end\n");
    put(root, "proj/dist/x.md/keep", "keep\n");
    // (working directory, arguments, the output as its status line names it)
    for (cwd, args, shown) in [
        (".", &["build", "msrc", "--out-dir", "stale"][..], "stale/x"),
        ("proj", &["build", "msrc"][..], "msrc/../dist/x"),
    ] {
        let out = run(&root.join(cwd), args);
        let stderr = text(&out.stderr);
        assert_eq!(out.status.code(), Some(0), "{args:?}: stderr: {stderr}");
        assert!(
            stderr.contains(&format!("Compiled to {shown}.json\n")),
            "{args:?}: the status line names the output as typed; stderr: {stderr}"
        );
        let warning =
            format!("warning: kept stale output {shown}.md: mds never removes a Markdown file\n");
        assert!(
            stderr.contains(&warning),
            "{args:?}: the warning names the stale output as typed, {warning:?}; stderr: {stderr}"
        );
        assert_eq!(leak(&stderr, root), None, "{args:?}: stderr: {stderr}");
    }

    // A temporary file in a read-only directory: the write's own file is never named.
    std::fs::create_dir(root.join("ro")).unwrap();
    std::fs::set_permissions(root.join("ro"), std::fs::Permissions::from_mode(0o555)).unwrap();
    let _writable = Writable(root.join("ro"));
    if std::fs::write(root.join("ro/.write-probe"), b"").is_ok() {
        let _ = std::fs::remove_file(root.join("ro/.write-probe"));
        eprintln!("skipped the read-only arm: ro is writable at mode 0o555 (running as root?)");
        return;
    }
    let out = run(root, &["build", "src/a.mds", "-o", "ro/y.md"]);
    let stderr = text(&out.stderr);
    assert_eq!(out.status.code(), Some(2), "stderr: {stderr}");
    let error = format!(
        "cannot write ro/y.md: {}",
        std::io::Error::from_raw_os_error(libc::EACCES)
    );
    assert!(
        squash(&stderr).contains(&squash(&error)),
        "{error:?}; stderr: {stderr}"
    );
    assert!(
        !stderr.contains(".mds-tmp-") && !stderr.contains("at path"),
        "no temporary file is named; stderr: {stderr}"
    );
    assert_eq!(leak(&stderr, root), None, "stderr: {stderr}");
}

/// `mds watch` names an output in the text of an error writing it as its `Compiled to`
/// line does (#390): beside the entry and beside a directory argument's source, where the
/// write goes to the canonical path, as well as under `-o` and below file mode's
/// `--out-dir`, whether a directory or a symlink stands at the output's path; and below a
/// directory argument's `--out-dir` in the warning that a stale output of the other kind
/// could not be removed, as the `Recompiled` line beside it does. Each error's presence is
/// the control for the absence of the scratch directory.
///
/// Runs on every platform; the symlink arm waits on `common::make_symlink`. The cause after
/// a directory's path is the operating system's, which words it its own way, so the line is
/// pinned up to it, and the cause is checked to name no temporary file.
#[test]
fn watch_names_an_output_as_its_status_line_does_in_an_error_writing_it() {
    let dir = scratch();
    let root = dir.path();
    // (the source, the arguments, the output the startup write refuses, as its status line
    // names it — and as it is planted)
    let cases: [(&str, &[&str], &str); 4] = [
        ("d1/a.mds", &["watch", "d1"], "d1/a.md"),
        ("w1/page.mds", &["watch", "w1/page.mds"], "w1/page.md"),
        (
            "w2/page.mds",
            &["watch", "w2/page.mds", "-o", "o2/y.md"],
            "o2/y.md",
        ),
        (
            "w3/page.mds",
            &["watch", "w3/page.mds", "--out-dir", "o3"],
            "o3/page.md",
        ),
    ];
    for link in [false, true] {
        let cwd = root.join(if link { "link" } else { "directory" });
        let mut planted = true;
        for (source, _, output) in cases {
            put(&cwd, source, "Page\n");
            if link {
                planted = planted && plant_symlink(&cwd, output);
            } else {
                put(&cwd, &format!("{output}/keep"), "keep\n");
            }
        }
        if !planted {
            // Only where this platform lets no test make a link (`common::make_symlink`).
            continue;
        }

        for (_, args, output) in cases {
            let args = typed_args(args);
            let label = format!("(link: {link}) mds {}", args.join(" "));
            let shown = native(output);
            let (child, tap, _) = common::spawn_watch_unsynchronized(
                mds_bin()
                    .current_dir(&cwd)
                    .args(&args)
                    .args(["--debounce", "0"])
                    .stdout(Stdio::null()),
            );
            let mut child = common::ChildGuard(child);
            let error = if link {
                refused(&shown)
            } else {
                format!("cannot write {shown}: ")
            };
            // An error frame may wrap the line between any two words.
            let printed = common::poll_tap_until(&tap, WATCH_STEP, |text| {
                squash(text).contains(&squash(&error))
            });
            let stderr = tap.finish_text(&mut child);
            assert!(printed.is_ok(), "{label}: {error:?}; stderr: {stderr}");
            assert!(
                !stderr.contains(".mds-tmp-"),
                "{label}: no temporary file is named; stderr: {stderr}"
            );
            assert_eq!(leak(&stderr, root), None, "{label}: stderr: {stderr}");
            if !link {
                assert!(
                    cwd.join(&shown).join("keep").is_file(),
                    "{label}: the directory is left as it was"
                );
            }
        }
    }

    // The stale output this session wrote, replaced by a directory no file removal
    // removes, when its source turns into a messages template.
    put(root, "d5/a.mds", "A\n");
    let (mut child, tap, _) = watch_live(root, &["watch", "d5", "--out-dir", "o5"], false);
    std::fs::remove_file(root.join(native("o5/a.md"))).expect("remove the startup output");
    put(root, "o5/a.md/keep", "keep\n");
    write_atomic(&root.join(native("d5/a.mds")), "@message user:\nHi\n@end\n");
    common::wait_for_tap(&tap, "stale", WATCH_STEP);
    let stderr = tap.finish_text(&mut child);
    let warning = format!(
        "warning: could not remove stale output {}: ",
        native("o5/a.md")
    );
    assert!(
        squash(&stderr).contains(&squash(&warning)),
        "{warning:?}; stderr: {stderr}"
    );
    let recompiled = format!("Recompiled {} (", native("o5/a.json"));
    assert!(
        stderr.contains(&recompiled),
        "the rebuild names the output as typed, {recompiled:?}; stderr: {stderr}"
    );
    assert_eq!(leak(&stderr, root), None, "stderr: {stderr}");
}

// ── Windows ──────────────────────────────────────────────────────────────────

/// Windows: a directory build under an out-dir that already exists — the case in which
/// canonicalizing it yields a verbatim `\\?\` path — names the output and its map below
/// the out-dir as typed, with no verbatim prefix anywhere.
#[cfg(windows)]
#[test]
fn compiled_to_and_map_lines_under_an_existing_out_dir_carry_no_verbatim_prefix() {
    let dir = scratch();
    put(dir.path(), "src/sub/page.mds", "Page\n");
    std::fs::create_dir(dir.path().join("out")).unwrap();
    // Control: canonicalizing the out-dir IS verbatim on this host, so the absence
    // assertions below can fail.
    assert!(
        dir.path()
            .join("out")
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .starts_with(r"\\?\"),
        "test assumption: canonicalize must yield a verbatim path on Windows"
    );

    let out = run(
        dir.path(),
        &["build", "src", "--out-dir", "out", "--source-map"],
    );
    let (stdout, stderr) = (text(&out.stdout), text(&out.stderr));
    assert_eq!(out.status.code(), Some(0), "stderr: {stderr}");
    assert_eq!(
        stderr,
        format!(
            "Compiled to {}\nSource map written to {}\n1 built, 0 failed\n",
            native("out/sub/page.md"),
            native("out/sub/page.md.map")
        ),
    );
    assert!(!stdout.contains(r"\\?\"), "stdout: {stdout}");
    assert!(!stderr.contains(r"\\?\"), "stderr: {stderr}");
    assert_eq!(leak(&stderr, dir.path()), None, "stderr: {stderr}");
}

/// Windows: `mds watch` matches events against canonical — verbatim `\\?\` — paths, yet
/// its banner and a rebuild's `Recompiled` line name the argument, and the output below
/// it, as typed, with no verbatim prefix, in directory mode under an out-dir that already
/// exists and in file mode.
#[cfg(windows)]
#[test]
fn watch_banner_and_recompiled_lines_carry_no_verbatim_prefix() {
    let dir = scratch();
    put(dir.path(), "src/sub/page.mds", "Page\n");
    std::fs::create_dir(dir.path().join("out")).unwrap();
    // Control: canonicalizing IS verbatim on this host, so the absence assertions below
    // can fail.
    assert!(
        dir.path()
            .join("src")
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .starts_with(r"\\?\"),
        "test assumption: canonicalize must yield a verbatim path on Windows"
    );

    // (arguments, the banner, the output's name)
    let cases: [(&[&str], &str, &str); 2] = [
        (
            &["watch", "src", "--out-dir", "out"],
            "Watching directory src",
            "out/sub/page.md",
        ),
        (
            &["watch", "src/sub/page.mds"],
            "Watching src/sub/page.mds",
            "src/sub/page.md",
        ),
    ];
    for (args, banner, output) in cases {
        // `mds watch` prints `Recompiled` only when an output's content changes, and the
        // previous session left `Edited\n`.
        put(dir.path(), "src/sub/page.mds", "Page\n");
        let args = typed_args(args);
        let (mut child, tap, _) = watch_live(dir.path(), &args, false);
        write_atomic(&dir.path().join(native("src/sub/page.mds")), "Edited\n");
        common::wait_for_tap(&tap, "Recompiled ", WATCH_STEP);
        let stderr = tap.finish_text(&mut child);

        assert_eq!(
            stderr.lines().next(),
            Some(native(banner).as_str()),
            "{args:?}: stderr: {stderr}"
        );
        let prefix = format!("Recompiled {} (", native(output));
        let recompiled = lines_starting(&stderr, "Recompiled ");
        assert!(
            !recompiled.is_empty() && recompiled.iter().all(|line| line.starts_with(&prefix)),
            "{args:?}: every rebuild names the output as {prefix:?}; stderr: {stderr}"
        );
        assert!(!stderr.contains(r"\\?\"), "{args:?}: stderr: {stderr}");
        assert_eq!(
            leak(&stderr, dir.path()),
            None,
            "{args:?}: stderr: {stderr}"
        );
    }
}

// ── spec.md §7.10: the table of these lines ──────────────────────────────────

/// The heading of the section of spec.md that holds the path-label table.
const LABEL_SECTION: &str = "### 7.10 Path labels";

/// The table's header row, cell by cell.
const LABEL_COLUMNS: [&str; 4] = ["Command", "Line", "Form", "Pinned by"];

/// The sweep the table cites for many rows.
const SWEEP: &str = "no_listed_build_check_or_lint_run_names_the_working_directory";

/// The tests each row of spec.md §7.10's table cites, row by row, in the table's order.
/// The table and this list change together: a row added, removed or moved, or a test
/// cited or no longer cited, fails [`the_spec_s_path_label_table_cites_exactly_these_tests`]
/// until the other follows.
const LABEL_TABLE: &[&[&str]] = &[
    &["auto_detection_names_the_file_as_found_in_the_working_directory"],
    &[SWEEP],
    &[SWEEP],
    &[SWEEP],
    &[SWEEP],
    &[
        "compiled_to_under_a_relative_out_dir_names_the_out_dir_as_typed",
        "compiled_to_under_a_symlinked_out_dir_names_the_link_not_its_target",
        "dir_build_out_dir_status_line_names_the_out_dir_as_typed",
    ],
    &["a_config_output_dir_is_named_through_the_directory_mds_json_was_reached_by"],
    &[
        "source_map_lines_under_an_out_dir_name_the_out_dir_as_typed",
        "a_config_output_dir_names_the_map_written_and_the_stale_map_removed",
        SWEEP,
    ],
    &["a_config_output_dir_names_the_map_written_and_the_stale_map_removed"],
    &["an_output_directory_that_cannot_be_created_is_named_as_its_output_is"],
    &["the_config_source_map_warning_names_mds_json_as_reached"],
    &["r3_error_frame_names_root_relative_path_for_subdir_file"],
    &["an_error_writing_an_output_names_it_as_its_status_line_does"],
    &[SWEEP],
    &["fmt_names_a_file_argument_as_typed_and_a_directory_s_entries_below_it"],
    &["fmt_names_a_file_argument_as_typed_and_a_directory_s_entries_below_it"],
    &["clean_names_a_file_argument_as_typed", SWEEP],
    &[
        "lint_names_a_file_argument_as_typed_and_its_findings_by_its_file_name",
        "a_partial_fix_of_a_file_is_announced_after_the_findings_it_leaves",
        SWEEP,
    ],
    &["lint_names_a_file_argument_as_typed_and_its_findings_by_its_file_name"],
    &[
        "lint_names_a_file_argument_as_typed_and_its_findings_by_its_file_name",
        SWEEP,
    ],
    &["unknown_rule_warning_names_the_mds_json_as_the_input_reached_it"],
    &[
        "watching_names_the_entry_and_the_directory_as_typed",
        "watching_names_a_path_reached_through_a_symlink_by_the_link",
    ],
    &[
        "watching_names_the_entry_and_the_directory_as_typed",
        "watching_names_a_path_reached_through_a_symlink_by_the_link",
        "watch_dot_forms_watch_the_canonical_directory",
    ],
    &[
        "watch_startup_names_an_out_dir_and_a_config_output_dir_as_build_does",
        "recompiled_and_removed_name_each_output_as_typed",
    ],
    &[
        "recompiled_and_removed_name_each_output_as_typed",
        "watching_names_a_path_reached_through_a_symlink_by_the_link",
    ],
    &["an_emptied_output_is_named_as_its_recompiled_line_names_it"],
    &[
        "recompiled_and_removed_name_each_output_as_typed",
        "removed_names_the_output_as_typed_when_the_vars_file_changes_in_the_same_batch",
    ],
    &["an_output_that_cannot_be_removed_is_named_as_typed"],
    &[
        "watch_keeps_the_hand_written_siblings_of_a_deleted_source",
        "watch_keeps_an_output_edited_since_the_session_wrote_it",
        "watch_removes_the_old_output_of_a_changed_kind_only_when_it_wrote_it",
        "watch_writes_a_file_whose_kind_changed_to_that_kinds_output",
        "watch_never_writes_over_a_file_it_did_not_write_when_the_kind_changes",
        "watch_never_writes_over_a_file_that_appears_while_a_change_of_kind_is_written",
        "watch_never_removes_the_output_of_a_source_that_is_still_there",
        "watch_never_replaces_the_output_of_another_source_when_the_kind_changes",
        "watch_names_a_file_it_wrote_then_the_user_changed_as_changed",
        "watch_replaces_its_own_file_once_the_user_restores_it_when_the_kind_changes",
        "watch_tells_an_old_kind_output_in_a_remade_out_dir_is_kept",
    ],
    &["an_entry_typed_in_another_case_names_its_output_by_the_name_on_disk"],
    &["a_watched_directory_is_named_as_the_user_typed_it"],
    &[
        "a_vars_directory_that_cannot_be_watched_is_named_as_typed",
        "a_watched_directory_is_named_as_the_user_typed_it",
    ],
    &["a_watched_directory_is_named_as_the_user_typed_it"],
    &["watch_names_an_output_as_its_status_line_does_in_an_error_writing_it"],
    &["init_names_the_file_it_creates_as_typed"],
    &[
        "a_relative_output_location_is_refused_where_the_working_directory_is_gone",
        "watch_with_a_relative_out_dir_stops_at_startup_where_the_working_directory_is_gone",
    ],
    &["auto_detection_in_a_working_directory_it_cannot_list_names_it_as_a_dot"],
    &[
        "compiled_to_and_map_lines_under_an_existing_out_dir_carry_no_verbatim_prefix",
        "dir_build_out_dir_status_line_has_no_verbatim_prefix_on_windows",
    ],
    &["watch_banner_and_recompiled_lines_carry_no_verbatim_prefix"],
];

/// One body row of the table: the spec.md line it is on (from 1) and the tests it cites.
#[derive(Debug, PartialEq)]
struct LabelRow {
    line: usize,
    tests: Vec<String>,
}

/// The cells of a table line, `| a | b |` → `["a", "b"]`: split at each `|` not escaped
/// as `\|`, each cell trimmed.
fn table_cells(line: &str) -> Vec<String> {
    let inner = line.trim();
    let inner = inner.strip_prefix('|').unwrap_or(inner);
    let inner = inner.strip_suffix('|').unwrap_or(inner);
    let mut cells = Vec::new();
    let mut cell = String::new();
    let mut escaped = false;
    for c in inner.chars() {
        if c == '|' && !escaped {
            cells.push(cell.trim().to_owned());
            cell.clear();
        } else {
            cell.push(c);
        }
        escaped = c == '\\' && !escaped;
    }
    cells.push(cell.trim().to_owned());
    cells
}

/// Is `name` spelled as a test function is: lower-case ASCII letters, digits and `_`,
/// starting with a letter?
fn is_test_name(name: &str) -> bool {
    name.starts_with(|c: char| c.is_ascii_lowercase())
        && name
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

/// The tests a `Pinned by` cell cites: one or more test names, each in backticks,
/// separated by `, `. Anything else — an empty cell, a dash, a name without backticks,
/// prose — is refused, so no row can stand without a test.
fn cited_tests(cell: &str) -> Result<Vec<String>, String> {
    if cell.is_empty() {
        return Err("the Pinned by cell cites no test".to_owned());
    }
    cell.split(", ")
        .map(|item| {
            item.strip_prefix('`')
                .and_then(|rest| rest.strip_suffix('`'))
                .filter(|name| is_test_name(name))
                .map(str::to_owned)
                .ok_or_else(|| format!("{item:?} is not a test name in backticks"))
        })
        .collect()
}

/// Does `line` end the section [`LABEL_SECTION`] heads: a heading of its level or above,
/// or a horizontal rule? A deeper heading is part of the section.
fn ends_label_section(line: &str) -> bool {
    let level = |text: &str| text.bytes().take_while(|&b| b == b'#').count();
    let heading = level(line);
    line == "---"
        || ((1..=level(LABEL_SECTION)).contains(&heading)
            && matches!(line.as_bytes().get(heading), None | Some(b' ')))
}

/// The body rows of the table in `spec`'s §7.10. The section must appear once and hold
/// one table, headed by [`LABEL_COLUMNS`] and ended by a blank line, whose every row has
/// four cells, none of them empty, and cites at least one test. A line may end in CRLF.
fn label_table(spec: &str) -> Result<Vec<LabelRow>, String> {
    let lines: Vec<&str> = spec.lines().map(str::trim_end).collect();
    let starts: Vec<usize> = lines
        .iter()
        .enumerate()
        .filter(|(_, line)| **line == LABEL_SECTION)
        .map(|(at, _)| at)
        .collect();
    let [start] = starts.as_slice() else {
        return Err(format!(
            "expected one {LABEL_SECTION:?} heading, found {}",
            starts.len()
        ));
    };
    // Line numbers count from 1.
    let section: Vec<(usize, &str)> = lines[start + 1..]
        .iter()
        .enumerate()
        .map(|(at, line)| (start + 2 + at, *line))
        .take_while(|(_, line)| !ends_label_section(line))
        .collect();
    let table: Vec<(usize, &str)> = section
        .iter()
        .copied()
        .filter(|(_, line)| line.starts_with('|'))
        .collect();
    let (Some(&(first, header)), Some(&(last, _))) = (table.first(), table.last()) else {
        return Err("the section holds no table".to_owned());
    };
    if table.len() != last - first + 1 {
        return Err(format!(
            "the table lines {first}..={last} are not one table: other lines lie between them"
        ));
    }
    // Markdown reads any line that follows a table before a blank line as one more row,
    // with a leading `|` or without one, so such a line would be a row this check skips.
    if let Some(&(after, _)) = section
        .iter()
        .find(|&&(line, text)| line == last + 1 && !text.is_empty())
    {
        return Err(format!("line {after}: the table must end at a blank line"));
    }
    if table_cells(header) != LABEL_COLUMNS {
        return Err(format!(
            "line {first}: the header is {:?}, not {LABEL_COLUMNS:?}",
            table_cells(header)
        ));
    }
    let is_rule = |cell: &String| {
        let dashes = cell.trim_start_matches(':').trim_end_matches(':');
        dashes.len() >= 3 && dashes.chars().all(|c| c == '-')
    };
    match table.get(1) {
        Some(&(_, separator))
            if table_cells(separator).len() == LABEL_COLUMNS.len()
                && table_cells(separator).iter().all(is_rule) => {}
        _ => return Err(format!("line {}: no separator row", first + 1)),
    }
    let rows = table[2..]
        .iter()
        .map(|&(line, text)| {
            let cells = table_cells(text);
            if cells.len() != LABEL_COLUMNS.len() {
                return Err(format!(
                    "line {line}: {} cells, not {}",
                    cells.len(),
                    LABEL_COLUMNS.len()
                ));
            }
            if let Some(empty) = cells[..3].iter().position(String::is_empty) {
                return Err(format!(
                    "line {line}: the {} cell is empty",
                    LABEL_COLUMNS[empty]
                ));
            }
            let tests = cited_tests(&cells[3]).map_err(|e| format!("line {line}: {e}"))?;
            Ok(LabelRow { line, tests })
        })
        .collect::<Result<Vec<_>, String>>()?;
    if rows.is_empty() {
        return Err(format!("line {first}: the table has no rows"));
    }
    Ok(rows)
}

/// Every `.rs` file directly under `crates/mds-cli/tests/` and `crates/mds-cli/src/`,
/// with its text.
fn cli_rust_sources() -> Vec<(PathBuf, String)> {
    let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let mut sources = Vec::new();
    for sub in ["tests", "src"] {
        for entry in std::fs::read_dir(crate_dir.join(sub)).expect("list a source directory") {
            let path = entry.expect("read a directory entry").path();
            if path.extension().is_some_and(|ext| ext == "rs") {
                let text = std::fs::read_to_string(&path).expect("read a source file");
                sources.push((path, text));
            }
        }
    }
    sources.sort();
    sources
}

/// The files of `sources` that define a test named `name`: a line `fn <name>() {` with
/// `#[test]`, and no `#[ignore …]`, among the attribute and doc-comment lines right above
/// it. A file that defines it once per platform counts once.
fn test_definitions<'a>(name: &str, sources: &'a [(PathBuf, String)]) -> Vec<&'a Path> {
    let signature = format!("fn {name}() {{");
    sources
        .iter()
        .filter(|(_, text)| {
            let lines: Vec<&str> = text.lines().map(str::trim).collect();
            lines
                .iter()
                .enumerate()
                .filter(|(_, line)| **line == signature)
                .any(|(at, _)| {
                    let attributes: Vec<&str> = lines[..at]
                        .iter()
                        .rev()
                        .take_while(|line| line.starts_with("#[") || line.starts_with("///"))
                        .copied()
                        .collect();
                    attributes.contains(&"#[test]")
                        && !attributes.iter().any(|line| line.starts_with("#[ignore"))
                })
        })
        .map(|(path, _)| path.as_path())
        .collect()
}

/// spec.md §7.10's table and [`LABEL_TABLE`] cite the same tests, row by row, and each
/// test they cite is a `#[test]` function, not ignored, defined in exactly one of mds-cli's
/// test and source files — so a row added or removed, a test cited or dropped, and a cited
/// test renamed, deleted or ignored each fail here.
#[test]
fn the_spec_s_path_label_table_cites_exactly_these_tests() {
    let spec_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../spec.md");
    let spec = std::fs::read_to_string(&spec_path).expect("read spec.md");
    let rows = label_table(&spec).unwrap_or_else(|e| panic!("spec.md §7.10: {e}"));

    let cited: BTreeSet<&str> = rows
        .iter()
        .flat_map(|row| row.tests.iter().map(String::as_str))
        .collect();
    let listed: BTreeSet<&str> = LABEL_TABLE
        .iter()
        .flat_map(|row| row.iter().copied())
        .collect();
    let unlisted: Vec<&str> = cited.difference(&listed).copied().collect();
    let uncited: Vec<&str> = listed.difference(&cited).copied().collect();
    assert!(
        unlisted.is_empty() && uncited.is_empty(),
        "spec.md §7.10 cites tests LABEL_TABLE does not list: {unlisted:?}; \
         LABEL_TABLE lists tests spec.md §7.10 does not cite: {uncited:?}"
    );

    let table: Vec<Vec<&str>> = rows
        .iter()
        .map(|row| row.tests.iter().map(String::as_str).collect())
        .collect();
    let lines: Vec<usize> = rows.iter().map(|row| row.line).collect();
    assert_eq!(
        table, LABEL_TABLE,
        "spec.md §7.10's rows (lines {lines:?}) and LABEL_TABLE differ row by row"
    );

    let sources = cli_rust_sources();
    let undefined: Vec<String> = listed
        .iter()
        .filter_map(|name| {
            let defined = test_definitions(name, &sources);
            (defined.len() != 1).then(|| format!("{name}: defined in {defined:?}"))
        })
        .collect();
    assert!(
        undefined.is_empty(),
        "each test spec.md §7.10 cites must be a #[test] fn, not ignored, defined in exactly \
         one file of crates/mds-cli/tests/*.rs and crates/mds-cli/src/*.rs: {undefined:#?}"
    );
}

/// The table check refuses each way a row could stand without a test, reads a CRLF spec
/// as an LF one, and finds a test only where a `#[test]` function of that name is defined
/// and not ignored (positive controls).
#[test]
fn the_table_check_refuses_a_row_without_a_test_and_finds_only_defined_tests() {
    let spec = |rows: &str| {
        format!(
            "## 7. CLI\n\n{LABEL_SECTION}\n\nProse.\n\n| Command | Line | Form | Pinned by |\n\
             |---|---|---|---|\n{rows}\n\n---\n\n## 8. Next\n\n| a | b |\n|---|---|\n"
        )
    };
    let good = spec("| `mds x` | `X` | as typed | `a_test`, `b_test` |");
    assert_eq!(
        label_table(&good),
        Ok(vec![LabelRow {
            line: 9,
            tests: vec!["a_test".to_owned(), "b_test".to_owned()],
        }])
    );
    assert_eq!(
        label_table(&good.replace('\n', "\r\n")),
        label_table(&good),
        "a CRLF spec reads as the LF one"
    );
    assert!(
        label_table(&spec("| `mds x` | `a \\| b` | as typed | `a_test` |")).is_ok(),
        "an escaped pipe stays inside its cell"
    );
    for (rows, what) in [
        ("| `mds x` | `X` | as typed | — |", "a dash"),
        ("| `mds x` | `X` | as typed |  |", "an empty Pinned by cell"),
        ("| `mds x` | `X` | as typed | a_test |", "a name without backticks"),
        ("| `mds x` | `X` | as typed | `a_test` and prose |", "prose"),
        ("| `mds x` | `X` | as typed | `a_test`,`b_test` |", "another separator"),
        ("| `mds x` | `X` | as typed | `A_Test` |", "a name no test has"),
        ("| `mds x` | `X` | `a_test` |", "three cells"),
        ("| `mds x` |  | as typed | `a_test` |", "an empty Line cell"),
        (
            "| `mds x` | `X` | as typed | `a_test` |\n\nProse.\n\n| `mds y` | `Y` | as typed | `b_test` |",
            "a second table",
        ),
        (
            "| `mds x` | `X` | as typed | `a_test` |\n`mds y` | `Y` | as typed | — |",
            "a row without a leading pipe, which still continues the table",
        ),
        (
            "| `mds x` | `X` | as typed | `a_test` |\n  | `mds y` | `Y` | as typed | — |",
            "an indented row",
        ),
        (
            "| `mds x` | `X` | as typed | `a_test` |\n\n#### Sub\n\n\
             | Command | Line | Form | Pinned by |\n|---|---|---|---|\n\
             | `mds y` | `Y` | as typed | — |",
            "a second table below a subsection's heading",
        ),
    ] {
        assert!(
            label_table(&spec(rows)).is_err(),
            "{what} must be refused: {rows:?}"
        );
    }
    assert!(label_table("# spec\n").is_err(), "no section");
    assert!(
        label_table(&format!("{good}{good}")).is_err(),
        "the section twice"
    );
    assert!(
        label_table(&good.replace("| Pinned by |", "| Tests |")).is_err(),
        "another header"
    );
    assert!(label_table(&spec("")).is_err(), "a table with no rows");
    assert_eq!(
        label_table(&good.replace("---\n\n## 8. Next", "### 7.11 Next")),
        label_table(&good),
        "a heading of the section's own level ends it, before the next table"
    );

    let planted = vec![
        (
            PathBuf::from("a.rs"),
            "/// Doc.\n#[cfg(unix)]\n#[test]\nfn planted_test() {\n}\n\nfn planted_helper() {\n}\n"
                .to_owned(),
        ),
        (PathBuf::from("b.rs"), "#[test]\nfn twice() {\n}\n".to_owned()),
        (PathBuf::from("c.rs"), "#[test]\nfn twice() {\n}\n".to_owned()),
        (
            PathBuf::from("d.rs"),
            "#[cfg(unix)]\n#[test]\nfn per_platform() {\n}\n\n\
             #[cfg(windows)]\n#[test]\nfn per_platform() {\n}\n\n\
             #[ignore]\n#[test]\nfn ignored() {\n}\n\n\
             #[test]\n#[ignore = \"slow\"]\nfn ignored_too() {\n}\n\n\
             #[cfg_attr(not(unix), ignore = \"unix only\")]\n#[test]\nfn ignored_elsewhere() {\n}\n"
                .to_owned(),
        ),
    ];
    assert_eq!(
        test_definitions("planted_test", &planted),
        [Path::new("a.rs")]
    );
    assert!(
        test_definitions("planted_helper", &planted).is_empty(),
        "a function without #[test] is no test"
    );
    assert!(
        test_definitions("planted", &planted).is_empty(),
        "no prefix match"
    );
    assert_eq!(
        test_definitions("twice", &planted).len(),
        2,
        "a test defined twice is found twice, which the table check refuses"
    );
    assert_eq!(
        test_definitions("per_platform", &planted),
        [Path::new("d.rs")],
        "a test defined per platform in one file is found in that file"
    );
    for ignored in ["ignored", "ignored_too"] {
        assert!(
            test_definitions(ignored, &planted).is_empty(),
            "an ignored test runs nowhere, so it pins nothing: {ignored}"
        );
    }
    assert_eq!(
        test_definitions("ignored_elsewhere", &planted),
        [Path::new("d.rs")],
        "a test ignored only on other platforms runs here"
    );
    let sources = cli_rust_sources();
    let here = test_definitions("clean_names_a_file_argument_as_typed", &sources);
    assert!(
        here.len() == 1 && here[0].ends_with("path_labels.rs"),
        "a real test is found where it is defined: {here:?}"
    );
    assert!(
        test_definitions("scratch", &sources).is_empty(),
        "a real helper is no test"
    );
}