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
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
use std::io::BufRead;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

use camino::{Utf8Path, Utf8PathBuf};
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};

use crate::error::{Error, Result};
use crate::progress::ProgressReport;
use crate::{CompressOpts, DecompressOpts};

/// Returns `true` when an entry at `path` should be extracted, considering
/// both include and exclude filters.  When includes are non-empty, the path
/// must match at least one include pattern.  Excludes are always applied
/// afterward.
pub fn should_extract(path: &str, includes: &GlobSet, excludes: &GlobSet) -> bool {
    let clean = path.trim_end_matches('/');
    if !includes.is_empty() && !includes.is_match(clean) {
        return false;
    }
    if !excludes.is_empty() && excludes.is_match(clean) {
        return false;
    }
    true
}

/// Build a [`GlobSet`] from glob patterns (used for both include and exclude
/// rules — semantics are identical, only the caller's interpretation differs).
///
/// Bare patterns (without `/`) are prefixed with `**/` so they match at any
/// directory depth (matching `tar --exclude` behaviour).  Each pattern also
/// generates a `<pattern>/**` variant so that matching a directory name also
/// matches everything inside it.
pub fn build_glob_set(patterns: &[String]) -> Result<GlobSet> {
    if patterns.is_empty() {
        return Ok(GlobSet::empty());
    }
    let mut builder = GlobSetBuilder::new();
    for pattern in patterns {
        let effective = if pattern.contains('/') {
            pattern.clone()
        } else {
            format!("**/{pattern}")
        };
        let glob = GlobBuilder::new(&effective)
            .literal_separator(true)
            .build()
            .map_err(|e| Error::InvalidExcludePattern(e.to_string()))?;
        builder.add(glob);

        // Also match contents of matching directories.
        let dir_glob = GlobBuilder::new(&format!("{effective}/**"))
            .literal_separator(true)
            .build()
            .map_err(|e| Error::InvalidExcludePattern(e.to_string()))?;
        builder.add(dir_glob);
    }
    builder
        .build()
        .map_err(|e| Error::InvalidExcludePattern(e.to_string()))
}

/// Strip the first `n` path components from a UTF-8 path.
///
/// Returns [`None`] when the path has fewer components than `n`, or when
/// stripping leaves an empty remainder (e.g. `strip_components("dir/", 1)`).
pub fn strip_components(path: &Utf8Path, n: u32) -> Option<Utf8PathBuf> {
    if n == 0 {
        return Some(path.to_owned());
    }
    let mut components = path.components();
    for _ in 0..n {
        components.next()?;
    }
    let remaining = components.as_path();
    if remaining.as_str().is_empty() {
        None
    } else {
        Some(remaining.to_owned())
    }
}

// ── Path rewriting ─────────────────────────────────────────────────────────

/// Apply user-supplied path rewrites: substring renames first (in order),
/// then optional prefix.  Re-validates that the result has no `..` or
/// absolute components so a hostile rule can't escape the output dir.
///
/// Returns an empty `Utf8PathBuf` when the entry should be skipped (i.e. a
/// rename rule erased the entire path).  Callers should treat
/// `result.as_str().is_empty()` as "skip this entry".
pub fn apply_path_rewrites(
    path: Utf8PathBuf,
    renames: &[(String, String)],
    prefix: Option<&Utf8Path>,
) -> Result<Utf8PathBuf> {
    let mut s = path.into_string();
    for (old, new) in renames {
        s = s.replace(old.as_str(), new.as_str());
    }
    if s.is_empty() {
        // A rule renamed the whole path away — treat as "skip".
        return Ok(Utf8PathBuf::new());
    }
    let combined = if let Some(p) = prefix {
        let mut joined = p.to_owned();
        joined.push(&s);
        joined
    } else {
        Utf8PathBuf::from(s)
    };
    safe_entry_path(combined.as_str())?;
    Ok(combined)
}

/// Map an archive-relative path through the full rewrite chain an extracted
/// entry goes through: `--strip-components`, `--no-directory` flattening, then
/// rename rules and `--prefix`.
///
/// `None` means the path was stripped away or renamed to nothing, which callers
/// treat as "skip this entry".
pub fn resolve_entry_path(
    path: &Utf8Path,
    opts: &DecompressOpts<'_>,
) -> Result<Option<Utf8PathBuf>> {
    let stripped = match strip_components(path, opts.strip_components) {
        Some(p) => p,
        None => return Ok(None),
    };

    let flattened = if opts.no_directory {
        match stripped.file_name() {
            Some(name) => Utf8PathBuf::from(name),
            None => return Ok(None),
        }
    } else {
        stripped
    };

    match apply_path_rewrites(flattened, &opts.renames, opts.prefix.as_deref())? {
        p if p.as_str().is_empty() => Ok(None),
        p => Ok(Some(normalize_rel_path(&p))),
    }
}

/// Collapse a relative path to its normal components: `./sub/.//f` → `sub/f`.
///
/// Archive entries and rename rules both produce noisy spellings (`./a`,
/// doubled separators from a rename that erased a component), and the noise
/// is not just cosmetic — deferred-directory ordering sorts by path string,
/// where `out/./a/b` and `out/a` disagree with the real hierarchy.  `..` and
/// root components never survive to this point (`safe_entry_path` rejects
/// them), so keeping only `Normal` components is lossless.  A path with no
/// normal components (the `.` root entry of an archive built from `.`) maps
/// to `.` — the output directory itself.
fn normalize_rel_path(p: &Utf8Path) -> Utf8PathBuf {
    let normalized: Utf8PathBuf = p
        .components()
        .filter(|c| matches!(c, camino::Utf8Component::Normal(_)))
        .collect();
    if normalized.as_str().is_empty() {
        Utf8PathBuf::from(".")
    } else {
        normalized
    }
}

// ── VCS-aware walking ───────────────────────────────────────────────────────

/// Build an `ignore::Walk` iterator that respects `.gitignore` rules.
///
/// This is the single source of truth for VCS-aware walking configuration.
/// Used by tar compress, zip compress, 7z compress, and dry-run collection.
pub fn vcs_walker(dir: &Utf8Path, follow_symlinks: bool) -> ignore::Walk {
    ignore::WalkBuilder::new(dir.as_std_path())
        .standard_filters(false)
        .git_ignore(true)
        .git_global(true)
        .git_exclude(true)
        .follow_links(follow_symlinks)
        .sort_by_file_name(|a, b| a.cmp(b))
        .build()
}

// ── Shared directory walker ────────────────────────────────────────────────

/// An entry discovered during a directory walk.
pub struct WalkEntry {
    /// Path this entry will have inside the archive.
    pub archive_name: String,
    /// Absolute path on the filesystem.
    pub fs_path: Utf8PathBuf,
    /// Whether this entry is a directory.
    pub is_dir: bool,
}

/// Walk a directory tree and call `visit` for each entry, applying exclude
/// filters and honouring `follow_symlinks`.
///
/// When `opts.exclude_vcs_ignores` is set the walk respects `.gitignore`
/// rules via the `ignore` crate.  Entries are yielded in sorted order for
/// deterministic archive output.
///
/// This is the single source of walking logic used by tar compress, zip
/// compress, 7z compress, and dry-run collection.
pub fn walk_dir<F>(
    dir: &Utf8Path,
    prefix: &str,
    opts: &CompressOpts<'_>,
    visit: &mut F,
) -> Result<()>
where
    F: FnMut(WalkEntry) -> Result<()>,
{
    if opts.exclude_vcs_ignores {
        walk_dir_vcs(dir, prefix, &opts.excludes, opts.follow_symlinks, visit)
    } else {
        // Yield the root directory entry, then recurse.
        visit(WalkEntry {
            archive_name: prefix.to_owned(),
            fs_path: dir.to_owned(),
            is_dir: true,
        })?;
        walk_dir_simple(dir, prefix, &opts.excludes, opts.follow_symlinks, visit)
    }
}

/// Standard directory walk (no VCS-ignore awareness).
fn walk_dir_simple<F>(
    dir: &Utf8Path,
    prefix: &str,
    excludes: &GlobSet,
    follow_symlinks: bool,
    visit: &mut F,
) -> Result<()>
where
    F: FnMut(WalkEntry) -> Result<()>,
{
    let mut entries: Vec<_> = fs_err::read_dir(dir)?.collect::<std::result::Result<Vec<_>, _>>()?;
    // `DirEntry::file_name()` returns an owned `OsString`.  Plain `sort_by_key`
    // would recompute (and reallocate) the key on every comparison — ~N log N
    // allocations.  `sort_by_cached_key` allocates each key exactly once.
    entries.sort_by_cached_key(|e| e.file_name());

    for entry in entries {
        let entry_path = entry.path();
        let file_name = entry_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| Error::InvalidUtf8Path(entry_path.display().to_string()))?;
        let archive_name = format!("{prefix}/{file_name}");

        if excludes.is_match(&archive_name) {
            continue;
        }

        let entry_str = entry_path
            .to_str()
            .ok_or_else(|| Error::InvalidUtf8Path(entry_path.display().to_string()))?;
        let utf8_path = Utf8Path::new(entry_str);

        let is_dir = if follow_symlinks {
            fs_err::metadata(utf8_path)?.is_dir()
        } else {
            entry.file_type()?.is_dir()
        };

        visit(WalkEntry {
            archive_name: archive_name.clone(),
            fs_path: utf8_path.to_owned(),
            is_dir,
        })?;

        if is_dir {
            walk_dir_simple(utf8_path, &archive_name, excludes, follow_symlinks, visit)?;
        }
    }
    Ok(())
}

/// Walk a directory using the `ignore` crate to respect `.gitignore` rules.
fn walk_dir_vcs<F>(
    dir: &Utf8Path,
    prefix: &str,
    excludes: &GlobSet,
    follow_symlinks: bool,
    visit: &mut F,
) -> Result<()>
where
    F: FnMut(WalkEntry) -> Result<()>,
{
    for result in vcs_walker(dir, follow_symlinks) {
        let entry = result.map_err(|e| std::io::Error::other(e.to_string()))?;
        let fs_path = entry.path();

        let relative = fs_path
            .strip_prefix(dir.as_std_path())
            .map_err(|e| std::io::Error::other(e.to_string()))?;

        // Root directory entry.
        if relative.as_os_str().is_empty() {
            visit(WalkEntry {
                archive_name: prefix.to_owned(),
                fs_path: dir.to_owned(),
                is_dir: true,
            })?;
            continue;
        }

        let rel_str = relative
            .to_str()
            .ok_or_else(|| Error::InvalidUtf8Path(relative.display().to_string()))?;
        let archive_name = format!("{prefix}/{rel_str}");

        if excludes.is_match(&archive_name) {
            continue;
        }

        let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir());
        let utf8_str = fs_path
            .to_str()
            .ok_or_else(|| Error::InvalidUtf8Path(fs_path.display().to_string()))?;

        visit(WalkEntry {
            archive_name,
            fs_path: Utf8PathBuf::from(utf8_str),
            is_dir,
        })?;
    }
    Ok(())
}

// ── Path safety ────────────────────────────────────────────────────────────

/// Validate that an archive entry path does not escape the output directory.
///
/// Rejects paths containing `..` components to prevent "zip-slip" style
/// path-traversal attacks (CVE-2018-1002200).  The check is purely lexical —
/// it does not touch the filesystem — so it works before any directories are
/// created.
pub fn safe_entry_path(name: &str) -> Result<()> {
    // Check for ".." components that could escape the output directory.
    for component in Utf8Path::new(name).components() {
        if matches!(component, camino::Utf8Component::ParentDir) {
            return Err(Error::PathTraversal(name.to_owned()));
        }
    }
    // Also reject absolute paths.
    if Utf8Path::new(name).is_absolute() {
        return Err(Error::PathTraversal(name.to_owned()));
    }
    Ok(())
}

/// Validate that a symlink/hardlink target doesn't escape the output directory.
///
/// The `tar` crate's default `Entry::unpack` will happily create a symlink
/// with an absolute or `..`-containing target, which opens a path-traversal
/// hole: a subsequent entry whose name resolves *through* the symlink writes
/// outside the extraction root.
///
/// Rejecting absolute paths and any `..` in targets closes the common
/// attack vector.  Legitimate intra-archive symlinks (e.g. `bin/sh ->
/// busybox`) remain valid.
pub fn safe_link_target(link: &str, target: &str) -> Result<()> {
    if Utf8Path::new(target).is_absolute() {
        return Err(Error::PathTraversal(format!("{link} -> {target}")));
    }
    for component in Utf8Path::new(target).components() {
        if matches!(component, camino::Utf8Component::ParentDir) {
            return Err(Error::PathTraversal(format!("{link} -> {target}")));
        }
    }
    Ok(())
}

// ── Symlink helper ──────────────────────────────────────────────────────────

/// Read file metadata, optionally following symlinks.
pub fn input_metadata(path: &Utf8Path, follow_symlinks: bool) -> Result<std::fs::Metadata> {
    if follow_symlinks {
        Ok(fs_err::metadata(path)?)
    } else {
        Ok(fs_err::symlink_metadata(path)?)
    }
}

/// Archive-name base for a top-level input.
///
/// `file_name` covers normal paths, and dot-only spellings (`.`, `./`) keep
/// their literal form — tar strips the dot components at encoding time and
/// zip stores them verbatim, both long-standing behaviour.  Inputs ending in
/// `..` resolve to the real directory's name instead: baking `..` into entry
/// names produces archives every extractor — rz's own `safe_entry_path`
/// included — rejects as traversal.
pub fn input_base_name(input: &Utf8Path) -> Result<String> {
    if let Some(name) = input.file_name() {
        return Ok(name.to_owned());
    }
    if !input.as_str().split('/').any(|c| c == "..") {
        return Ok(input.as_str().to_owned());
    }
    let canonical = input.canonicalize_utf8()?;
    match canonical.file_name() {
        Some(name) => Ok(name.to_owned()),
        None => Err(Error::Io(std::io::Error::other(format!(
            "cannot derive an entry name for `{input}`: it resolves to the filesystem root"
        )))),
    }
}

/// Warn-and-skip gate for filesystem objects zip and 7z cannot represent
/// (FIFOs, sockets, device nodes).  Opening one for reading can block
/// forever — a FIFO with no writer parks `open(2)` — so those walks skip
/// them the way Info-ZIP and 7-Zip do.  tar is unaffected: it stores them
/// as typed entries without reading any content.
pub fn skip_unarchivable_special(meta: &std::fs::Metadata, name: &str) -> bool {
    use std::io::Write;

    let ft = meta.file_type();
    if ft.is_file() || ft.is_dir() || ft.is_symlink() {
        return false;
    }
    let mut stderr = std::io::stderr().lock();
    let _ = writeln!(
        stderr,
        "rz: warning: skipping `{}`: special files are not representable in this format",
        crate::progress::escape_entry_name(name),
    );
    true
}

/// Stat a top-level input path without `fs_err`'s wrapping.
///
/// `fs_err`'s default error message says "failed to query metadata of
/// symlink ..." regardless of file type, which is confusing when the path
/// is a regular file or directory.  For input validation we want a clean
/// `io::Error` so we can produce a single error variant
/// ([`Error::CannotReadInput`]) with predictable wording.
#[allow(clippy::disallowed_methods)]
fn stat_input_raw(path: &Utf8Path, follow_symlinks: bool) -> std::io::Result<std::fs::Metadata> {
    if follow_symlinks {
        std::fs::metadata(path)
    } else {
        std::fs::symlink_metadata(path)
    }
}

// ── Input validation ────────────────────────────────────────────────────────

/// Pre-validate top-level compress inputs *before* the output file is
/// created.  This catches missing/unreadable paths up front, avoiding the
/// "empty 22-byte zip left on disk after first error" footgun.
///
/// Behaviour:
/// - Inputs whose `file_name()` matches an exclude pattern are silently
///   dropped.
/// - Inputs that fail to stat are either:
///   - reported as [`Error::CannotReadInput`] (default), aborting the whole
///     operation before the output file is touched, or
///   - warned to stderr and skipped (when `opts.ignore_failed_read` is set).
/// - If no inputs survive validation, returns [`Error::NoReadableInputs`]
///   so we never write an empty archive.
///
/// Inner directory walks are not validated here — only the user-supplied
/// top-level paths.  Per-entry failures during recursion still propagate
/// as before.
pub fn validate_inputs(
    inputs: &[Utf8PathBuf],
    opts: &CompressOpts<'_>,
) -> Result<Vec<Utf8PathBuf>> {
    use std::io::Write;

    let mut valid = Vec::with_capacity(inputs.len());
    for input in inputs {
        let name = input.file_name().unwrap_or(input.as_str());
        if opts.excludes.is_match(name) {
            continue;
        }
        match stat_input_raw(input, opts.follow_symlinks) {
            Ok(_) => valid.push(input.clone()),
            Err(source) if opts.ignore_failed_read => {
                let mut stderr = std::io::stderr().lock();
                let _ = writeln!(stderr, "rz: warning: cannot read `{input}`: {source}");
            }
            Err(source) => {
                return Err(Error::CannotReadInput {
                    path: input.clone(),
                    source,
                });
            }
        }
    }
    if valid.is_empty() {
        return Err(Error::NoReadableInputs);
    }
    Ok(valid)
}

// ── Stdout extraction ────────────────────────────────────────────────────────

/// Extract matching tar entries to a writer (typically stdout), skipping
/// directory entries.  Applies include/exclude filters and strip-components.
pub fn extract_tar_to_writer<R: std::io::Read, W: std::io::Write>(
    archive: &mut tar::Archive<R>,
    writer: &mut W,
    opts: &DecompressOpts<'_>,
) -> Result<()> {
    for entry in archive.entries()? {
        let mut entry = entry?;
        let orig_path = entry.path()?;
        let orig_path = Utf8PathBuf::try_from(orig_path.into_owned())
            .map_err(|e| Error::InvalidUtf8Path(e.into_path_buf().display().to_string()))?;

        // Reject entries that attempt path traversal.
        safe_entry_path(orig_path.as_str())?;

        if !should_extract(orig_path.as_str(), &opts.includes, &opts.excludes) {
            continue;
        }

        // Time-window filter against the archive's recorded mtime.
        let entry_mtime = entry.header().mtime().unwrap_or(0) as i64;
        if !passes_time_filter(entry_mtime, opts.newer_than, opts.older_than) {
            continue;
        }

        // Skip directory entries — only files have content.
        if entry.header().entry_type().is_dir() {
            continue;
        }

        let stripped = match strip_components(&orig_path, opts.strip_components) {
            Some(p) => p,
            None => continue,
        };

        let after_no_dir = if opts.no_directory {
            match stripped.file_name() {
                Some(name) => Utf8PathBuf::from(name),
                None => continue,
            }
        } else {
            stripped
        };

        // Apply rename rules and optional prefix for consistent naming.
        let display_path =
            match apply_path_rewrites(after_no_dir, &opts.renames, opts.prefix.as_deref())? {
                p if p.as_str().is_empty() => continue,
                p => p,
            };

        opts.progress.set_entry(display_path.as_str());
        let written = std::io::copy(&mut entry, writer)?;
        opts.progress.inc(written);
    }
    Ok(())
}

// ── Tar helpers ──────────────────────────────────────────────────────────────

/// Fully decompress every entry in a tar archive to [`io::sink`], verifying
/// data integrity beyond what header-only iteration (`list`) provides.
pub fn verify_tar_entries<R: std::io::Read>(
    archive: &mut tar::Archive<R>,
    progress: &dyn ProgressReport,
) -> Result<()> {
    for entry in archive.entries()? {
        let mut entry = entry?;
        let path = entry.path()?;
        let path = Utf8PathBuf::try_from(path.into_owned())
            .map_err(|e| Error::InvalidUtf8Path(e.into_path_buf().display().to_string()))?;
        progress.set_entry(path.as_str());
        let written = std::io::copy(&mut entry, &mut std::io::sink())?;
        progress.inc(written);
    }
    Ok(())
}

/// Apply reproducibility overrides (mtime, uid, gid, mode) to a tar header.
fn apply_header_overrides(header: &mut tar::Header, opts: &CompressOpts<'_>) {
    if let Some(mtime) = opts.fixed_mtime {
        header.set_mtime(mtime);
    }
    if let Some(uid) = opts.fixed_uid {
        header.set_uid(uid);
    }
    if let Some(gid) = opts.fixed_gid {
        header.set_gid(gid);
    }
    if let Some(mode) = opts.fixed_mode {
        header.set_mode(mode);
    }
}

/// Returns `true` when any reproducibility overrides are active.
fn has_header_overrides(opts: &CompressOpts<'_>) -> bool {
    opts.fixed_mtime.is_some()
        || opts.fixed_uid.is_some()
        || opts.fixed_gid.is_some()
        || opts.fixed_mode.is_some()
}

/// Extract Unix permission mode from filesystem metadata.
/// On Unix, returns the actual mode bits. On other platforms, returns a
/// sensible default (0o755 for directories, 0o644 for files).
fn metadata_mode(meta: &std::fs::Metadata) -> u32 {
    #[cfg(unix)]
    {
        meta.permissions().mode()
    }
    #[cfg(not(unix))]
    {
        if meta.is_dir() { 0o755 } else { 0o644 }
    }
}

/// Append a single file to a tar builder, applying header overrides if set.
fn append_file_entry<W: std::io::Write>(
    builder: &mut tar::Builder<W>,
    fs_path: &Utf8Path,
    archive_name: &str,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    if has_header_overrides(opts) {
        let meta = input_metadata(fs_path, opts.follow_symlinks)?;
        let mut header = tar::Header::new_gnu();
        header.set_metadata_in_mode(&meta, tar::HeaderMode::Deterministic);
        header.set_mode(metadata_mode(&meta));

        if opts.fixed_mtime.is_none() {
            // Preserve original mtime if not explicitly overridden.
            let mtime = meta
                .modified()
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_secs())
                .unwrap_or(0);
            header.set_mtime(mtime);
        }

        apply_header_overrides(&mut header, opts);

        let file_type = meta.file_type();
        if file_type.is_symlink() {
            // `set_metadata_in_mode` already leaves the header as
            // `EntryType::symlink()` with size 0. Reading the target through
            // `File::open` here would follow the link and stream the target's
            // contents under this header instead of a link record, shifting
            // every entry appended afterward and corrupting the archive.
            //
            // Pass the target straight through as raw bytes rather than
            // validating UTF-8: `append_link` accepts any `AsRef<Path>` and
            // handles non-UTF-8 targets (plus GNU long-link) the same way the
            // no-override `append_path_with_name` path already does.
            let target = fs_err::read_link(fs_path)?;
            builder.append_link(&mut header, archive_name, target)?;
        } else if file_type.is_file() {
            header.set_size(meta.len());
            let mut file = fs_err::File::open(fs_path)?;
            builder.append_data(&mut header, archive_name, &mut file)?;
        } else {
            #[cfg(unix)]
            {
                use std::os::unix::fs::{FileTypeExt, MetadataExt};

                if file_type.is_socket() {
                    return Err(Error::Io(std::io::Error::other(format!(
                        "{fs_path}: socket can not be archived"
                    ))));
                }
                if file_type.is_char_device() || file_type.is_block_device() {
                    // `Deterministic` mode's `fill_from` always zeroes
                    // devmajor/devminor, so restore them from the raw rdev
                    // the same way tar's own `append_special` does.
                    let dev_id = meta.rdev();
                    let dev_major = ((dev_id >> 32) & 0xffff_f000) | ((dev_id >> 8) & 0x0000_0fff);
                    let dev_minor = ((dev_id >> 12) & 0xffff_ff00) | (dev_id & 0x0000_00ff);
                    header.set_device_major(dev_major as u32)?;
                    header.set_device_minor(dev_minor as u32)?;
                }
            }
            // Fifo/char/block device — no payload, entry type already set by
            // `set_metadata_in_mode`.
            builder.append_data(&mut header, archive_name, std::io::empty())?;
        }
    } else {
        builder.append_path_with_name(fs_path, archive_name)?;
    }
    Ok(())
}

/// Append a directory entry to a tar builder, applying header overrides if set.
fn append_dir_entry<W: std::io::Write>(
    builder: &mut tar::Builder<W>,
    fs_path: &Utf8Path,
    archive_name: &str,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    if has_header_overrides(opts) {
        let meta = input_metadata(fs_path, opts.follow_symlinks)?;
        let mut header = tar::Header::new_gnu();
        header.set_metadata_in_mode(&meta, tar::HeaderMode::Deterministic);
        header.set_entry_type(tar::EntryType::Directory);
        header.set_size(0);
        header.set_mode(metadata_mode(&meta));
        if opts.fixed_mtime.is_none() {
            let mtime = meta
                .modified()
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_secs())
                .unwrap_or(0);
            header.set_mtime(mtime);
        }
        apply_header_overrides(&mut header, opts);
        header.set_cksum();
        builder.append_data(&mut header, archive_name, std::io::empty())?;
    } else {
        builder.append_dir(archive_name, fs_path)?;
    }
    Ok(())
}

/// Walk a directory tree and append entries to a tar builder, skipping paths
/// that match the exclude set.  Reports progress per file via `progress`.
///
/// Delegates to [`walk_dir`] for the actual directory traversal.
pub fn append_dir_filtered<W: std::io::Write>(
    builder: &mut tar::Builder<W>,
    dir: &Utf8Path,
    prefix: &str,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    if opts.no_recursion {
        append_dir_entry(builder, dir, prefix, opts)?;
        return Ok(());
    }

    walk_dir(dir, prefix, opts, &mut |entry| {
        if entry.is_dir {
            append_dir_entry(builder, &entry.fs_path, &entry.archive_name, opts)?;
        } else {
            let meta = input_metadata(&entry.fs_path, opts.follow_symlinks)?;
            if !passes_time_filter(fs_mtime_secs(&meta), opts.newer_than, opts.older_than) {
                return Ok(());
            }
            append_file_entry(builder, &entry.fs_path, &entry.archive_name, opts)?;
            opts.progress.set_entry(&entry.archive_name);
            opts.progress.inc(meta.len());
        }
        Ok(())
    })
}

/// Append each input (file or directory) to a tar builder, respecting
/// excludes.  This is the shared input-iteration loop used by every
/// tar-based compress function.
pub fn append_inputs<W: std::io::Write>(
    builder: &mut tar::Builder<W>,
    inputs: &[Utf8PathBuf],
    opts: &CompressOpts<'_>,
) -> Result<()> {
    for input in inputs {
        let meta = input_metadata(input, opts.follow_symlinks)?;
        let name = input_base_name(input)?;
        if opts.excludes.is_match(&name) {
            continue;
        }
        if meta.is_dir() {
            append_dir_filtered(builder, input, &name, opts)?;
        } else {
            if !passes_time_filter(fs_mtime_secs(&meta), opts.newer_than, opts.older_than) {
                continue;
            }
            let size = meta.len();
            append_file_entry(builder, input, &name, opts)?;
            opts.progress.set_entry(&name);
            opts.progress.inc(size);
        }
    }
    Ok(())
}

/// Collect entry metadata from a tar archive into a `Vec<Entry>`.
/// Shared by every tar-based `list` function.
pub fn list_tar_entries<R: std::io::Read>(
    archive: &mut tar::Archive<R>,
) -> Result<Vec<crate::Entry>> {
    let mut entries = Vec::new();
    for entry in archive.entries()? {
        let entry = entry?;
        let path = entry.path()?;
        let path = Utf8PathBuf::try_from(path.into_owned())
            .map_err(|e| Error::InvalidUtf8Path(e.into_path_buf().display().to_string()))?;
        let link_target = match entry.header().entry_type() {
            tar::EntryType::Symlink | tar::EntryType::Link => entry
                .link_name()?
                .map(|t| t.to_string_lossy().into_owned()),
            _ => None,
        };
        let header = entry.header();
        entries.push(crate::Entry {
            path,
            size: header.size()?,
            mtime: header.mtime()?,
            mode: header.mode()?,
            is_dir: header.entry_type().is_dir(),
            link_target,
        });
    }
    Ok(entries)
}

/// Count entries and sum uncompressed sizes in a tar archive.
/// Shared by every tar-based `info` function.
/// Read up to `max` bytes from `reader` into a fresh buffer, returning however
/// many were available (a short read or immediate EOF yields fewer).
///
/// Used to peek the leading bytes of a stream for magic-byte format detection
/// before chaining the prefix back onto the rest of the stream.
pub fn read_prefix<R: std::io::Read>(reader: &mut R, max: usize) -> std::io::Result<Vec<u8>> {
    let mut buf = vec![0u8; max];
    let mut filled = 0;
    while filled < max {
        let n = reader.read(&mut buf[filled..])?;
        if n == 0 {
            break;
        }
        filled += n;
    }
    buf.truncate(filled);
    Ok(buf)
}

/// A `Read` adapter that tallies every byte pulled through it into a shared
/// counter.  Wrap it around a *raw* (still-compressed) stream before handing
/// the stream to a decompressor: the counter then reflects the compressed
/// byte count — the stdin equivalent of `fs::metadata().len()`, which a pipe
/// can't answer.
///
/// The count lives behind an `Arc<AtomicU64>` so the caller keeps a handle to
/// it after the reader is swallowed by the decoder→`tar::Archive` ownership
/// chain (we can't reach back through `into_inner` uniformly across the
/// different decoder backends).
pub struct CountingReader<R> {
    inner: R,
    count: std::sync::Arc<std::sync::atomic::AtomicU64>,
}

impl<R> CountingReader<R> {
    pub fn new(inner: R, count: std::sync::Arc<std::sync::atomic::AtomicU64>) -> Self {
        Self { inner, count }
    }
}

impl<R: std::io::Read> std::io::Read for CountingReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.count
            .fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
        Ok(n)
    }
}

pub fn count_tar_entries<R: std::io::Read>(archive: &mut tar::Archive<R>) -> Result<(usize, u64)> {
    let mut entry_count: usize = 0;
    let mut total_uncompressed: u64 = 0;
    for entry in archive.entries()? {
        let entry = entry?;
        // Saturating to guard against adversarial archives with absurd
        // header-declared sizes summing past u64::MAX.
        total_uncompressed = total_uncompressed.saturating_add(entry.header().size()?);
        entry_count = entry_count.saturating_add(1);
    }
    Ok((entry_count, total_uncompressed))
}

/// The process umask, read once per process.
///
/// umask(2) can only be read by writing it, so set-and-restore.  The scratch
/// value is visible to other threads for a moment, but tar extraction is the
/// only operation running when this is first called and it creates files
/// serially, so nothing can race the window in practice.
#[cfg(unix)]
fn process_umask() -> u32 {
    use std::sync::OnceLock;
    static UMASK: OnceLock<u32> = OnceLock::new();
    *UMASK.get_or_init(|| {
        // SAFETY: umask(2) only swaps a per-process value and cannot fail.
        let mask = unsafe { libc::umask(0) };
        unsafe { libc::umask(mask) };
        mask as u32
    })
}

/// Extract entries from a tar archive, honouring exclude patterns and
/// path-component stripping.  Reports progress per entry.
pub fn unpack_tar_filtered<R: std::io::Read>(
    archive: &mut tar::Archive<R>,
    output: &Utf8Path,
    opts: &DecompressOpts<'_>,
) -> Result<()> {
    archive.set_preserve_permissions(opts.preserve_permissions);
    // Ownership restoration is tar-only and Unix + root only in practice;
    // the tar crate silently skips chown when the process lacks CAP_CHOWN,
    // matching GNU tar's non-root behaviour.
    archive.set_preserve_ownerships(opts.same_owner);

    let mut deferred_dirs: Vec<DeferredDir> = Vec::new();
    let walked = unpack_tar_entries(archive, output, opts, &mut deferred_dirs);

    // Children before parents (reverse path order), so a directory that ends
    // up read-only is locked down only after everything inside it — and its
    // mtime is set after its children stop bumping it.
    //
    // The flush runs even when the walk failed: whatever was extracted before
    // the abort must still get its recorded modes, or a 0700 directory whose
    // secrets already landed on disk would be left at create_dir_all's
    // permissive default.  GNU tar flushes its delayed set_stat on failure
    // the same way.  One failing directory doesn't abandon the rest; the
    // walk's own error takes precedence over a flush error.
    deferred_dirs.sort_by(|a, b| b.dest.as_str().cmp(a.dest.as_str()));
    let mut flush_err: Option<Error> = None;
    for dir in &deferred_dirs {
        if let Err(e) = apply_deferred_dir(dir, opts)
            && flush_err.is_none()
        {
            flush_err = Some(e);
        }
    }
    walked?;
    match flush_err {
        Some(e) => Err(e),
        None => Ok(()),
    }
}

fn unpack_tar_entries<R: std::io::Read>(
    archive: &mut tar::Archive<R>,
    output: &Utf8Path,
    opts: &DecompressOpts<'_>,
    deferred_dirs: &mut Vec<DeferredDir>,
) -> Result<()> {
    // Destinations already written by *this* run.  A later entry with the
    // same name replaces the earlier one silently — tar's last-wins rule —
    // rather than tripping the overwrite ladder, which exists to protect
    // files that predate the extraction.  Duplicate names are routine in
    // appended-to archives (including rz's own `append`/`update` output).
    let mut written: std::collections::HashSet<Utf8PathBuf> =
        std::collections::HashSet::new();

    for entry in archive.entries()? {
        let mut entry = entry?;
        let orig_path = entry.path()?;
        let orig_path = Utf8PathBuf::try_from(orig_path.into_owned())
            .map_err(|e| Error::InvalidUtf8Path(e.into_path_buf().display().to_string()))?;

        // Reject entries that attempt path traversal.
        safe_entry_path(orig_path.as_str())?;

        // Validate symlink/hardlink targets — the tar crate's unpack() will
        // happily create a symlink to `../../etc/passwd`, which a follow-up
        // entry can then be extracted through.
        //
        // The check runs on the raw path rather than requiring UTF-8: link
        // targets are arbitrary bytes on unix, and a legitimate archive (GNU
        // tar's, or rz's own raw-byte symlink entries) can carry a non-UTF-8
        // target. Traversal only depends on path structure, not encoding.
        let entry_type = entry.header().entry_type();
        if matches!(entry_type, tar::EntryType::Symlink | tar::EntryType::Link)
            && let Some(target) = entry.link_name()?
            && (target.is_absolute()
                || target
                    .components()
                    .any(|c| matches!(c, std::path::Component::ParentDir)))
        {
            return Err(Error::PathTraversal(format!(
                "{orig_path} -> {}",
                target.to_string_lossy()
            )));
        }

        // Include/exclude check against the original (pre-strip) path.
        if !should_extract(orig_path.as_str(), &opts.includes, &opts.excludes) {
            continue;
        }

        // Time-window filter against the archive's recorded mtime.
        let entry_mtime = entry.header().mtime().unwrap_or(0) as i64;
        if !passes_time_filter(entry_mtime, opts.newer_than, opts.older_than) {
            continue;
        }

        let is_dir = entry_type.is_dir();

        // --no-directory: skip directory entries, flatten file paths.
        if opts.no_directory && is_dir {
            continue;
        }

        let dest_path = match resolve_entry_path(&orig_path, opts)? {
            Some(p) => p,
            None => continue,
        };

        // The `.` root entry of an archive built from `.` is the output
        // directory itself; joining it verbatim yields `out/.`, whose
        // create_dir_all fails when `out` does not exist yet.
        let dest = if dest_path.as_str() == "." {
            output.to_owned()
        } else {
            output.join(&dest_path)
        };

        // Ensure parent directories exist.
        if let Some(parent) = dest.parent()
            && !parent.as_str().is_empty()
        {
            fs_err::create_dir_all(parent)?;
        }

        // Overwrite guard for non-directory entries.
        if !is_dir && !written.contains(&dest) && fs_err::symlink_metadata(&dest).is_ok() {
            if let Some(ref suffix) = opts.backup_suffix {
                let backup = Utf8PathBuf::from(format!("{dest}{suffix}"));
                fs_err::rename(&dest, &backup)?;
            } else if opts.keep_newer {
                let entry_mtime = entry.header().mtime().unwrap_or(0);
                if is_existing_newer(&dest, entry_mtime)? {
                    continue;
                }
            } else if opts.no_overwrite {
                continue;
            } else if !opts.force {
                return Err(Error::FileExists(dest));
            }
        }

        // GNU tar masks extracted modes with the process umask unless -p is
        // given; tar-rs's set_preserve_permissions(false) only truncates to
        // 0o777, which still yields world-writable files from a mode-0777
        // entry.  Entry::set_mask applies `mode & !mask` on top, for files
        // and directories alike.
        #[cfg(unix)]
        if !opts.preserve_permissions {
            entry.set_mask(process_umask());
        }

        opts.progress.set_entry(dest_path.as_str());
        let size = entry.header().size().unwrap_or(0);
        if is_dir {
            // Create permissively now, record the header metadata for later:
            // tar-rs's Entry::unpack chmods a directory immediately (even
            // without -P), so a dr-xr-xr-x entry appearing before its own
            // children would block their extraction with EACCES.  tar-rs's
            // Archive::_unpack and GNU tar both defer directories the same
            // way.
            fs_err::create_dir_all(&dest)?;
            let header = entry.header();
            deferred_dirs.push(DeferredDir {
                dest,
                mode: header.mode().ok(),
                mtime: header.mtime().ok(),
                uid: header.uid().ok(),
                gid: header.gid().ok(),
            });
        } else if entry_type == tar::EntryType::Link {
            unpack_hard_link(&entry, output, &dest, opts)?;
            written.insert(dest);
        } else {
            entry.unpack(&dest)?;
            written.insert(dest);
        }
        opts.progress.inc(size);
    }
    Ok(())
}

/// Directory metadata held back until every entry is extracted.
struct DeferredDir {
    dest: Utf8PathBuf,
    mode: Option<u32>,
    mtime: Option<u64>,
    uid: Option<u64>,
    gid: Option<u64>,
}

/// Apply a deferred directory's ownership, mode, and mtime — the same
/// semantics `Entry::unpack` would have applied inline: chown only under
/// `--same-owner` (skipped without privilege, like tar-rs), the mode
/// truncated to 0o777 and masked by the umask unless `-P`, and the mtime
/// restored best-effort.  Ordering matters: chown first, since it clears
/// setuid/setgid bits that a `-P` chmod may then restore.
fn apply_deferred_dir(dir: &DeferredDir, opts: &DecompressOpts<'_>) -> Result<()> {
    // The path may no longer be the directory we created — a pre-existing
    // symlink the create_dir_all silently followed, or a hostile swap while
    // extraction ran.  chmod and utimes both follow symlinks, so applying
    // through one would rewrite something outside the output tree.
    match fs_err::symlink_metadata(&dir.dest) {
        Ok(m) if m.file_type().is_dir() => {}
        _ => return Ok(()),
    }
    #[cfg(unix)]
    {
        if opts.same_owner
            && let (Some(uid), Some(gid)) = (dir.uid, dir.gid)
        {
            match std::os::unix::fs::chown(&dir.dest, Some(uid as u32), Some(gid as u32)) {
                Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {}
                other => other?,
            }
        }
        if let Some(mode) = dir.mode {
            let mode = if opts.preserve_permissions {
                mode
            } else {
                (mode & 0o777) & !process_umask()
            };
            fs_err::set_permissions(
                &dir.dest,
                std::fs::Permissions::from_mode(mode & 0o7777),
            )?;
        }
    }
    #[cfg(not(unix))]
    {
        let _ = (dir.mode, dir.uid, dir.gid, opts);
    }
    if let Some(mtime) = dir.mtime {
        // Best-effort, like the file-side mtime restoration elsewhere: a
        // filesystem that refuses timestamps must not fail the extraction.
        let ft = filetime::FileTime::from_unix_time(mtime as i64, 0);
        let _ = filetime::set_file_times(dir.dest.as_std_path(), ft, ft);
    }
    Ok(())
}

/// Create a hard link entry, resolving its target inside the output directory.
///
/// `Entry::unpack` only resolves hard-link targets against an output root when
/// the entry came from `unpack_in`, which populates tar-rs's `target_base`.
/// Called directly it hands the raw target to `hard_link(2)`, which resolves it
/// against the *process working directory* — so `y -> x` links to whatever `x`
/// happens to be next to the caller, and writes through the link reach a file
/// outside the output tree entirely.  `safe_link_target` cannot catch that: a
/// bare relative name has no `..` and no leading `/`.
///
/// The target goes through the same rewrite chain as the entry path, so
/// `--strip-components` and `--rename` leave the link pointing at the archive's
/// own copy rather than at a path that no longer exists.
fn unpack_hard_link<R: std::io::Read>(
    entry: &tar::Entry<'_, R>,
    output: &Utf8Path,
    dest: &Utf8Path,
    opts: &DecompressOpts<'_>,
) -> Result<()> {
    let target = entry
        .link_name()?
        .ok_or_else(|| Error::Io(std::io::Error::other("hard link entry has no link name")))?;
    let target = Utf8PathBuf::try_from(target.into_owned())
        .map_err(|e| Error::InvalidUtf8Path(e.into_path_buf().display().to_string()))?;

    let resolved = resolve_entry_path(&target, opts)?.ok_or_else(|| {
        Error::Io(std::io::Error::other(format!(
            "hard link target `{target}` is removed by the active path rewrites"
        )))
    })?;

    // hard_link(2) refuses an existing destination, and unlike the symlink
    // branch tar-rs never retries.  Reaching here with `dest` present means the
    // overwrite guard already cleared us to replace it.
    if fs_err::symlink_metadata(dest).is_ok() {
        fs_err::remove_file(dest)?;
    }
    fs_err::hard_link(output.join(resolved), dest)?;
    Ok(())
}

/// Decide whether an entry with the given mtime (unix seconds) falls within
/// the `[newer_than, older_than]` window supplied via CLI flags.
///
/// Both bounds are exclusive, matching GNU tar's `--newer` / `--newer-mtime`
/// semantics: `--newer-than 2024-01-01` excludes files modified exactly at
/// midnight on that date.  Negative mtimes (pre-epoch) are impossible from
/// filesystem metadata and tar headers, so the `as i64` cast is safe.
pub fn passes_time_filter(
    mtime_secs: i64,
    newer_than: Option<i64>,
    older_than: Option<i64>,
) -> bool {
    if let Some(after) = newer_than
        && mtime_secs <= after
    {
        return false;
    }
    if let Some(before) = older_than
        && mtime_secs >= before
    {
        return false;
    }
    true
}

/// Read filesystem mtime (unix seconds) from metadata, returning 0 if the
/// platform cannot produce a sensible value.
fn fs_mtime_secs(meta: &std::fs::Metadata) -> i64 {
    meta.modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Returns `true` when the file at `path` has an mtime >= the given unix
/// timestamp, meaning the existing file is at least as new as the entry.
pub fn is_existing_newer(path: &Utf8Path, entry_mtime: u64) -> Result<bool> {
    let meta = match fs_err::metadata(path) {
        // The destination stat'd as present via symlink_metadata but is gone
        // through the following stat: a dangling symlink.  Nothing newer is
        // there to keep, so let extraction replace it.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        other => other?,
    };
    let file_mtime = meta
        .modified()?
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    Ok(file_mtime >= entry_mtime)
}

// ── Exclude-set building ────────────────────────────────────────────────────

/// Merge inline exclude patterns with patterns read from `--exclude-from`
/// files, then build a [`GlobSet`].
///
/// Used by Compress, Decompress, and List commands.
pub fn build_excludes(patterns: Vec<String>, pattern_files: &[Utf8PathBuf]) -> Result<GlobSet> {
    let mut all = patterns;
    for path in pattern_files {
        all.extend(read_patterns_from_file(path)?);
    }
    build_glob_set(&all)
}

// ── Pattern / path file readers ─────────────────────────────────────────────

/// Read non-empty, non-comment lines from a file (one per line).
/// Blank lines and lines starting with `#` are ignored.
fn read_lines_from_file(path: &Utf8Path) -> Result<Vec<String>> {
    let file = fs_err::File::open(path)?;
    let reader = std::io::BufReader::new(file);
    let mut lines = Vec::new();
    for line in reader.lines() {
        let line = line?;
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        lines.push(trimmed.to_owned());
    }
    Ok(lines)
}

/// Read glob patterns from a file, one per line.
/// Blank lines and lines starting with `#` are ignored.
pub fn read_patterns_from_file(path: &Utf8Path) -> Result<Vec<String>> {
    read_lines_from_file(path)
}

/// Read file paths from a file, one per line.
/// Blank lines and lines starting with `#` are ignored.
pub fn read_paths_from_file(path: &Utf8Path) -> Result<Vec<Utf8PathBuf>> {
    Ok(read_lines_from_file(path)?
        .into_iter()
        .map(Utf8PathBuf::from)
        .collect())
}

// ── Dry-run helpers ─────────────────────────────────────────────────────────

/// Collect all file paths that would be added to an archive from the given
/// inputs, honouring exclude patterns.  Used by `--dry-run` on compress.
///
/// Delegates to [`walk_dir`] for directory traversal.
pub fn collect_compress_paths(
    inputs: &[Utf8PathBuf],
    opts: &CompressOpts<'_>,
) -> Result<Vec<String>> {
    let mut paths = Vec::new();
    for input in inputs {
        let meta = input_metadata(input, opts.follow_symlinks)?;
        let name = input_base_name(input)?;
        if opts.excludes.is_match(&name) {
            continue;
        }
        if meta.is_dir() {
            if opts.no_recursion {
                paths.push(format!("{name}/"));
            } else {
                walk_dir(input, &name, opts, &mut |entry| {
                    if entry.is_dir {
                        paths.push(format!("{}/", entry.archive_name));
                    } else {
                        let entry_meta = input_metadata(&entry.fs_path, opts.follow_symlinks)?;
                        if !passes_time_filter(
                            fs_mtime_secs(&entry_meta),
                            opts.newer_than,
                            opts.older_than,
                        ) {
                            return Ok(());
                        }
                        paths.push(entry.archive_name);
                    }
                    Ok(())
                })?;
            }
        } else if passes_time_filter(fs_mtime_secs(&meta), opts.newer_than, opts.older_than) {
            paths.push(name);
        }
    }
    Ok(paths)
}

#[cfg(test)]
mod tests {
    use camino::Utf8Path;

    use super::*;

    // ── strip_components ─────────────────────────────────────────────────

    #[test]
    fn strip_zero_is_identity() {
        let p = Utf8Path::new("a/b/c");
        assert_eq!(strip_components(p, 0), Some(p.to_owned()));
    }

    #[test]
    fn strip_one() {
        assert_eq!(
            strip_components(Utf8Path::new("project/src/main.rs"), 1),
            Some(Utf8PathBuf::from("src/main.rs")),
        );
    }

    #[test]
    fn strip_all_returns_none() {
        assert_eq!(strip_components(Utf8Path::new("a/b"), 2), None);
    }

    #[test]
    fn strip_more_than_depth_returns_none() {
        assert_eq!(strip_components(Utf8Path::new("a"), 2), None);
    }

    #[test]
    fn strip_dir_entry_with_trailing_slash() {
        // "a/b/" → strip 1 → "b/" which camino normalises to "b"
        assert_eq!(
            strip_components(Utf8Path::new("a/b/"), 1),
            Some(Utf8PathBuf::from("b")),
        );
    }

    #[test]
    fn strip_dot_prefix() {
        // "./dir/file" → strip 1 → "dir/file"
        assert_eq!(
            strip_components(Utf8Path::new("./dir/file"), 1),
            Some(Utf8PathBuf::from("dir/file")),
        );
    }

    // ── build_glob_set ────────────────────────────────────────────────

    #[test]
    fn empty_patterns_never_match() {
        let set = build_glob_set(&[]).ok();
        assert!(set.is_some());
        let set = set.map(|s| s.is_match("anything"));
        assert_eq!(set, Some(false));
    }

    #[test]
    fn star_pattern_matches_at_any_depth() {
        let set = build_glob_set(&["*.log".to_owned()]).ok();
        assert!(set.is_some());
        let set = set.as_ref().map(|s| s.is_match("foo.log"));
        assert_eq!(set, Some(true));
        let set2 = build_glob_set(&["*.log".to_owned()]).ok();
        let set2 = set2.as_ref().map(|s| s.is_match("dir/foo.log"));
        assert_eq!(set2, Some(true));
    }

    #[test]
    fn directory_name_excludes_children() {
        let set = build_glob_set(&["node_modules".to_owned()]).ok();
        assert!(set.is_some());
        let s = set.as_ref();
        assert_eq!(s.map(|s| s.is_match("node_modules")), Some(true));
        assert_eq!(
            s.map(|s| s.is_match("node_modules/package.json")),
            Some(true),
        );
        assert_eq!(s.map(|s| s.is_match("src/node_modules/foo")), Some(true),);
        assert_eq!(s.map(|s| s.is_match("src/other")), Some(false));
    }

    // ── safe_entry_path ──────────────────────────────────────────────────

    #[test]
    fn safe_entry_path_accepts_plain_relative() {
        assert!(safe_entry_path("a/b/c.txt").is_ok());
        assert!(safe_entry_path("file").is_ok());
        assert!(safe_entry_path("deep/nested/dir/x.log").is_ok());
    }

    #[test]
    fn safe_entry_path_rejects_absolute() {
        assert!(safe_entry_path("/etc/passwd").is_err());
    }

    #[test]
    fn safe_entry_path_rejects_parent_traversal() {
        assert!(safe_entry_path("../etc/passwd").is_err());
        assert!(safe_entry_path("a/../b").is_err());
        assert!(safe_entry_path("a/b/..").is_err());
    }

    #[test]
    fn safe_entry_path_accepts_current_dir_prefix() {
        // "./foo" is harmless and sometimes appears in legitimate archives.
        assert!(safe_entry_path("./foo").is_ok());
    }

    // ── safe_link_target ─────────────────────────────────────────────────

    #[test]
    fn safe_link_target_accepts_relative_intra_archive() {
        assert!(safe_link_target("bin/sh", "busybox").is_ok());
        assert!(safe_link_target("a/link", "b/target").is_ok());
    }

    #[test]
    fn safe_link_target_rejects_absolute() {
        assert!(safe_link_target("link", "/etc/passwd").is_err());
    }

    #[test]
    fn safe_link_target_rejects_parent_traversal() {
        assert!(safe_link_target("link", "../etc/passwd").is_err());
        assert!(safe_link_target("a/link", "../../etc").is_err());
    }

    // ── should_extract ───────────────────────────────────────────────────

    #[test]
    fn should_extract_excludes_take_precedence_over_includes() {
        // Include *.txt but exclude secret.txt — exclude wins.
        let includes = build_glob_set(&["*.txt".to_owned()]).unwrap_or(GlobSet::empty());
        let excludes = build_glob_set(&["secret.txt".to_owned()]).unwrap_or(GlobSet::empty());
        assert!(should_extract("notes.txt", &includes, &excludes));
        assert!(!should_extract("secret.txt", &includes, &excludes));
    }

    #[test]
    fn should_extract_empty_includes_means_include_all() {
        // When no includes are specified, everything not excluded matches.
        let includes = GlobSet::empty();
        let excludes = build_glob_set(&["*.log".to_owned()]).unwrap_or(GlobSet::empty());
        assert!(should_extract("any.txt", &includes, &excludes));
        assert!(!should_extract("debug.log", &includes, &excludes));
    }

    #[test]
    fn should_extract_non_matching_include_filters_out() {
        let includes = build_glob_set(&["*.txt".to_owned()]).unwrap_or(GlobSet::empty());
        let excludes = GlobSet::empty();
        assert!(!should_extract("something.bin", &includes, &excludes));
    }
}