ferrosys-cli 0.3.0

Command-line ext2/3/4 formatter, inspector, and extractor built on ferrosys
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
//! The command line: tokenizing `argv` and reading each subcommand's options.
//!
//! This module is pure. It takes the argument list and the one environment value the
//! tool honours (`SOURCE_DATE_EPOCH`) as inputs and returns a [`Command`] or a
//! [`UsageError`] — it opens no file, reads no clock, and consults no environment of
//! its own, so every path through it is a unit test with no I/O.
//!
//! Arguments are `OsString`s and stay that way. A value is never classified as a flag:
//! whatever token follows an option *is* that option's value, so `--offset -1` yields
//! the text `-1` to the size parser, which refuses it. There is no lookahead and no
//! negative-number special case. A `--` ends the options; every token after it is
//! positional.

use std::ffi::{OsStr, OsString};
use std::path::PathBuf;

use ferrosys::ext::ondisk::Timestamp;
use ferrosys::ext::{
    ErrorBehavior, FeatureError, FeatureSet, GrowReservation, HashSignedness, HashVersion,
    InodeCount, JournalSize, Profile, ReservedRatio, Severity, Slack,
};

use crate::parse::{self, ValueError};

/// The bytes of an OS string, and the OS string a slice of those bytes names.
///
/// Splitting `--name=value` cuts an argument at an ASCII byte, and a path *inside* an
/// image is a byte string to begin with, so the parser works in bytes. Both directions
/// are exact on a Unix host, where an OS string is a byte string. Elsewhere an OS string
/// is Unicode and a byte slice names one only when it is valid UTF-8 — which every
/// value but a host path already must be, and a host path on such a host is Unicode
/// anyway.
pub mod os {
    use std::ffi::{OsStr, OsString};

    /// The bytes of `s`.
    #[cfg(unix)]
    pub fn bytes(s: &OsStr) -> &[u8] {
        std::os::unix::ffi::OsStrExt::as_bytes(s)
    }

    /// The bytes of `s`. ASCII bytes survive this encoding unchanged, which is all the
    /// tokenizer cuts on.
    #[cfg(not(unix))]
    pub fn bytes(s: &OsStr) -> &[u8] {
        s.as_encoded_bytes()
    }

    /// The OS string `b` names.
    #[cfg(unix)]
    pub fn string(b: &[u8]) -> Option<OsString> {
        Some(<OsStr as std::os::unix::ffi::OsStrExt>::from_bytes(b).to_owned())
    }

    /// The OS string `b` names, or `None` when this platform's OS strings cannot hold
    /// those bytes.
    #[cfg(not(unix))]
    pub fn string(b: &[u8]) -> Option<OsString> {
        std::str::from_utf8(b).ok().map(OsString::from)
    }
}

/// The tool's name in its own messages.
pub const TOOL: &str = "ferrosys";

/// What the command line asked for.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Command {
    /// Write a filesystem.
    Format(Box<FormatArgs>),
    /// Report on a filesystem.
    Inspect(InspectArgs),
    /// Read a filesystem's contents back out.
    Extract(ExtractArgs),
    /// Say which filesystem an image holds.
    Detect(DetectArgs),
    /// Change what an existing filesystem is known by.
    Identity(IdentityArgs),
    /// Print usage, for the tool as a whole or for one subcommand.
    Help(Topic),
    /// Print the version.
    Version,
}

/// Which usage text to print.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Topic {
    /// The tool as a whole.
    General,
    /// One subcommand.
    Format,
    /// One subcommand.
    Inspect,
    /// One subcommand.
    Extract,
    /// One subcommand.
    Detect,
    /// One subcommand.
    Identity,
}

/// Where an archive is read from, or written to: a named file, or the standard stream,
/// which the single argument `-` names.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Stream {
    /// The process's standard input or standard output.
    Std,
    /// A named file.
    File(PathBuf),
}

impl Stream {
    /// The stream a value names: `-` is the standard one, anything else is a file.
    fn from_value(v: OsString) -> Self {
        if v == OsStr::new("-") {
            Stream::Std
        } else {
            Stream::File(PathBuf::from(v))
        }
    }
}

/// What a format populates the filesystem from. At most one is given; without either the
/// filesystem is empty but for `/lost+found`.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Contents {
    /// A tar archive: a named file, or the standard input.
    Tar(Stream),
    /// A directory tree on this host.
    Dir(PathBuf),
}

/// How large the filesystem is: a size named outright, or one found from what goes in it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Size {
    /// The byte count `--size` named.
    Bytes(u64),
    /// `--size auto`: the smallest filesystem that holds the contents with the room
    /// `--slack` asks for left free.
    Fit(Slack),
}

/// `ferrosys format`: everything the filesystem's bytes are a function of.
///
/// Every input is here, and nothing else is read: the identity (`uuid`, `hash_seed`),
/// the clock (`time`, `fixed_time`), the geometry (`size`, `feature`, `grow`,
/// `journal`), and the contents (`contents`, `owner`). Two runs given the same values
/// write the same bytes.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FormatArgs {
    /// The file to write. It must be a regular file.
    pub out: PathBuf,
    /// How large the filesystem is.
    pub size: Size,
    /// The filesystem UUID.
    pub uuid: [u8; 16],
    /// The filesystem's creation and write time.
    pub time: Timestamp,
    /// What to populate the filesystem from, or `None` for an empty one.
    pub contents: Option<Contents>,
    /// The user and group every entry is owned by, overriding what a walked directory
    /// tree records, or `None` to keep the host's.
    pub owner: Option<(u32, u32)>,
    /// The feature profile, with the block and inode sizes already folded in.
    pub feature: FeatureSet,
    /// What the kernel does on a detected filesystem error (`s_errors`).
    pub errors: ErrorBehavior,
    /// How many inodes to provide.
    pub inodes: InodeCount,
    /// The share of blocks held back for the super-user.
    pub reserved: ReservedRatio,
    /// The volume label (`s_volume_name`), NUL-padded; all zero when unlabelled.
    pub volume_name: [u8; 16],
    /// How much reserved descriptor headroom to build in.
    pub grow: GrowReservation,
    /// How large the journal is.
    pub journal: JournalSize,
    /// A time forced onto every inode, overriding the source's.
    pub fixed_time: Option<Timestamp>,
    /// The directory-hash algorithm.
    pub hash_version: HashVersion,
    /// Whether a name's bytes are hashed as signed or unsigned.
    pub hash_signedness: HashSignedness,
    /// The 16-byte directory-hash seed. Defaults to the UUID's bytes.
    pub hash_seed: [u8; 16],
    /// Print the geometry the format realized as JSON.
    pub json: bool,
    /// Write the image to a sibling temporary file and rename it over the destination once
    /// it is complete, so the destination never holds a partial image.
    pub atomic: bool,
    /// Report the geometry the format would realize and write nothing.
    pub dry_run: bool,
}

/// `ferrosys inspect`: what to report on, and what counts as a failing verdict.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct InspectArgs {
    /// The image to read.
    pub image: PathBuf,
    /// Where the filesystem begins within it.
    pub offset: u64,
    /// Report as JSON rather than as text.
    pub json: bool,
    /// Report the scan's findings as a SARIF log, and nothing else.
    pub sarif: bool,
    /// Report each block group's descriptor.
    pub groups: bool,
    /// Report the superblock alone, without scanning the image.
    pub quick: bool,
    /// The severity at which the scan's findings make the filesystem bad, or `None` when
    /// nothing does.
    pub fail_on: Option<Severity>,
}

/// `ferrosys detect`: which image to classify, and where the filesystem begins in it.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DetectArgs {
    /// The image to classify.
    pub image: PathBuf,
    /// Where the filesystem begins within it.
    pub offset: u64,
    /// Report as JSON rather than as one line of text.
    pub json: bool,
}

/// `ferrosys identity`: what an existing filesystem becomes known by.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct IdentityArgs {
    /// The image to rewrite, opened for reading and writing.
    pub image: PathBuf,
    /// The new filesystem UUID, or `None` to leave it.
    pub uuid: Option<[u8; 16]>,
    /// The new volume label, NUL-padded, or `None` to leave it.
    pub volume_name: Option<[u8; 16]>,
    /// Record the seed the current UUID implies and set `metadata_csum_seed`, so a UUID
    /// change leaves the filesystem's metadata checksums valid.
    pub set_checksum_seed: bool,
    /// Report what the rewrite wrote as JSON rather than as text.
    pub json: bool,
}

/// `ferrosys extract`: what to read the filesystem's contents into.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ExtractArgs {
    /// The image to read.
    pub image: PathBuf,
    /// Where the filesystem begins within it.
    pub offset: u64,
    /// What to produce.
    pub mode: ExtractMode,
    /// The largest file a read will return, or `None` for no cap. A file past it is an
    /// error rather than a truncated one.
    pub max_file_bytes: Option<u64>,
    /// Write `--to-tar`'s archive to a sibling temporary file and rename it over the
    /// destination once the walk is complete, so the destination never holds a partial
    /// archive.
    pub atomic: bool,
}

/// The one thing an extract produces. Exactly one is asked for.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ExtractMode {
    /// Write the whole tree as a tar archive.
    ToTar(Stream),
    /// Write the whole tree into a directory on this host.
    ToDir {
        /// The destination directory.
        path: PathBuf,
        /// Write what an unprivileged process may rather than failing on what it may not.
        skip_privileged: bool,
    },
    /// Write one file's bytes, and nothing else.
    Cat(Vec<u8>),
    /// Report everything one path's inode records, extended attributes included.
    Stat {
        /// The path inside the image.
        path: Vec<u8>,
        /// Report as JSON rather than as text.
        json: bool,
    },
    /// List the tree.
    List {
        /// List as JSON rather than as text.
        json: bool,
    },
}

/// A command line that cannot be understood.
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
pub enum UsageError {
    /// No subcommand was given.
    #[error("no command given")]
    NoCommand,
    /// The first argument names no subcommand.
    #[error("{0}: not a command")]
    UnknownCommand(String),
    /// An option this subcommand does not take.
    #[error(fmt = fmt_unknown_flag)]
    UnknownFlag {
        /// The subcommand it was given to, or empty when the tokenizer rejected the
        /// token before any subcommand claimed it.
        command: &'static str,
        /// The offending option.
        flag: String,
    },
    /// An option that takes a value was given none.
    #[error("{0} needs a value")]
    MissingValue(String),
    /// An option that takes no value was given one.
    #[error("{0} takes no value")]
    UnexpectedValue(String),
    /// A required option was not given.
    #[error("{command}: {flag} is required")]
    MissingRequired {
        /// The subcommand.
        command: &'static str,
        /// The option that must be given.
        flag: &'static str,
    },
    /// A required argument was not given.
    #[error("{command}: no {what} given")]
    MissingArgument {
        /// The subcommand.
        command: &'static str,
        /// What was expected.
        what: &'static str,
    },
    /// More arguments were given than the subcommand takes.
    #[error("{command}: unexpected argument {value}")]
    UnexpectedArgument {
        /// The subcommand.
        command: &'static str,
        /// The offending argument.
        value: String,
    },
    /// An option's value is not one the option takes.
    #[error("{flag}: {source}")]
    Value {
        /// The option.
        flag: String,
        /// Why its value was refused.
        #[source]
        source: ValueError,
    },
    /// The requested features cannot be written together.
    #[error(transparent)]
    Feature(#[from] FeatureError),
    /// `format` was given two things to populate the filesystem from.
    #[error("format: give at most one of --from-tar or --from-dir")]
    TwoSources,
    /// `--slack` was given to a format whose size was named outright.
    #[error(
        "format: --slack is the room to leave in a filesystem sized to its contents, so \
         it goes with --size auto"
    )]
    SlackWithoutFit,
    /// `--owner` was given to a format with no directory tree to apply it to.
    #[error(
        "format: --owner replaces the ownership a walked directory tree records, so it \
         goes with --from-dir"
    )]
    OwnerWithoutDir,
    /// `extract` was told to produce nothing, or more than one thing.
    #[error("extract: give exactly one of --to-tar, --to-dir, --cat, --stat, or --list")]
    ExtractMode,
    /// `--skip-privileged` was given to an extract that writes no tree it could apply to.
    #[error("extract: --skip-privileged applies to --to-dir")]
    SkipPrivilegedWithoutDir,
    /// `--json` was given to an extract that produces bytes, which have no JSON form.
    #[error("extract: --json applies to --list and --stat")]
    JsonWithoutReport,
    /// `--atomic` was given to an extract that writes no file it could rename into place.
    #[error("extract: --atomic applies to --to-tar FILE")]
    AtomicWithoutFile,
    /// `inspect` was given both `--json` and `--sarif`, two different output formats.
    #[error("inspect: --sarif and --json are different output formats; give one")]
    SarifWithJson,
    /// `inspect --sarif` reports scan findings, which `--quick` skips.
    #[error("inspect: --sarif reports scan findings, which --quick skips")]
    SarifWithQuick,
    /// `inspect --sarif` reports scan findings, and has no place to put a group table.
    #[error("inspect: --sarif reports scan findings; --groups has no place in one")]
    SarifWithGroups,
    /// A value this platform cannot name a file with.
    #[error("{0}: the value is not text this platform can name a file with")]
    NotAFilename(String),
}

/// Render [`UsageError::UnknownFlag`], omitting the `command:` prefix when the command
/// is empty — the tokenizer rejects a malformed token before any subcommand claims it,
/// and a leading `: ` would read as a stray colon under the tool-name prefix.
fn fmt_unknown_flag(
    command: &str,
    flag: &str,
    f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
    if command.is_empty() {
        write!(f, "{flag}: not an option")
    } else {
        write!(f, "{command}: {flag}: not an option")
    }
}

/// A single argument, classified.
#[derive(Clone, PartialEq, Eq, Debug)]
enum Arg {
    /// `--name`, or `--name=value` with its value attached.
    Long(String, Option<OsString>),
    /// `-n`, or `-nvalue` with its value attached.
    Short(char, Option<OsString>),
    /// A token that introduces nothing.
    Positional(OsString),
}

/// The argument list, consumed left to right.
struct Args {
    rest: std::vec::IntoIter<OsString>,
    /// Set by `--`: every token after it is positional, whatever it looks like.
    ended: bool,
}

impl Args {
    fn new(argv: Vec<OsString>) -> Self {
        Self {
            rest: argv.into_iter(),
            ended: false,
        }
    }

    /// The next argument, classified — unless `--` has ended the options, after which
    /// everything is positional.
    fn next(&mut self) -> Result<Option<Arg>, UsageError> {
        let Some(token) = self.rest.next() else {
            return Ok(None);
        };
        if self.ended {
            return Ok(Some(Arg::Positional(token)));
        }
        let bytes = os::bytes(&token);
        if bytes == b"--" {
            self.ended = true;
            return self.next();
        }
        if let Some(rest) = bytes.strip_prefix(b"--") {
            // The name is what precedes the first `=`; the value is the rest of the
            // token, whatever bytes it holds.
            let (name, value) = match rest.iter().position(|&b| b == b'=') {
                Some(i) => (&rest[..i], Some(&rest[i + 1..])),
                None => (rest, None),
            };
            let name = flag_name(name).ok_or_else(|| UsageError::UnknownFlag {
                command: "",
                flag: token.to_string_lossy().into_owned(),
            })?;
            let value = match value {
                Some(v) => Some(os::string(v).ok_or_else(|| {
                    UsageError::NotAFilename(token.to_string_lossy().into_owned())
                })?),
                None => None,
            };
            return Ok(Some(Arg::Long(name, value)));
        }
        // A lone `-` is a value naming the standard stream, not an option.
        if bytes.len() > 1 && bytes[0] == b'-' {
            let letter = char::from(bytes[1]);
            if !letter.is_ascii_alphabetic() {
                return Err(UsageError::UnknownFlag {
                    command: "",
                    flag: token.to_string_lossy().into_owned(),
                });
            }
            let value = if bytes.len() > 2 {
                Some(os::string(&bytes[2..]).ok_or_else(|| {
                    UsageError::NotAFilename(token.to_string_lossy().into_owned())
                })?)
            } else {
                None
            };
            return Ok(Some(Arg::Short(letter, value)));
        }
        Ok(Some(Arg::Positional(token)))
    }

    /// The value of the option just returned: the one attached to it, or the next token
    /// verbatim. The token is taken without being classified, so a value that looks like
    /// an option is still that option's value.
    fn value(&mut self, flag: &str, attached: Option<OsString>) -> Result<OsString, UsageError> {
        match attached {
            Some(v) => Ok(v),
            None => self
                .rest
                .next()
                .ok_or_else(|| UsageError::MissingValue(flag.to_string())),
        }
    }

    /// Refuse a value on an option that takes none, so `--json=yes` is a mistake caught
    /// rather than a `yes` silently discarded.
    fn no_value(flag: &str, attached: Option<OsString>) -> Result<(), UsageError> {
        match attached {
            None => Ok(()),
            Some(_) => Err(UsageError::UnexpectedValue(flag.to_string())),
        }
    }
}

/// A long option's name: ASCII, as every option this tool defines is. A name that is not
/// is not one of ours, and is reported as the unknown option it is.
fn flag_name(bytes: &[u8]) -> Option<String> {
    let name = std::str::from_utf8(bytes).ok()?;
    name.is_ascii().then(|| name.to_string())
}

/// Attach an option's name to the reason its value was refused.
fn value_err(flag: &str) -> impl Fn(ValueError) -> UsageError + '_ {
    move |source| UsageError::Value {
        flag: flag.to_string(),
        source,
    }
}

/// Parse a whole command line: the arguments past the program name, and the value of
/// `SOURCE_DATE_EPOCH`, which supplies `format --time` when that option is absent.
///
/// # Errors
///
/// A [`UsageError`] if the arguments name no command, name an option no command takes,
/// omit a required one, or give one a value it cannot hold.
pub fn parse(
    argv: Vec<OsString>,
    source_date_epoch: Option<OsString>,
) -> Result<Command, UsageError> {
    let mut args = Args::new(argv);
    let Some(first) = args.next()? else {
        return Err(UsageError::NoCommand);
    };
    match first {
        Arg::Positional(name) if name == OsStr::new("format") => {
            format(&mut args, source_date_epoch)
        }
        Arg::Positional(name) if name == OsStr::new("inspect") => inspect(&mut args),
        Arg::Positional(name) if name == OsStr::new("extract") => extract(&mut args),
        Arg::Positional(name) if name == OsStr::new("detect") => detect(&mut args),
        Arg::Positional(name) if name == OsStr::new("identity") => identity(&mut args),
        Arg::Positional(name) if name == OsStr::new("help") => Ok(Command::Help(Topic::General)),
        // An attached value is refused rather than dropped, here as everywhere: `--help=x`
        // asks for something this option cannot do, and answering it with help would be
        // answering a different question than the one asked.
        Arg::Long(name, attached) if name == "help" => {
            Args::no_value("--help", attached)?;
            Ok(Command::Help(Topic::General))
        }
        Arg::Long(name, attached) if name == "version" => {
            Args::no_value("--version", attached)?;
            Ok(Command::Version)
        }
        Arg::Short('h', attached) => {
            Args::no_value("-h", attached)?;
            Ok(Command::Help(Topic::General))
        }
        Arg::Short('V', attached) => {
            Args::no_value("-V", attached)?;
            Ok(Command::Version)
        }
        Arg::Positional(name) => Err(UsageError::UnknownCommand(
            name.to_string_lossy().into_owned(),
        )),
        Arg::Long(name, _) => Err(UsageError::UnknownFlag {
            command: TOOL,
            flag: format!("--{name}"),
        }),
        Arg::Short(letter, _) => Err(UsageError::UnknownFlag {
            command: TOOL,
            flag: format!("-{letter}"),
        }),
    }
}

/// `ferrosys format [options] OUT`.
fn format(args: &mut Args, source_date_epoch: Option<OsString>) -> Result<Command, UsageError> {
    const CMD: &str = "format";
    let mut out: Option<PathBuf> = None;
    let mut size: Option<u64> = None;
    // Whether the size is to be found from the contents (`--size auto`) rather than named.
    let mut fit = false;
    let mut slack: Option<Slack> = None;
    let mut uuid: Option<[u8; 16]> = None;
    let mut time: Option<i64> = None;
    let mut from_tar: Option<Stream> = None;
    let mut from_dir: Option<PathBuf> = None;
    let mut owner: Option<(u32, u32)> = None;
    // The feature set is composed once the whole line is read (below), not mutated in place
    // as options arrive. So the base profile (`-t`), the size overrides, and the `-O` deltas
    // take effect in a fixed order — profile seeds, sizes override, `-O` lists layer on last
    // — rather than in the order they happen to appear. This is the order `mke2fs -t … -O …`
    // composes in, and it makes `-t` position-independent.
    let mut profile: Option<Profile> = None;
    let mut block_size: Option<u32> = None;
    let mut inode_size: Option<u16> = None;
    let mut feature_ops: Vec<OsString> = Vec::new();
    let mut errors = ErrorBehavior::default();
    let mut inodes = InodeCount::default();
    let mut reserved = ReservedRatio::default();
    let mut volume_name = [0u8; 16];
    let mut grow = GrowReservation::default();
    let mut journal = JournalSize::Auto;
    let mut fixed_time: Option<i64> = None;
    let mut hash_version = HashVersion::default();
    let mut hash_signedness = HashSignedness::default();
    let mut hash_seed: Option<[u8; 16]> = None;
    let mut json = false;
    let mut atomic = false;
    let mut dry_run = false;

    while let Some(arg) = args.next()? {
        match arg {
            Arg::Long(name, attached) => {
                let flag = format!("--{name}");
                match name.as_str() {
                    "help" => {
                        Args::no_value(&flag, attached)?;
                        return Ok(Command::Help(Topic::Format));
                    }
                    // `auto` is the one value that is not a byte count: it asks for the
                    // size to be found from the contents rather than named. The two are one
                    // setting, so the last `--size` given wins whichever form it takes.
                    "size" => {
                        let value = args.value(&flag, attached)?;
                        if value == "auto" {
                            (size, fit) = (None, true);
                        } else {
                            size = Some(parse::size(&value).map_err(value_err(&flag))?);
                            fit = false;
                        }
                    }
                    "slack" => {
                        slack = Some(
                            parse::slack(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    "uuid" => {
                        uuid = Some(
                            parse::hex16(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    "time" => {
                        time = Some(
                            parse::seconds(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    "from-tar" => from_tar = Some(Stream::from_value(args.value(&flag, attached)?)),
                    "from-dir" => from_dir = Some(PathBuf::from(args.value(&flag, attached)?)),
                    "owner" => {
                        owner = Some(
                            parse::owner(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    // The base profile seeds the feature set; `--type` and `-t` name the same
                    // thing, and the last one given wins. `-O` and the size options layer on
                    // top of it when the set is composed below.
                    "type" => {
                        profile = Some(
                            parse::profile(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    "block-size" => {
                        block_size = Some(
                            parse::count_u32(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    "inode-size" => {
                        let v = parse::count_u32(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                        inode_size = Some(u16::try_from(v).map_err(|_| UsageError::Value {
                            flag: flag.clone(),
                            source: ValueError::OutOfRange(v.to_string()),
                        })?);
                    }
                    // The two inode knobs share one setting, last one wins: `--inodes` names
                    // the count outright, `--bytes-per-inode` names the density it derives
                    // from. Either overrides the size-driven default.
                    "inodes" => {
                        let count = parse::count_u32(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                        inodes = InodeCount::Count(count);
                    }
                    "bytes-per-inode" => {
                        inodes = parse::bytes_per_inode(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                    }
                    "reserved-percent" => {
                        reserved = parse::reserved_percent(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                    }
                    // A label is bytes, not text — the on-disk field holds sixteen of them
                    // and the reader reports whatever is there — so it is taken as the
                    // argument's bytes, as a path inside the image is.
                    "label" => {
                        let value = args.value(&flag, attached)?;
                        volume_name = parse::label(os::bytes(&value)).map_err(value_err(&flag))?;
                    }
                    "grow" => {
                        grow =
                            parse::grow(&args.value(&flag, attached)?).map_err(value_err(&flag))?;
                    }
                    "journal" => {
                        journal = parse::journal(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                    }
                    "errors" => {
                        errors = parse::error_behavior(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                    }
                    "fixed-time" => {
                        fixed_time = Some(
                            parse::seconds(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    "hash" => {
                        hash_version = parse::hash_version(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                    }
                    "hash-signedness" => {
                        hash_signedness = parse::hash_signedness(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                    }
                    "hash-seed" => {
                        hash_seed = Some(
                            parse::hex16(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    "json" => {
                        Args::no_value(&flag, attached)?;
                        json = true;
                    }
                    "atomic" => {
                        Args::no_value(&flag, attached)?;
                        atomic = true;
                    }
                    "dry-run" => {
                        Args::no_value(&flag, attached)?;
                        dry_run = true;
                    }
                    _ => {
                        return Err(UsageError::UnknownFlag { command: CMD, flag });
                    }
                }
            }
            // `-O` and `-t` are read here but applied below, once the whole line is known:
            // the base profile seeds the set and every `-O` list layers on top, left to
            // right, so two `-O`s compose and the last element to name a feature wins.
            Arg::Short('O', attached) => feature_ops.push(args.value("-O", attached)?),
            Arg::Short('t', attached) => {
                profile =
                    Some(parse::profile(&args.value("-t", attached)?).map_err(value_err("-t"))?);
            }
            Arg::Short('h', attached) => {
                Args::no_value("-h", attached)?;
                return Ok(Command::Help(Topic::Format));
            }
            Arg::Short(letter, _) => {
                return Err(UsageError::UnknownFlag {
                    command: CMD,
                    flag: format!("-{letter}"),
                });
            }
            Arg::Positional(value) => {
                if out.is_some() {
                    return Err(UsageError::UnexpectedArgument {
                        command: CMD,
                        value: value.to_string_lossy().into_owned(),
                    });
                }
                out = Some(PathBuf::from(value));
            }
        }
    }

    // The time comes from the option, or from SOURCE_DATE_EPOCH, and from nowhere else:
    // the tool does not read the clock, so an absent time is a missing input rather than
    // "now".
    let time = match time {
        Some(t) => t,
        None => match source_date_epoch {
            Some(v) => parse::seconds(&v).map_err(value_err("SOURCE_DATE_EPOCH"))?,
            None => {
                return Err(UsageError::MissingRequired {
                    command: CMD,
                    flag: "--time (or SOURCE_DATE_EPOCH)",
                });
            }
        },
    };
    let uuid = uuid.ok_or(UsageError::MissingRequired {
        command: CMD,
        flag: "--uuid",
    })?;
    // `--size auto` and a named size are one setting; `--slack` modifies only the first,
    // since a size that was named has no room to find.
    let size = match (size, fit) {
        (_, true) => Size::Fit(slack.unwrap_or_default()),
        (Some(bytes), false) => {
            if slack.is_some() {
                return Err(UsageError::SlackWithoutFit);
            }
            Size::Bytes(bytes)
        }
        (None, false) => {
            return Err(UsageError::MissingRequired {
                command: CMD,
                flag: "--size",
            });
        }
    };
    let out = out.ok_or(UsageError::MissingArgument {
        command: CMD,
        what: "output file",
    })?;
    // One source of contents, or none. Two would be a merge, which nothing here decides
    // the rules for.
    let contents = match (from_tar, from_dir) {
        (None, None) => None,
        (Some(stream), None) => Some(Contents::Tar(stream)),
        (None, Some(path)) => Some(Contents::Dir(path)),
        (Some(_), Some(_)) => return Err(UsageError::TwoSources),
    };
    // An archive carries its own ownership and an empty filesystem has nothing to own, so
    // an override with nothing to override is a mistake caught rather than ignored.
    if owner.is_some() && !matches!(contents, Some(Contents::Dir(_))) {
        return Err(UsageError::OwnerWithoutDir);
    }
    // Compose the feature set now that the whole line is read: the base profile seeds it
    // (ext4 when no `-t` was given), the size options override, and the `-O` lists layer on
    // last, left to right. A combination that must never reach disk is a request that cannot
    // be honoured, so it is refused here, by the name of the conflict, rather than deep in
    // the planner.
    let mut feature = profile.unwrap_or_default().feature_set();
    if let Some(block_size) = block_size {
        feature.block_size = block_size;
    }
    if let Some(inode_size) = inode_size {
        feature.inode_size = inode_size;
    }
    for op in &feature_ops {
        feature = parse::features(feature, op).map_err(value_err("-O"))?;
    }
    feature.validate()?;

    Ok(Command::Format(Box::new(FormatArgs {
        out,
        size,
        uuid,
        time: Timestamp::from_secs(time),
        contents,
        owner,
        feature,
        errors,
        inodes,
        reserved,
        volume_name,
        grow,
        journal,
        fixed_time: fixed_time.map(Timestamp::from_secs),
        hash_version,
        hash_signedness,
        // The seed defaults to the UUID's bytes: an identity the caller already supplied,
        // rather than one the tool would have to invent from a random source it does not
        // have.
        hash_seed: hash_seed.unwrap_or(uuid),
        json,
        atomic,
        dry_run,
    })))
}

/// `ferrosys inspect [options] IMAGE`.
fn inspect(args: &mut Args) -> Result<Command, UsageError> {
    const CMD: &str = "inspect";
    let mut image: Option<PathBuf> = None;
    let mut offset = 0u64;
    let mut json = false;
    let mut sarif = false;
    let mut groups = false;
    let mut quick = false;
    // Integrity by default: a filesystem is bad when its own bytes contradict each other —
    // a checksum that does not match what it covers — or when a structure the reader must
    // follow cannot be. That is the line between a filesystem that is sound and one that
    // is not.
    //
    // The threshold below it, `conformance`, means something else: valid ext4, but not the
    // form *this* tool writes. A filesystem another formatter made is exactly that, and it
    // is not thereby broken. Faulting it would make `inspect` a check on its own output
    // rather than on ext4, so `conformance` is an opt-in self-check and not the default.
    let mut fail_on = Some(Severity::Integrity);

    while let Some(arg) = args.next()? {
        match arg {
            Arg::Long(name, attached) => {
                let flag = format!("--{name}");
                match name.as_str() {
                    "help" => {
                        Args::no_value(&flag, attached)?;
                        return Ok(Command::Help(Topic::Inspect));
                    }
                    "offset" => {
                        offset =
                            parse::size(&args.value(&flag, attached)?).map_err(value_err(&flag))?;
                    }
                    "fail-on" => {
                        fail_on = parse::fail_on(&args.value(&flag, attached)?)
                            .map_err(value_err(&flag))?;
                    }
                    "json" => {
                        Args::no_value(&flag, attached)?;
                        json = true;
                    }
                    "sarif" => {
                        Args::no_value(&flag, attached)?;
                        sarif = true;
                    }
                    "groups" => {
                        Args::no_value(&flag, attached)?;
                        groups = true;
                    }
                    "quick" => {
                        Args::no_value(&flag, attached)?;
                        quick = true;
                    }
                    _ => {
                        return Err(UsageError::UnknownFlag { command: CMD, flag });
                    }
                }
            }
            Arg::Short('h', attached) => {
                Args::no_value("-h", attached)?;
                return Ok(Command::Help(Topic::Inspect));
            }
            Arg::Short(letter, _) => {
                return Err(UsageError::UnknownFlag {
                    command: CMD,
                    flag: format!("-{letter}"),
                });
            }
            Arg::Positional(value) => {
                if image.is_some() {
                    return Err(UsageError::UnexpectedArgument {
                        command: CMD,
                        value: value.to_string_lossy().into_owned(),
                    });
                }
                image = Some(PathBuf::from(value));
            }
        }
    }

    let image = image.ok_or(UsageError::MissingArgument {
        command: CMD,
        what: "image",
    })?;
    // SARIF is a findings dialect: it projects the scan, not the description JSON and text
    // report. So it selects a different output format from --json, it needs the scan
    // --quick would skip, and it has nowhere to render the group table --groups asks for.
    // The last is refused rather than ignored for the same reason as the first two: an
    // accepted flag that changes nothing reads as one that worked, and here it would also
    // let a descriptor read error abort a run before any SARIF was emitted — the inert
    // flag suppressing the very document the caller asked for.
    if sarif && json {
        return Err(UsageError::SarifWithJson);
    }
    if sarif && quick {
        return Err(UsageError::SarifWithQuick);
    }
    if sarif && groups {
        return Err(UsageError::SarifWithGroups);
    }
    Ok(Command::Inspect(InspectArgs {
        image,
        offset,
        json,
        sarif,
        groups,
        quick,
        fail_on,
    }))
}

/// `ferrosys detect [options] IMAGE`.
fn detect(args: &mut Args) -> Result<Command, UsageError> {
    const CMD: &str = "detect";
    let mut image: Option<PathBuf> = None;
    let mut offset = 0u64;
    let mut json = false;

    while let Some(arg) = args.next()? {
        match arg {
            Arg::Long(name, attached) => {
                let flag = format!("--{name}");
                match name.as_str() {
                    "help" => {
                        Args::no_value(&flag, attached)?;
                        return Ok(Command::Help(Topic::Detect));
                    }
                    "offset" => {
                        offset =
                            parse::size(&args.value(&flag, attached)?).map_err(value_err(&flag))?;
                    }
                    "json" => {
                        Args::no_value(&flag, attached)?;
                        json = true;
                    }
                    _ => {
                        return Err(UsageError::UnknownFlag { command: CMD, flag });
                    }
                }
            }
            Arg::Short('h', attached) => {
                Args::no_value("-h", attached)?;
                return Ok(Command::Help(Topic::Detect));
            }
            Arg::Short(letter, _) => {
                return Err(UsageError::UnknownFlag {
                    command: CMD,
                    flag: format!("-{letter}"),
                });
            }
            Arg::Positional(value) => {
                if image.is_some() {
                    return Err(UsageError::UnexpectedArgument {
                        command: CMD,
                        value: value.to_string_lossy().into_owned(),
                    });
                }
                image = Some(PathBuf::from(value));
            }
        }
    }

    let image = image.ok_or(UsageError::MissingArgument {
        command: CMD,
        what: "image",
    })?;
    Ok(Command::Detect(DetectArgs {
        image,
        offset,
        json,
    }))
}

/// `ferrosys identity [options] IMAGE`.
fn identity(args: &mut Args) -> Result<Command, UsageError> {
    const CMD: &str = "identity";
    let mut image: Option<PathBuf> = None;
    let mut uuid: Option<[u8; 16]> = None;
    let mut volume_name: Option<[u8; 16]> = None;
    let mut set_checksum_seed = false;
    let mut json = false;

    while let Some(arg) = args.next()? {
        match arg {
            Arg::Long(name, attached) => {
                let flag = format!("--{name}");
                match name.as_str() {
                    "help" => {
                        Args::no_value(&flag, attached)?;
                        return Ok(Command::Help(Topic::Identity));
                    }
                    "uuid" => {
                        uuid = Some(
                            parse::hex16(&args.value(&flag, attached)?)
                                .map_err(value_err(&flag))?,
                        );
                    }
                    // The label is the argument's bytes, as it is for a format: a label is
                    // a byte field on disk rather than text.
                    "label" => {
                        let value = args.value(&flag, attached)?;
                        volume_name =
                            Some(parse::label(os::bytes(&value)).map_err(value_err(&flag))?);
                    }
                    "set-checksum-seed" => {
                        Args::no_value(&flag, attached)?;
                        set_checksum_seed = true;
                    }
                    "json" => {
                        Args::no_value(&flag, attached)?;
                        json = true;
                    }
                    _ => {
                        return Err(UsageError::UnknownFlag { command: CMD, flag });
                    }
                }
            }
            Arg::Short('h', attached) => {
                Args::no_value("-h", attached)?;
                return Ok(Command::Help(Topic::Identity));
            }
            Arg::Short(letter, _) => {
                return Err(UsageError::UnknownFlag {
                    command: CMD,
                    flag: format!("-{letter}"),
                });
            }
            Arg::Positional(value) => {
                if image.is_some() {
                    return Err(UsageError::UnexpectedArgument {
                        command: CMD,
                        value: value.to_string_lossy().into_owned(),
                    });
                }
                image = Some(PathBuf::from(value));
            }
        }
    }

    let image = image.ok_or(UsageError::MissingArgument {
        command: CMD,
        what: "image",
    })?;
    // A run that would write nothing is a command line that meant to say something and
    // did not, so it is a usage error rather than a silent success.
    if uuid.is_none() && volume_name.is_none() && !set_checksum_seed {
        return Err(UsageError::MissingRequired {
            command: CMD,
            flag: "--uuid, --label, or --set-checksum-seed",
        });
    }
    Ok(Command::Identity(IdentityArgs {
        image,
        uuid,
        volume_name,
        set_checksum_seed,
        json,
    }))
}

/// `ferrosys extract [options] IMAGE`.
fn extract(args: &mut Args) -> Result<Command, UsageError> {
    const CMD: &str = "extract";
    let mut image: Option<PathBuf> = None;
    let mut offset = 0u64;
    let mut to_tar: Option<Stream> = None;
    let mut to_dir: Option<PathBuf> = None;
    let mut skip_privileged = false;
    let mut cat: Option<Vec<u8>> = None;
    let mut stat: Option<Vec<u8>> = None;
    let mut list = false;
    let mut json = false;
    let mut max_file_bytes: Option<u64> = None;
    let mut atomic = false;

    while let Some(arg) = args.next()? {
        match arg {
            Arg::Long(name, attached) => {
                let flag = format!("--{name}");
                match name.as_str() {
                    "help" => {
                        Args::no_value(&flag, attached)?;
                        return Ok(Command::Help(Topic::Extract));
                    }
                    "offset" => {
                        offset =
                            parse::size(&args.value(&flag, attached)?).map_err(value_err(&flag))?;
                    }
                    "to-tar" => to_tar = Some(Stream::from_value(args.value(&flag, attached)?)),
                    "to-dir" => to_dir = Some(PathBuf::from(args.value(&flag, attached)?)),
                    "skip-privileged" => {
                        Args::no_value(&flag, attached)?;
                        skip_privileged = true;
                    }
                    // A path inside the image is a byte string, not text: it is taken as
                    // the bytes the argument holds, and never rendered through a
                    // character encoding on the way in.
                    "cat" => {
                        let value = args.value(&flag, attached)?;
                        cat = Some(os::bytes(&value).to_vec());
                    }
                    // A path inside the image, taken as bytes for the same reason `--cat`'s
                    // is: a name in a filesystem is a byte string, not text.
                    "stat" => {
                        let value = args.value(&flag, attached)?;
                        stat = Some(os::bytes(&value).to_vec());
                    }
                    "max-file-bytes" => {
                        max_file_bytes = Some(
                            parse::size(&args.value(&flag, attached)?).map_err(value_err(&flag))?,
                        );
                    }
                    "list" => {
                        Args::no_value(&flag, attached)?;
                        list = true;
                    }
                    "json" => {
                        Args::no_value(&flag, attached)?;
                        json = true;
                    }
                    "atomic" => {
                        Args::no_value(&flag, attached)?;
                        atomic = true;
                    }
                    _ => {
                        return Err(UsageError::UnknownFlag { command: CMD, flag });
                    }
                }
            }
            Arg::Short('h', attached) => {
                Args::no_value("-h", attached)?;
                return Ok(Command::Help(Topic::Extract));
            }
            Arg::Short(letter, _) => {
                return Err(UsageError::UnknownFlag {
                    command: CMD,
                    flag: format!("-{letter}"),
                });
            }
            Arg::Positional(value) => {
                if image.is_some() {
                    return Err(UsageError::UnexpectedArgument {
                        command: CMD,
                        value: value.to_string_lossy().into_owned(),
                    });
                }
                image = Some(PathBuf::from(value));
            }
        }
    }

    let image = image.ok_or(UsageError::MissingArgument {
        command: CMD,
        what: "image",
    })?;
    // Exactly one artifact per run: the standard output carries a tar stream, a file's
    // bytes, one path's metadata, or a listing, and the tool is told which.
    let mode = match (to_tar, to_dir, cat, stat, list) {
        (Some(stream), None, None, None, false) => ExtractMode::ToTar(stream),
        (None, Some(path), None, None, false) => ExtractMode::ToDir {
            path,
            skip_privileged,
        },
        (None, None, Some(path), None, false) => ExtractMode::Cat(path),
        (None, None, None, Some(path), false) => ExtractMode::Stat { path, json },
        (None, None, None, None, true) => ExtractMode::List { json },
        _ => return Err(UsageError::ExtractMode),
    };
    // `--skip-privileged` is about the parts of a tree only a privileged process can write,
    // so it belongs to the mode that writes one. Accepting it elsewhere would promise
    // something no other mode does.
    if skip_privileged && !matches!(mode, ExtractMode::ToDir { .. }) {
        return Err(UsageError::SkipPrivilegedWithoutDir);
    }
    // JSON is a rendering of a report, so it goes with the two modes that produce one. A
    // tar stream and a file's bytes are not reports and have no JSON form.
    if json && !matches!(mode, ExtractMode::List { .. } | ExtractMode::Stat { .. }) {
        return Err(UsageError::JsonWithoutReport);
    }
    // `--atomic` is about what a destination holds when a run fails part-way, so it needs
    // a destination. Every other mode writes to the standard output, which has no rename
    // to make it whole, and accepting the flag there would promise something the run
    // cannot do.
    if atomic && !matches!(mode, ExtractMode::ToTar(Stream::File(_))) {
        return Err(UsageError::AtomicWithoutFile);
    }

    Ok(Command::Extract(ExtractArgs {
        image,
        offset,
        mode,
        max_file_bytes,
        atomic,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Parse a command line written as it would be typed.
    fn line(s: &str) -> Result<Command, UsageError> {
        let argv = s.split(' ').filter(|t| !t.is_empty()).map(OsString::from);
        parse(argv.collect(), None)
    }

    /// The `format` arguments a line parses to, for the cases that must parse.
    fn fmt(s: &str) -> FormatArgs {
        match line(s).expect("the line parses") {
            Command::Format(a) => *a,
            other => panic!("expected format, got {other:?}"),
        }
    }

    const UUID: &str = "f0e17055-0000-4000-8000-000000000000";
    const UUID_BYTES: [u8; 16] = [
        0xf0, 0xe1, 0x70, 0x55, 0, 0, 0x40, 0, 0x80, 0, 0, 0, 0, 0, 0, 0,
    ];

    #[test]
    fn format_takes_its_required_inputs() {
        let a = fmt(&format!(
            "format --size 512M --uuid {UUID} --time 1700000000 out.img"
        ));
        assert_eq!(a.out, PathBuf::from("out.img"));
        assert_eq!(a.size, Size::Bytes(512 << 20));
        assert_eq!(a.uuid, UUID_BYTES);
        assert_eq!(a.time, Timestamp::from_secs(1_700_000_000));
        // The hash seed defaults to the UUID: an identity the caller supplied, rather
        // than one the tool would have had to invent.
        assert_eq!(a.hash_seed, UUID_BYTES);
        assert_eq!(a.feature, FeatureSet::DEFAULT);
        assert_eq!(a.contents, None);
        assert_eq!(a.owner, None);
        assert!(!a.json);
    }

    #[test]
    fn a_size_is_named_or_found_and_slack_belongs_to_the_second() {
        // `auto` is not a byte count and never becomes one here: the size it stands for is
        // decided by the library, from contents this parser never sees.
        let auto = fmt(&format!(
            "format --size auto --uuid {UUID} --time 1 --from-dir staging out.img"
        ));
        assert_eq!(auto.size, Size::Fit(Slack::None));

        for (value, want) in [
            ("20%", Slack::Share(2000)),
            ("1.5%", Slack::Share(150)),
            ("64M", Slack::Bytes(64 << 20)),
            ("0%", Slack::Share(0)),
        ] {
            let a = fmt(&format!(
                "format --size auto --slack {value} --uuid {UUID} --time 1 out.img"
            ));
            assert_eq!(a.size, Size::Fit(want), "--slack {value}");
        }

        // The two forms are one setting, so the last --size wins whichever form it takes.
        let named = fmt(&format!(
            "format --size auto --size 64M --uuid {UUID} --time 1 out.img"
        ));
        assert_eq!(named.size, Size::Bytes(64 << 20));
        let found = fmt(&format!(
            "format --size 64M --size auto --uuid {UUID} --time 1 out.img"
        ));
        assert_eq!(found.size, Size::Fit(Slack::None));

        // A named size has no room to find, so --slack over one is a mistake caught rather
        // than ignored — including when a later --size takes the `auto` away.
        for line_text in [
            format!("format --size 64M --slack 20% --uuid {UUID} --time 1 out.img"),
            format!("format --size auto --slack 20% --size 64M --uuid {UUID} --time 1 out.img"),
        ] {
            assert_eq!(
                line(&line_text).unwrap_err(),
                UsageError::SlackWithoutFit,
                "{line_text}"
            );
        }

        // A share past what the library will search for is refused by name.
        let over = format!("format --size auto --slack 95% --uuid {UUID} --time 1 out.img");
        assert!(
            matches!(
                line(&over),
                Err(UsageError::Value { ref flag, source: ValueError::OutOfRange(_) })
                    if flag == "--slack"
            ),
            "a 95% share should be out of range"
        );
        // And a value that is neither a percentage nor a byte count.
        let bad = format!("format --size auto --slack lots --uuid {UUID} --time 1 out.img");
        assert!(matches!(line(&bad), Err(UsageError::Value { .. })));
    }

    #[test]
    fn format_requires_the_inputs_the_bytes_depend_on() {
        for (line_text, missing) in [
            (
                "format --uuid f0e17055000040008000000000000000 --time 1 o.img",
                "--size",
            ),
            ("format --size 64M --time 1 o.img", "--uuid"),
        ] {
            match line(line_text) {
                Err(UsageError::MissingRequired { flag, .. }) => assert_eq!(flag, missing),
                other => panic!("expected {missing} to be required, got {other:?}"),
            }
        }
        // The time may come from the environment instead, and from nowhere else: there is
        // no clock to fall back on.
        let argv = "format --size 64M --uuid f0e17055000040008000000000000000 o.img";
        assert!(matches!(
            line(argv),
            Err(UsageError::MissingRequired { .. })
        ));
        let from_env = parse(
            argv.split(' ').map(OsString::from).collect(),
            Some(OsString::from("1700000000")),
        );
        match from_env.expect("SOURCE_DATE_EPOCH supplies the time") {
            Command::Format(a) => assert_eq!(a.time, Timestamp::from_secs(1_700_000_000)),
            other => panic!("expected format, got {other:?}"),
        }
        // An option always wins over the environment.
        let both = parse(
            format!("format --size 64M --uuid {UUID} --time 42 o.img")
                .split(' ')
                .map(OsString::from)
                .collect(),
            Some(OsString::from("1700000000")),
        );
        match both.expect("parses") {
            Command::Format(a) => assert_eq!(a.time, Timestamp::from_secs(42)),
            other => panic!("expected format, got {other:?}"),
        }
    }

    #[test]
    fn format_takes_one_source_of_contents() {
        let tar = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --from-tar rootfs.tar out.img"
        ));
        assert_eq!(
            tar.contents,
            Some(Contents::Tar(Stream::File(PathBuf::from("rootfs.tar"))))
        );
        let dash = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --from-tar - out.img"
        ));
        assert_eq!(dash.contents, Some(Contents::Tar(Stream::Std)));
        let dir = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --from-dir staging out.img"
        ));
        assert_eq!(dir.contents, Some(Contents::Dir(PathBuf::from("staging"))));

        // Two sources would be a merge, and nothing here decides the rules for one.
        assert_eq!(
            line(&format!(
                "format --size 64M --uuid {UUID} --time 1 --from-tar r.tar --from-dir d out.img"
            ))
            .unwrap_err(),
            UsageError::TwoSources
        );
    }

    #[test]
    fn format_takes_an_ownership_override_for_a_walked_tree() {
        let a = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --from-dir staging --owner 0:0 out.img"
        ));
        assert_eq!(a.owner, Some((0, 0)));
        let a = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --from-dir staging --owner 1000:100 out.img"
        ));
        assert_eq!(a.owner, Some((1000, 100)));

        // An archive carries its own ownership and an empty filesystem has none to
        // override, so the option has nothing to apply to.
        for line_text in [
            format!("format --size 64M --uuid {UUID} --time 1 --owner 0:0 out.img"),
            format!(
                "format --size 64M --uuid {UUID} --time 1 --from-tar r.tar --owner 0:0 out.img"
            ),
        ] {
            assert_eq!(line(&line_text).unwrap_err(), UsageError::OwnerWithoutDir);
        }

        // Both halves are required, and each must fit the on-disk field.
        for bad in ["0", "0:", ":0", "root:root", "-1:0", "4294967296:0"] {
            assert!(
                matches!(
                    line(&format!(
                        "format --size 64M --uuid {UUID} --time 1 --from-dir d --owner {bad} out.img"
                    )),
                    Err(UsageError::Value {
                        source: ValueError::NotAnOwner(_),
                        ..
                    })
                ),
                "--owner {bad} should be a usage error"
            );
        }
    }

    #[test]
    fn format_folds_the_feature_options_together() {
        let a = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --block-size 1024 \
             --inode-size 128 -O ^has_journal -O ^orphan_file,^metadata_csum_seed \
             -O ^metadata_csum out.img"
        ));
        assert_eq!(a.feature.block_size, 1024);
        assert_eq!(a.feature.inode_size, 128);
        assert!(!a.feature.has_journal());
        assert!(!a.feature.has_metadata_csum());
        // Two `-O` options compose: the second applies to what the first left.
        assert!(!a.feature.has_orphan_file());
        assert!(a.feature.has_extents(), "the rest of the profile is intact");
    }

    #[test]
    fn format_seeds_the_base_profile() {
        // Each `-t`/`--type` seeds the whole feature set from that profile's baseline.
        let ext2 = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 -t ext2 out.img"
        ));
        assert_eq!(ext2.feature, FeatureSet::EXT2);
        assert_eq!(Profile::of(ext2.feature), Profile::Ext2);
        let ext3 = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --type ext3 out.img"
        ));
        assert_eq!(ext3.feature, FeatureSet::EXT3);
        // Naming no profile selects ext4, so the flag is an override rather than a
        // requirement.
        let ext4 = fmt(&format!("format --size 64M --uuid {UUID} --time 1 out.img"));
        assert_eq!(ext4.feature, FeatureSet::DEFAULT);
        assert_eq!(Profile::of(ext4.feature), Profile::Ext4);
    }

    #[test]
    fn the_base_profile_seeds_and_o_layers_on_top_in_any_order() {
        // `-O` composes over the profile whichever came first on the line: the profile is
        // the base, the `-O` deltas layer on last. A journal over the ext2 baseline is ext3.
        let a = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 -t ext2 -O has_journal out.img"
        ));
        let b = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 -O has_journal -t ext2 out.img"
        ));
        assert_eq!(
            a.feature, b.feature,
            "the order of -t and -O does not matter"
        );
        assert_eq!(a.feature, FeatureSet::EXT3);
        assert_eq!(Profile::of(a.feature), Profile::Ext3);

        // The size options override the profile's baseline sizes, in any position.
        let sized = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --block-size 1024 -t ext2 out.img"
        ));
        assert_eq!(sized.feature.block_size, 1024);
        assert_eq!(Profile::of(sized.feature), Profile::Ext2);

        // A name outside the family is a usage error, not a silent fallback.
        assert!(matches!(
            line(&format!(
                "format --size 64M --uuid {UUID} --time 1 -t ext5 out.img"
            )),
            Err(UsageError::Value { .. })
        ));
    }

    #[test]
    fn format_takes_the_sizing_and_label_options() {
        let a = fmt(&format!(
            "format --size 256M --uuid {UUID} --time 1 --inodes 5000 \
             --reserved-percent 1.5 --label rootfs out.img"
        ));
        assert_eq!(a.inodes, InodeCount::Count(5000));
        assert_eq!(
            a.reserved,
            ReservedRatio::from_hundredths_of_percent(150).unwrap()
        );
        assert_eq!(&a.volume_name[..6], b"rootfs");
        assert_eq!(a.volume_name[6], 0, "the label is NUL-padded");

        // The two inode knobs share one setting; the last to appear wins.
        let a = fmt(&format!(
            "format --size 256M --uuid {UUID} --time 1 --inodes 5000 --bytes-per-inode 65536 out.img"
        ));
        assert_eq!(
            a.inodes,
            InodeCount::BytesPerInode(std::num::NonZeroU64::new(65536).unwrap())
        );

        // The defaults when none are given: size-driven inodes, 5% reserved, no label.
        let a = fmt(&format!("format --size 64M --uuid {UUID} --time 1 out.img"));
        assert_eq!(a.inodes, InodeCount::Auto);
        assert_eq!(a.reserved, ReservedRatio::DEFAULT);
        assert_eq!(a.volume_name, [0u8; 16]);
    }

    #[test]
    fn format_takes_the_error_behavior_by_name() {
        // The three `mke2fs -e` names map to the three policies; the default is continue.
        for (name, want) in [
            ("continue", ErrorBehavior::Continue),
            ("remount-ro", ErrorBehavior::RemountReadOnly),
            ("panic", ErrorBehavior::Panic),
        ] {
            let a = fmt(&format!(
                "format --size 64M --uuid {UUID} --time 1 --errors {name} out.img"
            ));
            assert_eq!(a.errors, want, "--errors {name}");
        }
        let a = fmt(&format!("format --size 64M --uuid {UUID} --time 1 out.img"));
        assert_eq!(a.errors, ErrorBehavior::Continue, "the default is continue");

        // A name outside the set is a usage error, not a silent fallback to the default.
        let err = line(&format!(
            "format --size 64M --uuid {UUID} --time 1 --errors halt out.img"
        ))
        .unwrap_err();
        assert!(matches!(
            err,
            UsageError::Value {
                source: ValueError::NotOneOf { .. },
                ..
            }
        ));
    }

    #[test]
    fn format_refuses_an_over_long_label_and_a_bad_percent() {
        // A label past sixteen bytes is a usage error, not a silent truncation.
        let err = line(&format!(
            "format --size 64M --uuid {UUID} --time 1 --label 0123456789abcdefX out.img"
        ))
        .unwrap_err();
        assert!(matches!(
            err,
            UsageError::Value {
                source: ValueError::LabelTooLong { len: 17 },
                ..
            }
        ));

        // A reserved percentage past 50, or finer than two decimals, or signed, is refused.
        for bad in ["60", "1.234", "-1"] {
            let err = line(&format!(
                "format --size 64M --uuid {UUID} --time 1 --reserved-percent {bad} out.img"
            ))
            .unwrap_err();
            assert!(
                matches!(err, UsageError::Value { .. }),
                "--reserved-percent {bad} should be a usage error"
            );
        }
    }

    #[test]
    fn a_feature_set_that_cannot_reach_disk_is_refused_by_name() {
        // The orphan file's entries are journalled, so dropping the journal alone leaves
        // a filesystem that must never be written. The conflict is named at the command
        // line rather than deep in the planner.
        let err = line(&format!(
            "format --size 64M --uuid {UUID} --time 1 -O ^has_journal out.img"
        ))
        .unwrap_err();
        assert_eq!(
            err,
            UsageError::Feature(FeatureError::OrphanFileWithoutJournal)
        );
    }

    #[test]
    fn a_value_is_never_read_as_an_option() {
        // `--offset -1` gives `-1` to the size parser, which refuses it. Nothing looks
        // ahead at a value to decide whether it is a flag.
        let err = line("inspect --offset -1 image.img").unwrap_err();
        assert!(matches!(
            err,
            UsageError::Value {
                source: ValueError::NotASize(_),
                ..
            }
        ));
        // A value attached with `=` is the same value.
        assert!(matches!(
            line("inspect --offset=-1 image.img").unwrap_err(),
            UsageError::Value { .. }
        ));
    }

    #[test]
    fn double_dash_ends_the_options() {
        // A file named like an option is still a file.
        let a = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 -- --weird.img"
        ));
        assert_eq!(a.out, PathBuf::from("--weird.img"));
    }

    #[test]
    fn double_dash_in_value_position_is_the_options_value() {
        // An option that needs a value takes the next token verbatim, even `--`: it does
        // not end the options there. So `--label -- out.img` gives the label the value
        // `--` and leaves `out.img` the output, matching getopt and the value() rule.
        let a = fmt(&format!(
            "format --size 64M --uuid {UUID} --time 1 --label -- out.img"
        ));
        assert_eq!(a.out, PathBuf::from("out.img"));
        assert_eq!(&a.volume_name[..2], b"--");
        assert_eq!(a.volume_name[2], 0, "the label is exactly `--`, NUL-padded");
    }

    #[test]
    fn unknown_and_malformed_options_are_usage_errors() {
        assert!(matches!(
            line("format --nonesuch out.img"),
            Err(UsageError::UnknownFlag { .. })
        ));
        assert!(matches!(
            parse(Vec::new(), None),
            Err(UsageError::NoCommand)
        ));
        assert!(matches!(
            line("frobnicate"),
            Err(UsageError::UnknownCommand(_))
        ));
        assert!(matches!(
            line("inspect --offset"),
            Err(UsageError::MissingValue(_))
        ));
        // An option that takes no value is not a place to put one.
        assert!(matches!(
            line("inspect --json=yes image.img"),
            Err(UsageError::UnexpectedValue(_))
        ));
        assert!(matches!(
            line("inspect"),
            Err(UsageError::MissingArgument { .. })
        ));
        assert!(matches!(
            line("inspect a.img b.img"),
            Err(UsageError::UnexpectedArgument { .. })
        ));
    }

    #[test]
    fn a_malformed_token_renders_without_a_stray_command_colon() {
        // The tokenizer rejects a token that is not a well-formed option before any
        // subcommand claims it, so its UnknownFlag carries no command. It renders
        // "-1: not an option", not ": -1: not an option" — which under the tool-name
        // prefix would read "ferrosys: : -1: not an option" with a stray colon.
        let err = line("format -1 out.img").expect_err("a non-alpha short flag is rejected");
        assert_eq!(err.to_string(), "-1: not an option");

        // A well-formed flag a command does not take still names the command.
        let err = line("format --nonesuch out.img").expect_err("an unknown flag is rejected");
        assert_eq!(err.to_string(), "format: --nonesuch: not an option");
    }

    #[test]
    fn inspect_scans_by_default_and_faults_a_filesystem_that_is_unsound() {
        match line("inspect image.img").expect("parses") {
            Command::Inspect(a) => {
                assert!(!a.quick, "a scan is what makes a bad filesystem reportable");
                // Integrity, not conformance: a filesystem another formatter wrote is not
                // this tool's output, and it is not thereby broken.
                assert_eq!(a.fail_on, Some(Severity::Integrity));
                assert_eq!(a.offset, 0);
            }
            other => panic!("expected inspect, got {other:?}"),
        }
        // The threshold moves in every direction: down to the self-check, up so that only
        // a destroyed filesystem is bad, and away entirely so that nothing is.
        match line("inspect --fail-on conformance image.img").expect("parses") {
            Command::Inspect(a) => assert_eq!(a.fail_on, Some(Severity::Conformance)),
            other => panic!("expected inspect, got {other:?}"),
        }
        match line("inspect --fail-on structural image.img").expect("parses") {
            Command::Inspect(a) => assert_eq!(a.fail_on, Some(Severity::Structural)),
            other => panic!("expected inspect, got {other:?}"),
        }
        match line("inspect --fail-on never image.img").expect("parses") {
            Command::Inspect(a) => assert_eq!(a.fail_on, None),
            other => panic!("expected inspect, got {other:?}"),
        }
    }

    #[test]
    fn inspect_sarif_is_a_findings_dialect() {
        // The flag selects the SARIF projection and nothing else changes.
        match line("inspect --sarif image.img").expect("parses") {
            Command::Inspect(a) => {
                assert!(a.sarif);
                assert!(!a.json);
                assert!(!a.quick);
            }
            other => panic!("expected inspect, got {other:?}"),
        }
        // SARIF and JSON are two output formats: asking for both is a usage error, not a
        // silent precedence.
        assert_eq!(
            line("inspect --sarif --json image.img").unwrap_err(),
            UsageError::SarifWithJson
        );
        // SARIF reports the scan's findings, so it cannot pair with the flag that skips the
        // scan.
        assert_eq!(
            line("inspect --sarif --quick image.img").unwrap_err(),
            UsageError::SarifWithQuick
        );
        // Nor with the one that asks for a group table, which a findings log has no place
        // to render. Accepting it would read as having worked while changing nothing.
        assert_eq!(
            line("inspect --sarif --groups image.img").unwrap_err(),
            UsageError::SarifWithGroups
        );
    }

    #[test]
    fn extract_produces_exactly_one_thing() {
        match line("extract --to-tar - image.img").expect("parses") {
            Command::Extract(a) => assert_eq!(a.mode, ExtractMode::ToTar(Stream::Std)),
            other => panic!("expected extract, got {other:?}"),
        }
        match line("extract --cat /etc/hostname image.img").expect("parses") {
            Command::Extract(a) => {
                assert_eq!(a.mode, ExtractMode::Cat(b"/etc/hostname".to_vec()));
            }
            other => panic!("expected extract, got {other:?}"),
        }
        match line("extract --list --json image.img").expect("parses") {
            Command::Extract(a) => assert_eq!(a.mode, ExtractMode::List { json: true }),
            other => panic!("expected extract, got {other:?}"),
        }
        // Nothing, or more than one thing, is a usage error rather than a guess.
        assert_eq!(
            line("extract image.img").unwrap_err(),
            UsageError::ExtractMode
        );
        assert_eq!(
            line("extract --list --cat /x image.img").unwrap_err(),
            UsageError::ExtractMode
        );
        // Bytes have no JSON form.
        assert_eq!(
            line("extract --cat /x --json image.img").unwrap_err(),
            UsageError::JsonWithoutReport
        );
    }

    #[test]
    fn extract_writes_a_tree_and_the_skip_belongs_to_it() {
        match line("extract --to-dir unpacked image.img").expect("parses") {
            Command::Extract(a) => assert_eq!(
                a.mode,
                ExtractMode::ToDir {
                    path: "unpacked".into(),
                    skip_privileged: false,
                }
            ),
            other => panic!("expected extract, got {other:?}"),
        }
        match line("extract --to-dir unpacked --skip-privileged image.img").expect("parses") {
            Command::Extract(a) => assert_eq!(
                a.mode,
                ExtractMode::ToDir {
                    path: "unpacked".into(),
                    skip_privileged: true,
                }
            ),
            other => panic!("expected extract, got {other:?}"),
        }
        // A tree and an archive are two artifacts, and a run produces one.
        assert_eq!(
            line("extract --to-dir d --to-tar t image.img").unwrap_err(),
            UsageError::ExtractMode
        );
        // A tree is not a report, so it has no JSON form; and it is not a file, so there is
        // nothing to rename into place.
        assert_eq!(
            line("extract --to-dir d --json image.img").unwrap_err(),
            UsageError::JsonWithoutReport
        );
        assert_eq!(
            line("extract --to-dir d --atomic image.img").unwrap_err(),
            UsageError::AtomicWithoutFile
        );
        // And the skip is about writing a tree, so it goes nowhere else.
        for spelling in [
            "extract --to-tar out.tar --skip-privileged image.img",
            "extract --list --skip-privileged image.img",
        ] {
            assert_eq!(
                line(spelling).unwrap_err(),
                UsageError::SkipPrivilegedWithoutDir,
                "{spelling}"
            );
        }
    }

    #[test]
    fn extract_atomic_needs_a_destination_to_rename_into() {
        match line("extract --to-tar out.tar --atomic image.img").expect("parses") {
            Command::Extract(a) => {
                assert_eq!(a.mode, ExtractMode::ToTar(Stream::File("out.tar".into())));
                assert!(a.atomic);
            }
            other => panic!("expected extract, got {other:?}"),
        }
        // The standard output has no rename that could make it whole, and neither has a
        // mode that writes no file. An accepted flag that cannot do what it promises is
        // worse than a refused one.
        for spelling in [
            "extract --to-tar - --atomic image.img",
            "extract --list --atomic image.img",
            "extract --cat /x --atomic image.img",
        ] {
            assert_eq!(
                line(spelling).unwrap_err(),
                UsageError::AtomicWithoutFile,
                "{spelling}"
            );
        }
    }

    #[test]
    fn help_and_version_are_reachable_everywhere() {
        assert_eq!(line("--help").unwrap(), Command::Help(Topic::General));
        assert_eq!(line("-h").unwrap(), Command::Help(Topic::General));
        assert_eq!(line("help").unwrap(), Command::Help(Topic::General));
        assert_eq!(line("--version").unwrap(), Command::Version);
        assert_eq!(line("format --help").unwrap(), Command::Help(Topic::Format));
        assert_eq!(line("inspect -h").unwrap(), Command::Help(Topic::Inspect));
        assert_eq!(
            line("extract --help").unwrap(),
            Command::Help(Topic::Extract)
        );
        // Help wins over the arguments it would otherwise be missing.
        assert_eq!(line("format --help").unwrap(), Command::Help(Topic::Format));
    }

    #[test]
    fn a_path_inside_the_image_is_bytes_not_text() {
        // A path in a filesystem need not be text at all, so `--cat` takes the argument's
        // bytes rather than a string it would first have to decode.
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStringExt;
            let argv = vec![
                OsString::from("extract"),
                OsString::from("--cat"),
                OsString::from_vec(b"/od\xffd".to_vec()),
                OsString::from("image.img"),
            ];
            match parse(argv, None).expect("parses") {
                Command::Extract(a) => assert_eq!(a.mode, ExtractMode::Cat(b"/od\xffd".to_vec())),
                other => panic!("expected extract, got {other:?}"),
            }
        }
    }
}