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! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum SkipKind {
Duplicate => "duplicate",
ExtensionNotAllowed => "extension_not_allowed",
NotSelected => "not_selected",
StrippedAway => "stripped_away",
Excluded => "excluded",
Hidden => "hidden",
OverMaxFileSize => "over_max_file_size",
SymlinkUnsupported => "symlink_unsupported",
Unreadable => "unreadable",
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Skip {
pub kind: SkipKind,
pub path: PathBuf,
pub io_kind: Option<IoKind>,
}
impl Skip {
#[must_use]
pub fn new(kind: SkipKind, path: impl Into<PathBuf>) -> Self {
Self {
kind,
path: path.into(),
io_kind: None,
}
}
#[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}"))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Skips {
detail: Option<Box<SkipDetail>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct SkipDetail {
counts: BTreeMap<SkipKind, usize>,
sample: Vec<Skip>,
}
impl Skips {
pub const SAMPLE_CAP: usize = 64;
#[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))
})
}
#[must_use]
pub fn count(&self, kind: SkipKind) -> usize {
self.detail
.as_ref()
.and_then(|detail| detail.counts.get(&kind))
.copied()
.unwrap_or(0)
}
pub fn counts(&self) -> impl Iterator<Item = (SkipKind, usize)> + '_ {
self.detail
.iter()
.flat_map(|detail| detail.counts.iter().map(|(kind, count)| (*kind, *count)))
}
#[must_use]
pub fn sample(&self) -> &[Skip] {
self.detail
.as_ref()
.map_or(&[], |detail| detail.sample.as_slice())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.detail.is_none()
}
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! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BackupIdentity {
Verified => "verified",
Unverified => "unverified",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NarrowingReason {
AclUnreadable => "acl_unreadable",
DestinationChanged => "destination_changed",
UnmappedId => "unmapped_id",
OwnershipDiffers => "ownership_differs",
AclCopyFailed => "acl_copy_failed",
GroupNotKept => "group_not_kept",
ForeignWriteDropped => "foreign_write_dropped",
OwnerNotKept => "owner_not_kept",
DestinationVanished => "destination_vanished",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExtractionWarningKind {
AntiItemsSkipped => "anti_items_skipped",
BackupCleanupFailed => "backup_cleanup_failed",
RootAccessNarrowed => "root_access_narrowed",
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExtractionWarning {
AntiItemsSkipped {
count: u64,
},
BackupCleanupFailed {
path: PathBuf,
identity: BackupIdentity,
io_kind: IoKind,
message: Box<str>,
},
RootAccessNarrowed {
reason: NarrowingReason,
},
}
impl ExtractionWarning {
#[must_use]
pub const fn kind(&self) -> ExtractionWarningKind {
match self {
Self::AntiItemsSkipped { .. } => ExtractionWarningKind::AntiItemsSkipped,
Self::BackupCleanupFailed { .. } => ExtractionWarningKind::BackupCleanupFailed,
Self::RootAccessNarrowed { .. } => ExtractionWarningKind::RootAccessNarrowed,
}
}
#[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)"
)
}
}
}
}
#[derive(Debug)]
#[must_use = "record the narrowing on the report"]
pub(crate) struct Narrowed(Vec<NarrowingReason>);
impl Narrowed {
pub(crate) const fn none() -> Self {
Self(Vec::new())
}
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
}
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ExtractionReport {
pub files_extracted: usize,
pub directories_created: usize,
pub symlinks_created: usize,
pub bytes_written: u64,
pub duration: Duration,
pub skipped: Skips,
pub warnings: Vec<ExtractionWarning>,
pub mark: MarkOutcome,
}
impl ExtractionReport {
#[must_use]
pub fn new() -> Self {
Self::default()
}
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 }),
);
}
#[must_use]
pub fn files_skipped(&self) -> usize {
self.skipped.total()
}
#[must_use]
pub fn total_items(&self) -> usize {
self.files_extracted
.saturating_add(self.directories_created)
.saturating_add(self.symlinks_created)
}
#[must_use]
pub fn has_warnings(&self) -> bool {
!self.warnings.is_empty()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EntryTotal {
Known(usize),
Unknown,
}
impl EntryTotal {
#[must_use]
pub const fn known(self) -> Option<usize> {
match self {
Self::Known(total) => Some(total),
Self::Unknown => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct EntryPosition {
pub current: NonZeroUsize,
pub total: EntryTotal,
}
impl EntryPosition {
#[must_use]
pub const fn new(current: NonZeroUsize, total: EntryTotal) -> Self {
Self { current, total }
}
#[must_use]
pub const fn at_index(index: usize, total: EntryTotal) -> Self {
Self::new(NonZeroUsize::MIN.saturating_add(index), total)
}
}
pub trait ProgressCallback: Send {
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);
fn is_cancelled(&mut self) -> bool {
false
}
}
#[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)] 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
);
}
}