use crate::ArchiveError;
use crate::Limit;
use crate::PermissionPolicy;
use crate::Result;
use crate::error::RequestedLevel;
use crate::pattern::EntryPattern;
use std::num::NonZeroU64;
use std::num::NonZeroUsize;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CompressionLevel(u8);
impl CompressionLevel {
pub const DEFAULT: Self = Self(6);
pub const MAX: Self = Self(9);
pub const MIN: Self = Self(1);
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
impl Default for CompressionLevel {
fn default() -> Self {
Self::DEFAULT
}
}
impl TryFrom<u8> for CompressionLevel {
type Error = ArchiveError;
fn try_from(level: u8) -> Result<Self> {
if (Self::MIN.0..=Self::MAX.0).contains(&level) {
Ok(Self(level))
} else {
Err(ArchiveError::InvalidCompressionLevel {
level: RequestedLevel::Integer(i64::from(level)),
})
}
}
}
impl TryFrom<u32> for CompressionLevel {
type Error = ArchiveError;
fn try_from(level: u32) -> Result<Self> {
Self::from_i128(i128::from(level))
}
}
impl TryFrom<RequestedLevel> for CompressionLevel {
type Error = ArchiveError;
fn try_from(requested: RequestedLevel) -> Result<Self> {
match requested {
RequestedLevel::Integer(level) => Self::from_i128(i128::from(level)),
other => Err(ArchiveError::InvalidCompressionLevel { level: other }),
}
}
}
impl CompressionLevel {
pub fn from_i128(level: i128) -> Result<Self> {
u8::try_from(level)
.ok()
.filter(|level| (Self::MIN.0..=Self::MAX.0).contains(level))
.map(Self)
.ok_or_else(|| ArchiveError::InvalidCompressionLevel {
level: i64::try_from(level)
.map_or(RequestedLevel::OutOfRange, RequestedLevel::Integer),
})
}
#[expect(
clippy::cast_possible_truncation,
reason = "a whole number saturated by `as`; any value outside 1-9 is refused by from_i128"
)]
pub fn from_f64(level: f64) -> Result<Self> {
if !level.is_finite() {
return Err(ArchiveError::InvalidCompressionLevel {
level: RequestedLevel::NonFinite,
});
}
if level.fract() != 0.0 {
return Err(ArchiveError::InvalidCompressionLevel {
level: RequestedLevel::Fractional(level),
});
}
Self::from_i128(level as i128)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Parallelism {
#[default]
Sequential,
Threads(NonZeroUsize),
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CreationConfig {
pub follow_symlinks: bool,
pub include_hidden: bool,
pub max_file_size: Limit<NonZeroU64>,
pub exclude_patterns: Vec<EntryPattern>,
pub strip_prefix: Option<PathBuf>,
pub compression_level: CompressionLevel,
pub permissions: PermissionPolicy,
pub parallelism: Parallelism,
}
impl Default for CreationConfig {
fn default() -> Self {
Self {
follow_symlinks: false,
include_hidden: false,
max_file_size: Limit::Unbounded,
exclude_patterns: vec![
EntryPattern::literal_name(".git"),
EntryPattern::literal_name(".DS_Store"),
EntryPattern::suffix_name(".tmp"),
],
strip_prefix: None,
compression_level: CompressionLevel::default(),
permissions: PermissionPolicy::Preserve,
parallelism: Parallelism::Sequential,
}
}
}
impl CreationConfig {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_follow_symlinks(mut self, follow: bool) -> Self {
self.follow_symlinks = follow;
self
}
#[must_use]
pub fn with_parallelism(mut self, parallelism: Parallelism) -> Self {
self.parallelism = parallelism;
self
}
#[must_use]
pub fn with_include_hidden(mut self, include: bool) -> Self {
self.include_hidden = include;
self
}
#[must_use]
pub fn with_max_file_size(mut self, max_size: impl Into<Limit<NonZeroU64>>) -> Self {
self.max_file_size = max_size.into();
self
}
#[must_use]
pub fn with_exclude_patterns(mut self, patterns: Vec<EntryPattern>) -> Self {
self.exclude_patterns = patterns;
self
}
#[must_use]
pub fn with_strip_prefix(mut self, prefix: Option<PathBuf>) -> Self {
self.strip_prefix = prefix;
self
}
#[must_use]
pub fn with_compression_level(mut self, level: CompressionLevel) -> Self {
self.compression_level = level;
self
}
#[must_use]
pub fn with_preserve_permissions(mut self, preserve: bool) -> Self {
self.permissions = PermissionPolicy::from_preserve(preserve);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::assert_matches;
#[test]
fn test_creation_config_default() {
let config = CreationConfig::default();
assert!(!config.follow_symlinks);
assert!(!config.include_hidden);
assert_eq!(config.max_file_size, Limit::Unbounded);
assert_eq!(config.exclude_patterns.len(), 3);
let shown: Vec<String> = config
.exclude_patterns
.iter()
.map(ToString::to_string)
.collect();
assert_eq!(shown, [".git", ".DS_Store", "*.tmp"]);
assert_eq!(config.strip_prefix, None);
assert_eq!(config.compression_level, CompressionLevel::default());
assert!(config.permissions.preserves());
}
#[test]
fn test_creation_config_builder() {
let level = CompressionLevel::try_from(9u8).unwrap();
let config = CreationConfig::default()
.with_follow_symlinks(true)
.with_include_hidden(true)
.with_max_file_size(crate::non_zero!(1024 * 1024))
.with_exclude_patterns(vec![EntryPattern::try_from("*.log").unwrap()])
.with_strip_prefix(Some(PathBuf::from("/base")))
.with_compression_level(level)
.with_preserve_permissions(false);
assert!(config.follow_symlinks);
assert!(config.include_hidden);
assert_eq!(
config.max_file_size,
Limit::Bounded(crate::non_zero!(1024 * 1024))
);
assert_eq!(
config.exclude_patterns,
vec![EntryPattern::try_from("*.log").unwrap()]
);
assert_eq!(config.strip_prefix, Some(PathBuf::from("/base")));
assert_eq!(config.compression_level, level);
assert!(!config.permissions.preserves());
}
#[test]
fn test_compression_level_refuses_out_of_range() {
for level in [0u8, 10, 200] {
assert_matches!(
CompressionLevel::try_from(level),
Err(ArchiveError::InvalidCompressionLevel { level: RequestedLevel::Integer(l) }) if l == i64::from(level)
);
}
for level in [0u32, 10, 256, 4_294_967_295] {
assert_matches!(
CompressionLevel::try_from(level),
Err(ArchiveError::InvalidCompressionLevel { level: RequestedLevel::Integer(l) }) if l == i64::from(level)
);
}
}
#[test]
fn test_compression_level_accepts_the_whole_scale() {
for level in 1u8..=9 {
assert_eq!(CompressionLevel::try_from(level).unwrap().get(), level);
assert_eq!(
CompressionLevel::try_from(u32::from(level)).unwrap().get(),
level
);
}
assert_eq!(CompressionLevel::default().get(), 6);
}
#[test]
fn test_creation_config_new() {
let config = CreationConfig::new();
assert_eq!(config.compression_level, CompressionLevel::default());
assert!(config.permissions.preserves());
}
#[test]
fn test_creation_config_secure_defaults() {
let config = CreationConfig::default();
assert!(
!config.follow_symlinks,
"should not follow symlinks by default (security)"
);
assert!(
!config.include_hidden,
"should not include hidden files by default"
);
assert!(
config
.exclude_patterns
.contains(&EntryPattern::literal_name(".git")),
"should exclude .git by default"
);
}
}