fig-sys 3.4.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
//! 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 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 .yaml;
    return std.meta.stringToEnum(Format, name);
}

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;
            },
            '[' => {
                // 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;
            },
            else => {
                const start = i;
                // Loop until a dot or open bracket
                while (i < path.len and path[i] != '.' and path[i] != '[') : (i += 1) {}
                if (i == start) return ArgError.InvalidPath;
                const key = path[start..i];

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

/// 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 {
    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.
    if (std.meta.stringToEnum(Format, ext)) |format| return .{ .format = 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 canonical extension — `.fig` is the
    // back-compat spelling, and matches the enum anyway), `.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 };

    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: legacy
    // spellings that predate the parametric families, and the blessed presets
    // whose delimiter is its own distinct token rather than a language tag.
    //
    // Markdown `---` frontmatter (bare ⇒ yaml; see the `md-yaml` note above).
    if (eql(u8, name, "frontmatter") or eql(u8, name, "frontmatter-yaml")) return .{ .frontmatter = .yaml };
    // `frontmatter-fig` is the legacy alias of `fenced-fig` — it names a FENCED
    // block, not `---fig` frontmatter, which is why it cannot ride the loop.
    if (eql(u8, name, "frontmatter-fig")) return .{ .fenced = .fig };
    // Blessed distinct-delimiter presets (`frontmatter-json/-toml` are the
    // historical names for the `;;;`/`+++` blocks).
    if (eql(u8, name, "semicolons") or eql(u8, name, "frontmatter-json")) return .semicolons_json;
    if (eql(u8, name, "plus") or eql(u8, name, "frontmatter-toml")) 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 legacy-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.
pub const embed_archetype_names = "frontmatter, md-json, md-toml, md-fig, fenced-yaml, fenced-json, fenced-toml, fenced-fig, frontmatter-json (;;;), frontmatter-toml (+++), html-script[-yaml/json/toml], html-code[-yaml/json/toml], endmatter";

/// 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 frontmatter-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.)
pub fn embedFormat(t: fig.Embed.Type) Format {
    return 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 e;
    if (!detect_embed) return null;
    return fig.Embed.detect(content) orelse .{ .frontmatter = .yaml };
}

/// 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 e;
    if (!detect_embed) return null;
    const content = try fileio.readAll(allocator, io, input);
    defer allocator.free(content);
    return fig.Embed.detect(content) orelse .{ .frontmatter = .yaml };
}

pub fn parseConfig(allocator: std.mem.Allocator, args: anytype) ArgError!CliConfig {
    const log = std.log.scoped(.parseConfig);
    var config = CliConfig{};
    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 } };
    } 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 = .{} };
    } else if (std.mem.eql(u8, action_str, "edit") or std.mem.eql(u8, action_str, "e")) {
        config.action = .edit;

        var edit_key = false;
        var file_path_arg = args.next();
        if (file_path_arg) |arg| {
            if (std.mem.eql(u8, arg, "--key")) {
                edit_key = true;
                file_path_arg = args.next();
            }
        }
        const file_path = file_path_arg orelse {
            log.err("No file provided.\n", .{});
            return ArgError.MissingEditArgument;
        };

        const requested_help = std.mem.eql(u8, file_path, "--help") or std.mem.eql(u8, file_path, "-h");

        var path: []fig.AST.PathSegment = &.{};
        var replacement: []const u8 = "";
        if (!requested_help) {
            const path_str = args.next() orelse {
                log.err("No path provided.\n", .{});
                return ArgError.MissingEditArgument;
            };
            path = try parsePath(allocator, path_str);

            replacement = args.next() orelse {
                log.err("No replacement provided.\n", .{});
                return ArgError.MissingEditArgument;
            };
        }

        // Skip extension detection when the user only asked for help (the
        // "file" is then `--help`, which has no real format). 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);
        config.options = .{ .edit = .{
            .file = file_path,
            .path = path,
            .replacement = replacement,
            .key = edit_key,
            .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, "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 embed_override: ?fig.Embed.Type = null;
        var requested_help = false;
        var positionals: std.ArrayList([]const u8) = .empty;
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
                requested_help = true;
            } else if (std.mem.eql(u8, arg, "--seq")) {
                seq = true;
            } 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.UnsupportedFileFormat;
                };
            } else {
                try positionals.append(allocator, arg);
            }
        }

        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 (positionals.items.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;
            }
            const file_path = positionals.items[0];
            const path = try parsePath(allocator, positionals.items[1]);
            const ext = detectLanguageFromFileEnding(file_path);
            const embed = embed_override;
            config.options = .{
                .set = .{
                    .file = file_path,
                    .path = path,
                    .value = if (seq) "" else positionals.items[2],
                    .seq = seq,
                    .values = if (seq) try allocator.dupe([]const u8, positionals.items[2..]) else &.{},
                    .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;

        const file_path = args.next() orelse {
            log.err("No file provided.\n", .{});
            return ArgError.MissingInsertArgument;
        };
        const requested_help = std.mem.eql(u8, file_path, "--help") or std.mem.eql(u8, file_path, "-h");

        var path: []fig.AST.PathSegment = &.{};
        var value: []const u8 = "";
        if (!requested_help) {
            const path_str = args.next() orelse {
                log.err("No path provided.\n", .{});
                return ArgError.MissingInsertArgument;
            };
            path = try parsePath(allocator, path_str);

            value = args.next() orelse {
                log.err("No value provided.\n", .{});
                return ArgError.MissingInsertArgument;
            };
        }

        const ext = if (requested_help) null else detectLanguageFromFileEnding(file_path);
        config.options = .{ .insert = .{
            .file = file_path,
            .path = path,
            .value = value,
            .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;

        const file_path = args.next() orelse {
            log.err("No file provided.\n", .{});
            return ArgError.MissingDeleteArgument;
        };
        const requested_help = std.mem.eql(u8, file_path, "--help") or std.mem.eql(u8, file_path, "-h");

        var path: []fig.AST.PathSegment = &.{};
        if (!requested_help) {
            const path_str = args.next() orelse {
                log.err("No path provided.\n", .{});
                return ArgError.MissingDeleteArgument;
            };
            path = try parsePath(allocator, path_str);
        }

        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;

        // Leading flags, in any order: `--inline`, `--delete`, `--get`. Consume
        // them until the first non-flag token (the file).
        var inline_comment = false;
        var delete = false;
        var get = false;
        var file_path_arg = args.next();
        while (file_path_arg) |arg| {
            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 break;
            file_path_arg = args.next();
        }
        const file_path = file_path_arg orelse {
            log.err("No file provided.\n", .{});
            return ArgError.MissingCommentArgument;
        };

        const requested_help = std.mem.eql(u8, file_path, "--help") or std.mem.eql(u8, file_path, "-h");

        var path: []fig.AST.PathSegment = &.{};
        var text: []const u8 = "";
        if (!requested_help) {
            const path_str = args.next() orelse {
                log.err("No path provided.\n", .{});
                return ArgError.MissingCommentArgument;
            };
            path = try parsePath(allocator, path_str);

            // Delete/get need no text; add/set requires it.
            if (!delete and !get) {
                text = args.next() orelse {
                    log.err("No comment text provided.\n", .{});
                    return ArgError.MissingCommentArgument;
                };
            }
        }

        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 positionals: std.ArrayList([]const u8) = .empty;
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            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.UnsupportedFileFormat;
                };
            } 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 {
                try positionals.append(allocator, arg);
            }
        }

        const file_path = if (positionals.items.len > 0) positionals.items[0] else {
            log.err("No file provided.\n", .{});
            return ArgError.MissingGetArgument;
        };

        const requested_help = std.mem.eql(u8, file_path, "--help") or std.mem.eql(u8, file_path, "-h");

        var path: ?[]fig.AST.PathSegment = null;
        if (!requested_help and positionals.items.len > 1) {
            path = try parsePath(allocator, positionals.items[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 frontmatter-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 requested_help = false;
        var files: std.ArrayList([]const u8) = .empty;
        defer files.deinit(allocator);

        while (args.next()) |arg| {
            if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
                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, "--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 {
                try files.append(allocator, arg);
            }
        }

        if (!requested_help and files.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.toOwnedSlice(allocator),
                .format = input_override,
                .spec = spec,
                .quiet = quiet,
                .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: std.ArrayList([]const u8) = .empty;
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
                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.UnsupportedFileFormat;
                };
            } 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 {
                try positionals.append(allocator, arg);
            }
        }

        if (!requested_help and positionals.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`/`edit`/etc. take one.
        if (!requested_help and positionals.items.len > 1) {
            log.err("fmt takes a single file, not a path within it: {s}\n", .{positionals.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.len > 0) positionals.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: std.ArrayList([]const u8) = .empty;
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
                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.UnsupportedFileFormat;
                };
            } 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} (frontmatter, frontmatter-json, frontmatter-fig, endmatter)\n", .{name});
                    return ArgError.UnsupportedFileFormat;
                };
            } 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 {
                try positionals.append(allocator, arg);
            }
        }

        if (!requested_help and positionals.items.len == 0) {
            log.err("No file provided.\n", .{});
            return ArgError.MissingConvertArgument;
        }
        if (!requested_help and positionals.items.len > 1) {
            log.err("convert takes a single file, not a path within it: {s}\n", .{positionals.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.len > 0) positionals.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 requested_help = false;
        var positionals: std.ArrayList([]const u8) = .empty;
        defer positionals.deinit(allocator);

        while (args.next()) |arg| {
            if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
                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")) {
                quiet = 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 parsePath(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 parsePath(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 parsePath(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;
                };
            } 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.UnsupportedFileFormat;
                };
            } 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.UnsupportedFileFormat;
                };
            } else {
                try positionals.append(allocator, arg);
            }
        }

        if (!requested_help and positionals.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.len > 2) {
            log.err("patch takes two files; use --at/--from to name a path within one: {s}\n", .{positionals.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.len > 0) positionals.items[0] else "-";
        const source_path = if (positionals.items.len > 1) positionals.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,
        } };
    } 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 "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 "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, .semicolons_json), embedTypeFromName("frontmatter-json"));
    try t.expectEqual(@as(?fig.Embed.Type, .{ .fenced = .fig }), 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, .plus_toml), 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` remains accepted for back-compat.
    const fig_ext = detectLanguageFromFileEnding("f.fig").?;
    try t.expectEqual(Format.fig, fig_ext.format);
    try t.expect(!fig_ext.embed_detect);
}

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 frontmatter-fig routes to the fig-fenced archetype.
    var fm = TestArgs{ .items = &.{ "fig", "set", "--embed", "frontmatter-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", "frontmatter-json", "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", "frontmatter-json", "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", "frontmatter-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);
}