use std::collections::BTreeMap;
use std::fmt;
use std::io;
use std::num::NonZeroUsize;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use crate::ArchiveError;
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",
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<io::ErrorKind>,
}
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 const fn with_io_kind(mut self, io_kind: io::ErrorKind) -> Self {
self.io_kind = Some(io_kind);
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(0, |detail| {
detail
.counts
.values()
.fold(0, |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)
}
#[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(),
})),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExtractionWarning {
AntiItemsSkipped {
count: u64,
},
BackupCleanupFailed {
path: PathBuf,
identity_unverified: bool,
error: String,
},
}
impl fmt::Display for ExtractionWarning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BackupCleanupFailed {
path,
identity_unverified,
error,
} => {
let qualifier = if *identity_unverified {
" (its identity could not be verified on this platform)"
} else {
""
};
write!(
f,
"failed to remove backup of the original destination at {}{qualifier} \
({error}); it must be cleaned up manually",
path.display()
)
}
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, 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>,
}
impl ExtractionReport {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn add_warning(&mut self, warning: ExtractionWarning) {
self.warnings.push(warning);
}
#[must_use]
pub fn files_skipped(&self) -> usize {
self.skipped.total()
}
#[must_use]
pub fn total_items(&self) -> usize {
self.files_extracted + self.directories_created + 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 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(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
);
}
}