use crate::ArchiveError;
use crate::CompressionRatio;
use crate::IoContext;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::Skip;
use crate::SkipKind;
use crate::ZipBombDetails;
use crate::ZipBombScope;
use crate::copy::CancelClock;
use crate::creation::config::CreationConfig;
use crate::creation::open::LinkPolicy;
use crate::creation::open::WalkedSource;
use crate::creation::open::open_source;
use crate::creation::progress::ProgressTracker;
use crate::creation::progress::check_cancelled;
use crate::creation::report::CreationReport;
use crate::creation::report::CreationWarning;
use crate::creation::source::source_error;
use crate::creation::staged::ExcludedOutput;
use crate::creation::walker::Collected;
use crate::creation::walker::EntryType;
use crate::creation::walker::FilteredEntry;
use crate::creation::walker::collect_entries;
use crate::creation::zip_prepared::Executor;
use crate::creation::zip_prepared::Inline;
use crate::creation::zip_prepared::PREPARED_ENTRY_LIMIT;
use crate::creation::zip_prepared::PreparedJob;
use crate::creation::zip_prepared::Workers;
use crate::creation::zip_prepared::worker_count;
use crate::creation::zip_prepared::zip_error;
use crate::security::Compressed;
use crate::security::Uncompressed;
use std::collections::BTreeMap;
use std::io::Read;
use std::io::Seek;
use std::io::Write;
use std::path::Path;
use zip::CompressionMethod;
use zip::ZipWriter;
use zip::write::SimpleFileOptions;
pub(crate) fn write_zip<W: Write + Seek, P: AsRef<Path>>(
mut out: W,
sources: &[P],
config: &CreationConfig,
excluded: &ExcludedOutput,
progress: &mut dyn ProgressCallback,
) -> Result<(CreationReport, W)> {
if out.stream_position()? != 0 {
return Err(ArchiveError::InvalidConfiguration {
setting: crate::ConfigSetting::ZipOutputWriter,
problem: crate::ConfigProblem::NotAtStart,
});
}
let mut zip = ZipWriter::new(out);
let mut report = CreationReport::default();
let start = std::time::Instant::now();
let options = SimpleFileOptions::default()
.compression_method(CompressionMethod::Deflated)
.compression_level(Some(config.compression_level.to_zip_level()));
let Collected { entries, skipped } = collect_entries(sources, config, excluded)?;
report.skipped = skipped;
let total_entries = entries.len();
let mut tracker = ProgressTracker::new(progress, total_entries);
std::thread::scope(|scope| -> Result<()> {
let mut write = EntryWriter {
zip: &mut zip,
entries: &entries,
config,
options: &options,
tracker: &mut tracker,
report: &mut report,
};
match worker_count(config.parallelism) {
Some(count) => write.run(Workers::spawn(scope, count)?),
None => write.run(Inline),
}
})?;
tracker.check_cancelled()?;
let mut writer = zip
.finish()
.map_err(|e| zip_error("failed to finish zip archive", &e))?;
writer.flush()?;
report.bytes_compressed = writer.stream_position()?;
report.duration = start.elapsed();
tracker.on_complete();
Ok((report, writer))
}
struct EntryWriter<'a, 'p, W: Write + Seek> {
zip: &'a mut ZipWriter<W>,
entries: &'a [FilteredEntry],
config: &'a CreationConfig,
options: &'a SimpleFileOptions,
tracker: &'a mut ProgressTracker<'p>,
report: &'a mut CreationReport,
}
impl<W: Write + Seek> EntryWriter<'_, '_, W> {
fn run<E: Executor>(&mut self, executor: E) -> Result<()> {
let mut staging = Staging::new(self.entries, self.config, self.options, executor);
let mut buffer = vec![0u8; 64 * 1024];
for (index, entry) in self.entries.iter().enumerate() {
let mut guard = self.tracker.begin(&entry.archive_path)?;
match &entry.entry_type {
EntryType::Content { .. } => staging.add_file(
self.zip,
index,
self.report,
guard.progress_mut(),
&mut buffer,
)?,
EntryType::Directory { metadata } => {
let dir_path = format!("{}/", normalize_zip_path(&entry.archive_path)?);
let dir_options = options_with_mode(self.options, self.config, metadata);
self.zip
.add_directory(&dir_path, dir_options)
.map_err(|e| zip_error("failed to add directory to zip archive", &e))?;
self.report.directories_added = self.report.directories_added.saturating_add(1);
}
EntryType::Symlink { .. } => {
self.report.skipped.record(Skip::new(
SkipKind::SymlinkUnsupported,
entry.archive_path.to_path_buf(),
))?;
}
}
guard.complete();
}
Ok(())
}
}
pub(crate) fn warn_on_extraction_ratio<R: Read + Seek>(archive: R, report: &mut CreationReport) {
match extraction_ratio_warning(archive) {
Ok(Some(warning)) => report.add_warning(warning),
Ok(None) => {}
Err(e) => report.add_warning(CreationWarning::ZipRatioCheckFailed {
reason: e.to_string(),
}),
}
}
fn extraction_ratio_warning<R: Read + Seek>(
archive: R,
) -> std::result::Result<Option<CreationWarning>, zip::result::ZipError> {
let limit = SecurityConfig::default().max_compression_ratio.get();
let mut zip = zip::ZipArchive::new(archive)?;
let mut over_limit = 0usize;
let mut highest = 0.0_f64;
for index in 0..zip.len() {
let entry = zip.by_index_raw(index)?;
let details = ZipBombDetails::new(
ZipBombScope::Entry,
Compressed(entry.compressed_size()),
Uncompressed(entry.size()),
);
if let CompressionRatio::Finite(ratio) = details.ratio()
&& ratio > limit
{
over_limit = over_limit.saturating_add(1);
highest = highest.max(ratio);
}
}
if over_limit == 0 {
return Ok(None);
}
Ok(Some(CreationWarning::ZipRatioOverDefaultLimit {
entries: over_limit,
limit,
needed_ratio: highest.ceil(),
}))
}
enum Staged<P> {
Skipped(Skip),
Failed(ArchiveError),
Prepared(P, u64),
Streamed(PreparedJob),
}
struct Staging<'a, E: Executor> {
entries: &'a [FilteredEntry],
config: &'a CreationConfig,
options: &'a SimpleFileOptions,
executor: E,
staged: BTreeMap<usize, Staged<E::Pending>>,
next: usize,
}
impl<'a, E: Executor> Staging<'a, E> {
fn new(
entries: &'a [FilteredEntry],
config: &'a CreationConfig,
options: &'a SimpleFileOptions,
executor: E,
) -> Self {
Self {
entries,
config,
options,
executor,
staged: BTreeMap::new(),
next: 0,
}
}
fn fill(&mut self, index: usize) -> Result<()> {
let room = self.executor.capacity();
while let Some(entry) = self.entries.get(self.next) {
if self.next > index && self.staged.len() >= room {
break;
}
if let EntryType::Content { walked, links } = &entry.entry_type {
let staged = self.stage(self.next, entry, *walked, *links)?;
self.staged.insert(self.next, staged);
}
self.next = self.next.saturating_add(1);
}
Ok(())
}
fn stage(
&self,
index: usize,
entry: &FilteredEntry,
walked: WalkedSource,
links: LinkPolicy,
) -> Result<Staged<E::Pending>> {
let source = match open_source(&entry.path, walked, links) {
Ok(source) => source,
Err(error) => return Ok(Staged::Failed(error)),
};
let size = source.size();
if !self.config.max_file_size.admits(size) {
return Ok(Staged::Skipped(Skip::new(
SkipKind::OverMaxFileSize,
entry.archive_path.to_path_buf(),
)));
}
let (metadata, reader) = source.into_exact();
let name = match normalize_zip_path(&entry.archive_path) {
Ok(name) => name,
Err(error) => return Ok(Staged::Failed(error)),
};
let job = PreparedJob {
path: entry.path.clone(),
name,
options: options_with_mode(self.options, self.config, &metadata),
reader,
};
if size > PREPARED_ENTRY_LIMIT {
return Ok(Staged::Streamed(job));
}
Ok(Staged::Prepared(self.executor.dispatch(index, job)?, size))
}
fn add_file<W: Write + Seek>(
&mut self,
zip: &mut ZipWriter<W>,
index: usize,
report: &mut CreationReport,
progress: &mut dyn ProgressCallback,
buffer: &mut [u8],
) -> Result<()> {
self.fill(index)?;
let staged = self.staged.remove(&index).ok_or_else(|| {
ArchiveError::Io(std::io::Error::other(IoContext::new(
"zip entry was not staged",
index.to_string(),
)))
})?;
let size = match staged {
Staged::Skipped(skip) => {
report.skipped.record(skip)?;
return Ok(());
}
Staged::Failed(error) => return Err(error),
Staged::Streamed(job) => return stream_file(zip, job, report, progress, buffer),
Staged::Prepared(pending, size) => {
append_prepared(zip, self.executor.collect(index, pending)?)?;
size
}
};
progress.on_bytes_written(size);
report.files_added = report.files_added.saturating_add(1);
report.bytes_written = report.bytes_written.saturating_add(size);
Ok(())
}
}
fn append_prepared<W: Write + Seek>(
zip: &mut ZipWriter<W>,
prepared: zip::PreparedZipFile,
) -> Result<()> {
zip.add_prepared_file(prepared)
.map_err(|e| zip_error("failed to add file to zip archive", &e))
}
fn stream_file<W: Write + Seek>(
zip: &mut ZipWriter<W>,
job: PreparedJob,
report: &mut CreationReport,
progress: &mut dyn ProgressCallback,
buffer: &mut [u8],
) -> Result<()> {
let PreparedJob {
path,
name,
options,
mut reader,
} = job;
zip.start_file(&name, options)
.map_err(|e| zip_error("failed to start file in zip archive", &e))?;
let mut bytes_written = 0u64;
let mut clock = CancelClock::standard();
loop {
if clock.due(bytes_written) {
check_cancelled(&mut *progress)?;
}
let bytes_read = match reader.read(buffer) {
Ok(bytes_read) => bytes_read,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => return Err(source_error(&path, e)),
};
if bytes_read == 0 {
break;
}
let chunk = buffer.get(..bytes_read).ok_or_else(|| {
source_error(&path, std::io::Error::from(std::io::ErrorKind::InvalidData))
})?;
zip.write_all(chunk)?;
bytes_written = bytes_written.saturating_add(bytes_read as u64);
progress.on_bytes_written(bytes_read as u64);
}
report.files_added = report.files_added.saturating_add(1);
report.bytes_written = report.bytes_written.saturating_add(bytes_written);
Ok(())
}
fn options_with_mode(
options: &SimpleFileOptions,
config: &CreationConfig,
metadata: &std::fs::Metadata,
) -> SimpleFileOptions {
let options = options.last_modified_time(modified_time(metadata));
#[cfg(unix)]
if config.permissions.preserves() {
use std::os::unix::fs::PermissionsExt;
return options.unix_permissions(metadata.permissions().mode());
}
#[cfg(not(unix))]
let _ = config;
options
}
fn modified_time(metadata: &std::fs::Metadata) -> zip::DateTime {
let Some(at) = metadata.modified().ok().map(time::OffsetDateTime::from) else {
return zip::DateTime::default();
};
if at.year() > i32::from(LAST_DOS_YEAR) {
return zip::DateTime::from_date_and_time(LAST_DOS_YEAR, 12, 31, 23, 59, 58)
.unwrap_or_default();
}
zip::DateTime::try_from(time::PrimitiveDateTime::new(at.date(), at.time())).unwrap_or_default()
}
const LAST_DOS_YEAR: u16 = 2107;
fn normalize_zip_path(path: &Path) -> Result<String> {
let path_str = path.to_str().ok_or_else(|| {
ArchiveError::Io(std::io::Error::other(IoContext::new(
"archive path is not valid UTF-8",
crate::path_text(path),
)))
})?;
#[cfg(windows)]
let normalized = path_str.replace('\\', "/");
#[cfg(not(windows))]
let normalized = path_str.to_string();
Ok(normalized)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)] mod tests {
use super::*;
use crate::create_archive;
use crate::creation::CompressionLevel;
use std::assert_matches;
use std::fs;
use std::fs::File;
use tempfile::TempDir;
#[test]
fn test_create_zip_single_file() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("test.txt"), "Hello ZIP").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
let report =
create_archive(&output, &[source_dir.path().join("test.txt")], &config).unwrap();
assert_eq!(report.files_added, 1);
assert!(report.bytes_written > 0);
assert!(output.exists());
}
fn zip_report_for(content: &[u8]) -> CreationReport {
let temp = TempDir::new().unwrap();
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("data"), content).unwrap();
let config = CreationConfig::default();
create_archive(
temp.path().join("out.zip"),
&[source_dir.path().join("data")],
&config,
)
.unwrap()
}
fn needed_ratio(warning: &CreationWarning) -> f64 {
match warning {
CreationWarning::ZipRatioOverDefaultLimit { needed_ratio, .. } => *needed_ratio,
other => panic!("expected the ratio warning, got {other:?}"),
}
}
#[test]
fn test_create_zip_warns_when_default_extraction_would_refuse_an_entry() {
let report = zip_report_for(&[b'B'; 5000]);
assert_eq!(report.warnings.len(), 1, "{:?}", report.warnings);
let warning = &report.warnings[0];
assert!(warning.to_string().starts_with(
"ZIP archive has 1 entry over the default extraction ratio limit of 100x"
));
assert!(needed_ratio(warning) > 100.0);
}
#[test]
fn test_create_zip_needed_ratio_admits_the_archive() {
let temp = TempDir::new().unwrap();
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("data"), [b'B'; 5000]).unwrap();
let output = temp.path().join("out.zip");
let config = CreationConfig::default();
let report = create_archive(&output, &[source_dir.path().join("data")], &config).unwrap();
let needed = needed_ratio(&report.warnings[0]);
let dest = temp.path().join("dest");
let admitting = crate::SecurityConfig::default().with_max_compression_ratio(
crate::RatioLimit::parse(crate::ConfigSetting::MaxCompressionRatio, needed).unwrap(),
);
crate::api::extract_archive(&output, &dest, &admitting).unwrap();
assert!(dest.join("data").exists());
}
#[test]
fn test_ratio_scan_failure_degrades_to_a_warning() {
let mut report = CreationReport::default();
warn_on_extraction_ratio(std::io::Cursor::new(b"not a zip".to_vec()), &mut report);
assert_eq!(report.warnings.len(), 1, "{:?}", report.warnings);
assert!(
report.warnings[0]
.to_string()
.starts_with("could not check the ZIP entries")
);
}
#[test]
fn test_create_zip_no_ratio_warning_for_ordinary_content() {
let report = zip_report_for(b"Hello ZIP");
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
}
#[test]
fn test_create_zip_directory() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("file1.txt"), "content1").unwrap();
fs::write(source_dir.path().join("file2.txt"), "content2").unwrap();
fs::create_dir(source_dir.path().join("subdir")).unwrap();
fs::write(source_dir.path().join("subdir/file3.txt"), "content3").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 3);
assert_eq!(report.directories_added, 1);
assert!(output.exists());
}
#[test]
fn test_create_zip_compression() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("test.txt"), "a".repeat(1000)).unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_compression_level(CompressionLevel::try_from(9u8).unwrap());
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 1);
assert!(output.exists());
let data = fs::read(&output).unwrap();
assert_eq!(&data[0..4], b"PK\x03\x04"); }
#[test]
fn test_create_zip_compression_levels() {
let temp = TempDir::new().unwrap();
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("test.txt"), "a".repeat(10000)).unwrap();
for level in [1u8, 6, 9] {
let output = temp.path().join(format!("output_{level}.zip"));
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_compression_level(CompressionLevel::try_from(level).unwrap());
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 1);
assert!(output.exists());
}
}
#[test]
fn test_create_zip_explicit_directories() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::create_dir(source_dir.path().join("dir1")).unwrap();
fs::create_dir(source_dir.path().join("dir1/dir2")).unwrap();
fs::write(source_dir.path().join("dir1/dir2/file.txt"), "content").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert!(report.directories_added >= 2); assert!(output.exists());
let file = File::open(&output).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
let mut dir_entries = 0;
for i in 0..archive.len() {
let entry = archive.by_index(i).unwrap();
if entry.is_dir() {
dir_entries += 1;
assert!(
entry.name().unwrap().ends_with('/'),
"Directory entry should end with /"
);
}
}
assert!(dir_entries >= 2, "Expected at least 2 directory entries");
}
#[cfg(unix)]
#[test]
fn test_create_zip_preserves_permissions() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
let file_path = source_dir.path().join("test.txt");
fs::write(&file_path, "content").unwrap();
fs::set_permissions(&file_path, fs::Permissions::from_mode(0o755)).unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_preserve_permissions(true);
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 1);
let file = File::open(&output).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
for i in 0..archive.len() {
let entry = archive.by_index(i).unwrap();
if entry.name().unwrap().contains("test.txt")
&& let Some(mode) = entry.unix_mode()
{
assert_eq!(mode & 0o777, 0o755, "Permissions should be preserved");
}
}
}
#[cfg(unix)]
fn zip_directory_modes(preserve: bool) -> Vec<(String, u32)> {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source = TempDir::new().unwrap();
for (name, mode) in [("d700", 0o700), ("d750", 0o750)] {
let dir = source.path().join(name);
fs::create_dir(&dir).unwrap();
fs::write(dir.join("f"), "x").unwrap();
fs::set_permissions(&dir, fs::Permissions::from_mode(mode)).unwrap();
}
let config = CreationConfig::default().with_preserve_permissions(preserve);
create_archive(&output, &[source.path()], &config).unwrap();
let mut archive = zip::ZipArchive::new(File::open(&output).unwrap()).unwrap();
let mut modes = Vec::new();
for i in 0..archive.len() {
let entry = archive.by_index(i).unwrap();
let name = entry.name().unwrap().into_owned();
if entry.is_dir()
&& matches!(
name.trim_end_matches('/').rsplit('/').next(),
Some("d700" | "d750")
)
{
modes.push((name, entry.unix_mode().unwrap() & 0o777));
}
}
modes.sort();
modes
}
#[cfg(unix)]
#[test]
fn test_create_zip_directory_entries_carry_the_source_mode() {
let modes = zip_directory_modes(true);
let leaf_modes: Vec<u32> = modes.iter().map(|(_, mode)| *mode).collect();
assert_eq!(leaf_modes, [0o700, 0o750]);
}
#[cfg(unix)]
#[test]
fn test_create_zip_directory_entries_are_0755_without_preserve() {
let modes = zip_directory_modes(false);
assert_eq!(modes.len(), 2);
assert!(modes.iter().all(|(_, mode)| *mode == 0o755));
}
#[test]
fn test_create_zip_report_statistics() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("file1.txt"), "content1").unwrap();
fs::write(source_dir.path().join("file2.txt"), "content2").unwrap();
fs::create_dir(source_dir.path().join("subdir")).unwrap();
fs::write(source_dir.path().join("subdir/file3.txt"), "content3").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 3);
assert!(report.directories_added >= 1);
assert_eq!(report.files_skipped(), 0);
assert!(!report.has_warnings());
assert!(report.duration.as_nanos() > 0);
}
#[test]
fn test_create_zip_roundtrip() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("file1.txt"), "content1").unwrap();
fs::create_dir(source_dir.path().join("subdir")).unwrap();
fs::write(source_dir.path().join("subdir/file2.txt"), "content2").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert!(report.files_added >= 2);
let file = File::open(&output).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
let extract_dir = TempDir::new().unwrap();
for i in 0..archive.len() {
let mut entry = archive.by_index(i).unwrap();
let outpath = extract_dir.path().join(entry.name().unwrap().as_ref());
if entry.is_dir() {
fs::create_dir_all(&outpath).unwrap();
} else {
if let Some(parent) = outpath.parent() {
fs::create_dir_all(parent).unwrap();
}
let mut outfile = File::create(&outpath).unwrap();
std::io::copy(&mut entry, &mut outfile).unwrap();
}
}
let extracted1 = fs::read_to_string(extract_dir.path().join("file1.txt")).unwrap();
assert_eq!(extracted1, "content1");
let extracted2 = fs::read_to_string(extract_dir.path().join("subdir/file2.txt")).unwrap();
assert_eq!(extracted2, "content2");
}
#[test]
fn test_create_zip_forward_slashes() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::create_dir(source_dir.path().join("dir1")).unwrap();
fs::write(source_dir.path().join("dir1/file.txt"), "content").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
create_archive(&output, &[source_dir.path()], &config).unwrap();
let file = File::open(&output).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
for i in 0..archive.len() {
let entry = archive.by_index(i).unwrap();
let name = entry.name().unwrap();
assert!(
!name.contains('\\'),
"ZIP path should use forward slashes: {name}"
);
if name.contains("dir1") && name.contains("file") {
assert!(name.contains("dir1/file"), "Expected forward slash in path");
}
}
}
#[test]
fn test_create_zip_source_not_found() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let config = CreationConfig::default();
let result = create_archive(&output, &[Path::new("/nonexistent/path")], &config);
assert!(result.is_err());
assert_matches!(result.unwrap_err(), ArchiveError::SourceNotFound { .. });
}
#[test]
fn test_normalize_zip_path() {
let path = Path::new("dir/file.txt");
let normalized = normalize_zip_path(path).unwrap();
assert_eq!(normalized, "dir/file.txt");
let path = Path::new("file.txt");
let normalized = normalize_zip_path(path).unwrap();
assert_eq!(normalized, "file.txt");
let path = Path::new("a/b/c/file.txt");
let normalized = normalize_zip_path(path).unwrap();
assert_eq!(normalized, "a/b/c/file.txt");
}
#[cfg(windows)]
#[test]
fn test_normalize_zip_path_windows() {
let path = Path::new("dir\\file.txt");
let normalized = normalize_zip_path(path).unwrap();
assert_eq!(normalized, "dir/file.txt");
let path = Path::new("a\\b\\c\\file.txt");
let normalized = normalize_zip_path(path).unwrap();
assert_eq!(normalized, "a/b/c/file.txt");
}
#[test]
fn test_create_zip_max_file_size() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("small.txt"), "tiny").unwrap(); fs::write(source_dir.path().join("large.txt"), "a".repeat(1000)).unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_max_file_size(crate::non_zero!(100));
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 1);
assert_eq!(report.skipped.count(SkipKind::OverMaxFileSize), 1);
assert_eq!(report.files_skipped(), 1);
}
#[cfg(unix)]
#[test]
fn test_create_zip_skips_symlinks() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("target.txt"), "content").unwrap();
std::os::unix::fs::symlink(
source_dir.path().join("target.txt"),
source_dir.path().join("link.txt"),
)
.unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 1);
assert_eq!(report.files_skipped(), 1);
assert_eq!(report.skipped.count(SkipKind::SymlinkUnsupported), 1);
assert_eq!(report.skipped.sample()[0].path, Path::new("link.txt"));
assert!(!report.has_warnings());
}
#[cfg(unix)]
#[test]
fn test_create_zip_follow_symlinks_embeds_target_content() {
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("target.txt"), "content").unwrap();
std::os::unix::fs::symlink(
source_dir.path().join("target.txt"),
source_dir.path().join("link.txt"),
)
.unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true)
.with_follow_symlinks(true);
let report = create_archive(&output, &[source_dir.path()], &config).unwrap();
assert_eq!(report.files_added, 2);
assert_eq!(report.files_skipped(), 0);
assert!(!report.has_warnings());
let file = File::open(&output).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
let mut entry = archive.by_name("link.txt").unwrap();
let mut contents = String::new();
entry.read_to_string(&mut contents).unwrap();
assert_eq!(contents, "content");
}
#[test]
fn test_create_zip_with_progress_callback() {
#[derive(Debug, Default, Clone)]
struct TestProgress {
entries_started: Vec<String>,
entries_completed: Vec<String>,
bytes_written: u64,
completed: bool,
}
impl ProgressCallback for TestProgress {
fn on_entry_start(&mut self, path: &Path, _position: crate::EntryPosition) {
self.entries_started
.push(path.to_string_lossy().to_string());
}
fn on_bytes_written(&mut self, bytes: u64) {
self.bytes_written += bytes;
}
fn on_entry_complete(&mut self, path: &Path) {
self.entries_completed
.push(path.to_string_lossy().to_string());
}
fn on_complete(&mut self) {
self.completed = true;
}
}
let temp = TempDir::new().unwrap();
let output = temp.path().join("output.zip");
let source_dir = TempDir::new().unwrap();
fs::write(source_dir.path().join("file1.txt"), "content1").unwrap();
fs::write(source_dir.path().join("file2.txt"), "content2").unwrap();
fs::create_dir(source_dir.path().join("subdir")).unwrap();
fs::write(source_dir.path().join("subdir/file3.txt"), "content3").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true);
let mut progress = TestProgress::default();
let report = crate::CreateRequest::new(&config)
.with_progress(&mut progress)
.create(&crate::OutputFile::replace(&output), &[source_dir.path()])
.unwrap();
assert_eq!(report.files_added, 3);
assert!(report.directories_added >= 1);
assert!(
progress.entries_started.len() >= 3,
"Expected at least 3 entry starts, got {}",
progress.entries_started.len()
);
assert!(
progress.entries_completed.len() >= 3,
"Expected at least 3 entry completions, got {}",
progress.entries_completed.len()
);
assert!(
progress.bytes_written > 0,
"Expected bytes written > 0, got {}",
progress.bytes_written
);
assert!(progress.completed, "Expected on_complete to be called");
let has_file1 = progress
.entries_started
.iter()
.any(|p| p.contains("file1.txt"));
let has_file2 = progress
.entries_started
.iter()
.any(|p| p.contains("file2.txt"));
let has_file3 = progress
.entries_started
.iter()
.any(|p| p.contains("file3.txt"));
assert!(has_file1, "Expected file1.txt in progress callbacks");
assert!(has_file2, "Expected file2.txt in progress callbacks");
assert!(has_file3, "Expected file3.txt in progress callbacks");
}
}