exarch-core 0.11.0

Memory-safe archive extraction library with security validation
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
//! Extraction operation reporting.

use std::collections::BTreeMap;
use std::fmt;
use std::num::NonZeroUsize;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;

use crate::ArchiveError;
use crate::IoKind;
use crate::MarkOutcome;
use crate::Result;
use crate::closed_enum::closed_enum;
use crate::error::QuotaResource;

closed_enum! {
    /// Why an entry was left out of an extraction or creation.
    ///
    /// The string form is stable and shared by every front end (for example as
    /// a `--json` key).
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SkipKind;
    ///
    /// assert_eq!(SkipKind::Duplicate.as_str(), "duplicate");
    /// assert!(SkipKind::ALL.contains(&SkipKind::Excluded));
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[non_exhaustive]
    pub enum SkipKind {
        /// A pre-existing destination entry kept under the skip-duplicates policy
        Duplicate => "duplicate",
        /// A file refused by the extension allowlist
        ExtensionNotAllowed => "extension_not_allowed",
        /// An entry that the extraction selection leaves out
        NotSelected => "not_selected",
        /// An entry whose whole path was removed by stripping leading
        /// components
        StrippedAway => "stripped_away",
        /// An entry matched by a creation exclude pattern
        Excluded => "excluded",
        /// A hidden entry left out by a creation configuration
        Hidden => "hidden",
        /// A file larger than the creation file size limit
        OverMaxFileSize => "over_max_file_size",
        /// A symlink that cannot be stored (not followed, or unsupported here)
        SymlinkUnsupported => "symlink_unsupported",
        /// A FIFO, socket or device that creation does not archive
        SpecialFile => "special_file",
        /// An entry that could not be read
        Unreadable => "unreadable",
    }
}

/// One entry left out of an operation, with the reason.
///
/// # Examples
///
/// ```
/// use exarch_core::Skip;
/// use exarch_core::SkipKind;
///
/// let skip = Skip::new(SkipKind::Excluded, "target/debug");
/// assert_eq!(skip.kind, SkipKind::Excluded);
/// assert_eq!(skip.to_string(), "skipped target/debug (excluded)");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Skip {
    /// Why the entry was skipped.
    pub kind: SkipKind,

    /// The entry's path as the operation names it.
    pub path: PathBuf,

    /// The I/O failure behind an [`SkipKind::Unreadable`] skip.
    pub io_kind: Option<IoKind>,
}

impl Skip {
    /// Builds a skip of `kind` for `path`, with no I/O failure attached.
    #[must_use]
    pub fn new(kind: SkipKind, path: impl Into<PathBuf>) -> Self {
        Self {
            kind,
            path: path.into(),
            io_kind: None,
        }
    }

    /// Attaches the I/O failure that caused the skip.
    #[must_use]
    pub fn with_io_kind(mut self, io_kind: impl Into<IoKind>) -> Self {
        self.io_kind = Some(io_kind.into());
        self
    }
}

impl fmt::Display for Skip {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "skipped {} ({})", self.path.display(), self.kind)?;
        self.io_kind
            .map_or(Ok(()), |io_kind| write!(f, ": {io_kind}"))
    }
}

/// Everything an operation left out: exact counts per [`SkipKind`] plus a
/// bounded sample of the individual entries.
///
/// The counts are exact however many entries are skipped. The sample keeps the
/// first [`Skips::SAMPLE_CAP`] entries, so a report stays small on an archive
/// with millions of skipped entries (#490, #495).
///
/// # Examples
///
/// ```
/// use exarch_core::ExtractionReport;
///
/// let report = ExtractionReport::new();
/// assert_eq!(report.skipped.total(), 0);
/// assert!(report.skipped.sample().is_empty());
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Skips {
    // Boxed so a report with nothing skipped stays small: the report rides
    // inside `ArchiveError::PartialExtraction`.
    detail: Option<Box<SkipDetail>>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct SkipDetail {
    counts: BTreeMap<SkipKind, usize>,
    sample: Vec<Skip>,
}

impl Skips {
    /// The most individual skips [`sample`](Self::sample) keeps.
    pub const SAMPLE_CAP: usize = 64;

    /// Returns how many entries were skipped, over all kinds.
    #[must_use]
    pub fn total(&self) -> usize {
        self.detail.as_ref().map_or_default(|detail| {
            detail
                .counts
                .values()
                .fold(0_usize, |sum, count| sum.saturating_add(*count))
        })
    }

    /// Returns how many entries were skipped for `kind`.
    #[must_use]
    pub fn count(&self, kind: SkipKind) -> usize {
        self.detail
            .as_ref()
            .and_then(|detail| detail.counts.get(&kind))
            .copied()
            .unwrap_or(0)
    }

    /// Returns the non-zero count of each [`SkipKind`], in `SkipKind` order.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::Skip;
    /// use exarch_core::SkipKind;
    /// use exarch_core::Skips;
    ///
    /// let mut skips = Skips::default();
    /// skips.record(Skip::new(SkipKind::Excluded, "a.tmp"))?;
    /// skips.record(Skip::new(SkipKind::Duplicate, "b"))?;
    /// skips.record(Skip::new(SkipKind::Duplicate, "c"))?;
    /// let counts: Vec<_> = skips.counts().collect();
    /// assert_eq!(counts, [(SkipKind::Duplicate, 2), (SkipKind::Excluded, 1)]);
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    pub fn counts(&self) -> impl Iterator<Item = (SkipKind, usize)> + '_ {
        self.detail
            .iter()
            .flat_map(|detail| detail.counts.iter().map(|(kind, count)| (*kind, *count)))
    }

    /// Returns the first [`SAMPLE_CAP`](Self::SAMPLE_CAP) skipped entries, in
    /// the order they were skipped.
    #[must_use]
    pub fn sample(&self) -> &[Skip] {
        self.detail
            .as_ref()
            .map_or(&[], |detail| detail.sample.as_slice())
    }

    /// Returns whether nothing was skipped.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.detail.is_none()
    }

    /// Counts `skip`, failing closed instead of wrapping when its kind's
    /// counter is at its maximum (#515).
    ///
    /// # Errors
    ///
    /// Returns [`ArchiveError::QuotaExceeded`] with
    /// [`QuotaResource::IntegerOverflow`] when the counter would overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::Skip;
    /// use exarch_core::SkipKind;
    /// use exarch_core::Skips;
    ///
    /// let mut skips = Skips::default();
    /// skips.record(Skip::new(SkipKind::Excluded, "a.tmp"))?;
    /// assert_eq!(skips.count(SkipKind::Excluded), 1);
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    pub fn record(&mut self, skip: Skip) -> Result<()> {
        let detail = self.detail.get_or_insert_default();
        let count = detail.counts.entry(skip.kind).or_insert(0);
        *count = count.checked_add(1).ok_or(ArchiveError::QuotaExceeded {
            resource: QuotaResource::IntegerOverflow,
        })?;
        if detail.sample.len() < Self::SAMPLE_CAP {
            detail.sample.push(skip);
        }
        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn with_saturated_count(kind: SkipKind) -> Self {
        Self {
            detail: Some(Box::new(SkipDetail {
                counts: BTreeMap::from([(kind, usize::MAX)]),
                sample: Vec::new(),
            })),
        }
    }
}

closed_enum! {
    /// Whether the identity of a leftover backup was confirmed before its
    /// removal failed.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::BackupIdentity;
    ///
    /// assert_eq!(BackupIdentity::Unverified.as_str(), "unverified");
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum BackupIdentity {
        /// The path still names the backup that was created.
        Verified => "verified",
        /// The platform cannot confirm that the path still names the backup.
        Unverified => "unverified",
    }
}

closed_enum! {
    /// Why the root of an atomic publication gives less access than the
    /// destination it replaces or fills.
    ///
    /// The string form is stable and shared by every front end.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::NarrowingReason;
    ///
    /// assert_eq!(NarrowingReason::AclUnreadable.as_str(), "acl_unreadable");
    /// assert!(NarrowingReason::ALL.contains(&NarrowingReason::OwnerNotKept));
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum NarrowingReason {
        /// The destination's access control list could not be read in full.
        AclUnreadable => "acl_unreadable",
        /// The destination was no longer the directory that was pinned.
        DestinationChanged => "destination_changed",
        /// The list names a user or group the reading process cannot map.
        UnmappedId => "unmapped_id",
        /// The root belongs to another user or group than the destination, so
        /// its list would grant the wrong principals.
        OwnershipDiffers => "ownership_differs",
        /// Writing an access control list failed, in one of two places.
        ///
        /// Writing the destination's list onto the root happens after the
        /// publishing rename, so the run still succeeds and the root is made
        /// private (`0700`, no list) where the OS allows. On Windows the same
        /// holds for resetting the published root to its parent's inherited
        /// ACL, which also fails when the parent has no inheritable entries:
        /// the root then stays owner-only.
        ///
        /// Seeding the staging directory with the entries its children
        /// inherit (from the destination, or from the parent of an absent
        /// destination) happens before the rename. The seed is removed again
        /// and the published root stays `0700` with no list.
        AclCopyFailed => "acl_copy_failed",
        /// The root could not join the destination's group, so its group
        /// access and setgid bit were dropped.
        GroupNotKept => "group_not_kept",
        /// The destination belongs to another user, so its group and world
        /// write bits and setgid bit were dropped.
        ForeignWriteDropped => "foreign_write_dropped",
        /// The root could not take the destination's owner, so the owner's
        /// access now belongs to the caller.
        OwnerNotKept => "owner_not_kept",
        /// The destination disappeared before its mode could be read.
        DestinationVanished => "destination_vanished",
    }
}

closed_enum! {
    /// The class of an [`ExtractionWarning`], without its payload.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ExtractionWarning;
    /// use exarch_core::ExtractionWarningKind;
    ///
    /// let warning = ExtractionWarning::AntiItemsSkipped { count: 1 };
    /// assert_eq!(warning.kind(), ExtractionWarningKind::AntiItemsSkipped);
    /// assert_eq!(warning.kind().as_str(), "anti_items_skipped");
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum ExtractionWarningKind {
        /// [`ExtractionWarning::AntiItemsSkipped`].
        AntiItemsSkipped => "anti_items_skipped",
        /// [`ExtractionWarning::BackupCleanupFailed`].
        BackupCleanupFailed => "backup_cleanup_failed",
        /// [`ExtractionWarning::RootAccessNarrowed`].
        RootAccessNarrowed => "root_access_narrowed",
    }
}

/// A condition of an extraction worth surfacing that is not a skipped entry.
///
/// # Examples
///
/// ```
/// use exarch_core::ExtractionWarning;
///
/// let warning = ExtractionWarning::AntiItemsSkipped { count: 1 };
/// assert_eq!(
///     warning.to_string(),
///     "skipped 1 7z anti-item (deletion markers are not applied)"
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExtractionWarning {
    /// 7z anti-items, which mark deletions in an update archive, were not
    /// applied.
    AntiItemsSkipped {
        /// How many anti-items the archive holds.
        count: u64,
    },

    /// The backup of the original destination, kept for an atomic
    /// replacement, could not be removed and must be cleaned up manually.
    BackupCleanupFailed {
        /// Where the backup remains.
        path: PathBuf,
        /// Whether the backup's identity was confirmed before removal.
        identity: BackupIdentity,
        /// The kind of the removal failure.
        io_kind: IoKind,
        /// The failure text, redacted like an I/O error message.
        message: Box<str>,
    },

    /// The published root of an atomic extraction gives less access than the
    /// destination it replaced or filled; one warning is raised per reason.
    RootAccessNarrowed {
        /// Why the access was narrowed.
        reason: NarrowingReason,
    },
}

impl ExtractionWarning {
    /// The class of this warning.
    #[must_use]
    pub const fn kind(&self) -> ExtractionWarningKind {
        match self {
            Self::AntiItemsSkipped { .. } => ExtractionWarningKind::AntiItemsSkipped,
            Self::BackupCleanupFailed { .. } => ExtractionWarningKind::BackupCleanupFailed,
            Self::RootAccessNarrowed { .. } => ExtractionWarningKind::RootAccessNarrowed,
        }
    }

    /// A copy whose host paths are redacted like those of an error message
    /// (the file name only in release builds), so a binding or a JSON consumer
    /// can show it without leaking the host layout.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ExtractionWarning;
    ///
    /// let warning = ExtractionWarning::AntiItemsSkipped { count: 2 };
    /// assert_eq!(warning.redacted(), warning);
    /// ```
    #[must_use]
    pub fn redacted(&self) -> Self {
        match self {
            Self::AntiItemsSkipped { .. } | Self::RootAccessNarrowed { .. } => self.clone(),
            Self::BackupCleanupFailed {
                path,
                identity,
                io_kind,
                message,
            } => Self::BackupCleanupFailed {
                path: crate::sanitize_path_for_error(path).into(),
                identity: *identity,
                io_kind: *io_kind,
                message: message.clone(),
            },
        }
    }
}

impl fmt::Display for ExtractionWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BackupCleanupFailed {
                path,
                identity,
                message,
                ..
            } => {
                let qualifier = match identity {
                    BackupIdentity::Verified => "",
                    BackupIdentity::Unverified => {
                        " (its identity could not be verified on this platform)"
                    }
                };
                write!(
                    f,
                    "failed to remove backup of the original destination at {}{qualifier} \
                     ({message}); it must be cleaned up manually",
                    path.display()
                )
            }
            Self::RootAccessNarrowed { reason } => write!(
                f,
                "the published root gives less access than the destination it replaced ({reason})"
            ),
            Self::AntiItemsSkipped { count } => {
                let noun = if *count == 1 {
                    "anti-item"
                } else {
                    "anti-items"
                };
                write!(
                    f,
                    "skipped {count} 7z {noun} (deletion markers are not applied)"
                )
            }
        }
    }
}

/// The reasons an atomic publication narrowed the root's access, to be
/// recorded on the report.
///
/// Only [`ExtractionReport::record_narrowing`] consumes it, and it is
/// `#[must_use]`, so a publication path that drops it fails `-D warnings`.
#[derive(Debug)]
#[must_use = "record the narrowing on the report"]
pub(crate) struct Narrowed(Vec<NarrowingReason>);

impl Narrowed {
    /// A publication that narrowed nothing.
    pub(crate) const fn none() -> Self {
        Self(Vec::new())
    }

    /// Adds `reason`, once.
    pub(crate) fn push(&mut self, reason: NarrowingReason) {
        if !self.0.contains(&reason) {
            self.0.push(reason);
        }
    }

    #[cfg(all(test, unix))]
    pub(crate) fn reasons(&self) -> &[NarrowingReason] {
        &self.0
    }
}

/// Report of an archive extraction operation.
///
/// Contains statistics and metadata about the extraction process.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ExtractionReport {
    /// Number of files successfully extracted.
    pub files_extracted: usize,

    /// Number of directories created.
    pub directories_created: usize,

    /// Number of symlinks created.
    pub symlinks_created: usize,

    /// Total bytes written to disk.
    pub bytes_written: u64,

    /// Duration of the extraction operation.
    pub duration: Duration,

    /// Entries left out of the extraction, by reason.
    pub skipped: Skips,

    /// Conditions worth surfacing that are not skipped entries.
    pub warnings: Vec<ExtractionWarning>,

    /// What download-origin mark propagation did; see [`MarkOutcome`].
    pub mark: MarkOutcome,
}

impl ExtractionReport {
    /// Creates a new empty extraction report.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a warning to the report.
    pub fn add_warning(&mut self, warning: ExtractionWarning) {
        self.warnings.push(warning);
    }

    pub(crate) fn record_narrowing(&mut self, narrowed: Narrowed) {
        self.warnings.extend(
            narrowed
                .0
                .into_iter()
                .map(|reason| ExtractionWarning::RootAccessNarrowed { reason }),
        );
    }

    /// Returns how many entries were skipped, over all reasons.
    #[must_use]
    pub fn files_skipped(&self) -> usize {
        self.skipped.total()
    }

    /// Returns the total number of items actually written to disk
    /// (`files_extracted + directories_created + symlinks_created`).
    ///
    /// This deliberately excludes [`files_skipped`](Self::files_skipped): a
    /// report can carry meaningful progress — skipped entries, warnings —
    /// while this is `0`. Callers deciding whether a report is worth
    /// surfacing (e.g. `ArchiveError::partial_or`) must check
    /// `files_skipped`/[`has_warnings`](Self::has_warnings) too, not rely on
    /// this alone.
    #[must_use]
    pub fn total_items(&self) -> usize {
        self.files_extracted
            .saturating_add(self.directories_created)
            .saturating_add(self.symlinks_created)
    }

    /// Returns whether any warnings were generated.
    #[must_use]
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }
}

/// How many entries an operation has, when it knows.
///
/// A stream such as a TAR archive cannot count its entries before reading
/// them, so it reports [`Unknown`](Self::Unknown) rather than a count a
/// callback might divide by.
///
/// # Examples
///
/// ```
/// use exarch_core::EntryTotal;
///
/// let total = EntryTotal::Known(3);
/// assert_eq!(total.known(), Some(3));
/// assert_eq!(EntryTotal::Unknown.known(), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EntryTotal {
    /// The operation holds exactly this many entries.
    Known(usize),

    /// The entry count is not known until the operation ends.
    Unknown,
}

impl EntryTotal {
    /// Returns the count when it is known.
    #[must_use]
    pub const fn known(self) -> Option<usize> {
        match self {
            Self::Known(total) => Some(total),
            Self::Unknown => None,
        }
    }
}

/// Where an entry sits in the operation: its 1-based number and the total.
///
/// # Examples
///
/// ```
/// use exarch_core::EntryPosition;
/// use exarch_core::EntryTotal;
///
/// let position = EntryPosition::at_index(0, EntryTotal::Known(4));
/// assert_eq!(position.current.get(), 1);
/// assert_eq!(position.total, EntryTotal::Known(4));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct EntryPosition {
    /// The entry's number, counting from 1.
    pub current: NonZeroUsize,

    /// How many entries the operation holds, when known.
    pub total: EntryTotal,
}

impl EntryPosition {
    /// Builds a position from its parts.
    #[must_use]
    pub const fn new(current: NonZeroUsize, total: EntryTotal) -> Self {
        Self { current, total }
    }

    /// Builds the position of the entry at the 0-based `index`.
    #[must_use]
    pub const fn at_index(index: usize, total: EntryTotal) -> Self {
        Self::new(NonZeroUsize::MIN.saturating_add(index), total)
    }
}

/// Callback trait for progress reporting during archive operations.
///
/// Implement this trait to receive progress updates during extraction or
/// creation. The trait requires `Send` to allow use in multi-threaded contexts.
///
/// # Examples
///
/// ```
/// use exarch_core::EntryPosition;
/// use exarch_core::EntryTotal;
/// use exarch_core::ProgressCallback;
/// use std::path::Path;
///
/// struct SimpleProgress;
///
/// impl ProgressCallback for SimpleProgress {
///     fn on_entry_start(&mut self, path: &Path, position: EntryPosition) {
///         match position.total {
///             EntryTotal::Known(total) => {
///                 println!(
///                     "Processing {}/{}: {}",
///                     position.current,
///                     total,
///                     path.display()
///                 );
///             }
///             _ => println!("Processing {}: {}", position.current, path.display()),
///         }
///     }
///
///     fn on_bytes_written(&mut self, bytes: u64) {
///         // Track bytes written
///     }
///
///     fn on_entry_complete(&mut self, path: &Path) {
///         println!("Completed: {}", path.display());
///     }
///
///     fn on_complete(&mut self) {
///         println!("Operation complete");
///     }
/// }
/// ```
pub trait ProgressCallback: Send {
    /// Called when starting to process an entry.
    ///
    /// # Arguments
    ///
    /// * `path` - Path of the entry being processed
    /// * `position` - The entry's 1-based number and the entry total, which is
    ///   [`EntryTotal::Unknown`] for a stream
    fn on_entry_start(&mut self, path: &Path, position: EntryPosition);

    /// Called when bytes are written during extraction or read during creation.
    ///
    /// Granularity is per-entry: called once after the full entry is written.
    /// Partial writes on failure are not reported. Not called for entries that
    /// produce no output (directories, skipped entries).
    ///
    /// # Arguments
    ///
    /// * `bytes` - Number of bytes written/read in this update
    fn on_bytes_written(&mut self, bytes: u64);

    /// Called when an entry has been completely processed.
    ///
    /// Always called after [`on_entry_start`](Self::on_entry_start) for the
    /// same entry, including when extraction of that entry fails. Callers can
    /// rely on this pairing for cleanup or progress accounting.
    ///
    /// # Arguments
    ///
    /// * `path` - Path of the entry that was completed
    fn on_entry_complete(&mut self, path: &Path);

    /// Called when the entire operation completes successfully.
    ///
    /// Not called if the operation fails or results in a partial extraction.
    /// Implementors must not rely on this method for cleanup — use `Drop`
    /// instead.
    fn on_complete(&mut self);

    /// Whether the operation should stop, polled by every operation
    /// (extraction, listing, verification and creation) before each entry, and
    /// once more before an archive is published or a staged extraction is
    /// committed. Extraction and creation also poll about every 8 MiB inside
    /// one entry's copy; listing and verification do not, so one very large
    /// entry delays a verification until its end.
    ///
    /// The callbacks above cannot fail, so a callback that hit an error of its
    /// own (a raising script callback, a closed channel) reports it here: the
    /// operation then stops with [`ArchiveError::Cancelled`]. An extraction
    /// that had already recorded progress reports it as
    /// [`ArchiveError::PartialExtraction`] wrapping `Cancelled`, rolled back
    /// under atomic staging; a creation discards its staged output and leaves a
    /// previous archive at the output path untouched; the partial file of the
    /// entry being copied is removed. The default never cancels.
    fn is_cancelled(&mut self) -> bool {
        false
    }
}

/// No-op implementation of `ProgressCallback` that does nothing.
///
/// Use this when you don't need progress reporting but the API requires
/// a callback implementation.
#[derive(Debug, Default)]
pub struct NoopProgress;

impl ProgressCallback for NoopProgress {
    fn on_entry_start(&mut self, _path: &Path, _position: EntryPosition) {}

    fn on_bytes_written(&mut self, _bytes: u64) {}

    fn on_entry_complete(&mut self, _path: &Path) {}

    fn on_complete(&mut self) {}
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Allow unwrap in tests for brevity
mod tests {
    use super::*;
    use std::assert_matches;

    #[test]
    fn redacted_backup_warning_keeps_no_directory_in_release() {
        let warning = ExtractionWarning::BackupCleanupFailed {
            path: "/srv/private/backup".into(),
            identity: BackupIdentity::Verified,
            io_kind: IoKind::Other,
            message: "denied".into(),
        };
        let redacted = warning.redacted();
        assert_eq!(redacted.kind(), warning.kind());
        if !cfg!(debug_assertions) {
            assert!(!redacted.to_string().contains("/srv/private"));
        }
    }

    #[test]
    fn every_narrowing_reason_becomes_a_typed_warning() {
        for reason in NarrowingReason::ALL {
            let warning = ExtractionWarning::RootAccessNarrowed { reason: *reason };
            assert_eq!(warning.kind(), ExtractionWarningKind::RootAccessNarrowed);
            assert!(NarrowingReason::NAMES.contains(&reason.as_str()));
            assert!(warning.to_string().contains(reason.as_str()));
            assert_eq!(warning.redacted(), warning);
        }
    }

    #[test]
    fn a_narrowing_records_one_warning_per_distinct_reason() {
        let mut narrowed = Narrowed::none();
        narrowed.push(NarrowingReason::GroupNotKept);
        narrowed.push(NarrowingReason::OwnerNotKept);
        narrowed.push(NarrowingReason::GroupNotKept);
        let mut report = ExtractionReport::new();

        report.record_narrowing(narrowed);

        assert_eq!(
            report.warnings,
            [
                ExtractionWarning::RootAccessNarrowed {
                    reason: NarrowingReason::GroupNotKept
                },
                ExtractionWarning::RootAccessNarrowed {
                    reason: NarrowingReason::OwnerNotKept
                },
            ]
        );
    }

    #[test]
    fn recording_nothing_adds_no_warning() {
        let mut report = ExtractionReport::new();
        report.record_narrowing(Narrowed::none());
        assert!(!report.has_warnings());
    }

    #[test]
    fn test_new_report() {
        let report = ExtractionReport::new();
        assert_eq!(report.files_extracted, 0);
        assert_eq!(report.directories_created, 0);
        assert_eq!(report.bytes_written, 0);
        assert!(!report.has_warnings());
        assert_eq!(report.files_skipped(), 0);
    }

    #[test]
    fn test_add_warning() {
        let mut report = ExtractionReport::new();
        report.add_warning(ExtractionWarning::AntiItemsSkipped { count: 2 });
        assert!(report.has_warnings());
        assert_eq!(report.warnings.len(), 1);
    }

    #[test]
    fn test_total_items() {
        let mut report = ExtractionReport::new();
        report.files_extracted = 10;
        report.directories_created = 5;
        report.symlinks_created = 2;
        assert_eq!(report.total_items(), 17);
    }

    #[test]
    fn skips_count_per_kind_and_bound_the_sample() {
        let mut skips = Skips::default();
        for i in 0..Skips::SAMPLE_CAP + 10 {
            skips
                .record(Skip::new(SkipKind::Duplicate, format!("f{i}")))
                .unwrap();
        }
        skips
            .record(Skip::new(SkipKind::Excluded, "x").with_io_kind(std::io::ErrorKind::NotFound))
            .unwrap();
        assert_eq!(skips.count(SkipKind::Duplicate), Skips::SAMPLE_CAP + 10);
        assert_eq!(skips.count(SkipKind::Excluded), 1);
        assert_eq!(skips.count(SkipKind::Hidden), 0);
        assert_eq!(skips.total(), Skips::SAMPLE_CAP + 11);
        assert_eq!(skips.sample().len(), Skips::SAMPLE_CAP);
        assert!(!skips.is_empty());
    }

    #[test]
    fn skips_fail_closed_at_a_saturated_counter() {
        let mut skips = Skips::with_saturated_count(SkipKind::Duplicate);
        let err = skips
            .record(Skip::new(SkipKind::Duplicate, "a"))
            .unwrap_err();
        assert_matches!(
            err,
            ArchiveError::QuotaExceeded {
                resource: QuotaResource::IntegerOverflow
            }
        );
        assert_eq!(skips.count(SkipKind::Duplicate), usize::MAX);
        assert!(skips.sample().is_empty());
    }

    #[test]
    fn every_skip_kind_has_a_distinct_string_form() {
        let mut seen: Vec<&str> = SkipKind::ALL.iter().map(|kind| kind.as_str()).collect();
        seen.sort_unstable();
        seen.dedup();
        assert_eq!(seen.len(), SkipKind::ALL.len());
    }

    #[test]
    fn entry_position_numbers_from_one() {
        let position = EntryPosition::at_index(usize::MAX, EntryTotal::Unknown);
        assert_eq!(position.current.get(), usize::MAX);
        assert_eq!(
            EntryPosition::at_index(0, EntryTotal::Unknown)
                .current
                .get(),
            1
        );
    }
}