use std::io::Seek;
use std::io::Write;
use std::path::Path;
use crate::CreationConfig;
use crate::CreationReport;
use crate::ProgressCallback;
use crate::Result;
use crate::creation::staged::ExcludedOutput;
use crate::creation::tar::write_tar;
use crate::creation::zip::write_zip;
use crate::formats::compression::CompressionCodec;
use crate::formats::detect::CreatableFormat;
use crate::formats::detect::CreationFamily;
pub(crate) trait WriteSeek: Write + Seek + Send {}
impl<T: Write + Seek + Send> WriteSeek for T {}
#[derive(Debug)]
pub(crate) struct CountingWriter<W> {
inner: W,
bytes: u64,
}
impl<W> CountingWriter<W> {
pub(crate) const fn new(inner: W) -> Self {
Self { inner, bytes: 0 }
}
pub(crate) const fn bytes(&self) -> u64 {
self.bytes
}
}
impl<W: Write> Write for CountingWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let written = self.inner.write(buf)?;
self.bytes = self.bytes.saturating_add(written as u64);
Ok(written)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
enum Destination<'a> {
Tar {
stream: Box<dyn Write + Send + 'a>,
codec: Option<CompressionCodec>,
},
Zip {
stream: Box<dyn WriteSeek + 'a>,
},
}
pub struct ArchiveWriter<'a> {
destination: Destination<'a>,
}
impl std::fmt::Debug for ArchiveWriter<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArchiveWriter")
.field("format", &self.format())
.finish_non_exhaustive()
}
}
impl<'a> ArchiveWriter<'a> {
#[must_use]
pub fn tar<W: Write + Send + 'a>(writer: W, codec: Option<CompressionCodec>) -> Self {
Self {
destination: Destination::Tar {
stream: Box::new(writer),
codec,
},
}
}
#[must_use]
pub fn zip<W: Write + Seek + Send + 'a>(writer: W) -> Self {
Self {
destination: Destination::Zip {
stream: Box::new(writer),
},
}
}
pub fn of_type<W: Write + Seek + Send + 'a>(writer: W, format: CreatableFormat) -> Self {
match format.family() {
CreationFamily::Tar(codec) => Self::tar(writer, codec),
CreationFamily::Zip => Self::zip(writer),
}
}
#[must_use]
pub const fn format(&self) -> CreatableFormat {
match self.destination {
Destination::Tar { codec, .. } => CreatableFormat::tar_with(codec),
Destination::Zip { .. } => CreatableFormat::Zip,
}
}
pub(crate) fn write<P: AsRef<Path>>(
self,
sources: &[P],
config: &CreationConfig,
progress: &mut dyn ProgressCallback,
) -> Result<CreationReport> {
let excluded = ExcludedOutput::none();
match self.destination {
Destination::Tar { stream, codec } => {
write_tar(stream, codec, sources, config, &excluded, progress)
}
Destination::Zip { stream } => {
write_zip(stream, sources, config, &excluded, progress).map(|(report, _)| report)
}
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crate::ArchiveError;
use crate::CreateRequest;
use crate::SecurityConfig;
use crate::api::create_archive;
use crate::api::extract_archive;
use std::assert_matches;
use std::fs;
use std::io::Cursor;
use tempfile::TempDir;
fn source_tree() -> TempDir {
let src = TempDir::new().unwrap();
fs::write(src.path().join("a.txt"), "alpha").unwrap();
fs::create_dir(src.path().join("sub")).unwrap();
fs::write(src.path().join("sub/b.txt"), "bravo".repeat(500)).unwrap();
src
}
fn config() -> CreationConfig {
CreationConfig::default()
.with_exclude_patterns(vec![])
.with_include_hidden(true)
}
const TAR_FORMATS: [(Option<CompressionCodec>, &str); 5] = [
(None, "tar"),
(Some(CompressionCodec::Gzip), "tar.gz"),
(Some(CompressionCodec::Bzip2), "tar.bz2"),
(Some(CompressionCodec::Xz), "tar.xz"),
(Some(CompressionCodec::Zstd), "tar.zst"),
];
fn assert_extracts_equal(archive: &Path, src: &Path) {
let dest = TempDir::new().unwrap();
extract_archive(archive, dest.path(), &SecurityConfig::default()).unwrap();
let root = dest.path();
assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "alpha");
assert_eq!(
fs::read(root.join("sub/b.txt")).unwrap(),
fs::read(src.join("sub/b.txt")).unwrap()
);
}
#[test]
fn test_tar_round_trip_every_codec() {
let src = source_tree();
for (codec, ext) in TAR_FORMATS {
let mut buf = Vec::new();
let report = CreateRequest::new(&config())
.write(ArchiveWriter::tar(&mut buf, codec), &[src.path()])
.unwrap();
assert_eq!(report.bytes_compressed, buf.len() as u64, "{ext}");
assert_eq!(report.files_added, 2, "{ext}");
let out = TempDir::new().unwrap();
let archive = out.path().join(format!("out.{ext}"));
fs::write(&archive, &buf).unwrap();
assert_extracts_equal(&archive, src.path());
}
}
#[test]
fn test_zip_round_trip() {
let src = source_tree();
let mut out = Cursor::new(Vec::new());
let report = CreateRequest::new(&config())
.write(ArchiveWriter::zip(&mut out), &[src.path()])
.unwrap();
let buf = out.into_inner();
assert_eq!(report.bytes_compressed, buf.len() as u64);
let dir = TempDir::new().unwrap();
let archive = dir.path().join("out.zip");
fs::write(&archive, &buf).unwrap();
assert_extracts_equal(&archive, src.path());
}
#[test]
fn test_writer_output_equals_path_output() {
let src = source_tree();
let dir = TempDir::new().unwrap();
for (codec, ext) in TAR_FORMATS {
let path = dir.path().join(format!("p.{ext}"));
let path_report = create_archive(&path, &[src.path()], &config()).unwrap();
let mut buf = Vec::new();
let report = CreateRequest::new(&config())
.write(ArchiveWriter::tar(&mut buf, codec), &[src.path()])
.unwrap();
assert_eq!(fs::read(&path).unwrap(), buf, "{ext}");
assert_eq!(
path_report.bytes_compressed,
fs::metadata(&path).unwrap().len()
);
assert_eq!(
report.bytes_compressed, path_report.bytes_compressed,
"{ext}"
);
}
}
#[test]
fn test_path_zip_bytes_compressed_equals_file_length() {
let src = source_tree();
let dir = TempDir::new().unwrap();
let path = dir.path().join("p.zip");
let report = create_archive(&path, &[src.path()], &config()).unwrap();
assert_eq!(report.bytes_compressed, fs::metadata(&path).unwrap().len());
}
#[test]
fn test_create_to_bytes_round_trips_every_creatable_format() {
let src = source_tree();
for &format in CreatableFormat::ALL {
let (bytes, report) = CreateRequest::new(&config())
.to_bytes(format, &[src.path()])
.unwrap();
assert_eq!(report.bytes_compressed, bytes.len() as u64, "{format}");
let reader = crate::ArchiveReader::from_bytes(bytes, None).unwrap();
assert_eq!(
crate::formats::detect::ArchiveType::from(format),
reader.format()
);
}
}
#[test]
fn test_create_to_bytes_zip_warns_about_extraction_ratio() {
let src = TempDir::new().unwrap();
fs::write(src.path().join("zeros"), vec![0u8; 100_000]).unwrap();
let (_, report) = CreateRequest::new(&config())
.to_bytes(CreatableFormat::Zip, &[src.path()])
.unwrap();
assert!(
report
.warnings
.iter()
.any(|warning| warning.to_string().contains("extraction ratio limit")),
"{:?}",
report.warnings
);
let (_, report) = CreateRequest::new(&config())
.to_bytes(CreatableFormat::TarGz, &[src.path()])
.unwrap();
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
}
#[test]
fn test_of_type_round_trips_every_creatable_format() {
let src = source_tree();
for &format in CreatableFormat::ALL {
let mut out = Cursor::new(Vec::new());
let writer = ArchiveWriter::of_type(&mut out, format);
assert_eq!(writer.format(), format);
CreateRequest::new(&config())
.write(writer, &[src.path()])
.unwrap();
assert!(!out.get_ref().is_empty());
}
}
#[test]
fn test_zip_writer_not_at_start_is_rejected() {
let src = source_tree();
let mut out = Cursor::new(vec![0u8; 4]);
out.set_position(4);
let result = CreateRequest::new(&config()).write(ArchiveWriter::zip(out), &[src.path()]);
assert_matches!(result, Err(ArchiveError::InvalidConfiguration { .. }));
}
#[test]
fn test_missing_source_is_an_error() {
let result = CreateRequest::new(&config()).write(
ArchiveWriter::tar(Vec::new(), None),
&[Path::new("/nonexistent/exarch-source")],
);
assert!(result.is_err());
}
#[test]
fn test_progress_events_match_path_creation() {
#[derive(Default)]
struct Recorder {
starts: Vec<std::path::PathBuf>,
completes: usize,
done: usize,
}
impl ProgressCallback for Recorder {
fn on_entry_start(&mut self, path: &Path, _position: crate::EntryPosition) {
self.starts.push(path.to_path_buf());
}
fn on_bytes_written(&mut self, _bytes: u64) {}
fn on_entry_complete(&mut self, _path: &Path) {
self.completes += 1;
}
fn on_complete(&mut self) {
self.done += 1;
}
}
let src = source_tree();
let dir = TempDir::new().unwrap();
let mut by_path = Recorder::default();
crate::CreateRequest::new(&config())
.with_progress(&mut by_path)
.create(
&crate::OutputFile::replace(dir.path().join("p.tar")),
&[src.path()],
)
.unwrap();
let mut by_writer = Recorder::default();
CreateRequest::new(&config())
.with_progress(&mut by_writer)
.write(ArchiveWriter::tar(Vec::new(), None), &[src.path()])
.unwrap();
assert_eq!(by_path.starts, by_writer.starts);
assert_eq!(by_path.completes, by_writer.completes);
assert_eq!((by_path.done, by_writer.done), (1, 1));
}
#[test]
fn test_created_archive_lists_through_reader() {
let src = source_tree();
let mut buf = Vec::new();
CreateRequest::new(&config())
.write(
ArchiveWriter::tar(&mut buf, Some(CompressionCodec::Zstd)),
&[src.path()],
)
.unwrap();
let manifest = crate::ListRequest::new(&SecurityConfig::default())
.with_options(crate::ListOptions::default())
.list_reader(crate::ArchiveReader::tar(
Cursor::new(buf),
Some(CompressionCodec::Zstd),
))
.unwrap();
assert!(manifest.total_entries() >= 2);
}
}