fig-sys 5.0.0

FFI bindings and native library for fig (the comment-preserving JSON/YAML/TOML/… config engine). Used by the `fig` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
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
//! Command-line parsing: turns the raw arg iterator into a `CliConfig`
//! (`parseConfig`), plus the small format/path/embed-archetype resolvers that
//! parsing (and later, the action handlers) share.
const std = @import("std");
const fig = @import("fig");
const build_options = @import("build_options");

const gron = @import("gron.zig");
const languages = @import("languages.zig");
const types = @import("types.zig");
const fileio = @import("fileio.zig");

const Format = types.Format;
const CliAction = types.CliAction;
const CliConfig = types.CliConfig;
const ArgError = types.ArgError;
const Detected = types.Detected;
const append_index = types.append_index;
const Io = std.Io;

/// Map a `--input`/`-i` format name to a `Format`. The enum member names cover
/// every accepted token (including `canonical` and `fig`) directly, plus the
/// one alias below. Returns null for an unknown name so callers can emit a
/// tailored error.
pub fn parseFormatName(name: []const u8) ?Format {
    // `yml` is an accepted SPELLING of yaml, not a format of its own: it used
    // to be a `Format` member, which bought a second `@tagName` echo and a
    // duplicated arm in every switch over the enum, and nothing else. It
    // collapses here instead, so downstream code only ever sees `.yaml`.
    if (std.mem.eql(u8, name, "yml")) return languages.standIn(.yaml);
    if (std.meta.stringToEnum(Format, name)) |f| return languages.standIn(f);
    // A language the CLI did not compile in: configured in `languages.figl`
    // (spawned and registered on this first ask) or already registered.
    return languages.resolveName(name);
}

/// Parse a command-line path — `a.b[2].c` — into segments. A `.` separates
/// keys and a `[n]` is an index; `[-]`/`[$]` is the end sentinel.
///
/// A key that holds a `.` or a `[` is written quoted or escaped:
///
///   * `a."b.c"` — double quotes, with JSON's escapes inside (`\"`, `\\`,
///     `\n`, `\u00e9`, …);
///   * `a.'b.c'` — single quotes, verbatim, as a TOML literal key;
///   * `a["b.c"]` / `a['b.c']` — the same quoting in brackets, which is how
///     `-o gron` prints such a key, so a gron line reads back;
///   * `a.b\.c` — a backslash in a bare key takes the next byte as it is.
///
/// Key bytes are allocated from `allocator` where quoting or escaping
/// changed them, and otherwise borrowed from `path`.
pub fn parsePath(allocator: std.mem.Allocator, path: []const u8) ![]fig.AST.PathSegment {
    const log = std.log.scoped(.parsePath);
    var path_in_progress: std.ArrayList(fig.AST.PathSegment) = .empty;
    var i: usize = 0;
    while (i < path.len) {
        switch (path[i]) {
            '.' => {
                // Dot is a separator. Else branch parses the key.
                i += 1;
            },
            '[' => {
                // A quoted key in brackets — gron's spelling of a key that
                // is not a bare identifier.
                if (i + 1 < path.len and (path[i + 1] == '"' or path[i + 1] == '\'')) {
                    i += 1;
                    const key = try quotedKey(allocator, path, &i);
                    if (i >= path.len or path[i] != ']') return ArgError.InvalidPath;
                    i += 1;
                    log.debug("key: {s}", .{key});
                    try path_in_progress.append(allocator, .{ .key = key });
                    continue;
                }
                // Skip open bracket
                const start = i + 1;
                i = start;
                // Loop until end or close bracket
                while (i < path.len and path[i] != ']') : (i += 1) {}
                if (i >= path.len or i == start) return error.InvalidPath;

                // `[-]` and `[$]` are the "end" tokens: `insert` reads the
                // sentinel as "append", and `delete` reads it as "the last
                // item" (`editor.removeSeqItem` special-cases it). Any other
                // caller that walks the path literally (e.g. `get`) just
                // sees an out-of-range index and surfaces NotFound.
                const inner = path[start..i];
                log.debug("number: {s}", .{inner});
                const seg: fig.AST.PathSegment = if (std.mem.eql(u8, inner, "-") or std.mem.eql(u8, inner, "$"))
                    .{ .index = append_index }
                else
                    .{ .index = try std.fmt.parseInt(usize, inner, 10) };
                try path_in_progress.append(allocator, seg);
                // Skip close bracket
                i += 1;
            },
            '"', '\'' => {
                const key = try quotedKey(allocator, path, &i);
                // A quoted key ends its segment.
                if (i < path.len and path[i] != '.' and path[i] != '[') return ArgError.InvalidPath;
                log.debug("key: {s}", .{key});
                try path_in_progress.append(allocator, .{ .key = key });
            },
            else => {
                const start = i;
                var escaped = false;
                // Loop until a dot or open bracket; a backslash carries the
                // byte after it past both.
                while (i < path.len and path[i] != '.' and path[i] != '[') : (i += 1) {
                    if (path[i] == '\\') {
                        if (i + 1 >= path.len) return ArgError.InvalidPath;
                        escaped = true;
                        i += 1;
                    }
                }
                if (i == start) return ArgError.InvalidPath;
                const key = if (!escaped) path[start..i] else blk: {
                    var out: std.ArrayList(u8) = .empty;
                    var j = start;
                    while (j < i) : (j += 1) {
                        if (path[j] == '\\') j += 1;
                        try out.append(allocator, path[j]);
                    }
                    break :blk try out.toOwnedSlice(allocator);
                };

                log.debug("key: {s}", .{key});
                try path_in_progress.append(allocator, .{ .key = key });
            },
        }
    }
    return path_in_progress.toOwnedSlice(allocator);
}

/// `parsePath` for a path on the command line: one that does not parse is a
/// usage error (exit 2) naming it, rather than an error name escaping `main`.
fn pathArg(allocator: std.mem.Allocator, path: []const u8) ArgError![]fig.AST.PathSegment {
    return parsePath(allocator, path) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        else => {
            std.log.scoped(.parseConfig).err("`{s}` is not a path: keys are separated by `.`, an index is `[n]` (or `[-]` for the end), and a key holding `.` or `[` is quoted: a.\"b.c\"\n", .{path});
            return ArgError.InvalidPath;
        },
    };
}

/// The key quoted at `path[i.*]` — `'…'` verbatim, `"…"` with JSON's
/// escapes decoded — leaving `i.*` just past the closing quote.
fn quotedKey(allocator: std.mem.Allocator, path: []const u8, i: *usize) ![]const u8 {
    const quote = path[i.*];
    const start = i.* + 1;
    var j = start;
    if (quote == '\'') {
        while (j < path.len and path[j] != '\'') : (j += 1) {}
        if (j >= path.len) return ArgError.InvalidPath;
        i.* = j + 1;
        return path[start..j];
    }
    var out: std.ArrayList(u8) = .empty;
    while (true) : (j += 1) {
        if (j >= path.len) return ArgError.InvalidPath;
        const c = path[j];
        if (c == '"') break;
        if (c != '\\') {
            try out.append(allocator, c);
            continue;
        }
        j += 1;
        if (j >= path.len) return ArgError.InvalidPath;
        switch (path[j]) {
            '"', '\\', '/' => |e| try out.append(allocator, e),
            'b' => try out.append(allocator, 0x08),
            'f' => try out.append(allocator, 0x0c),
            'n' => try out.append(allocator, '\n'),
            'r' => try out.append(allocator, '\r'),
            't' => try out.append(allocator, '\t'),
            'u' => {
                var cp: u21 = try hex4(path, j + 1);
                j += 4;
                // A high surrogate takes the `\uXXXX` low half after it.
                if (cp >= 0xD800 and cp <= 0xDBFF) {
                    if (j + 2 >= path.len or path[j + 1] != '\\' or path[j + 2] != 'u') return ArgError.InvalidPath;
                    const lo = try hex4(path, j + 3);
                    if (lo < 0xDC00 or lo > 0xDFFF) return ArgError.InvalidPath;
                    cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
                    j += 6;
                } else if (cp >= 0xDC00 and cp <= 0xDFFF) return ArgError.InvalidPath;
                var buf: [4]u8 = undefined;
                const n = std.unicode.utf8Encode(cp, &buf) catch return ArgError.InvalidPath;
                try out.appendSlice(allocator, buf[0..n]);
            },
            else => return ArgError.InvalidPath,
        }
    }
    i.* = j + 1;
    return out.toOwnedSlice(allocator);
}

fn hex4(path: []const u8, at: usize) !u21 {
    if (at + 4 > path.len) return ArgError.InvalidPath;
    return std.fmt.parseInt(u21, path[at .. at + 4], 16) catch ArgError.InvalidPath;
}

/// Infer the parse strategy from a file's extension, or null when the extension
/// is missing/unrecognized — the caller then falls back to content sniffing
/// (`Language.detect`) rather than failing outright.
pub fn detectLanguageFromFileEnding(file_path: []const u8) ?Detected {
    // `--lang <name>` names the language outright, whatever the extension
    // says — it is how a file a compiled format owns by extension is read
    // through a runtime language instead (`secrets.env --lang lua-dotenv`).
    if (languages.langOverride()) |f| return .{ .format = f };

    const dot = std.mem.findLast(u8, file_path, ".");
    const ext = file_path[(dot orelse 0) + 1 .. file_path.len];

    // Markdown conventionally carries an embedded region (frontmatter, or
    // endmatter), but which archetype it is still has to be sniffed from the
    // actual bytes — a `` ```fig ``` ``-fenced or JSON frontmatter block (or a
    // YAML endmatter fence) must not be mistaken for `---` YAML frontmatter
    // just because the file ends in `.md`.
    if (std.mem.eql(u8, ext, "md") or std.mem.eql(u8, ext, "markdown")) {
        return .{ .format = .yaml, .embed_detect = true };
    }

    // An extension that names a `Format` member IS that format. Tried first so
    // every token the enum spells keeps its exact meaning — notably the
    // dialect members (`jsonc`, `json5`) that share a language with the
    // default spelling, and the format-only members (`canonical`, `gron`) that
    // no `Language` declares. `yml` is NOT one of them any more: it falls
    // through to `extensionFormat` below, where `Language.YAML.extensions`
    // owns it and resolves it to `.yaml` — the same parse it always got.
    // The one exception is `fig`: its extension is `.figl`, and `.fig`,
    // accepted until 5.0, is no longer the format's.
    // A format this build compiled out is the configured language standing
    // in for it, where there is one (`languages.standIn`).
    if (std.meta.stringToEnum(Format, ext)) |format| if (format != .fig) return .{ .format = languages.standIn(format) };

    // Otherwise ask the languages. Each declares the extensions it owns
    // (`Language.extensions`), which is where the ones that DON'T match an enum
    // member name live: `.figl` (fig's extension), `.env` (dotenv files
    // are conventionally named exactly `.env`, so the last-dot split gives a
    // literal `env`), and `.nt` (NestedText's conventional extension). Those
    // three used to be hand-written special cases here; they are now the
    // formats' own declarations, so a new format's extension arrives with it.
    //
    // Not recognized here, before or now: multi-suffix variants like
    // `.env.production`, whose last-dot extension is `production`. Pass
    // `--input dotenv` for those. The canonical form deliberately owns no
    // extension at all — select it with `--input canonical`.
    if (extensionFormat(ext)) |format| return .{ .format = format };

    // Last, the languages `languages.figl` configures: a compiled format's
    // extension always wins, so a configured language is only reached by an
    // extension nothing compiled in owns (proposal §7.1).
    if (languages.resolveExtension(ext)) |format| return .{ .format = format };

    return null;
}

/// The `Format` owning file extension `ext`, per the languages' own
/// `extensions` declarations, or null.
///
/// The `Language`→`Format` pairing this walks is per-LANGUAGE while `Format` is
/// per-DIALECT (json/jsonc/json5 are three members over one `Language`), so
/// a language resolves to whichever member is its DEFAULT spelling. That used
/// to be a hand-written table; it is now derived from the format registry —
/// see `ext_pairs`.
fn extensionFormat(ext: []const u8) ?Format {
    inline for (ext_pairs) |pair| {
        if (pair[0] != void) {
            for (pair[0].extensions) |owned| {
                if (std.mem.eql(u8, owned, ext)) return pair[1];
            }
        }
    }
    return null;
}

/// Each `Language` and the `Format` member that is its default spelling,
/// derived from the format registry: a language's default spelling IS its
/// FIRST entry in `dialects` — `json`, ahead of the `jsonc`/`json5` dialects
/// of the same module; every other language's single entry. That is exactly
/// what the hand-written table this replaces spelled out row by row.
///
/// A gated-out language is `void` here — the registry keeps every entry in
/// every build and collapses `Lang` instead — and `extensionFormat` skips it,
/// exactly as it skipped the `void` rows of the old table.
const ext_pairs = blk: {
    const Pair = struct { type, Format };
    var pairs: []const Pair = &.{};
    outer: for (fig.Language.dialects) |d| {
        // First entry per distinct language wins. A gated-out language is
        // `void` in EVERY entry, so this test cannot tell JSON's three rows
        // apart in a `-Djson=false` build (nor one gated language's row from
        // another's) — and it does not need to: `extensionFormat` skips a
        // `void` row, so a duplicate of one is a row that is skipped twice.
        if (d.Lang != void) {
            for (pairs) |p| {
                if (p[0] == d.Lang) continue :outer;
            }
        }
        pairs = pairs ++ [_]Pair{.{ d.Lang, @field(Format, d.name) }};
    }
    break :blk pairs;
};

// A language missing from `ext_pairs` would silently stop resolving by
// extension — the failure would look like "that file just isn't detected",
// which is exactly the kind of quiet gap this work exists to remove. The
// derivation above makes that unreachable rather than merely detectable, so
// this is now a check on the DERIVATION rather than on a hand-written table;
// it costs one comptime loop and it is what would catch a first-entry-per-
// language rule that silently skipped a row.
comptime {
    outer: for (fig.Language.compiled) |Lang| {
        for (ext_pairs) |pair| {
            if (pair[0] == Lang) continue :outer;
        }
        @compileError("cli/args.zig `ext_pairs` is missing the language '" ++ Lang.name ++
            "', so its declared extensions would never resolve");
    }
}

/// Map a `--embed <archetype>` flag value to its `Embed.Type`. Lets any
/// embed-capable action target a region explicitly — overriding whatever
/// `resolveEmbedType`/`resolveEmbedTypeFromContent` would otherwise sniff —
/// so endmatter and JSON frontmatter are reachable. Returns null for an
/// unknown name.
pub fn embedTypeFromName(name: []const u8) ?fig.Embed.Type {
    const eql = std.mem.eql;

    // The four PARAMETRIC families, derived: every embeddable format is
    // reachable in every parametric container as `<container>-<format>`. The
    // container half is this file's own spelling (there is no container
    // registry — `Embed.Type`'s union tags are it); the `<format>` half is the
    // registry entry's name, which is also the `InnerFormat` member name, so a
    // format that grows an embedded spelling arrives here with all of its
    // archetype names at once.
    inline for (@typeInfo(fig.Embed.InnerFormat).@"enum".fields) |field| {
        const f: fig.Embed.InnerFormat = @enumFromInt(field.value);
        // `md-yaml` is deliberately not a spelling: a bare `---` block IS YAML
        // frontmatter, so it answers to `frontmatter`/`frontmatter-yaml` below
        // — which is what the `--help` prose documents and what `set`'s
        // open-or-init default resolves to.
        if (comptime !eql(u8, field.name, "yaml")) {
            if (eql(u8, name, "md-" ++ field.name)) return .{ .frontmatter = f };
        }
        if (eql(u8, name, "fenced-" ++ field.name)) return .{ .fenced = f };
        if (eql(u8, name, "html-script-" ++ field.name)) return .{ .html_script = f };
        if (eql(u8, name, "html-code-" ++ field.name)) return .{ .html_code = f };
    }

    // The rest are not `<container>-<format>` pairs and do not derive: the
    // blessed presets whose delimiter is its own distinct token rather than a
    // language tag, and the bare container names.
    //
    // Markdown `---` frontmatter (bare ⇒ yaml; see the `md-yaml` note above).
    if (eql(u8, name, "frontmatter") or eql(u8, name, "frontmatter-yaml")) return .{ .frontmatter = .yaml };
    // Blessed distinct-delimiter presets: the `;;;` and `+++` blocks. (fig 5
    // dropped their older names `frontmatter-json`/`frontmatter-toml`, and
    // `frontmatter-fig` for `fenced-fig`: each read as the `md-<lang>` block
    // it was not.)
    if (eql(u8, name, "semicolons")) return .semicolons_json;
    if (eql(u8, name, "plus")) return .plus_toml;
    if (eql(u8, name, "endmatter") or eql(u8, name, "endmatter-yaml")) return .endmatter_yaml;
    // The bare container names, whose default format is fig rather than the
    // registry's first entry — a deliberate choice this project made, not a
    // fact the registry states.
    if (eql(u8, name, "html-script")) return .{ .html_script = .fig };
    if (eql(u8, name, "html-code")) return .{ .html_code = .fig };
    return null;
}

/// The canonical `--embed` spelling of an archetype — the inverse of
/// `embedTypeFromName`, for diagnostics that have a `Type` in hand and need to
/// name it back to the user in the vocabulary they typed. Canonical means: the
/// derived `<container>-<format>` name for the parametric families, and the
/// primary (not alias) name for the presets, so round-tripping the
/// result back through `embedTypeFromName` returns the same `Type`.
pub fn embedTypeName(t: fig.Embed.Type) []const u8 {
    return switch (t) {
        // `frontmatter = .yaml` is spelled `frontmatter`, not `md-yaml` — a bare
        // `---` block IS YAML frontmatter, which is why `md-yaml` is not a
        // spelling at all (see `embedTypeFromName`).
        .frontmatter => |f| switch (f) {
            .yaml => "frontmatter",
            inline else => |g| "md-" ++ @tagName(g),
        },
        .fenced => |f| switch (f) {
            inline else => |g| "fenced-" ++ @tagName(g),
        },
        .html_script => |f| switch (f) {
            inline else => |g| "html-script-" ++ @tagName(g),
        },
        .html_code => |f| switch (f) {
            inline else => |g| "html-code-" ++ @tagName(g),
        },
        .semicolons_json => "semicolons",
        .plus_toml => "plus",
        .endmatter_yaml => "endmatter",
    };
}

test "embedTypeName round-trips through embedTypeFromName" {
    // Every archetype the CLI can name must name itself back to the same Type,
    // so a diagnostic never prints a spelling the parser would reject.
    for ([_]fig.Embed.Type{
        .{ .frontmatter = .yaml }, .{ .frontmatter = .json }, .{ .frontmatter = .toml }, .{ .frontmatter = .fig },
        .{ .fenced = .yaml },      .{ .fenced = .json },      .{ .fenced = .toml },      .{ .fenced = .fig },
        .{ .html_script = .yaml }, .{ .html_script = .json }, .{ .html_script = .toml }, .{ .html_script = .fig },
        .{ .html_code = .yaml },   .{ .html_code = .json },   .{ .html_code = .toml },   .{ .html_code = .fig },
        .semicolons_json,          .plus_toml,                .endmatter_yaml,
    }) |t| {
        try std.testing.expectEqual(@as(?fig.Embed.Type, t), embedTypeFromName(embedTypeName(t)));
    }
}

/// The `--embed <archetype>` names accepted by `embedTypeFromName`, for error
/// messages — one source of truth so a new archetype is listed everywhere.
/// The `<lang>` half is derived from `Embed.InnerFormat`, the set the
/// parametric loop in `embedTypeFromName` spells, so it cannot fall behind it.
pub const embed_archetype_names = blk: {
    var langs: []const u8 = "";
    for (@typeInfo(fig.Embed.InnerFormat).@"enum".fields, 0..) |f, i|
        langs = langs ++ (if (i == 0) "" else ", ") ++ f.name;
    break :blk "frontmatter, semicolons (;;;), plus (+++), endmatter, " ++
        "md-<lang>, fenced-<lang>, html-script[-<lang>], html-code[-<lang>]; " ++
        "<lang> is one of " ++ langs ++ " (there is no md-yaml: that is `frontmatter`)";
};

/// The CLI `Format` an embed archetype's content is written in — the `get`
/// action's `--input`/`--output` twin of `Embed.innerFormat`. Lets an explicit
/// `--embed <archetype>` pick the right parser/printer on its own, without
/// also requiring a redundant `--input`/`--output` (or, worse, silently
/// keeping a same-named-extension guess that doesn't match the archetype —
/// e.g. `--embed fenced-fig` on a `.md` file, whose extension alone
/// says nothing about which archetype it actually is).
///
/// A name identity, not a mapping: both enums draw their members from the same
/// format registry, so an `InnerFormat` member and the `Format` member it means
/// are the same string by construction. (`Format` is the larger of the two —
/// every embeddable format is a CLI format, but not every CLI format has an
/// embedded spelling — so `@field` is total in this direction only.) A
/// format this build compiled out is the configured language standing in
/// for it, registered on this ask (`languages.standIn`).
pub fn embedFormat(t: fig.Embed.Type) Format {
    return languages.standIn(switch (fig.Embed.innerFormat(t)) {
        inline else => |f| @field(Format, @tagName(f)),
    });
}

/// Resolve the embed archetype an action should operate on, given
/// already-read `content`. An explicit `embed` (a `--embed` flag, or a format
/// pinned outright some other way) always wins. Otherwise, when the file's
/// extension only implied "there's probably an embedded region here" without
/// saying which archetype (`detect_embed` — today only `.md`/`.markdown`,
/// via `Detected.embed_detect`), sniff the real bytes with `Embed.detect` so
/// a `` ```fig ``` ``-fenced or JSON frontmatter block (or a YAML endmatter
/// fence) isn't silently mistaken for `---` YAML frontmatter. Falls back to
/// the conventional `FrontmatterYaml` default when nothing is found at all —
/// e.g. a brand-new host file with no frontmatter yet — so `set`'s
/// open-or-init still seeds the same archetype it always has. Returns `null`
/// when this isn't an embed operation at all (no override, and the extension
/// implies no embed).
pub fn resolveEmbedTypeFromContent(content: []const u8, embed: ?fig.Embed.Type, detect_embed: bool) ?fig.Embed.Type {
    if (embed) |e| return registerInner(e);
    if (!detect_embed) return null;
    return registerInner(fig.Embed.detect(content) orelse .{ .frontmatter = .yaml });
}

/// `t`, once whatever stands in for its inner format is registered. The
/// core parses an embedded region itself, and reaches a compiled-out inner
/// format through the language registered at its integer; the CLI
/// registers a configured language only when asked for one, so this is the
/// asking (`languages.standIn`).
fn registerInner(t: fig.Embed.Type) fig.Embed.Type {
    _ = embedFormat(t);
    return t;
}

/// Same as `resolveEmbedTypeFromContent`, but reads `input` itself first, for
/// call sites that haven't already buffered the file's bytes at the point
/// they need to decide. This only performs that read when a sniff is
/// actually needed (`embed == null and detect_embed`) — which today only
/// happens for a real `.md`/`.markdown` path, never stdin (`-`), so the extra
/// positional read is always safe: it's a second read of a regular, seekable
/// file, not a second (and empty) read of a pipe.
pub fn resolveEmbedType(io: Io, allocator: std.mem.Allocator, input: Io.File, embed: ?fig.Embed.Type, detect_embed: bool) !?fig.Embed.Type {
    if (embed) |e| return registerInner(e);
    if (!detect_embed) return null;
    const content = try fileio.readAll(allocator, io, input);
    defer allocator.free(content);
    return registerInner(fig.Embed.detect(content) orelse .{ .frontmatter = .yaml });
}

/// The argument list with `--lang <name>` taken out: the one flag every
/// action accepts, read here once rather than in each action's loop, and
/// recorded for `detectLanguageFromFileEnding` to answer with.
const Args = struct {
    items: []const []const u8,
    i: usize = 0,
    fn next(self: *Args) ?[]const u8 {
        if (self.i >= self.items.len) return null;
        defer self.i += 1;
        return self.items[self.i];
    }
};

/// An action's positional arguments, read strictly. An argument that begins
/// with `-` and is none of the action's flags is a usage error, not a file
/// name; `--` ends the flags, so everything after it is a positional (a file
/// really named `-x` is `-- -x`). `-` alone (stdin) and a negative number
/// (`fig set f.yaml n -5`) are positionals wherever they stand.
///
/// Each action's loop asks `rest` first, so `--` and what follows it never
/// reach the flag comparisons, and hands `add` whatever no flag matched.
const Positionals = struct {
    items: std.ArrayList([]const u8) = .empty,
    /// Set once `--` is seen.
    flags_done: bool = false,

    /// True when `arg` is taken here without being read as a flag: `--`
    /// itself, or anything after it.
    fn rest(self: *Positionals, allocator: std.mem.Allocator, arg: []const u8) ArgError!bool {
        if (self.flags_done) {
            try self.items.append(allocator, arg);
            return true;
        }
        if (std.mem.eql(u8, arg, "--")) {
            self.flags_done = true;
            return true;
        }
        return false;
    }

    /// Take `arg`, which matched none of `action`'s flags, as a positional.
    /// False, having said so, when it is spelled like a flag.
    fn add(self: *Positionals, allocator: std.mem.Allocator, action: []const u8, arg: []const u8) ArgError!bool {
        if (spelledAsFlag(arg)) {
            std.log.scoped(.parseConfig).err("{s} has no flag {s} (a file or value that begins with `-` goes after `--`)\n", .{ action, arg });
            return false;
        }
        try self.items.append(allocator, arg);
        return true;
    }

    /// False, having said so, when there are more than `max` positionals.
    fn atMost(self: *const Positionals, action: []const u8, max: usize, what: []const u8) bool {
        if (self.items.items.len <= max) return true;
        std.log.scoped(.parseConfig).err("{s} takes {s}; unexpected argument: {s}\n", .{ action, what, self.items.items[max] });
        return false;
    }

    fn deinit(self: *Positionals, allocator: std.mem.Allocator) void {
        self.items.deinit(allocator);
    }
};

/// Whether `flag` takes the next argument as its value in `action` — every
/// flag of every action that does, for `parseConfig`'s `--lang` pre-pass,
/// which reads the line before any action does. `--seq` takes a strategy in
/// `patch` and nothing in `set`.
fn takesValue(flag: []const u8, action: []const u8) bool {
    const valued = [_][]const u8{
        "--lang",     "--input",       "-i",            "--output",  "-o",
        "--embed",    "--to-embed",    "--indent",      "--width",   "--gron-root",
        "--gron-sep", "--gron-term",   "--at",          "--from",    "--delete",
        "--comments", "--patch-input", "--patch-embed", "--against", "--spec",
        "-s",
    };
    for (valued) |v| if (std.mem.eql(u8, flag, v)) return !(std.mem.eql(u8, flag, "--delete") and !isPatch(action));
    return std.mem.eql(u8, flag, "--seq") and isPatch(action);
}

fn isPatch(action: []const u8) bool {
    return std.mem.eql(u8, action, "patch") or std.mem.eql(u8, action, "p");
}

/// Whether `arg` reads as a flag: a leading `-` with something after it
/// that does not start a number. `-inf` and `-nan` are flags here: fig has
/// no bare non-finite float (docs/spec.md § 5.3 — bare `-inf` is the string
/// it spells), so taking one as a value would quietly write a string where
/// a float was meant. `-- -inf` passes the string on purpose.
fn spelledAsFlag(arg: []const u8) bool {
    if (arg.len < 2 or arg[0] != '-') return false;
    return !(std.ascii.isDigit(arg[1]) or arg[1] == '.');
}

/// Take `arg` as `--string`/`--raw` into `mode`, refusing the pair: true when
/// it was one of them. `null` in `mode` is "not given" (the default reading).
fn valueModeFlag(action: []const u8, arg: []const u8, mode: *?types.ValueMode, usage: ArgError) ArgError!bool {
    const this: types.ValueMode = if (std.mem.eql(u8, arg, "--string"))
        .string
    else if (std.mem.eql(u8, arg, "--raw"))
        .raw
    else
        return false;
    if (mode.*) |prev| if (prev != this) {
        std.log.scoped(.parseConfig).err("{s}: --string and --raw are two readings of the value; pass one.\n", .{action});
        return usage;
    };
    mode.* = this;
    return true;
}

fn isHelp(arg: []const u8) bool {
    return std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h");
}

pub fn parseConfig(allocator: std.mem.Allocator, args_in: anytype) ArgError!CliConfig {
    const log = std.log.scoped(.parseConfig);
    var config = CliConfig{};

    var collected: std.ArrayList([]const u8) = .empty;
    // Past `--` every argument is a positional, `--lang` included — unless
    // that `--` is the value of the flag before it (`--gron-sep --`), which
    // ends nothing.
    var flags_done = false;
    var prev: []const u8 = "";
    while (args_in.next()) |arg| {
        defer prev = arg;
        if (std.mem.eql(u8, arg, "--") and !takesValue(prev, if (collected.items.len > 1) collected.items[1] else "")) flags_done = true;
        if (!flags_done and std.mem.eql(u8, arg, "--lang")) {
            const name = args_in.next() orelse {
                log.err("Missing language name after --lang\n", .{});
                return ArgError.UnsupportedFileFormat;
            };
            const format = parseFormatName(name) orelse {
                // A refused helper has already said why, through `ensure`.
                if (!languages.isConfigured(name)) log.err("No language named `{s}`: not a compiled format, and no languages.figl configures it (see `fig lang --help`)\n", .{name});
                return ArgError.UnsupportedFileFormat;
            };
            languages.setLangOverride(format);
            continue;
        }
        collected.append(allocator, arg) catch return ArgError.OutOfMemory;
    }
    var args_storage: Args = .{ .items = collected.items };
    const args = &args_storage;

    config.binary_name = args.next() orelse "fig";

    const action_str = args.next() orelse {
        config.action = .help;
        config.options = .{ .help = .{} };
        return config;
    };

    if (std.mem.eql(u8, action_str, "help") or std.mem.eql(u8, action_str, "--help") or std.mem.eql(u8, action_str, "-h")) {
        config.action = .help;
        config.options = .{ .help = .{ .requested_help = true } };
        // Nothing follows but a repeated `--help` (`fig help --help`): strict
        // like every other action, so `fig help --bogus` is not a silent 0.
        while (args.next()) |arg| {
            if (isHelp(arg)) continue;
            // `fig help set` reads as asking for `set`'s help: say where it is.
            if (std.meta.stringToEnum(CliAction, arg)) |named| if (named != .external) {
                log.err("{s} takes no arguments; for {s}'s help, run `fig {s} --help`\n", .{ action_str, arg, arg });
                return ArgError.HelpNamesAction;
            };
            log.err("{s} takes no arguments; unexpected argument: {s}\n", .{ action_str, arg });
            return ArgError.SurplusArgument;
        }
    } else if (std.mem.eql(u8, action_str, "version") or std.mem.eql(u8, action_str, "--version") or std.mem.eql(u8, action_str, "-v")) {
        config.action = .version;
        config.options = .{ .version = .{} };
        // `--help` is the one thing that may follow, as for every action.
        while (args.next()) |arg| {
            if (isHelp(arg)) {
                config.options.version.requested_help = true;
                continue;
            }
            log.err("{s} takes no arguments; unexpected argument: {s}\n", .{ action_str, arg });
            return ArgError.SurplusArgument;
        }
    } else if (std.mem.eql(u8, action_str, "replace") or std.mem.eql(u8, action_str, "rename")) {
        // `replace` swaps the value at a path; `rename` renames the key there.
        // One operation each — no flag turns one into the other (cli-5 §7).
        const rename = std.mem.eql(u8, action_str, "rename");
        const usage = if (rename) ArgError.MissingRenameArgument else ArgError.MissingReplaceArgument;
        config.action = if (rename) .rename else .replace;

        var value_mode: ?types.ValueMode = null;
        var requested_help = false;
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);
        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (!rename and try valueModeFlag(action_str, arg, &value_mode, usage)) {
                // taken
            } else if (!try positionals.add(allocator, action_str, arg)) return usage;
        }
        const pos = positionals.items.items;

        var file_path: []const u8 = "";
        var path: []fig.AST.PathSegment = &.{};
        var replacement: []const u8 = "";
        if (!requested_help) {
            if (pos.len < 3) {
                log.err("{s}\n", .{switch (pos.len) {
                    0 => "No file provided.",
                    1 => "No path provided.",
                    else => if (rename) "No new key name provided." else "No value provided.",
                }});
                return usage;
            }
            if (!positionals.atMost(action_str, 3, if (rename) "a file, a path and a new name" else "a file, a path and a value")) return usage;
            file_path = pos[0];
            path = try pathArg(allocator, pos[1]);
            replacement = pos[2];
        }

        // Skip extension detection when the user only asked for help. An
        // unrecognized extension is not an error here: `detect = true`
        // defers to content sniffing in the handler.
        const ext = if (requested_help) null else detectLanguageFromFileEnding(file_path);
        const opts: types.EditOptions = .{
            .file = file_path,
            .path = path,
            .replacement = replacement,
            .key = rename,
            .value_mode = value_mode orelse .fig,
            .requested_help = requested_help,
            .format = if (ext) |d| d.format else .json,
            .detect = !requested_help and ext == null,
            .embed = null,
            .detect_embed = if (ext) |d| d.embed_detect else false,
        };
        config.options = if (rename) .{ .rename = opts } else .{ .replace = opts };
    } else if (std.mem.eql(u8, action_str, "set") or std.mem.eql(u8, action_str, "s")) {
        config.action = .set;

        // Leading flags in any order: `--seq`, `--embed <archetype>`, `--help`.
        // Positionals follow: file, path, then the value (or, with `--seq`, the
        // sequence items).
        var seq = false;
        var value_mode: ?types.ValueMode = null;
        var embed_override: ?fig.Embed.Type = null;
        var requested_help = false;
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--seq")) {
                seq = true;
            } else if (try valueModeFlag("set", arg, &value_mode, ArgError.MissingSetArgument)) {
                // taken
            } else if (std.mem.eql(u8, arg, "--embed")) {
                const name = args.next() orelse {
                    log.err("Missing archetype after {s}\n", .{arg});
                    return ArgError.MissingSetArgument;
                };
                embed_override = embedTypeFromName(name) orelse {
                    log.err("Unknown --embed archetype: {s} (" ++ embed_archetype_names ++ ")\n", .{name});
                    return ArgError.UnknownArchetype;
                };
            } else if (!try positionals.add(allocator, "set", arg)) return ArgError.MissingSetArgument;
        }
        const pos = positionals.items.items;

        if (requested_help) {
            config.options = .{ .set = .{ .file = "", .path = &.{}, .value = "", .requested_help = true, .format = .json } };
        } else {
            // Need file, path, and at least one value (a scalar, or one or more
            // sequence items with `--seq`).
            if (pos.len < 3) {
                log.err("set needs a file, a path, and a value (e.g. `fig set f.yaml a.b 1`).\n", .{});
                return ArgError.MissingSetArgument;
            }
            if (!seq and !positionals.atMost("set", 3, "a file, a path and one value (--seq takes several)")) return ArgError.MissingSetArgument;
            const file_path = pos[0];
            const path = try pathArg(allocator, pos[1]);
            const ext = detectLanguageFromFileEnding(file_path);
            const embed = embed_override;
            config.options = .{
                .set = .{
                    .file = file_path,
                    .path = path,
                    .value = if (seq) "" else pos[2],
                    .seq = seq,
                    .values = if (seq) try allocator.dupe([]const u8, pos[2..]) else &.{},
                    .value_mode = value_mode orelse .fig,
                    .requested_help = false,
                    .format = if (ext) |d| d.format else .json,
                    // Skip content sniffing when targeting an embed (the inner format
                    // is fixed by the archetype) or when the extension resolved it.
                    .detect = ext == null and embed == null,
                    .embed = embed,
                    .detect_embed = embed == null and (if (ext) |d| d.embed_detect else false),
                },
            };
        }
    } else if (std.mem.eql(u8, action_str, "insert") or std.mem.eql(u8, action_str, "i")) {
        config.action = .insert;

        var value_mode: ?types.ValueMode = null;
        var requested_help = false;
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);
        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (try valueModeFlag("insert", arg, &value_mode, ArgError.MissingInsertArgument)) {
                // taken
            } else if (!try positionals.add(allocator, "insert", arg)) return ArgError.MissingInsertArgument;
        }
        const pos = positionals.items.items;

        var file_path: []const u8 = "";
        var path: []fig.AST.PathSegment = &.{};
        var value: []const u8 = "";
        if (!requested_help) {
            if (pos.len < 3) {
                log.err("{s}\n", .{switch (pos.len) {
                    0 => "No file provided.",
                    1 => "No path provided.",
                    else => "No value provided.",
                }});
                return ArgError.MissingInsertArgument;
            }
            if (!positionals.atMost("insert", 3, "a file, a path and a value")) return ArgError.MissingInsertArgument;
            file_path = pos[0];
            path = try pathArg(allocator, pos[1]);
            value = pos[2];
        }

        const ext = if (requested_help) null else detectLanguageFromFileEnding(file_path);
        config.options = .{ .insert = .{
            .file = file_path,
            .path = path,
            .value = value,
            .value_mode = value_mode orelse .fig,
            .requested_help = requested_help,
            .format = if (ext) |d| d.format else .json,
            .detect = !requested_help and ext == null,
            .embed = null,
            .detect_embed = if (ext) |d| d.embed_detect else false,
        } };
    } else if (std.mem.eql(u8, action_str, "delete") or std.mem.eql(u8, action_str, "d")) {
        config.action = .delete;

        var requested_help = false;
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);
        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (!try positionals.add(allocator, "delete", arg)) return ArgError.MissingDeleteArgument;
        }
        const pos = positionals.items.items;

        var file_path: []const u8 = "";
        var path: []fig.AST.PathSegment = &.{};
        if (!requested_help) {
            if (pos.len < 2) {
                log.err("{s}\n", .{if (pos.len == 0) "No file provided." else "No path provided."});
                return ArgError.MissingDeleteArgument;
            }
            if (!positionals.atMost("delete", 2, "a file and a path")) return ArgError.MissingDeleteArgument;
            file_path = pos[0];
            path = try pathArg(allocator, pos[1]);
        }

        const ext = if (requested_help) null else detectLanguageFromFileEnding(file_path);
        config.options = .{ .delete = .{
            .file = file_path,
            .path = path,
            .requested_help = requested_help,
            .format = if (ext) |d| d.format else .json,
            .detect = !requested_help and ext == null,
            .embed = null,
            .detect_embed = if (ext) |d| d.embed_detect else false,
        } };
    } else if (std.mem.eql(u8, action_str, "comment") or std.mem.eql(u8, action_str, "c")) {
        config.action = .comment;

        // Flags, in any order: `--inline`, `--delete`, `--get`.
        var inline_comment = false;
        var delete = false;
        var get = false;
        var requested_help = false;
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);
        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--inline")) {
                inline_comment = true;
            } else if (std.mem.eql(u8, arg, "--delete")) {
                delete = true;
            } else if (std.mem.eql(u8, arg, "--get")) {
                get = true;
            } else if (!try positionals.add(allocator, "comment", arg)) return ArgError.MissingCommentArgument;
        }
        const pos = positionals.items.items;

        var file_path: []const u8 = "";
        var path: []fig.AST.PathSegment = &.{};
        var text: []const u8 = "";
        if (!requested_help) {
            // Delete/get need no text; add/set requires it.
            const wants_text = !delete and !get;
            if (pos.len < 2 or (wants_text and pos.len < 3)) {
                log.err("{s}\n", .{switch (pos.len) {
                    0 => "No file provided.",
                    1 => "No path provided.",
                    else => "No comment text provided.",
                }});
                return ArgError.MissingCommentArgument;
            }
            if (!positionals.atMost("comment", if (wants_text) 3 else 2, if (wants_text) "a file, a path and the comment text" else "a file and a path with --get/--delete")) return ArgError.MissingCommentArgument;
            file_path = pos[0];
            path = try pathArg(allocator, pos[1]);
            if (wants_text) text = pos[2];
        }

        const ext = if (requested_help) null else detectLanguageFromFileEnding(file_path);
        config.options = .{ .comment = .{
            .file = file_path,
            .path = path,
            .text = text,
            .inline_comment = inline_comment,
            .delete = delete,
            .get = get,
            .requested_help = requested_help,
            .format = if (ext) |d| d.format else .json,
            .detect = !requested_help and ext == null,
            .embed = null,
            .detect_embed = if (ext) |d| d.embed_detect else false,
        } };
    } else if (std.mem.eql(u8, action_str, "get") or std.mem.eql(u8, action_str, "g")) {
        config.action = .get;

        var input_override: ?Format = null;
        var output_override: ?Format = null;
        var lax_tags = false;
        var lossless = false;
        var quiet = false;
        var strict = false;
        // Explicit `--embed <archetype>` override and `--body` projection.
        var embed_override: ?fig.Embed.Type = null;
        var body = false;
        var serialize: fig.AST.SerializeOptions = .{};
        // gron projection overrides; null means "keep the gron default".
        var gron_root: ?[]const u8 = null;
        var gron_sep: ?[]const u8 = null;
        var gron_term: ?[]const u8 = null;
        var requested_help = false;
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--lax-tags")) {
                lax_tags = true;
            } else if (std.mem.eql(u8, arg, "--gron-root")) {
                gron_root = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
            } else if (std.mem.eql(u8, arg, "--gron-sep")) {
                gron_sep = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
            } else if (std.mem.eql(u8, arg, "--gron-term")) {
                // Empty is allowed (drop the terminator entirely).
                gron_term = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
            } else if (std.mem.eql(u8, arg, "--lossless")) {
                lossless = true;
            } else if (std.mem.eql(u8, arg, "--lossy")) {
                lossless = false;
            } else if (std.mem.eql(u8, arg, "--compact")) {
                serialize.pretty = false;
            } else if (std.mem.eql(u8, arg, "--pretty")) {
                serialize.pretty = true;
            } else if (std.mem.eql(u8, arg, "--strip-comments")) {
                serialize.strip_comments = true;
            } else if (std.mem.eql(u8, arg, "--quiet") or std.mem.eql(u8, arg, "-q") or std.mem.eql(u8, arg, "--no-warnings")) {
                quiet = true;
            } else if (std.mem.eql(u8, arg, "--strict")) {
                strict = true;
            } else if (std.mem.eql(u8, arg, "--embed")) {
                const name = args.next() orelse {
                    log.err("Missing archetype after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
                embed_override = embedTypeFromName(name) orelse {
                    log.err("Unknown --embed archetype: {s} (" ++ embed_archetype_names ++ ")\n", .{name});
                    return ArgError.UnknownArchetype;
                };
            } else if (std.mem.eql(u8, arg, "--body")) {
                body = true;
            } else if (std.mem.eql(u8, arg, "--indent")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
                serialize.indent = std.fmt.parseInt(u8, n, 10) catch {
                    log.err("Invalid --indent value: {s}\n", .{n});
                    return ArgError.MissingGetArgument;
                };
                // fig has no `pretty` gate of its own to read `indent`'s value
                // against (see `SerializeOptions.fig_indent`'s doc comment), so
                // an explicit `--indent` is fig's own on/off signal, independent
                // of the numeric width other formats use it for.
                serialize.fig_indent = true;
            } else if (std.mem.eql(u8, arg, "--width")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
                serialize.width = std.fmt.parseInt(u16, n, 10) catch {
                    log.err("Invalid --width value: {s}\n", .{n});
                    return ArgError.MissingGetArgument;
                };
            } else if (std.mem.eql(u8, arg, "--input") or std.mem.eql(u8, arg, "-i")) {
                const fmt = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
                // Delegate to the same enum-driven lookup `check`/`fmt`/`convert`
                // use, so this never again drifts out of sync with `Format` as
                // formats are added (this used to be its own hand-rolled chain
                // of literal comparisons — see git blame — which is exactly how
                // it silently fell behind when ini/dotenv/properties were added).
                input_override = parseFormatName(fmt) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (std.mem.eql(u8, arg, "--output") or std.mem.eql(u8, arg, "-o")) {
                const fmt = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingGetArgument;
                };
                output_override = parseFormatName(fmt) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (!try positionals.add(allocator, "get", arg)) return ArgError.MissingGetArgument;
        }
        const pos = positionals.items.items;

        if (!requested_help and pos.len == 0) {
            log.err("No file provided.\n", .{});
            return ArgError.MissingGetArgument;
        }
        if (!requested_help and !positionals.atMost("get", 2, "a file and at most one path")) return ArgError.MissingGetArgument;
        const file_path = if (pos.len > 0) pos[0] else "-";

        var path: ?[]fig.AST.PathSegment = null;
        if (!requested_help and pos.len > 1) {
            path = try pathArg(allocator, pos[1]);
        }

        const detected_input: ?Detected = if (!requested_help and input_override == null)
            detectLanguageFromFileEnding(file_path)
        else
            null;
        // An explicit `--embed` archetype wins outright; otherwise, when the
        // extension implies SOME embedded region (`.md`), the handler sniffs
        // which archetype it actually is at runtime (`resolveEmbedType`).
        const embed = embed_override;
        // No `--input` and an unrecognized extension ⇒ sniff the contents in the
        // handler. `.json` here is a placeholder `from`/`to`, overwritten once the
        // real format is known. An explicit `--embed` is never sniffed: its
        // archetype fixes the inner format outright (`embedFormat`), and that
        // wins over a same-named extension guess — e.g. `--embed md-fig`
        // on a `.md` file (whose extension alone says nothing about which
        // archetype it actually is) must read/render the embed as fig, not YAML.
        const needs_detect = !requested_help and input_override == null and embed_override == null and detected_input == null;
        const input_format = input_override orelse
            (if (embed_override) |et| embedFormat(et) else null) orelse
            (if (detected_input) |d| d.format else null) orelse .json;

        var gron_projection: gron.Projection = .gron;
        if (gron_root) |r| gron_projection.root_name = r;
        if (gron_sep) |s| gron_projection.assign = s;
        if (gron_term) |t| gron_projection.terminator = t;

        config.options = .{ .get = .{
            .file = file_path,
            .path = path,
            .from = input_format,
            .to = output_override orelse input_format,
            .requested_help = requested_help,
            .detect = needs_detect,
            .output_explicit = output_override != null,
            .lax_tags = lax_tags,
            .lossless = lossless,
            .embed = embed,
            .detect_embed = embed == null and (if (detected_input) |d| d.embed_detect else false),
            .body = body,
            .serialize = serialize,
            .quiet = quiet,
            .strict = strict,
            .gron_projection = gron_projection,
        } };
    } else if (std.mem.eql(u8, action_str, "check") or std.mem.eql(u8, action_str, "ck")) {
        config.action = .check;

        var input_override: ?Format = null;
        var spec: ?[]const u8 = null;
        var quiet = false;
        var strict = false;
        var requested_help = false;
        var files: Positionals = .{};
        defer files.deinit(allocator);

        while (args.next()) |arg| {
            if (try files.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--quiet") or std.mem.eql(u8, arg, "-q") or std.mem.eql(u8, arg, "--no-warnings")) {
                quiet = true;
            } else if (std.mem.eql(u8, arg, "--strict")) {
                strict = true;
            } else if (std.mem.eql(u8, arg, "--input") or std.mem.eql(u8, arg, "-i")) {
                const fmt = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingCheckArgument;
                };
                input_override = parseFormatName(fmt) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (std.mem.eql(u8, arg, "--spec") or std.mem.eql(u8, arg, "-s")) {
                spec = args.next() orelse {
                    log.err("Missing version value after {s}\n", .{arg});
                    return ArgError.MissingCheckArgument;
                };
            } else if (!try files.add(allocator, "check", arg)) return ArgError.MissingCheckArgument;
        }

        if (!requested_help and files.items.items.len == 0) {
            log.err("No file provided.\n", .{});
            return ArgError.MissingCheckArgument;
        }

        config.options = .{
            .check = .{
                // toOwnedSlice: the whole slice (allocated in the arena passed to
                // parseConfig) outlives this function, unlike `get` which only keeps
                // copies of individual positional headers.
                .files = try files.items.toOwnedSlice(allocator),
                .format = input_override,
                .spec = spec,
                .quiet = quiet,
                .strict = strict,
                .requested_help = requested_help,
            },
        };
    } else if (std.mem.eql(u8, action_str, "fmt") or std.mem.eql(u8, action_str, "f")) {
        config.action = .fmt;

        var input_override: ?Format = null;
        var quiet = false;
        var strict = false;
        var dry_run = false;
        var diff_mode = false;
        var requested_help = false;
        var embed_override: ?fig.Embed.Type = null;
        var serialize: fig.AST.SerializeOptions = .{};
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--dry-run")) {
                dry_run = true;
            } else if (std.mem.eql(u8, arg, "--diff")) {
                diff_mode = true;
            } else if (std.mem.eql(u8, arg, "--compact")) {
                serialize.pretty = false;
            } else if (std.mem.eql(u8, arg, "--pretty")) {
                serialize.pretty = true;
            } else if (std.mem.eql(u8, arg, "--strip-comments")) {
                serialize.strip_comments = true;
            } else if (std.mem.eql(u8, arg, "--quiet") or std.mem.eql(u8, arg, "-q") or std.mem.eql(u8, arg, "--no-warnings")) {
                quiet = true;
            } else if (std.mem.eql(u8, arg, "--strict")) {
                strict = true;
            } else if (std.mem.eql(u8, arg, "--embed")) {
                const name = args.next() orelse {
                    log.err("Missing archetype after {s}\n", .{arg});
                    return ArgError.MissingFmtArgument;
                };
                embed_override = embedTypeFromName(name) orelse {
                    log.err("Unknown --embed archetype: {s} (" ++ embed_archetype_names ++ ")\n", .{name});
                    return ArgError.UnknownArchetype;
                };
            } else if (std.mem.eql(u8, arg, "--indent")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingFmtArgument;
                };
                serialize.indent = std.fmt.parseInt(u8, n, 10) catch {
                    log.err("Invalid --indent value: {s}\n", .{n});
                    return ArgError.MissingFmtArgument;
                };
                // See the matching comment on `get`'s `--indent` handling above.
                serialize.fig_indent = true;
            } else if (std.mem.eql(u8, arg, "--width")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingFmtArgument;
                };
                serialize.width = std.fmt.parseInt(u16, n, 10) catch {
                    log.err("Invalid --width value: {s}\n", .{n});
                    return ArgError.MissingFmtArgument;
                };
            } else if (std.mem.eql(u8, arg, "--input") or std.mem.eql(u8, arg, "-i")) {
                const fmt_name = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingFmtArgument;
                };
                input_override = parseFormatName(fmt_name) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt_name});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (!try positionals.add(allocator, "fmt", arg)) return ArgError.MissingFmtArgument;
        }

        if (!requested_help and positionals.items.items.len == 0) {
            log.err("No file provided.\n", .{});
            return ArgError.MissingFmtArgument;
        }
        // `fmt` reformats a whole file (or a whole embedded region) — there is no
        // sub-document path argument the way `get`/`replace`/etc. take one.
        if (!requested_help and positionals.items.items.len > 1) {
            log.err("fmt takes a single file, not a path within it: {s}\n", .{positionals.items.items[1]});
            return ArgError.MissingFmtArgument;
        }
        if (!requested_help and dry_run and diff_mode) {
            log.err("--dry-run and --diff are mutually exclusive.\n", .{});
            return ArgError.MissingFmtArgument;
        }

        const file_path = if (positionals.items.items.len > 0) positionals.items.items[0] else "-";

        const detected_input: ?Detected = if (!requested_help and input_override == null)
            detectLanguageFromFileEnding(file_path)
        else
            null;
        // An explicit `--embed` archetype wins outright; otherwise, when the
        // extension implies SOME embedded region (`.md`), the handler sniffs
        // which archetype it actually is at runtime.
        const embed = embed_override;
        const needs_detect = !requested_help and input_override == null and embed_override == null and detected_input == null;
        const from = input_override orelse
            (if (embed_override) |et| embedFormat(et) else null) orelse
            (if (detected_input) |d| d.format else null) orelse .json;

        config.options = .{ .fmt = .{
            .file = file_path,
            .from = from,
            .requested_help = requested_help,
            .detect = needs_detect,
            .serialize = serialize,
            .quiet = quiet,
            .strict = strict,
            .dry_run = dry_run,
            .diff = diff_mode,
            .embed = embed,
            .detect_embed = embed == null and (if (detected_input) |d| d.embed_detect else false),
        } };
    } else if (std.mem.eql(u8, action_str, "convert") or std.mem.eql(u8, action_str, "cv")) {
        config.action = .convert;

        var input_override: ?Format = null;
        var output_override: ?Format = null;
        var embed_override: ?fig.Embed.Type = null;
        var to_embed_override: ?fig.Embed.Type = null;
        var lax_tags = false;
        var lossless = false;
        var quiet = false;
        var strict = false;
        var write = false;
        var diff_mode = false;
        var requested_help = false;
        var serialize: fig.AST.SerializeOptions = .{};
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--write") or std.mem.eql(u8, arg, "-w")) {
                write = true;
            } else if (std.mem.eql(u8, arg, "--dry-run")) {
                log.err("convert prints to stdout by default; pass --write/-w to write in place instead.\n", .{});
                return ArgError.MissingConvertArgument;
            } else if (std.mem.eql(u8, arg, "--diff")) {
                diff_mode = true;
            } else if (std.mem.eql(u8, arg, "--compact")) {
                serialize.pretty = false;
            } else if (std.mem.eql(u8, arg, "--pretty")) {
                serialize.pretty = true;
            } else if (std.mem.eql(u8, arg, "--strip-comments")) {
                serialize.strip_comments = true;
            } else if (std.mem.eql(u8, arg, "--lax-tags")) {
                lax_tags = true;
            } else if (std.mem.eql(u8, arg, "--lossless")) {
                lossless = true;
            } else if (std.mem.eql(u8, arg, "--lossy")) {
                lossless = false;
            } else if (std.mem.eql(u8, arg, "--quiet") or std.mem.eql(u8, arg, "-q") or std.mem.eql(u8, arg, "--no-warnings")) {
                quiet = true;
            } else if (std.mem.eql(u8, arg, "--strict")) {
                strict = true;
            } else if (std.mem.eql(u8, arg, "--embed")) {
                const name = args.next() orelse {
                    log.err("Missing archetype after {s}\n", .{arg});
                    return ArgError.MissingConvertArgument;
                };
                embed_override = embedTypeFromName(name) orelse {
                    log.err("Unknown --embed archetype: {s} (" ++ embed_archetype_names ++ ")\n", .{name});
                    return ArgError.UnknownArchetype;
                };
            } else if (std.mem.eql(u8, arg, "--to-embed")) {
                const name = args.next() orelse {
                    log.err("Missing archetype after {s}\n", .{arg});
                    return ArgError.MissingConvertArgument;
                };
                to_embed_override = embedTypeFromName(name) orelse {
                    log.err("Unknown --to-embed archetype: {s} (" ++ embed_archetype_names ++ ")\n", .{name});
                    return ArgError.UnknownArchetype;
                };
            } else if (std.mem.eql(u8, arg, "--indent")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingConvertArgument;
                };
                serialize.indent = std.fmt.parseInt(u8, n, 10) catch {
                    log.err("Invalid --indent value: {s}\n", .{n});
                    return ArgError.MissingConvertArgument;
                };
                // See the matching comment on `get`'s `--indent` handling above.
                serialize.fig_indent = true;
            } else if (std.mem.eql(u8, arg, "--width")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingConvertArgument;
                };
                serialize.width = std.fmt.parseInt(u16, n, 10) catch {
                    log.err("Invalid --width value: {s}\n", .{n});
                    return ArgError.MissingConvertArgument;
                };
            } else if (std.mem.eql(u8, arg, "--input") or std.mem.eql(u8, arg, "-i")) {
                const fmt_name = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingConvertArgument;
                };
                input_override = parseFormatName(fmt_name) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt_name});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (std.mem.eql(u8, arg, "--output") or std.mem.eql(u8, arg, "-o")) {
                const fmt_name = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingConvertArgument;
                };
                output_override = parseFormatName(fmt_name) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt_name});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (!try positionals.add(allocator, "convert", arg)) return ArgError.MissingConvertArgument;
        }

        if (!requested_help and positionals.items.items.len == 0) {
            log.err("No file provided.\n", .{});
            return ArgError.MissingConvertArgument;
        }
        if (!requested_help and positionals.items.items.len > 1) {
            log.err("convert takes a single file, not a path within it: {s}\n", .{positionals.items.items[1]});
            return ArgError.MissingConvertArgument;
        }
        if (!requested_help and output_override != null and to_embed_override != null) {
            log.err("--output and --to-embed are mutually exclusive: whole-file conversion picks the target format directly, embed-archetype conversion picks it via the archetype.\n", .{});
            return ArgError.MissingConvertArgument;
        }
        if (!requested_help and output_override == null and to_embed_override == null) {
            log.err("convert needs a target: pass --output <format> to convert the whole file, or --to-embed <archetype> to rehouse an embedded region.\n", .{});
            return ArgError.MissingConvertArgument;
        }
        if (!requested_help and input_override != null and to_embed_override != null) {
            log.err("--input is not used with --to-embed: the source archetype (--embed, else detected) fixes the input format.\n", .{});
            return ArgError.MissingConvertArgument;
        }
        if (!requested_help and embed_override != null and to_embed_override == null) {
            log.err("--embed requires --to-embed (embed-archetype conversion always changes the archetype); use `fmt --embed` to reformat without changing format.\n", .{});
            return ArgError.MissingConvertArgument;
        }

        const file_path = if (positionals.items.items.len > 0) positionals.items.items[0] else "-";

        const detected_input: ?Detected = if (!requested_help) detectLanguageFromFileEnding(file_path) else null;

        if (!requested_help and to_embed_override != null) {
            // Embed-archetype mode: `from`/`to`/`detect` are unused — the
            // source and target archetypes fix both formats. The source
            // archetype is never pinned by the extension alone (`.md` only
            // implies SOME embed, not which one) — an explicit `--embed`
            // wins, else `detect_embed` sniffs it from the content at runtime.
            const embed = embed_override;
            config.options = .{ .convert = .{
                .file = file_path,
                .requested_help = requested_help,
                .to_embed = to_embed_override,
                .embed = embed,
                .detect_embed = embed == null,
                .lax_tags = lax_tags,
                .lossless = lossless,
                .serialize = serialize,
                .quiet = quiet,
                .strict = strict,
                .write = write,
                .diff = diff_mode,
            } };
        } else {
            // Whole-file mode. A host document whose extension implies an
            // embed (currently only `.md`/`.markdown`) can't be converted
            // whole without either destroying its prose or guessing at a
            // fence convention for `--output`'s format — point the user at
            // `--to-embed` instead, unless they passed an explicit `--input`
            // that overrides the extension's guess entirely.
            if (!requested_help and input_override == null) {
                if (detected_input) |d| if (d.embed_detect) {
                    log.err("{s} is a host document (embedded config detected); use --to-embed <archetype> to convert its embedded region, or pass --input explicitly to force whole-file conversion.\n", .{file_path});
                    return ArgError.MissingConvertArgument;
                };
            }
            const needs_detect = !requested_help and input_override == null and detected_input == null;
            const from = input_override orelse (if (detected_input) |d| d.format else null) orelse .json;
            config.options = .{ .convert = .{
                .file = file_path,
                .requested_help = requested_help,
                .from = from,
                .to = output_override orelse .json,
                .detect = needs_detect,
                .lax_tags = lax_tags,
                .lossless = lossless,
                .serialize = serialize,
                .quiet = quiet,
                .strict = strict,
                .write = write,
                .diff = diff_mode,
            } };
        }
    } else if (std.mem.eql(u8, action_str, "patch") or std.mem.eql(u8, action_str, "p")) {
        config.action = .patch;

        var input_override: ?Format = null;
        var patch_input_override: ?Format = null;
        var embed_override: ?fig.Embed.Type = null;
        var patch_embed_override: ?fig.Embed.Type = null;
        var at: []fig.AST.PathSegment = &.{};
        var from: []fig.AST.PathSegment = &.{};
        var deletes: std.ArrayList(fig.Patch.Deletion) = .empty;
        defer deletes.deinit(allocator);
        var patch_options: fig.Patch.Options = .{};
        var lossless = false;
        var dry_run = false;
        var diff_mode = false;
        var quiet = false;
        var strict = false;
        var strip_comments = false;
        var comments_given = false;
        var requested_help = false;
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--dry-run")) {
                dry_run = true;
            } else if (std.mem.eql(u8, arg, "--diff")) {
                diff_mode = true;
            } else if (std.mem.eql(u8, arg, "--quiet") or std.mem.eql(u8, arg, "-q") or std.mem.eql(u8, arg, "--no-warnings")) {
                quiet = true;
            } else if (std.mem.eql(u8, arg, "--strict")) {
                strict = true;
            } else if (std.mem.eql(u8, arg, "--strip-comments")) {
                strip_comments = true;
            } else if (std.mem.eql(u8, arg, "--lossless")) {
                lossless = true;
            } else if (std.mem.eql(u8, arg, "--lossy")) {
                lossless = false;
            } else if (std.mem.eql(u8, arg, "--compact")) {
                patch_options.serialize.pretty = false;
            } else if (std.mem.eql(u8, arg, "--pretty")) {
                patch_options.serialize.pretty = true;
            } else if (std.mem.eql(u8, arg, "--at")) {
                const p = args.next() orelse {
                    log.err("Missing path after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                at = try pathArg(allocator, p);
            } else if (std.mem.eql(u8, arg, "--from")) {
                const p = args.next() orelse {
                    log.err("Missing path after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                from = try pathArg(allocator, p);
            } else if (std.mem.eql(u8, arg, "--delete")) {
                const p = args.next() orelse {
                    log.err("Missing path after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                const parsed_path = try pathArg(allocator, p);
                if (parsed_path.len == 0) {
                    log.err("--delete needs a path within the document; the root cannot be deleted.\n", .{});
                    return ArgError.MissingPatchArgument;
                }
                try deletes.append(allocator, parsed_path);
            } else if (std.mem.eql(u8, arg, "--seq")) {
                const name = args.next() orelse {
                    log.err("Missing strategy after {s} (replace, append, union)\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                // `union` is a Zig keyword, so the enum member is `unite`;
                // the CLI keeps the word a user would reach for.
                patch_options.seq = if (std.mem.eql(u8, name, "union"))
                    .unite
                else
                    std.meta.stringToEnum(fig.Patch.SeqStrategy, name) orelse {
                        log.err("Unknown --seq strategy: {s} (replace, append, union)\n", .{name});
                        return ArgError.MissingPatchArgument;
                    };
            } else if (std.mem.eql(u8, arg, "--comments")) {
                const name = args.next() orelse {
                    log.err("Missing strategy after {s} (ours, theirs, none)\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                patch_options.comments = std.meta.stringToEnum(fig.Patch.CommentStrategy, name) orelse {
                    log.err("Unknown --comments strategy: {s} (ours, theirs, none)\n", .{name});
                    return ArgError.MissingPatchArgument;
                };
                comments_given = true;
            } else if (std.mem.eql(u8, arg, "--indent")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                patch_options.serialize.indent = std.fmt.parseInt(u8, n, 10) catch {
                    log.err("Invalid --indent value: {s}\n", .{n});
                    return ArgError.MissingPatchArgument;
                };
                patch_options.serialize.fig_indent = true;
            } else if (std.mem.eql(u8, arg, "--width")) {
                const n = args.next() orelse {
                    log.err("Missing value after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                patch_options.serialize.width = std.fmt.parseInt(u16, n, 10) catch {
                    log.err("Invalid --width value: {s}\n", .{n});
                    return ArgError.MissingPatchArgument;
                };
            } else if (std.mem.eql(u8, arg, "--input") or std.mem.eql(u8, arg, "-i")) {
                const fmt_name = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                input_override = parseFormatName(fmt_name) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt_name});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (std.mem.eql(u8, arg, "--patch-input")) {
                const fmt_name = args.next() orelse {
                    log.err("Missing format value after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                patch_input_override = parseFormatName(fmt_name) orelse {
                    log.err("Unsupported format: {s}\n", .{fmt_name});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (std.mem.eql(u8, arg, "--embed")) {
                const name = args.next() orelse {
                    log.err("Missing archetype after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                embed_override = embedTypeFromName(name) orelse {
                    log.err("Unknown --embed archetype: {s} (" ++ embed_archetype_names ++ ")\n", .{name});
                    return ArgError.UnknownArchetype;
                };
            } else if (std.mem.eql(u8, arg, "--patch-embed")) {
                const name = args.next() orelse {
                    log.err("Missing archetype after {s}\n", .{arg});
                    return ArgError.MissingPatchArgument;
                };
                patch_embed_override = embedTypeFromName(name) orelse {
                    log.err("Unknown --patch-embed archetype: {s} (" ++ embed_archetype_names ++ ")\n", .{name});
                    return ArgError.UnknownArchetype;
                };
            } else if (!try positionals.add(allocator, "patch", arg)) return ArgError.MissingPatchArgument;
        }

        // `--strip-comments` is `get`/`convert`'s word for what `patch` calls
        // `--comments none`: no comment from the patch reaches the target.
        // (The target's own are never stripped — they are what patch keeps.)
        if (strip_comments) {
            if (comments_given and patch_options.comments != .none) {
                log.err("--strip-comments carries no comment from the patch; --comments {s} asks for some. Pass one.\n", .{@tagName(patch_options.comments)});
                return ArgError.MissingPatchArgument;
            }
            patch_options.comments = .none;
        }
        if (!requested_help and positionals.items.items.len < 2) {
            log.err("patch takes two files: the document to change, then the one supplying the change.\n", .{});
            return ArgError.MissingPatchArgument;
        }
        if (!requested_help and positionals.items.items.len > 2) {
            log.err("patch takes two files; use --at/--from to name a path within one: {s}\n", .{positionals.items.items[2]});
            return ArgError.MissingPatchArgument;
        }
        // Both from a pipe would mean reading one stream twice and getting
        // half of each; the second read comes back empty and the failure is
        // an empty patch, which is silent. Refuse it up front.
        const target_path = if (positionals.items.items.len > 0) positionals.items.items[0] else "-";
        const source_path = if (positionals.items.items.len > 1) positionals.items.items[1] else "-";
        if (!requested_help and std.mem.eql(u8, target_path, "-") and std.mem.eql(u8, source_path, "-")) {
            log.err("only one of the two files can be stdin.\n", .{});
            return ArgError.MissingPatchArgument;
        }

        const target_ext: ?Detected = if (!requested_help) detectLanguageFromFileEnding(target_path) else null;
        const source_ext: ?Detected = if (!requested_help) detectLanguageFromFileEnding(source_path) else null;

        config.options = .{ .patch = .{
            .file = target_path,
            .patch_file = source_path,
            .at = at,
            .from = from,
            .deletes = try deletes.toOwnedSlice(allocator),
            .patch_options = patch_options,
            .requested_help = requested_help,
            .format = input_override orelse (if (target_ext) |d| d.format else null) orelse .json,
            .detect = !requested_help and input_override == null and target_ext == null,
            .patch_format = patch_input_override orelse (if (source_ext) |d| d.format else null) orelse .json,
            .detect_patch = !requested_help and patch_input_override == null and source_ext == null,
            .embed = embed_override,
            .detect_embed = embed_override == null and if (target_ext) |d| d.embed_detect else false,
            .patch_embed = patch_embed_override,
            .detect_patch_embed = patch_embed_override == null and if (source_ext) |d| d.embed_detect else false,
            .lossless = lossless,
            .dry_run = dry_run,
            .diff = diff_mode,
            .quiet = quiet,
            .strict = strict,
        } };
    } else if (std.mem.eql(u8, action_str, "lang")) {
        config.action = .lang;
        var opts: types.LangOptions = .{};
        var positionals: Positionals = .{};
        defer positionals.deinit(allocator);
        while (args.next()) |arg| {
            if (try positionals.rest(allocator, arg)) continue;
            if (isHelp(arg)) {
                opts.requested_help = true;
            } else if (std.mem.eql(u8, arg, "--against")) {
                opts.against = args.next() orelse {
                    log.err("Missing format after --against\n", .{});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (std.mem.eql(u8, arg, "--input") or std.mem.eql(u8, arg, "-i")) {
                const name = args.next() orelse {
                    log.err("Missing format after --input\n", .{});
                    return ArgError.UnsupportedFileFormat;
                };
                opts.input = parseFormatName(name) orelse {
                    log.err("Unsupported input format: {s}\n", .{name});
                    return ArgError.UnsupportedFileFormat;
                };
            } else if (std.mem.eql(u8, arg, "--spec") or std.mem.eql(u8, arg, "-s")) {
                opts.spec = args.next() orelse {
                    log.err("Missing version value after {s}\n", .{arg});
                    return ArgError.MissingLangArgument;
                };
            } else if (!try positionals.add(allocator, "lang", arg)) return ArgError.MissingLangArgument;
        }
        const pos = positionals.items.items;
        if (pos.len == 0 or std.mem.eql(u8, pos[0], "list")) {
            opts.verb = .list;
            if (!opts.requested_help and !positionals.atMost("lang list", 1, "no arguments")) return ArgError.MissingLangArgument;
        } else if (std.mem.eql(u8, pos[0], "check")) {
            opts.verb = .check;
            if (pos.len >= 2) {
                opts.name = pos[1];
                opts.files = try allocator.dupe([]const u8, pos[2..]);
            } else if (!opts.requested_help) {
                log.err("lang check needs a language name (e.g. `fig lang check lua-dotenv --against dotenv`).\n", .{});
                return ArgError.MissingLangArgument;
            }
        } else if (std.mem.eql(u8, pos[0], "table")) {
            opts.verb = .table;
            if (pos.len >= 2) {
                opts.name = pos[1];
                if (!opts.requested_help and !positionals.atMost("lang table", 2, "one file")) return ArgError.MissingLangArgument;
            } else if (!opts.requested_help) {
                log.err("lang table needs a file (e.g. `fig lang table secrets.env`).\n", .{});
                return ArgError.MissingLangArgument;
            }
        } else {
            log.err("Unknown lang verb: {s} (list, check, table)\n", .{pos[0]});
            return ArgError.MissingLangArgument;
        }
        config.options = .{ .lang = opts };
    } else if (externalCommandName(action_str)) |name| {
        // Git's fallback, and the reason fig-schema can grow a CLI without
        // fig growing a `schema` action: a word fig has no verb for is handed
        // to a `fig-<word>` executable. Everything after the word is passed
        // through untouched — see `ExternalOptions.argv` — so this branch
        // consumes the rest of the iterator and parses none of it.
        config.action = .external;
        const program = try std.fmt.allocPrint(allocator, "fig-{s}", .{name});
        var argv: std.ArrayList([]const u8) = .empty;
        try argv.append(allocator, program);
        while (args.next()) |arg| try argv.append(allocator, arg);
        config.options = .{ .external = .{
            .name = name,
            .program = program,
            .argv = try argv.toOwnedSlice(allocator),
        } };
    } else {
        // Not one of fig's verbs, and not a word that could name a program
        // either (`externalCommandName` says which shapes those are). Still
        // an `.external`: a null `program` means the handoff was never on the
        // table, so one place gets to say "no such action" for both halves of
        // the unrecognized case rather than two places saying it differently.
        config.action = .external;
        config.options = .{ .external = .{ .name = action_str, .program = null, .argv = &.{} } };
    }

    return config;
}

/// The `<name>` for a `fig-<name>` handoff, or null if this word can't be one
/// — in which case it stays an ordinary unrecognized action.
///
/// The rule is deliberately narrower than "whatever `execvp` would take".
/// Restricting it to ASCII letters, digits, `-` and `_` keeps two shapes out:
/// a leading `-`, so a mistyped flag (`fig --colour`) reports itself as a flag
/// instead of hunting for `fig---colour`; and anything containing a path
/// separator or a `.`, so a forgotten verb (`fig config.toml`, `fig ../x`)
/// can't reach the filesystem as a program name. That second one is the load-
/// bearing half: `argv[0]` with a separator in it bypasses PATH lookup
/// entirely and runs a file at that path, which is not something a typo should
/// be able to do.
fn externalCommandName(word: []const u8) ?[]const u8 {
    if (word.len == 0 or word[0] == '-') return null;
    for (word) |c| switch (c) {
        'a'...'z', 'A'...'Z', '0'...'9', '-', '_' => {},
        else => return null,
    };
    return word;
}

// A slice-backed stand-in for the process arg iterator `parseConfig` consumes.
const TestArgs = struct {
    items: []const []const u8,
    i: usize = 0,
    fn next(self: *TestArgs) ?[]const u8 {
        if (self.i >= self.items.len) return null;
        defer self.i += 1;
        return self.items[self.i];
    }
};

test "parsePath reads the [-]/[$] append sentinel and literal indices" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    const dash = try parsePath(a, "list[-]");
    try t.expectEqual(@as(usize, 2), dash.len);
    try t.expectEqualStrings("list", dash[0].key);
    try t.expectEqual(append_index, dash[1].index);

    const dollar = try parsePath(a, "list[$]");
    try t.expectEqual(append_index, dollar[1].index);

    const literal = try parsePath(a, "a.b[2]");
    try t.expectEqual(@as(usize, 2), literal[2].index);
}

test "parsePath takes a key with a `.` or `[` quoted, bracketed or escaped" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    for ([_][]const u8{ "a.\"b.c\"", "a.'b.c'", "a[\"b.c\"]", "a['b.c']", "a.b\\.c" }) |spelling| {
        const p = try parsePath(a, spelling);
        try t.expectEqual(@as(usize, 2), p.len);
        try t.expectEqualStrings("a", p[0].key);
        try t.expectEqualStrings("b.c", p[1].key);
    }
    // A quoted segment is followed by more path, and holds a `[` too.
    const deeper = try parsePath(a, "\"x[0]\".y[1]");
    try t.expectEqualStrings("x[0]", deeper[0].key);
    try t.expectEqualStrings("y", deeper[1].key);
    try t.expectEqual(@as(usize, 1), deeper[2].index);
    // Double quotes decode JSON's escapes, which is how gron prints a key.
    const esc = try parsePath(a, "[\"q\\\"\\u00e9\\ud83d\\ude00\"]");
    try t.expectEqualStrings("q\"\u{e9}\u{1f600}", esc[0].key);
    // Single quotes are verbatim.
    const lit = try parsePath(a, "'a\\n'");
    try t.expectEqualStrings("a\\n", lit[0].key);
    // An unclosed quote, a quote run into more key, and a trailing
    // backslash are refused.
    for ([_][]const u8{ "a.\"b", "a.'b", "a.\"b\"c", "a\\", "[\"b\"", "[\"\\x\"]" }) |bad|
        try t.expectError(ArgError.InvalidPath, parsePath(a, bad));
}

test "parseConfig routes insert/delete to the right action and path tail" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // insert into a mapping: trailing key, value captured.
    var ins = TestArgs{ .items = &.{ "fig", "insert", "f.yaml", "a.newkey", "42" } };
    const ic = try parseConfig(a, &ins);
    try t.expectEqual(CliAction.insert, ic.action);
    try t.expectEqualStrings("newkey", ic.options.insert.path[1].key);
    try t.expectEqualStrings("42", ic.options.insert.value);
    try t.expectEqual(Format.yaml, ic.options.insert.format);

    // insert append onto a sequence: trailing sentinel index.
    var app = TestArgs{ .items = &.{ "fig", "insert", "f.yaml", "list[-]", "z" } };
    const ac = try parseConfig(a, &app);
    try t.expectEqual(append_index, ac.options.insert.path[1].index);

    // delete by index: format sniffed later, path tail is an index.
    var del = TestArgs{ .items = &.{ "fig", "delete", "f.toml", "list[1]" } };
    const dc = try parseConfig(a, &del);
    try t.expectEqual(CliAction.delete, dc.action);
    try t.expectEqual(@as(usize, 1), dc.options.delete.path[1].index);
    try t.expectEqual(Format.toml, dc.options.delete.format);
}

test "parseTarget names the file a failed action is re-parsed from, and its format" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // An in-place edit: the file and the format its extension named.
    var set = TestArgs{ .items = &.{ "fig", "set", "f.yaml", "a", "1" } };
    const st = types.parseTarget(try parseConfig(a, &set)).?;
    try t.expectEqualStrings("f.yaml", st.file);
    try t.expectEqual(@as(?Format, .yaml), st.format);

    // A read: its `from` format.
    var get = TestArgs{ .items = &.{ "fig", "get", "f.toml" } };
    try t.expectEqual(@as(?Format, .toml), types.parseTarget(try parseConfig(a, &get)).?.format);

    // A host document: the region is the extension's to find, so no format
    // is forced onto the whole file.
    var md = TestArgs{ .items = &.{ "fig", "set", "notes.md", "a", "1" } };
    try t.expectEqual(@as(?Format, null), types.parseTarget(try parseConfig(a, &md)).?.format);

    // stdin has been read once already, and `check` reports for itself.
    var stdin = TestArgs{ .items = &.{ "fig", "get", "-", "-i", "json" } };
    try t.expect(types.parseTarget(try parseConfig(a, &stdin)) == null);
    var check = TestArgs{ .items = &.{ "fig", "check", "f.yaml" } };
    try t.expect(types.parseTarget(try parseConfig(a, &check)) == null);
}

test "parseConfig hands an unknown action to fig-<action> with its arguments untouched" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // The case this exists for. Note `--help` and `check`: fig owns both
    // words, and neither is parsed here — everything after `schema` is the
    // other tool's to read.
    var ext = TestArgs{ .items = &.{ "fig", "schema", "check", "--help", "-" } };
    const ec = try parseConfig(a, &ext);
    try t.expectEqual(CliAction.external, ec.action);
    try t.expectEqualStrings("schema", ec.options.external.name);
    try t.expectEqualStrings("fig-schema", ec.options.external.program.?);
    try t.expectEqual(@as(usize, 4), ec.options.external.argv.len);
    try t.expectEqualStrings("fig-schema", ec.options.external.argv[0]);
    try t.expectEqualStrings("check", ec.options.external.argv[1]);
    try t.expectEqualStrings("--help", ec.options.external.argv[2]);
    try t.expectEqualStrings("-", ec.options.external.argv[3]);

    // The program name is `fig-`, not `argv[0]-`: what fig was invoked as
    // says nothing about what its siblings are installed as.
    var qualified = TestArgs{ .items = &.{ "./zig-out/bin/fig", "schema" } };
    const qc = try parseConfig(a, &qualified);
    try t.expectEqualStrings("fig-schema", qc.options.external.program.?);

    // A word that can't name a program is still `.external` — with a null
    // `program`, so the report knows PATH was never searched.
    for ([_][]const u8{ "config.toml", "--colour", "../evil", "a/b" }) |word| {
        var bad = TestArgs{ .items = &.{ "fig", word } };
        const bc = try parseConfig(a, &bad);
        try t.expectEqual(CliAction.external, bc.action);
        try t.expectEqualStrings(word, bc.options.external.name);
        try t.expectEqual(@as(?[]const u8, null), bc.options.external.program);
    }

    // ...and an action fig does own never gets there, alias included.
    var owned = TestArgs{ .items = &.{ "fig", "ck", "f.yaml" } };
    try t.expectEqual(CliAction.check, (try parseConfig(a, &owned)).action);
}

test "externalCommandName accepts only words that could name a program" {
    const t = std.testing;
    try t.expectEqualStrings("schema", externalCommandName("schema").?);
    try t.expectEqualStrings("two-words_9", externalCommandName("two-words_9").?);
    // A leading `-` is a mistyped flag, not a subcommand.
    try t.expectEqual(@as(?[]const u8, null), externalCommandName("-x"));
    try t.expectEqual(@as(?[]const u8, null), externalCommandName("--colour"));
    // Anything with a separator or a dot is a path or a filename the user
    // meant to give an action. A separator in argv[0] would skip PATH lookup
    // and execute that file, which no typo should be able to do.
    try t.expectEqual(@as(?[]const u8, null), externalCommandName("./x"));
    try t.expectEqual(@as(?[]const u8, null), externalCommandName("../../tmp/x"));
    try t.expectEqual(@as(?[]const u8, null), externalCommandName("a\\b"));
    try t.expectEqual(@as(?[]const u8, null), externalCommandName("config.toml"));
    try t.expectEqual(@as(?[]const u8, null), externalCommandName(""));
}

test "embedTypeFromName maps archetype names" {
    const t = std.testing;
    try t.expectEqual(@as(?fig.Embed.Type, .{ .frontmatter = .yaml }), embedTypeFromName("frontmatter"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .frontmatter = .yaml }), embedTypeFromName("frontmatter-yaml"));
    try t.expectEqual(@as(?fig.Embed.Type, null), embedTypeFromName("frontmatter-json"));
    try t.expectEqual(@as(?fig.Embed.Type, null), embedTypeFromName("frontmatter-fig"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .frontmatter = .toml }), embedTypeFromName("md-toml"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .fenced = .yaml }), embedTypeFromName("fenced-yaml"));
    try t.expectEqual(@as(?fig.Embed.Type, null), embedTypeFromName("frontmatter-toml"));
    try t.expectEqual(@as(?fig.Embed.Type, .endmatter_yaml), embedTypeFromName("endmatter"));
    try t.expectEqual(@as(?fig.Embed.Type, null), embedTypeFromName("bogus"));

    // The parametric families are derived over the format registry, so the
    // ACCEPTED SET is what needs pinning rather than any one row: all four
    // formats in each of the three `<container>-<format>` families, plus the
    // three-of-four `md-<format>` one, and nothing else.
    try t.expectEqual(@as(?fig.Embed.Type, .{ .fenced = .json }), embedTypeFromName("fenced-json"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .fenced = .toml }), embedTypeFromName("fenced-toml"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .fenced = .fig }), embedTypeFromName("fenced-fig"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .frontmatter = .json }), embedTypeFromName("md-json"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .frontmatter = .fig }), embedTypeFromName("md-fig"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_script = .fig }), embedTypeFromName("html-script"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_script = .fig }), embedTypeFromName("html-script-fig"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_script = .yaml }), embedTypeFromName("html-script-yaml"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_script = .json }), embedTypeFromName("html-script-json"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_script = .toml }), embedTypeFromName("html-script-toml"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_code = .fig }), embedTypeFromName("html-code"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_code = .fig }), embedTypeFromName("html-code-fig"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_code = .yaml }), embedTypeFromName("html-code-yaml"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_code = .json }), embedTypeFromName("html-code-json"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .html_code = .toml }), embedTypeFromName("html-code-toml"));
    try t.expectEqual(@as(?fig.Embed.Type, .semicolons_json), embedTypeFromName("semicolons"));
    try t.expectEqual(@as(?fig.Embed.Type, .plus_toml), embedTypeFromName("plus"));
    try t.expectEqual(@as(?fig.Embed.Type, .endmatter_yaml), embedTypeFromName("endmatter-yaml"));

    // Deliberately NOT spellings: `md-yaml` (a bare `---` block IS YAML
    // frontmatter — `frontmatter`/`frontmatter-yaml` name it), and the
    // container names that never had a bare form.
    try t.expectEqual(@as(?fig.Embed.Type, null), embedTypeFromName("md-yaml"));
    try t.expectEqual(@as(?fig.Embed.Type, null), embedTypeFromName("fenced"));
    try t.expectEqual(@as(?fig.Embed.Type, null), embedTypeFromName("md"));
}

test "detectLanguageFromFileEnding: .md/.markdown defer the archetype to a runtime sniff" {
    // The extension table is derived from each compiled-in language's own
    // `extensions`, so a gated-out language contributes none — `.yaml`/`.figl`
    // below simply have no entry in a build without YAML/fig.
    if (comptime !(build_options.lang_yaml and build_options.lang_fig)) return error.SkipZigTest;
    const t = std.testing;
    const md = detectLanguageFromFileEnding("post.md").?;
    try t.expectEqual(Format.yaml, md.format);
    try t.expect(md.embed_detect);

    const markdown = detectLanguageFromFileEnding("post.markdown").?;
    try t.expect(markdown.embed_detect);

    // Other extensions imply no embed at all.
    const yaml = detectLanguageFromFileEnding("f.yaml").?;
    try t.expect(!yaml.embed_detect);

    const figl_ext = detectLanguageFromFileEnding("f.figl").?;
    try t.expectEqual(Format.fig, figl_ext.format);
    try t.expect(!figl_ext.embed_detect);

    // `.fig` is not an extension of the format any more (5.0).
    try t.expect(detectLanguageFromFileEnding("f.fig") == null);
}

test "yml is an accepted spelling of yaml, as a --input value and as an extension" {
    const t = std.testing;
    if (comptime !build_options.lang_yaml) return error.SkipZigTest;

    // `--input yml`: the alias line above, not an enum member of its own.
    try t.expectEqual(@as(?Format, .yaml), parseFormatName("yml"));
    try t.expectEqual(@as(?Format, .yaml), parseFormatName("yaml"));

    // `.yml` files: `stringToEnum` no longer answers for the extension, so it
    // falls through to `Language.YAML.extensions`, which owns both spellings —
    // the same `.yaml` parse either way.
    const yml_ext = detectLanguageFromFileEnding("f.yml").?;
    try t.expectEqual(Format.yaml, yml_ext.format);
    try t.expect(!yml_ext.embed_detect);
    try t.expectEqual(Format.yaml, detectLanguageFromFileEnding("f.yaml").?.format);

    // An unknown token is still unknown (the alias must not widen the lookup).
    try t.expectEqual(@as(?Format, null), parseFormatName("yamll"));
}

test "resolveEmbedTypeFromContent: explicit override wins, else sniffs, else falls back to YAML" {
    const t = std.testing;

    // An explicit override always wins, regardless of content.
    try t.expectEqual(@as(?fig.Embed.Type, .endmatter_yaml), resolveEmbedTypeFromContent("anything", .endmatter_yaml, true));

    // Not a detect_embed case at all (e.g. a plain .json file): no embed.
    try t.expectEqual(@as(?fig.Embed.Type, null), resolveEmbedTypeFromContent("{}", null, false));

    // detect_embed sniffs the real archetype from the bytes — this is the
    // fig-frontmatter regression: a `.md` file whose actual content is a
    // ```fig fenced block must resolve to FrontmatterFig, not be assumed to
    // be YAML just because the extension is `.md`.
    try t.expectEqual(
        @as(?fig.Embed.Type, .{ .fenced = .fig }),
        resolveEmbedTypeFromContent("```fig\ntitle = hi\n```\nbody\n", null, true),
    );
    try t.expectEqual(
        @as(?fig.Embed.Type, .semicolons_json),
        resolveEmbedTypeFromContent(";;;\n{\"a\":1}\n;;;\nbody\n", null, true),
    );
    try t.expectEqual(
        @as(?fig.Embed.Type, .{ .frontmatter = .yaml }),
        resolveEmbedTypeFromContent("---\na: 1\n---\nbody\n", null, true),
    );

    // Nothing detected at all (e.g. a brand-new/plain host file): falls back
    // to the historical FrontmatterYaml default rather than `null`, so `set`'s
    // open-or-init still seeds the same archetype it always has.
    try t.expectEqual(@as(?fig.Embed.Type, .{ .frontmatter = .yaml }), resolveEmbedTypeFromContent("just prose\n", null, true));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .frontmatter = .yaml }), resolveEmbedTypeFromContent("", null, true));
}

test "parseConfig routes patch: both files, both sides' formats, and the merge strategies" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // Two positionals, in order: the file being changed, then the one
    // supplying the change. Each side resolves its own format from its own
    // extension, so a cross-format patch needs no flags at all.
    var basic = TestArgs{ .items = &.{ "fig", "patch", "config.yaml", "overlay.toml" } };
    const b = try parseConfig(a, &basic);
    try t.expectEqual(CliAction.patch, b.action);
    try t.expectEqualStrings("config.yaml", b.options.patch.file);
    try t.expectEqualStrings("overlay.toml", b.options.patch.patch_file);
    try t.expectEqual(Format.yaml, b.options.patch.format);
    try t.expectEqual(Format.toml, b.options.patch.patch_format);
    try t.expect(!b.options.patch.detect);
    try t.expect(!b.options.patch.detect_patch);
    // The defaults are the conservative ones: the target's comments stand and
    // a sequence is taken whole.
    try t.expectEqual(fig.Patch.SeqStrategy.replace, b.options.patch.patch_options.seq);
    try t.expectEqual(fig.Patch.CommentStrategy.ours, b.options.patch.patch_options.comments);

    // `--at`/`--from` are separate paths into separate documents.
    var paths = TestArgs{ .items = &.{ "fig", "patch", "a.yaml", "b.yaml", "--at", "service.db", "--from", "db" } };
    const p = try parseConfig(a, &paths);
    try t.expectEqual(@as(usize, 2), p.options.patch.at.len);
    try t.expectEqualStrings("service", p.options.patch.at[0].key);
    try t.expectEqualStrings("db", p.options.patch.at[1].key);
    try t.expectEqual(@as(usize, 1), p.options.patch.from.len);
    try t.expectEqualStrings("db", p.options.patch.from[0].key);

    // `--delete` accumulates; `union` is the CLI spelling of `.unite` (the
    // enum can't be called `union`).
    var strat = TestArgs{ .items = &.{
        "fig",      "patch", "a.yaml",     "b.yaml",
        "--seq",    "union", "--comments", "theirs",
        "--delete", "x.y",   "--delete",   "z[2]",
    } };
    const s = try parseConfig(a, &strat);
    try t.expectEqual(fig.Patch.SeqStrategy.unite, s.options.patch.patch_options.seq);
    try t.expectEqual(fig.Patch.CommentStrategy.theirs, s.options.patch.patch_options.comments);
    try t.expectEqual(@as(usize, 2), s.options.patch.deletes.len);
    try t.expectEqualStrings("x", s.options.patch.deletes[0][0].key);
    try t.expectEqual(@as(usize, 2), s.options.patch.deletes[1][1].index);

    // A `.md` on either side implies SOME embedded region but never which
    // archetype, so each side defers to its own runtime sniff — the same rule
    // the other actions follow.
    var md = TestArgs{ .items = &.{ "fig", "patch", "post.md", "meta.md" } };
    const m = try parseConfig(a, &md);
    try t.expect(m.options.patch.detect_embed);
    try t.expect(m.options.patch.detect_patch_embed);
    try t.expectEqual(@as(?fig.Embed.Type, null), m.options.patch.embed);

    // An explicit archetype pins one side without touching the other.
    var pinned = TestArgs{ .items = &.{ "fig", "patch", "post.md", "meta.md", "--embed", "endmatter" } };
    const pin = try parseConfig(a, &pinned);
    try t.expectEqual(@as(?fig.Embed.Type, .endmatter_yaml), pin.options.patch.embed);
    try t.expect(!pin.options.patch.detect_embed);
    try t.expect(pin.options.patch.detect_patch_embed);

    // Unknown extensions on both sides defer both formats to a content sniff.
    var sniff = TestArgs{ .items = &.{ "fig", "patch", "a.weird", "-" } };
    const sn = try parseConfig(a, &sniff);
    try t.expect(sn.options.patch.detect);
    try t.expect(sn.options.patch.detect_patch);

    // The rejections (fewer or more than two files, both files stdin, an
    // unknown --seq/--comments strategy, a rootless --delete) all return
    // `ArgError.MissingPatchArgument` after a `log.err`, which this test
    // binary's runner counts as a failure regardless — see the note in the
    // `convert` test above.
}

test "parseConfig routes set, --seq, and --embed" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // Scalar upsert: path + value captured, format from extension.
    var s = TestArgs{ .items = &.{ "fig", "set", "f.yaml", "a.b", "1" } };
    const sc = try parseConfig(a, &s);
    try t.expectEqual(CliAction.set, sc.action);
    try t.expectEqualStrings("b", sc.options.set.path[1].key);
    try t.expectEqualStrings("1", sc.options.set.value);
    try t.expect(!sc.options.set.seq);
    try t.expectEqual(Format.yaml, sc.options.set.format);

    // --seq collects the trailing items into `values`.
    var sq = TestArgs{ .items = &.{ "fig", "set", "--seq", "f.yaml", "tags", "x", "y", "z" } };
    const sqc = try parseConfig(a, &sq);
    try t.expect(sqc.options.set.seq);
    try t.expectEqual(@as(usize, 3), sqc.options.set.values.len);
    try t.expectEqualStrings("z", sqc.options.set.values[2]);

    // --embed selects the archetype explicitly (endmatter here).
    var em = TestArgs{ .items = &.{ "fig", "set", "--embed", "endmatter", "post.md", "k", "v" } };
    const emc = try parseConfig(a, &em);
    try t.expectEqual(@as(?fig.Embed.Type, .endmatter_yaml), emc.options.set.embed);

    // --embed fenced-fig routes to the fig-fenced archetype.
    var fm = TestArgs{ .items = &.{ "fig", "set", "--embed", "fenced-fig", "post.md", "k", "v" } };
    const fmc = try parseConfig(a, &fm);
    try t.expectEqual(@as(?fig.Embed.Type, .{ .fenced = .fig }), fmc.options.set.embed);

    // No --embed on a `.md` file: the fix for the fig-frontmatter
    // autodetection bug — `embed` stays null and `detect_embed` fires, so
    // the handler sniffs the actual archetype from the file's bytes at
    // runtime instead of the extension alone assuming YAML frontmatter.
    var md = TestArgs{ .items = &.{ "fig", "set", "post.md", "k", "v" } };
    const mdc = try parseConfig(a, &md);
    try t.expectEqual(@as(?fig.Embed.Type, null), mdc.options.set.embed);
    try t.expect(mdc.options.set.detect_embed);
}

test "parseConfig routes convert: whole-file mode, embed mode, and their guards" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // Whole-file mode: --input/--output resolve `from`/`to` directly.
    var wf = TestArgs{ .items = &.{ "fig", "convert", "-i", "yaml", "-o", "toml", "f.yaml" } };
    const wfc = try parseConfig(a, &wf);
    try t.expectEqual(CliAction.convert, wfc.action);
    try t.expectEqual(Format.yaml, wfc.options.convert.from);
    try t.expectEqual(Format.toml, wfc.options.convert.to);
    try t.expectEqual(@as(?fig.Embed.Type, null), wfc.options.convert.to_embed);
    try t.expect(!wfc.options.convert.detect);

    // Whole-file mode with an unrecognized extension: `--output` alone still
    // needs `from` sniffed at runtime.
    var det = TestArgs{ .items = &.{ "fig", "convert", "-o", "json", "f.weirdext" } };
    const detc = try parseConfig(a, &det);
    try t.expect(detc.options.convert.detect);

    // Embed mode: --to-embed alone (no --embed) defers source detection to
    // the handler (`detect_embed`); the file extension doesn't imply an
    // archetype here (not .md), so `embed` stays null.
    var em = TestArgs{ .items = &.{ "fig", "convert", "--to-embed", "semicolons", "f.txt" } };
    const emc = try parseConfig(a, &em);
    try t.expectEqual(@as(?fig.Embed.Type, .semicolons_json), emc.options.convert.to_embed);
    try t.expectEqual(@as(?fig.Embed.Type, null), emc.options.convert.embed);
    try t.expect(emc.options.convert.detect_embed);

    // Embed mode on a `.md` file: the extension alone only implies SOME
    // embedded region, never which archetype — `embed` stays null and
    // `detect_embed` fires so the handler sniffs the actual fences at
    // runtime instead of assuming YAML frontmatter outright.
    var md = TestArgs{ .items = &.{ "fig", "convert", "--to-embed", "semicolons", "post.md" } };
    const mdc = try parseConfig(a, &md);
    try t.expectEqual(@as(?fig.Embed.Type, null), mdc.options.convert.embed);
    try t.expect(mdc.options.convert.detect_embed);

    // Embed mode: explicit --embed overrides the extension default.
    var ov = TestArgs{ .items = &.{ "fig", "convert", "--embed", "endmatter", "--to-embed", "fenced-fig", "post.md" } };
    const ovc = try parseConfig(a, &ov);
    try t.expectEqual(@as(?fig.Embed.Type, .endmatter_yaml), ovc.options.convert.embed);
    try t.expectEqual(@as(?fig.Embed.Type, .{ .fenced = .fig }), ovc.options.convert.to_embed);

    // The four guard rejections (no target at all; --output+--to-embed
    // together; --embed without --to-embed; whole-file --output on a `.md`
    // host document without an explicit --input) all return
    // `ArgError.MissingConvertArgument` after a `log.err` — verified manually
    // against the built CLI rather than here, since this test binary's
    // default runner (Zig 0.16) fails any test that logs at `.err`
    // regardless of whether the returned error was expected (see
    // `test_runner.zig`'s `log_err_count`), the same reason no other
    // `parseConfig` error path in this file is exercised as a unit test.

    // An explicit --input forces whole-file conversion on a `.md` file anyway.
    var mdforced = TestArgs{ .items = &.{ "fig", "convert", "-i", "yaml", "-o", "toml", "post.md" } };
    const mdforcedc = try parseConfig(a, &mdforced);
    try t.expectEqual(Format.yaml, mdforcedc.options.convert.from);
    try t.expect(!mdforcedc.options.convert.detect);
}

test "parseConfig: --lang is taken from anywhere in the line and names the format" {
    if (comptime !build_options.lang_json) return error.SkipZigTest;
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    var args = TestArgs{ .items = &.{ "fig", "get", "secrets.env", "--lang", "json" } };
    const config = try parseConfig(a, &args);
    try t.expectEqual(types.CliAction.get, config.action);
    try t.expectEqualStrings("secrets.env", config.options.get.file);
    try t.expectEqual(Format.json, languages.langOverride().?);
    // The override is what the extension would otherwise decide.
    try t.expectEqual(Format.json, detectLanguageFromFileEnding("secrets.env").?.format);
    languages.setLangOverride(.yaml);
    try t.expectEqual(Format.yaml, detectLanguageFromFileEnding("secrets.env").?.format);

    // `--lang nosuch` and a bare `--lang` return `UnsupportedFileFormat`
    // after a `log.err` — the test runner counts a logged error as a
    // failure, so that path is proven by `tools/cli-lang-check.sh` instead.
    languages.setLangOverride(null);
}

test "parseConfig routes lang: list by default, check with a name, --against and files, table with -i" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    var bare = TestArgs{ .items = &.{ "fig", "lang" } };
    const c1 = try parseConfig(a, &bare);
    try t.expectEqual(types.CliAction.lang, c1.action);
    try t.expectEqual(types.LangOptions.Verb.list, c1.options.lang.verb);

    var check = TestArgs{ .items = &.{ "fig", "lang", "check", "lua-dotenv", "--against", "dotenv", "a.env", "b.env" } };
    const c2 = try parseConfig(a, &check);
    try t.expectEqual(types.LangOptions.Verb.check, c2.options.lang.verb);
    try t.expectEqualStrings("lua-dotenv", c2.options.lang.name);
    try t.expectEqualStrings("dotenv", c2.options.lang.against.?);
    try t.expectEqual(@as(usize, 2), c2.options.lang.files.len);
    try t.expectEqualStrings("b.env", c2.options.lang.files[1]);

    var table = TestArgs{ .items = &.{ "fig", "lang", "table", "secrets.env", "-i", "json" } };
    const ct = try parseConfig(a, &table);
    try t.expectEqual(types.LangOptions.Verb.table, ct.options.lang.verb);
    try t.expectEqualStrings("secrets.env", ct.options.lang.name);
    try t.expectEqual(Format.json, ct.options.lang.input.?);
    try t.expect(ct.options.lang.spec == null);

    var versioned = TestArgs{ .items = &.{ "fig", "lang", "table", "a.yaml", "--spec", "1.1" } };
    const cv = try parseConfig(a, &versioned);
    try t.expectEqualStrings("1.1", cv.options.lang.spec.?);

    // `check --help` asks for the help text without a name.
    var helpful = TestArgs{ .items = &.{ "fig", "lang", "check", "--help" } };
    const c3 = try parseConfig(a, &helpful);
    try t.expect(c3.options.lang.requested_help);
}

test "parseConfig: `--` ends the flags, a negative number is a value, and flags stand anywhere" {
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // A file whose name begins with `-`, after `--`.
    var dashed = TestArgs{ .items = &.{ "fig", "get", "--", "-x.yaml", "a" } };
    const dc = try parseConfig(a, &dashed);
    try t.expectEqualStrings("-x.yaml", dc.options.get.file);
    try t.expectEqualStrings("a", dc.options.get.path.?[0].key);

    // A value that begins with `-`: a number stands on its own, anything
    // else goes after `--`, and `--help` there is a value too.
    var neg = TestArgs{ .items = &.{ "fig", "set", "f.yaml", "n", "-5" } };
    try t.expectEqualStrings("-5", (try parseConfig(a, &neg)).options.set.value);
    var frac = TestArgs{ .items = &.{ "fig", "insert", "f.yaml", "n", "-.5" } };
    try t.expectEqualStrings("-.5", (try parseConfig(a, &frac)).options.insert.value);
    var word = TestArgs{ .items = &.{ "fig", "replace", "f.yaml", "n", "--", "--help" } };
    const wc = try parseConfig(a, &word);
    try t.expect(!wc.options.replace.requested_help);
    try t.expectEqualStrings("--help", wc.options.replace.replacement);

    // `-` alone is stdin, not a flag.
    var stdin = TestArgs{ .items = &.{ "fig", "delete", "-", "a" } };
    try t.expectEqualStrings("-", (try parseConfig(a, &stdin)).options.delete.file);

    // A flag after the positionals is still a flag.
    var late = TestArgs{ .items = &.{ "fig", "comment", "f.yaml", "a", "--get", "--inline" } };
    const lc = try parseConfig(a, &late);
    try t.expect(lc.options.comment.get and lc.options.comment.inline_comment);
    var key = TestArgs{ .items = &.{ "fig", "rename", "f.yaml", "a", "b" } };
    const kc = try parseConfig(a, &key);
    try t.expectEqual(CliAction.rename, kc.action);
    try t.expect(kc.options.rename.key);
    try t.expectEqualStrings("b", kc.options.rename.replacement);
    var value = TestArgs{ .items = &.{ "fig", "replace", "f.yaml", "a", "b", "--string" } };
    const vc = try parseConfig(a, &value);
    try t.expect(!vc.options.replace.key);
    try t.expectEqual(types.ValueMode.string, vc.options.replace.value_mode);

    // `--lang` after `--` is a positional, not the global flag.
    var lang = TestArgs{ .items = &.{ "fig", "check", "--", "--lang" } };
    const lgc = try parseConfig(a, &lang);
    try t.expectEqualStrings("--lang", lgc.options.check.files[0]);
    try t.expectEqual(@as(?Format, null), languages.langOverride());

    // The refusals (an unknown flag, one positional too many) return the
    // action's usage error after a `log.err`, which this runner counts as a
    // failure — `tools/cli-args-check.sh` drives them through the binary.
}

test "spelledAsFlag: a leading `-` is a flag unless it starts a number or stands alone" {
    const t = std.testing;
    for ([_][]const u8{ "-x", "--bogus", "-h", "--", "-inf", "-nan" }) |s| try t.expect(spelledAsFlag(s));
    for ([_][]const u8{ "-", "-5", "-0.5", "-.5", "x", "" }) |s| try t.expect(!spelledAsFlag(s));
}

test "parseConfig: a `--` that is a flag's value does not end the flags for --lang" {
    if (comptime !build_options.lang_json) return error.SkipZigTest;
    const t = std.testing;
    var arena = std.heap.ArenaAllocator.init(t.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    defer languages.setLangOverride(null);

    var args = TestArgs{ .items = &.{ "fig", "get", "f.txt", "--gron-sep", "--", "--lang", "json" } };
    const config = try parseConfig(a, &args);
    try t.expectEqualStrings("--", config.options.get.gron_projection.assign);
    try t.expectEqual(Format.json, languages.langOverride().?);
}