rz-archive 0.15.0

Multi-format archive tool — tar, zip, 7z with a unified CLI
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
use std::io::{IsTerminal, Read, Write};
use std::process::ExitCode;

use camino::{Utf8Path, Utf8PathBuf};
use clap::{CommandFactory, Parser};

use rz_archive::cmd::{Cli, Command, Format, PasswordArgs, SortField};
use rz_archive::error::{Error, Result};
use rz_archive::filter;
use rz_archive::format::{resolve_compress_format, resolve_input_format};
use rz_archive::modify::{self, AppendMode};
use rz_archive::progress::{BarProgress, NoProgress, ProgressReport, VerboseReport};
#[cfg(feature = "bzip2")]
use rz_archive::tar_bz2;
use rz_archive::{CompressOpts, DecompressOpts, seven_z, tar, tar_gz, tar_xz, tar_zst, zip};

/// Resolve a password from any of the three password-source flags.
///
/// Returns `Ok(None)` when no flag is set.  Returns an error when:
/// - `--password-stdin` is set and stdin is empty.
/// - `--password-file PATH` is set and the first line is empty or the file
///   cannot be read.
fn resolve_password(args: &PasswordArgs) -> Result<Option<String>> {
    if args.password_stdin {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).map_err(Error::Io)?;
        // Strip one trailing \r\n or \n.
        if buf.ends_with('\n') {
            buf.pop();
            if buf.ends_with('\r') {
                buf.pop();
            }
        }
        if buf.is_empty() {
            return Err(Error::EmptyPassword);
        }
        return Ok(Some(buf));
    }
    if let Some(ref path) = args.password_file {
        let content = fs_err::read_to_string(path)?;
        let line = content.lines().next().unwrap_or("").to_owned();
        if line.is_empty() {
            return Err(Error::EmptyPassword);
        }
        return Ok(Some(line));
    }
    if let Some(ref pw) = args.password {
        return Ok(Some(pw.clone()));
    }
    Ok(None)
}

/// Reject encryption flags for formats that don't support it (everything
/// except zip and 7z).
fn reject_encryption_for_non_supported(fmt: &Format, password: &Option<String>) -> Result<()> {
    if password.is_none() {
        return Ok(());
    }
    if matches!(fmt, Format::Zip | Format::SevenZ) {
        return Ok(());
    }
    Err(Error::EncryptionUnsupported(fmt.to_string()))
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    if let Some(n) = cli.threads
        && n > 0
    {
        let _ = rayon::ThreadPoolBuilder::new()
            .num_threads(n)
            .build_global();
    }
    if let Err(e) = run(cli) {
        let mut stderr = std::io::stderr().lock();
        // Error messages embed archive entry names (FileExists, PathTraversal,
        // unpack I/O errors), which hostile archives can lace with terminal
        // control bytes — escape the whole message, same as entry listings.
        let msg = e.to_string();
        let _ = writeln!(
            stderr,
            "rz: {}",
            rz_archive::progress::escape_entry_name(&msg)
        );
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

/// Returns `true` when the path is the conventional stdin/stdout placeholder.
fn is_stdio(path: &str) -> bool {
    path == "-"
}

/// Returns `true` when the format requires seekable I/O (not streamable).
fn requires_seek(fmt: &Format) -> bool {
    matches!(fmt, Format::Zip | Format::SevenZ)
}

/// Reproducibility overrides (`--mtime`, `--owner`, `--group`, `--mode`)
/// require writing per-entry metadata that zip and 7z don't expose through
/// our underlying writers: zip has no UID/GID field in its central directory,
/// and `sevenz-rust2::ArchiveWriter` has no per-entry metadata hook.  Rather
/// than silently no-op the flags, reject up front with a clear pointer to the
/// tar-family formats that do support reproducibility.
fn reject_reproducibility_for_non_tar(
    fmt: &Format,
    mtime: Option<u64>,
    owner: Option<u64>,
    group: Option<u64>,
    mode: Option<u32>,
    newer_than: Option<i64>,
    older_than: Option<i64>,
) -> Result<()> {
    let is_tar_family = matches!(
        fmt,
        Format::Tar | Format::TarGz | Format::TarZst | Format::TarXz | Format::TarBz2
    );
    if is_tar_family {
        return Ok(());
    }
    let check = |flag: &'static str, present: bool| -> Result<()> {
        if present {
            return Err(Error::ReproducibilityFlagUnsupported {
                flag,
                format: fmt.to_string(),
            });
        }
        Ok(())
    };
    check("--mtime", mtime.is_some())?;
    check("--owner", owner.is_some())?;
    check("--group", group.is_some())?;
    check("--mode", mode.is_some())?;
    check("--newer-than", newer_than.is_some())?;
    check("--older-than", older_than.is_some())?;
    Ok(())
}

/// Format a byte count for display.  When `human` is true, uses IEC-style
/// units (KiB, MiB, …); otherwise returns the raw number followed by "bytes".
fn format_size(bytes: u64, human: bool) -> String {
    if !human {
        return format!("{bytes} bytes");
    }
    const UNITS: &[&str] = &["B", "KiB", "MiB", "GiB", "TiB"];
    let mut value = bytes as f64;
    for &unit in UNITS {
        if value < 1024.0 {
            return if unit == "B" {
                format!("{bytes} B")
            } else {
                format!("{value:.1} {unit}")
            };
        }
        value /= 1024.0;
    }
    format!("{value:.1} PiB")
}

/// Maximum bytes peeked from stdin for magic-byte format detection.
///
/// Plain tar's `ustar` magic sits at offset 257, so we need at least 262 bytes
/// to recognise it; 512 (one tar block) is a safe round figure that also covers
/// the offset-0 magics (gzip, zstd, xz, bzip2, zip, 7z).
const STDIN_MAGIC_PREFIX: usize = 512;

/// The reader returned for a stdin archive: the peeked prefix chained ahead of
/// the unread remainder of the stream, so the format detector and the decoder
/// both see the whole archive.
type StdinReader = std::io::Chain<std::io::Cursor<Vec<u8>>, std::io::StdinLock<'static>>;

/// Resolve a stdin archive into its format and a replayable reader.
///
/// Peeks a prefix of stdin, determines the format (explicit `--format` wins,
/// else magic-byte auto-detection), then chains the prefix back onto the rest
/// of the stream. zip and 7z need seekable input and are rejected here, as is
/// a terminal/empty stdin (nothing was piped in).
fn resolve_stdin_source(format: Option<Format>) -> Result<(Format, StdinReader)> {
    // A terminal stdin means nothing was piped in; reading would block forever.
    if std::io::stdin().is_terminal() {
        return Err(Error::NoInput);
    }

    let mut stdin = std::io::stdin().lock();
    let prefix = filter::read_prefix(&mut stdin, STDIN_MAGIC_PREFIX)?;
    if prefix.is_empty() {
        return Err(Error::NoInput);
    }

    let fmt = match format {
        Some(f) => f,
        None => Format::from_magic_bytes(&prefix).ok_or(Error::CannotInferFormatStdin)?,
    };
    rz_archive::format::ensure_format_enabled(&fmt)?;

    // zip and 7z need seekable input to read their central directory / header.
    if requires_seek(&fmt) {
        return Err(Error::StdinNotSupported(fmt.to_string()));
    }

    // Re-attach the peeked prefix ahead of the unread remainder of stdin.
    let reader = std::io::Cursor::new(prefix).chain(stdin);
    Ok((fmt, reader))
}

/// Read archive metadata from stdin.
fn info_from_stdin(
    format: Option<Format>,
    password: &Option<String>,
) -> Result<rz_archive::ArchiveInfo> {
    let (fmt, reader) = resolve_stdin_source(format)?;
    reject_encryption_for_non_supported(&fmt, password)?;
    let info = match fmt {
        Format::Tar => tar::info_from_reader(reader)?,
        Format::TarGz => tar_gz::info_from_reader(reader)?,
        Format::TarZst => tar_zst::info_from_reader(std::io::BufReader::new(reader))?,
        Format::TarXz => tar_xz::info_from_reader(reader)?,
        #[cfg(feature = "bzip2")]
        Format::TarBz2 => tar_bz2::info_from_reader(reader)?,
        _ => return Err(Error::StdinNotSupported(fmt.to_string())),
    };
    Ok(info)
}

/// List archive entries from stdin.
fn list_from_stdin(
    format: Option<Format>,
    password: &Option<String>,
) -> Result<Vec<rz_archive::Entry>> {
    let (fmt, reader) = resolve_stdin_source(format)?;
    reject_encryption_for_non_supported(&fmt, password)?;
    let entries = match fmt {
        Format::Tar => tar::list_from_reader(reader)?,
        Format::TarGz => tar_gz::list_from_reader(reader)?,
        Format::TarZst => tar_zst::list_from_reader(std::io::BufReader::new(reader))?,
        Format::TarXz => tar_xz::list_from_reader(reader)?,
        #[cfg(feature = "bzip2")]
        Format::TarBz2 => tar_bz2::list_from_reader(reader)?,
        _ => return Err(Error::StdinNotSupported(fmt.to_string())),
    };
    Ok(entries)
}

/// Verify archive integrity from stdin.
fn test_from_stdin(
    format: Option<Format>,
    password: &Option<String>,
    progress: &dyn ProgressReport,
) -> Result<()> {
    let (fmt, reader) = resolve_stdin_source(format)?;
    reject_encryption_for_non_supported(&fmt, password)?;
    match fmt {
        Format::Tar => tar::test_from_reader(reader, progress)?,
        Format::TarGz => tar_gz::test_from_reader(reader, progress)?,
        Format::TarZst => tar_zst::test_from_reader(std::io::BufReader::new(reader), progress)?,
        Format::TarXz => tar_xz::test_from_reader(reader, progress)?,
        #[cfg(feature = "bzip2")]
        Format::TarBz2 => tar_bz2::test_from_reader(reader, progress)?,
        _ => return Err(Error::StdinNotSupported(fmt.to_string())),
    }
    Ok(())
}

fn run(cli: Cli) -> Result<()> {
    match cli.command {
        Command::Compress {
            mut input,
            output,
            format,
            level,
            store,
            exclude,
            exclude_from,
            files_from,
            exclude_vcs,
            exclude_backups,
            follow_symlinks,
            exclude_vcs_ignores,
            no_recursion,
            totals,
            dry_run,
            mtime,
            owner,
            group,
            mode,
            newer_than,
            older_than,
            ignore_failed_read,
            password_args,
        } => {
            let password = resolve_password(&password_args)?;
            let level = if store { Some(0) } else { level };

            // Merge --files-from paths into input list.
            if let Some(ref list_file) = files_from {
                let extra = filter::read_paths_from_file(list_file)?;
                input.extend(extra);
            }

            // `input` can only be empty here when it came entirely from
            // --files-from (clap requires it otherwise) and the list held no
            // usable lines.  Bail before the dry-run branch silently prints
            // nothing and before `fmt.default_output(&input[0])` indexes an
            // empty vec.
            if input.is_empty() {
                return Err(Error::NoReadableInputs);
            }

            // Build combined exclude set.
            let mut extra_patterns = exclude;
            if exclude_vcs {
                for pat in &[".git", ".hg", ".svn", ".bzr", "_darcs", ".pijul", "CVS"] {
                    extra_patterns.push((*pat).to_owned());
                }
            }
            if exclude_backups {
                for pat in &["*~", "*.bak", "#*#", ".#*"] {
                    extra_patterns.push((*pat).to_owned());
                }
            }
            let excludes = filter::build_excludes(extra_patterns, &exclude_from)?;

            // Dry-run: list what would be compressed and exit.
            if dry_run {
                // Mirror the real run's format-level rejections so a preview
                // never exits 0 for a command the real run refuses (disabled
                // feature build, unsupported flag combinations).  A bare
                // `compress -n <paths>` with no output or format still
                // previews the walk — there the format is unknowable.
                let to_stdout = output.as_ref().is_some_and(|o| is_stdio(o.as_str()));
                let known_fmt = if to_stdout {
                    format
                } else {
                    resolve_compress_format(format, output.as_deref()).ok()
                };
                if let Some(fmt) = known_fmt {
                    rz_archive::format::ensure_format_enabled(&fmt)?;
                    if to_stdout && requires_seek(&fmt) {
                        return Err(Error::StdoutNotSupported(fmt.to_string()));
                    }
                    reject_reproducibility_for_non_tar(
                        &fmt, mtime, owner, group, mode, newer_than, older_than,
                    )?;
                    reject_encryption_for_non_supported(&fmt, &password)?;
                }
                let dry_opts = CompressOpts {
                    level,
                    excludes,
                    follow_symlinks,
                    exclude_vcs_ignores,
                    no_recursion,
                    progress: &NoProgress,
                    fixed_mtime: mtime,
                    fixed_uid: owner,
                    fixed_gid: group,
                    fixed_mode: mode,
                    newer_than,
                    older_than,
                    ignore_failed_read,
                    password: None,
                };
                let paths = filter::collect_compress_paths(&input, &dry_opts)?;
                let mut stdout = std::io::stdout().lock();
                for p in &paths {
                    let _ = writeln!(stdout, "{p}");
                }
                return Ok(());
            }

            let to_stdout = output.as_ref().is_some_and(|o| is_stdio(o.as_str()));

            let fmt = if to_stdout {
                format.ok_or(Error::CannotInferOutput)?
            } else {
                resolve_compress_format(format, output.as_deref())?
            };
            rz_archive::format::ensure_format_enabled(&fmt)?;

            if to_stdout && requires_seek(&fmt) {
                return Err(Error::StdoutNotSupported(fmt.to_string()));
            }

            // Reproducibility flags are implemented only for tar-family formats;
            // zip and 7z either lack fields for the metadata (zip has no UID/GID)
            // or the writer doesn't expose per-entry overrides (sevenz-rust2).
            // Reject rather than silently no-op so users don't get misleading
            // results when chasing bit-for-bit reproducibility.
            reject_reproducibility_for_non_tar(
                &fmt, mtime, owner, group, mode, newer_than, older_than,
            )?;

            // Encryption is only supported for zip and 7z; reject early for
            // tar-family so the user gets a clear message before any I/O.
            reject_encryption_for_non_supported(&fmt, &password)?;

            let base_progress: Box<dyn ProgressReport> = if cli.progress && !to_stdout {
                Box::new(BarProgress::spinner())
            } else if totals {
                Box::new(BarProgress::hidden())
            } else {
                Box::new(NoProgress)
            };
            let verbose_progress;
            let progress: &dyn ProgressReport = if cli.verbose {
                verbose_progress = VerboseReport::new(&*base_progress);
                &verbose_progress
            } else {
                &*base_progress
            };
            let opts = CompressOpts {
                level,
                excludes,
                follow_symlinks,
                exclude_vcs_ignores,
                no_recursion,
                progress,
                fixed_mtime: mtime,
                fixed_uid: owner,
                fixed_gid: group,
                fixed_mode: mode,
                newer_than,
                older_than,
                ignore_failed_read,
                password,
            };

            if to_stdout {
                let stdout = std::io::stdout().lock();
                match fmt {
                    Format::Tar => tar::compress_to_writer(&input, stdout, &opts)?,
                    Format::TarGz => tar_gz::compress_to_writer(&input, stdout, &opts)?,
                    Format::TarZst => tar_zst::compress_to_writer(&input, stdout, &opts)?,
                    Format::TarXz => tar_xz::compress_to_writer(&input, stdout, &opts)?,
                    #[cfg(feature = "bzip2")]
                    Format::TarBz2 => tar_bz2::compress_to_writer(&input, stdout, &opts)?,
                    _ => return Err(Error::StdoutNotSupported(fmt.to_string())),
                }
                // The lock above was moved into the writer; re-acquire it to force
                // out anything still sitting in Stdout's own buffer and surface a
                // late write failure (e.g. a full disk) instead of exiting 0.
                std::io::stdout().lock().flush()?;
            } else {
                let output = match output {
                    Some(o) => o,
                    None => fmt.default_output(&input[0]),
                };
                match fmt {
                    Format::Zip => zip::compress(&input, &output, &opts)?,
                    Format::Tar => tar::compress(&input, &output, &opts)?,
                    Format::TarGz => tar_gz::compress(&input, &output, &opts)?,
                    Format::TarZst => tar_zst::compress(&input, &output, &opts)?,
                    Format::TarXz => tar_xz::compress(&input, &output, &opts)?,
                    #[cfg(feature = "bzip2")]
                    Format::TarBz2 => tar_bz2::compress(&input, &output, &opts)?,
                    Format::SevenZ => seven_z::compress(&input, &output, &opts)?,
                    #[allow(unreachable_patterns)]
                    other => return Err(Error::UnsupportedFormat(other.to_string())),
                }
            }
            progress.finish();
            if totals {
                let mut stderr = std::io::stderr().lock();
                let _ = writeln!(
                    stderr,
                    "Total bytes: {}",
                    format_size(progress.position(), false)
                );
            }
        }

        Command::Decompress {
            input,
            output,
            format,
            force,
            no_overwrite,
            keep_newer,
            no_directory,
            to_stdout,
            strip_components,
            exclude,
            exclude_from,
            include,
            backup,
            suffix,
            preserve_permissions,
            same_owner,
            newer_than,
            older_than,
            totals,
            dry_run,
            rename,
            prefix,
            paths,
            one_top_level,
            password_args,
        } => {
            let password = resolve_password(&password_args)?;
            let from_stdin = input.as_ref().is_none_or(|p| is_stdio(p.as_str()));

            // For stdin, peek + detect the format now; the returned reader
            // carries the rest of the stream through to extraction. The
            // requires_seek (zip/7z) and terminal/empty-stdin rejections happen
            // inside resolve_stdin_source.
            let (fmt, mut stdin_reader) = if from_stdin {
                let (fmt, reader) = resolve_stdin_source(format)?;
                (fmt, Some(reader))
            } else {
                let fmt = match input.as_deref() {
                    Some(p) => resolve_input_format(format, p)?,
                    None => return Err(Error::NoInput),
                };
                rz_archive::format::ensure_format_enabled(&fmt)?;
                (fmt, None)
            };
            // From here on treat input as a concrete path; it is empty and
            // unused on the stdin path (every use is gated by `from_stdin`).
            let input = input.unwrap_or_default();

            // `--one-top-level` derives a sub-directory from the archive
            // filename (`foo.tar.gz` → `foo/`).  Stdin has no filename, so
            // we can't derive anything — bail with a clear error rather
            // than silently treating "-" as the stem.  The directory itself
            // is created further down, after the dry-run early return.
            let output = if one_top_level {
                if from_stdin {
                    return Err(Error::OneTopLevelStdin);
                }
                Some(fmt.derive_output_dir(&input))
            } else {
                output
            };

            let excludes = filter::build_excludes(exclude, &exclude_from)?;
            let includes = {
                let mut all_includes = include;
                all_includes.extend(paths);
                filter::build_glob_set(&all_includes)?
            };

            // Flag-support validation runs before the dry-run branch so a
            // preview never exits 0 for a command whose real run would be
            // rejected.
            //
            // --same-owner only applies to tar-family extraction (zip/7z
            // don't carry portable uid/gid).  Reject up front so users don't
            // assume ownership is being restored silently.
            let is_tar_family = matches!(
                fmt,
                Format::Tar | Format::TarGz | Format::TarZst | Format::TarXz | Format::TarBz2
            );
            if same_owner && !is_tar_family {
                return Err(Error::ReproducibilityFlagUnsupported {
                    flag: "--same-owner",
                    format: fmt.to_string(),
                });
            }
            // Time-based filters read the entry mtime from the tar header;
            // zip and 7z entries don't expose reliable mtime through the
            // current crates (sevenz-rust2 in particular).  Reject rather
            // than silently returning no matches.
            if !is_tar_family && (newer_than.is_some() || older_than.is_some()) {
                let flag = if newer_than.is_some() {
                    "--newer-than"
                } else {
                    "--older-than"
                };
                return Err(Error::ReproducibilityFlagUnsupported {
                    flag,
                    format: fmt.to_string(),
                });
            }
            // Mirror the 7z module's own rejections so dry-run predicts them
            // instead of printing paths a real run would refuse to create.
            if fmt == Format::SevenZ {
                if strip_components > 0 {
                    return Err(Error::StripComponentsUnsupported("7z".to_owned()));
                }
                if keep_newer {
                    return Err(Error::KeepNewerUnsupported("7z".to_owned()));
                }
            }

            reject_encryption_for_non_supported(&fmt, &password)?;

            // Dry-run: list what would be extracted and exit.
            if dry_run {
                let entries = if from_stdin {
                    // Consume the peeked reader to list; dry-run never extracts,
                    // so spending the stream here is fine.
                    let reader = stdin_reader.take().ok_or(Error::NoInput)?;
                    match fmt {
                        Format::Tar => tar::list_from_reader(reader)?,
                        Format::TarGz => tar_gz::list_from_reader(reader)?,
                        Format::TarZst => {
                            tar_zst::list_from_reader(std::io::BufReader::new(reader))?
                        }
                        Format::TarXz => tar_xz::list_from_reader(reader)?,
                        #[cfg(feature = "bzip2")]
                        Format::TarBz2 => tar_bz2::list_from_reader(reader)?,
                        _ => return Err(Error::StdinNotSupported(fmt.to_string())),
                    }
                } else {
                    match fmt {
                        Format::Zip => zip::list(&input)?,
                        Format::Tar => tar::list(&input)?,
                        Format::TarGz => tar_gz::list(&input)?,
                        Format::TarZst => tar_zst::list(&input)?,
                        Format::TarXz => tar_xz::list(&input)?,
                        #[cfg(feature = "bzip2")]
                        Format::TarBz2 => tar_bz2::list(&input)?,
                        Format::SevenZ => seven_z::list(&input)?,
                        #[allow(unreachable_patterns)]
                        other => return Err(Error::UnsupportedFormat(other.to_string())),
                    }
                };
                // Resolve each entry through the same chain the extractors
                // use (mtime window, --no-directory, --rename, --prefix via
                // filter::resolve_entry_path), so the preview names the paths
                // a real run would create — not just the stripped originals.
                let dry_opts = DecompressOpts {
                    force,
                    no_overwrite,
                    keep_newer,
                    no_directory,
                    strip_components,
                    includes,
                    excludes,
                    backup_suffix: None,
                    preserve_permissions,
                    same_owner,
                    newer_than,
                    older_than,
                    renames: rename,
                    prefix,
                    progress: &NoProgress,
                    password: None,
                };
                let mut stdout = std::io::stdout().lock();
                for entry in &entries {
                    // The real run rejects hostile shapes before any
                    // filtering — raw-name traversal and absolute/`..` link
                    // targets — so the preview must fail identically instead
                    // of predicting paths.  (7z link targets live in the
                    // solid stream and stay extraction-time-only.)
                    filter::safe_entry_path(entry.path.as_str())?;
                    if let Some(target) = &entry.link_target {
                        let target_path = camino::Utf8Path::new(target);
                        if target_path.is_absolute()
                            || target_path
                                .components()
                                .any(|c| matches!(c, camino::Utf8Component::ParentDir))
                        {
                            return Err(Error::PathTraversal(format!(
                                "{} -> {target}",
                                entry.path
                            )));
                        }
                    }
                    if !filter::should_extract(
                        entry.path.as_str(),
                        &dry_opts.includes,
                        &dry_opts.excludes,
                    ) {
                        continue;
                    }
                    if !filter::passes_time_filter(entry.mtime as i64, newer_than, older_than) {
                        continue;
                    }
                    if entry.is_dir && no_directory {
                        continue;
                    }
                    if let Some(dest) = filter::resolve_entry_path(&entry.path, &dry_opts)? {
                        // --one-top-level's whole effect is the derived
                        // destination directory; show it, or the preview is
                        // indistinguishable from a run without the flag.
                        let dest = if one_top_level {
                            match &output {
                                Some(dir) => dir.join(&dest),
                                None => dest,
                            }
                        } else {
                            dest
                        };
                        let _ = writeln!(
                            stdout,
                            "{}",
                            rz_archive::progress::escape_entry_name(dest.as_str())
                        );
                    }
                }
                return Ok(());
            }

            // Tar-family extraction expects its output directory to already
            // exist, so create the --one-top-level dir here — after the
            // dry-run early return (a preview must not touch the disk), and
            // only once the input archive is known to exist, so a failed run
            // doesn't leave an empty directory behind.
            if one_top_level {
                fs_err::metadata(&input)?;
                if let Some(ref dir) = output {
                    fs_err::create_dir_all(dir)?;
                }
            }

            let base_progress: Box<dyn ProgressReport> = if cli.progress && !from_stdin {
                let file_size = fs_err::metadata(&input)?.len();
                Box::new(BarProgress::bytes(file_size))
            } else if cli.progress {
                Box::new(BarProgress::spinner())
            } else if totals {
                Box::new(BarProgress::hidden())
            } else {
                Box::new(NoProgress)
            };
            let verbose_progress;
            let progress: &dyn ProgressReport = if cli.verbose {
                verbose_progress = VerboseReport::new(&*base_progress);
                &verbose_progress
            } else {
                &*base_progress
            };
            let backup_suffix = if let Some(s) = suffix {
                Some(s)
            } else if backup {
                Some(".bak".to_owned())
            } else {
                None
            };

            let opts = DecompressOpts {
                force,
                no_overwrite,
                keep_newer,
                no_directory,
                strip_components,
                includes,
                excludes,
                backup_suffix,
                preserve_permissions,
                same_owner,
                newer_than,
                older_than,
                renames: rename,
                prefix,
                progress,
                password,
            };

            if to_stdout {
                let mut stdout = std::io::stdout().lock();
                if from_stdin {
                    let reader = stdin_reader.take().ok_or(Error::NoInput)?;
                    match fmt {
                        Format::Tar => {
                            tar::decompress_reader_to_writer(reader, &mut stdout, &opts)?
                        }
                        Format::TarGz => {
                            tar_gz::decompress_reader_to_writer(reader, &mut stdout, &opts)?
                        }
                        Format::TarZst => tar_zst::decompress_reader_to_writer(
                            std::io::BufReader::new(reader),
                            &mut stdout,
                            &opts,
                        )?,
                        Format::TarXz => {
                            tar_xz::decompress_reader_to_writer(reader, &mut stdout, &opts)?
                        }
                        #[cfg(feature = "bzip2")]
                        Format::TarBz2 => {
                            tar_bz2::decompress_reader_to_writer(reader, &mut stdout, &opts)?
                        }
                        _ => return Err(Error::StdinNotSupported(fmt.to_string())),
                    }
                } else {
                    match fmt {
                        Format::Zip => zip::decompress_to_writer(&input, &mut stdout, &opts)?,
                        Format::Tar => tar::decompress_to_writer(&input, &mut stdout, &opts)?,
                        Format::TarGz => tar_gz::decompress_to_writer(&input, &mut stdout, &opts)?,
                        Format::TarZst => {
                            tar_zst::decompress_to_writer(&input, &mut stdout, &opts)?
                        }
                        Format::TarXz => tar_xz::decompress_to_writer(&input, &mut stdout, &opts)?,
                        #[cfg(feature = "bzip2")]
                        Format::TarBz2 => {
                            tar_bz2::decompress_to_writer(&input, &mut stdout, &opts)?
                        }
                        Format::SevenZ => {
                            seven_z::decompress_to_writer(&input, &mut stdout, &opts)?
                        }
                        #[allow(unreachable_patterns)]
                        other => return Err(Error::UnsupportedFormat(other.to_string())),
                    }
                }
            } else if from_stdin {
                let output = output.unwrap_or_else(|| ".".into());
                let reader = stdin_reader.take().ok_or(Error::NoInput)?;
                match fmt {
                    Format::Tar => tar::decompress_from_reader(reader, &output, &opts)?,
                    Format::TarGz => tar_gz::decompress_from_reader(reader, &output, &opts)?,
                    Format::TarZst => tar_zst::decompress_from_reader(
                        std::io::BufReader::new(reader),
                        &output,
                        &opts,
                    )?,
                    Format::TarXz => tar_xz::decompress_from_reader(reader, &output, &opts)?,
                    #[cfg(feature = "bzip2")]
                    Format::TarBz2 => tar_bz2::decompress_from_reader(reader, &output, &opts)?,
                    _ => return Err(Error::StdinNotSupported(fmt.to_string())),
                }
            } else {
                let output = output.unwrap_or_else(|| ".".into());
                match fmt {
                    Format::Zip => zip::decompress(&input, &output, &opts)?,
                    Format::Tar => tar::decompress(&input, &output, &opts)?,
                    Format::TarGz => tar_gz::decompress(&input, &output, &opts)?,
                    Format::TarZst => tar_zst::decompress(&input, &output, &opts)?,
                    Format::TarXz => tar_xz::decompress(&input, &output, &opts)?,
                    #[cfg(feature = "bzip2")]
                    Format::TarBz2 => tar_bz2::decompress(&input, &output, &opts)?,
                    Format::SevenZ => seven_z::decompress(&input, &output, &opts)?,
                    #[allow(unreachable_patterns)]
                    other => return Err(Error::UnsupportedFormat(other.to_string())),
                }
            }
            progress.finish();
            if totals {
                let mut stderr = std::io::stderr().lock();
                let _ = writeln!(
                    stderr,
                    "Total bytes: {}",
                    format_size(progress.position(), false)
                );
            }
        }

        Command::List {
            input,
            format,
            long,
            exclude,
            exclude_from,
            sort,
            human_readable,
            json,
            password_args,
        } => {
            let password = resolve_password(&password_args)?;
            let from_stdin = input.as_ref().is_none_or(|p| is_stdio(p.as_str()));

            let mut entries = if from_stdin {
                list_from_stdin(format, &password)?
            } else {
                let input = input.unwrap_or_default();
                let fmt = resolve_input_format(format, &input)?;
                rz_archive::format::ensure_format_enabled(&fmt)?;
                reject_encryption_for_non_supported(&fmt, &password)?;
                match fmt {
                    Format::Zip => zip::list(&input)?,
                    Format::Tar => tar::list(&input)?,
                    Format::TarGz => tar_gz::list(&input)?,
                    Format::TarZst => tar_zst::list(&input)?,
                    Format::TarXz => tar_xz::list(&input)?,
                    #[cfg(feature = "bzip2")]
                    Format::TarBz2 => tar_bz2::list(&input)?,
                    Format::SevenZ => seven_z::list(&input)?,
                    #[allow(unreachable_patterns)]
                    other => return Err(Error::UnsupportedFormat(other.to_string())),
                }
            };

            let excludes = filter::build_excludes(exclude, &exclude_from)?;

            if let Some(ref field) = sort {
                match field {
                    SortField::Name => entries.sort_by(|a, b| a.path.cmp(&b.path)),
                    SortField::Size => entries.sort_by_key(|e| e.size),
                    SortField::Date => entries.sort_by_key(|e| e.mtime),
                }
            }

            let includes = globset::GlobSet::empty();
            let filtered: Vec<_> = entries
                .into_iter()
                .filter(|e| filter::should_extract(e.path.as_str(), &includes, &excludes))
                .collect();

            let mut stdout = std::io::stdout().lock();
            if json {
                let _ = serde_json::to_writer_pretty(&mut stdout, &filtered);
                let _ = writeln!(stdout);
            } else {
                for entry in &filtered {
                    // Entry names come straight from archive metadata —
                    // defang control characters before they reach the
                    // terminal (see progress::escape_entry_name).
                    let name = rz_archive::progress::escape_entry_name(entry.path.as_str());
                    if long {
                        let kind = if entry.is_dir { "d" } else { "-" };
                        let size_str = format_size(entry.size, human_readable);
                        let _ = writeln!(
                            stdout,
                            "{kind}{:06o}  {:>10}  {name}",
                            entry.mode, size_str,
                        );
                    } else {
                        let _ = writeln!(stdout, "{name}");
                    }
                }
            }
        }

        Command::Test {
            input,
            format,
            password_args,
        } => {
            let password = resolve_password(&password_args)?;
            let from_stdin = input.as_ref().is_none_or(|p| is_stdio(p.as_str()));

            // A file gives us a byte total for a real progress bar; stdin can't
            // be sized ahead of time, so it falls back to a spinner.
            let base_progress: Box<dyn ProgressReport> = match input.as_ref() {
                Some(p) if cli.progress && !from_stdin => {
                    Box::new(BarProgress::bytes(fs_err::metadata(p)?.len()))
                }
                _ if cli.progress => Box::new(BarProgress::spinner()),
                _ => Box::new(NoProgress),
            };
            let verbose_progress;
            let progress: &dyn ProgressReport = if cli.verbose {
                verbose_progress = VerboseReport::new(&*base_progress);
                &verbose_progress
            } else {
                &*base_progress
            };
            if from_stdin {
                test_from_stdin(format, &password, progress)?;
            } else {
                let input = input.unwrap_or_default();
                let fmt = resolve_input_format(format, &input)?;
                rz_archive::format::ensure_format_enabled(&fmt)?;
                reject_encryption_for_non_supported(&fmt, &password)?;
                match fmt {
                    Format::Zip => zip::test(&input, password.as_deref(), progress)?,
                    Format::Tar => tar::test(&input, progress)?,
                    Format::TarGz => tar_gz::test(&input, progress)?,
                    Format::TarZst => tar_zst::test(&input, progress)?,
                    Format::TarXz => tar_xz::test(&input, progress)?,
                    #[cfg(feature = "bzip2")]
                    Format::TarBz2 => tar_bz2::test(&input, progress)?,
                    Format::SevenZ => seven_z::test(&input, password.as_deref(), progress)?,
                    #[allow(unreachable_patterns)]
                    other => return Err(Error::UnsupportedFormat(other.to_string())),
                }
            }
            progress.finish();
            if !cli.quiet {
                let mut stderr = std::io::stderr().lock();
                let _ = writeln!(stderr, "ok");
            }
        }

        Command::Info {
            input,
            format,
            human_readable,
            json,
            password_args,
        } => {
            let password = resolve_password(&password_args)?;
            // Stdin when no path is given or it's the `-` sentinel.
            let from_stdin = input.as_ref().is_none_or(|p| is_stdio(p.as_str()));

            let info = if from_stdin {
                info_from_stdin(format, &password)?
            } else {
                // Safe: `from_stdin` is false only when `input` is `Some` and
                // not `-`.
                let input = input.unwrap_or_default();
                let fmt = resolve_input_format(format, &input)?;
                rz_archive::format::ensure_format_enabled(&fmt)?;
                reject_encryption_for_non_supported(&fmt, &password)?;
                match fmt {
                    Format::Zip => zip::info(&input)?,
                    Format::Tar => tar::info(&input)?,
                    Format::TarGz => tar_gz::info(&input)?,
                    Format::TarZst => tar_zst::info(&input)?,
                    Format::TarXz => tar_xz::info(&input)?,
                    #[cfg(feature = "bzip2")]
                    Format::TarBz2 => tar_bz2::info(&input)?,
                    Format::SevenZ => seven_z::info(&input)?,
                    #[allow(unreachable_patterns)]
                    other => return Err(Error::UnsupportedFormat(other.to_string())),
                }
            };

            let mut stdout = std::io::stdout().lock();
            if json {
                let _ = serde_json::to_writer_pretty(&mut stdout, &info);
                let _ = writeln!(stdout);
            } else {
                let _ = writeln!(stdout, "Format:       {}", info.format);
                let _ = writeln!(stdout, "Entries:      {}", info.entry_count);
                let _ = writeln!(
                    stdout,
                    "Compressed:   {}",
                    format_size(info.compressed_size, human_readable)
                );
                let _ = writeln!(
                    stdout,
                    "Uncompressed: {}",
                    format_size(info.total_uncompressed, human_readable)
                );
            }
        }

        Command::Formats { json } => {
            print_formats(json)?;
        }

        Command::Completions { shell } => {
            let mut cmd = Cli::command();
            clap_complete::generate(shell, &mut cmd, "rz", &mut std::io::stdout().lock());
        }

        Command::Man => {
            let cmd = Cli::command();
            let man = clap_mangen::Man::new(cmd);
            let mut stdout = std::io::stdout().lock();
            man.render(&mut stdout).map_err(Error::Io)?;
        }

        Command::Append {
            archive,
            input,
            format,
            level,
            exclude,
            exclude_from,
            follow_symlinks,
        } => {
            run_append(
                cli.progress,
                cli.verbose,
                archive,
                input,
                format,
                level,
                exclude,
                exclude_from,
                follow_symlinks,
                AppendMode::Append,
            )?;
        }

        Command::Update {
            archive,
            input,
            format,
            level,
            exclude,
            exclude_from,
            follow_symlinks,
        } => {
            run_append(
                cli.progress,
                cli.verbose,
                archive,
                input,
                format,
                level,
                exclude,
                exclude_from,
                follow_symlinks,
                AppendMode::Update,
            )?;
        }

        Command::Remove {
            archive,
            patterns,
            format,
            level,
        } => {
            let fmt = resolve_input_format(format, &archive)?;
            rz_archive::format::ensure_format_enabled(&fmt)?;
            modify::remove(&archive, fmt, &patterns, level)?;
        }

        Command::Convert {
            input,
            output,
            from,
            to,
            level,
            force,
        } => {
            run_convert(input, output, from, to, level, force)?;
        }
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn run_append(
    show_progress: bool,
    verbose: bool,
    archive: camino::Utf8PathBuf,
    input: Vec<camino::Utf8PathBuf>,
    format: Option<Format>,
    level: Option<u32>,
    exclude: Vec<String>,
    exclude_from: Vec<camino::Utf8PathBuf>,
    follow_symlinks: bool,
    mode: AppendMode,
) -> Result<()> {
    let fmt = resolve_input_format(format, &archive)?;
    rz_archive::format::ensure_format_enabled(&fmt)?;
    let excludes = filter::build_excludes(exclude, &exclude_from)?;
    let base_progress: Box<dyn ProgressReport> = if show_progress {
        Box::new(BarProgress::spinner())
    } else {
        Box::new(NoProgress)
    };
    let verbose_progress;
    let progress: &dyn ProgressReport = if verbose {
        verbose_progress = VerboseReport::new(&*base_progress);
        &verbose_progress
    } else {
        &*base_progress
    };
    let opts = CompressOpts {
        level,
        excludes,
        follow_symlinks,
        exclude_vcs_ignores: false,
        no_recursion: false,
        progress,
        fixed_mtime: None,
        fixed_uid: None,
        fixed_gid: None,
        fixed_mode: None,
        newer_than: None,
        older_than: None,
        ignore_failed_read: false,
        password: None,
    };
    modify::append(&archive, fmt, &input, mode, &opts)?;
    progress.finish();
    Ok(())
}

/// Resolve the output format for `rz convert`.
///
/// Priority: explicit `--to` → extension of `--output` → error.
fn resolve_convert_output_format(
    to_format: Option<Format>,
    output: Option<&Utf8Path>,
) -> Result<Format> {
    if let Some(f) = to_format {
        return Ok(f);
    }
    if let Some(out) = output {
        if let Some(f) = Format::from_path(out) {
            return Ok(f);
        }
        return Err(Error::CannotInferFormat(out.to_owned()));
    }
    Err(Error::ConvertCannotInferOutputFormat)
}

/// Derive the output path when `--output` was omitted but `--to` was given.
///
/// Strips the input's extension(s) for `fmt_in` and appends `fmt_out`'s
/// canonical extension.  The directory component of `input` is preserved so
/// the output lands alongside the input.
///
/// Example: `/path/foo.tar.gz` + `--to tar-zst` → `/path/foo.tar.zst`
fn derive_convert_output(input: &Utf8Path, fmt_out: Format, fmt_in: Format) -> Utf8PathBuf {
    // We need to work on the file name, then re-join with the parent.
    let name = input.file_name().unwrap_or("archive");
    let stem = {
        let mut s = name;
        for ext in fmt_in.recognized_extensions() {
            if s.len() >= ext.len() && s[s.len() - ext.len()..].eq_ignore_ascii_case(ext) {
                s = &s[..s.len() - ext.len()];
                break;
            }
        }
        if s.is_empty() { "archive" } else { s }
    };
    let new_name = format!("{stem}{}", fmt_out.extension());
    match input.parent() {
        Some(parent) if !parent.as_str().is_empty() => parent.join(new_name),
        _ => Utf8PathBuf::from(new_name),
    }
}

/// Return `true` when two paths refer to the same filesystem object.
///
/// Canonicalization is attempted on both sides; if either fails (e.g. the
/// output doesn't exist yet) the raw `Utf8Path` strings are compared instead.
fn paths_canonically_equal(a: &Utf8Path, b: &Utf8Path) -> bool {
    let canon_a = a.canonicalize().ok();
    let canon_b = b.canonicalize().ok();
    match (canon_a, canon_b) {
        (Some(ca), Some(cb)) => ca == cb,
        _ => a == b,
    }
}

/// Dispatch list to the correct format module.
fn dispatch_list(fmt: Format, input: &Utf8Path) -> Result<Vec<rz_archive::Entry>> {
    match fmt {
        Format::Zip => zip::list(input),
        Format::Tar => tar::list(input),
        Format::TarGz => tar_gz::list(input),
        Format::TarZst => tar_zst::list(input),
        Format::TarXz => tar_xz::list(input),
        #[cfg(feature = "bzip2")]
        Format::TarBz2 => tar_bz2::list(input),
        Format::SevenZ => seven_z::list(input),
        #[allow(unreachable_patterns)]
        other => Err(Error::UnsupportedFormat(other.to_string())),
    }
}

/// Dispatch decompress to the correct format module.
fn dispatch_decompress(
    fmt: Format,
    input: &Utf8Path,
    output_dir: &Utf8Path,
    opts: &DecompressOpts<'_>,
) -> Result<()> {
    match fmt {
        Format::Zip => zip::decompress(input, output_dir, opts)?,
        Format::Tar => tar::decompress(input, output_dir, opts)?,
        Format::TarGz => tar_gz::decompress(input, output_dir, opts)?,
        Format::TarZst => tar_zst::decompress(input, output_dir, opts)?,
        Format::TarXz => tar_xz::decompress(input, output_dir, opts)?,
        #[cfg(feature = "bzip2")]
        Format::TarBz2 => tar_bz2::decompress(input, output_dir, opts)?,
        Format::SevenZ => seven_z::decompress(input, output_dir, opts)?,
        #[allow(unreachable_patterns)]
        other => return Err(Error::UnsupportedFormat(other.to_string())),
    }
    Ok(())
}

/// Dispatch compress to the correct format module.
fn dispatch_compress(
    fmt: Format,
    inputs: &[Utf8PathBuf],
    output: &Utf8Path,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    match fmt {
        Format::Zip => zip::compress(inputs, output, opts)?,
        Format::Tar => tar::compress(inputs, output, opts)?,
        Format::TarGz => tar_gz::compress(inputs, output, opts)?,
        Format::TarZst => tar_zst::compress(inputs, output, opts)?,
        Format::TarXz => tar_xz::compress(inputs, output, opts)?,
        #[cfg(feature = "bzip2")]
        Format::TarBz2 => tar_bz2::compress(inputs, output, opts)?,
        Format::SevenZ => seven_z::compress(inputs, output, opts)?,
        #[allow(unreachable_patterns)]
        other => return Err(Error::UnsupportedFormat(other.to_string())),
    }
    Ok(())
}

fn run_convert(
    input: Utf8PathBuf,
    output: Option<Utf8PathBuf>,
    from_format: Option<Format>,
    to_format: Option<Format>,
    level: Option<u32>,
    force: bool,
) -> Result<()> {
    let fmt_in = resolve_input_format(from_format, &input)?;
    let fmt_out = resolve_convert_output_format(to_format, output.as_deref())?;
    rz_archive::format::ensure_format_enabled(&fmt_in)?;
    rz_archive::format::ensure_format_enabled(&fmt_out)?;

    let output_path = match output {
        Some(p) => p,
        None => derive_convert_output(&input, fmt_out, fmt_in),
    };

    if !force && fs_err::metadata(&output_path).is_ok() {
        return Err(Error::FileExists(output_path));
    }

    if paths_canonically_equal(&input, &output_path) {
        return Err(Error::ConvertSamePath(output_path));
    }

    // Extract input into a temporary directory, then re-compress from there.
    let tmp = tempfile::tempdir()?;
    let tmp_dir = Utf8Path::from_path(tmp.path())
        .ok_or_else(|| Error::InvalidUtf8Path(tmp.path().display().to_string()))?
        .to_owned();

    // Convert is a fidelity-preserving re-encode, not a user-facing extract:
    // the tempdir is the only carrier for entry metadata, so anything not
    // preserved here is silently lost from the output archive.  Hence
    // preserve_permissions — DecompressOpts::new hardcodes it off, which
    // stripped the executable bit from every zip entry on the way through.
    let dec_opts = DecompressOpts {
        preserve_permissions: true,
        ..DecompressOpts::new(
            true,
            0,
            globset::GlobSet::empty(),
            globset::GlobSet::empty(),
        )
    };
    dispatch_decompress(fmt_in, &input, &tmp_dir, &dec_opts)?;

    // Same story for mtimes: tar restores file mtimes but nothing restores
    // directory mtimes (writing the children bumps them again), and zip
    // extraction restores no mtimes at all — so entries of a supposedly
    // format-only conversion got stamped with the conversion time.  Re-apply
    // what the source archive itself records.
    restore_entry_mtimes(&tmp_dir, &dispatch_list(fmt_in, &input)?)?;

    // Compress from the children of tmp_dir so the archive entries are named
    // after the original archive's top-level entries, not the tempdir itself.
    let mut children: Vec<Utf8PathBuf> = Vec::new();
    for entry in fs_err::read_dir(&tmp_dir)? {
        let entry = entry?;
        let p = entry.path();
        let utf8 = Utf8PathBuf::try_from(p)
            .map_err(|e| Error::InvalidUtf8Path(e.into_path_buf().display().to_string()))?;
        children.push(utf8);
    }

    let comp_opts = CompressOpts::new(level, globset::GlobSet::empty());
    dispatch_compress(fmt_out, &children, &output_path, &comp_opts)?;

    Ok(())
}

/// Stamp source-archive mtimes onto the extracted tempdir tree.
///
/// mtime 0 is stamped too: it is a real value in epoch-stamped reproducible
/// tars (and tar-rs's extractor writes such entries back as mtime 1, so
/// skipping would leave the drift in place).  For formats where 0 means
/// "unrecorded" (7z without dates) the entry deterministically becomes epoch
/// rather than the conversion wall-clock.  Entries missing on disk are
/// skipped.  Symlinks get `set_symlink_file_times` so the link itself is
/// stamped, not its target.  Setting a child's mtime does not touch its
/// parent directory's, so ordering is irrelevant here.
fn restore_entry_mtimes(tmp_dir: &Utf8Path, entries: &[rz_archive::Entry]) -> Result<()> {
    for entry in entries {
        let path = tmp_dir.join(entry.path.as_str().trim_end_matches('/'));
        let Ok(meta) = fs_err::symlink_metadata(&path) else {
            continue;
        };
        let ft = filetime::FileTime::from_unix_time(entry.mtime as i64, 0);
        if meta.file_type().is_symlink() {
            let _ = filetime::set_symlink_file_times(path.as_std_path(), ft, ft);
        } else {
            filetime::set_file_times(path.as_std_path(), ft, ft)?;
        }
    }
    Ok(())
}

fn print_formats(json: bool) -> Result<()> {
    use clap::ValueEnum;
    use serde::Serialize;

    #[derive(Serialize)]
    #[serde(rename_all = "lowercase")]
    enum OutputStatus {
        Enabled,
        Disabled,
    }

    #[derive(Serialize)]
    struct OutputFormat {
        format: String,
        extension: String,
        backend: Option<String>,
        status: OutputStatus,
    }

    // Built from the `Format` variants so the listed ids and extensions are
    // the exact strings `--format` accepts and `from_path` recognises — a
    // hand-written table here once drifted (`tar-cz`) and fed users an id the
    // parser rejects.
    let formats: Vec<OutputFormat> = Format::value_variants()
        .iter()
        .map(|fmt| {
            let (backend, status) = match fmt {
                Format::Zip => (Some("zip"), OutputStatus::Enabled),
                Format::Tar => (None, OutputStatus::Enabled),
                Format::TarGz => (Some("flate2"), OutputStatus::Enabled),
                Format::TarZst => (Some("ruzstd"), OutputStatus::Enabled),
                Format::TarXz => (
                    Some(if cfg!(feature = "xz2") {
                        "xz2 (C)"
                    } else {
                        "lzma-rust2"
                    }),
                    OutputStatus::Enabled,
                ),
                Format::TarBz2 => (
                    Some("bzip2 (C)"),
                    if cfg!(feature = "bzip2") {
                        OutputStatus::Enabled
                    } else {
                        OutputStatus::Disabled
                    },
                ),
                Format::SevenZ => (Some("sevenz-rust2"), OutputStatus::Enabled),
            };
            OutputFormat {
                format: fmt.to_string(),
                extension: fmt.extension().to_owned(),
                backend: backend.map(str::to_owned),
                status,
            }
        })
        .collect();

    if json {
        let mut stdout = std::io::stdout().lock();
        let json = serde_json::to_string(&formats).map_err(std::io::Error::other)?;
        let _ = writeln!(stdout, "{}", json);
    } else {
        let mut stdout = std::io::stdout().lock();
        let _ = writeln!(
            stdout,
            "{:<12} {:<12} {:<16} STATUS",
            "FORMAT", "EXTENSION", "BACKEND"
        );
        let _ = writeln!(stdout, "{}", "-".repeat(52));

        for OutputFormat {
            format,
            extension,
            backend,
            status,
        } in formats
        {
            let status = match status {
                OutputStatus::Enabled => "enabled",
                OutputStatus::Disabled => "disabled",
            };

            let backend = match backend {
                Some(backend) => backend,
                None => "-".into(),
            };

            let _ = writeln!(
                stdout,
                "{format:<12} {extension:<12} {backend:<16} {status}"
            );
        }
    }
    Ok(())
}