Skip to main content

exarch_core/
request.rs

1//! Request values: one type per operation, optional inputs as setters.
2//!
3//! Every operation (extract, list, verify, extract into a sink, create) is
4//! described by a request that holds the configuration it runs under, the
5//! options of that operation and an optional [`ProgressCallback`]. A terminal
6//! method runs it. Adding an optional input to an operation is a setter on its
7//! request, not another function per combination.
8//!
9//! The plain functions ([`extract_archive`](crate::extract_archive),
10//! [`list_archive`](crate::list_archive), ...) remain for the common case; they
11//! are requests with the defaults.
12
13use std::io::Cursor;
14use std::path::Path;
15use std::path::PathBuf;
16
17use crate::ArchiveReader;
18use crate::ArchiveWriter;
19use crate::DecodeReuse;
20use crate::EntrySink;
21use crate::ExtractionOptions;
22use crate::ExtractionReport;
23use crate::ListOptions;
24use crate::NoopProgress;
25use crate::ProgressCallback;
26use crate::Result;
27use crate::SecurityConfig;
28use crate::SinkOptions;
29use crate::VerificationOptions;
30use crate::api::extract_staged;
31use crate::api::extract_to_sink_reusing;
32use crate::api::extract_validated;
33use crate::api::resolve_output_format;
34use crate::closed_enum::closed_enum;
35use crate::creation::CreationConfig;
36use crate::creation::CreationReport;
37use crate::creation::progress::check_cancelled;
38use crate::creation::staged::StagedOutput;
39use crate::creation::tar::write_tar;
40use crate::creation::zip::warn_on_extraction_ratio;
41use crate::creation::zip::write_zip;
42use crate::formats::detect::CreatableFormat;
43use crate::formats::detect::CreationFamily;
44use crate::inspection::ArchiveManifest;
45use crate::inspection::VerificationReport;
46use crate::inspection::list::ListPass;
47use crate::listed::ListedArchive;
48
49/// The optional progress callback of a request; a missing one is a no-op.
50struct OptionalProgress<'a>(Option<&'a mut dyn ProgressCallback>);
51
52impl std::fmt::Debug for OptionalProgress<'_> {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.write_str(if self.0.is_some() { "Some(..)" } else { "None" })
55    }
56}
57
58impl OptionalProgress<'_> {
59    fn run<R>(self, operation: impl FnOnce(&mut dyn ProgressCallback) -> R) -> R {
60        match self.0 {
61            Some(progress) => operation(progress),
62            None => operation(&mut NoopProgress),
63        }
64    }
65}
66
67/// Extracts an archive into a directory.
68///
69/// Holds the [`SecurityConfig`] the extraction runs under, the
70/// [`ExtractionOptions`] and an optional [`ProgressCallback`]. Every entry
71/// passes the validation pipeline before it is written.
72///
73/// # Errors
74///
75/// [`extract`](Self::extract) returns an error if:
76/// - the archive cannot be opened
77/// - the archive format is unsupported
78/// - security validation fails
79/// - an I/O operation fails
80/// - the atomic staging directory cannot be created or renamed into place
81///
82/// # Examples
83///
84/// ```no_run
85/// use exarch_core::ExtractRequest;
86/// use exarch_core::ExtractionOptions;
87/// use exarch_core::NoopProgress;
88/// use exarch_core::SecurityConfig;
89///
90/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
91/// let config = SecurityConfig::default();
92/// let mut progress = NoopProgress;
93/// let report = ExtractRequest::new(&config)
94///     .with_options(ExtractionOptions::default().with_atomic(true))
95///     .with_progress(&mut progress)
96///     .extract("archive.tar.gz", "/tmp/output")?;
97/// println!("Extracted {} files", report.files_extracted);
98/// # Ok(())
99/// # }
100/// ```
101#[derive(Debug)]
102pub struct ExtractRequest<'a> {
103    config: &'a SecurityConfig,
104    options: ExtractionOptions,
105    progress: OptionalProgress<'a>,
106}
107
108impl<'a> ExtractRequest<'a> {
109    /// An extraction under `config` with default options and no progress
110    /// callback.
111    #[must_use]
112    pub fn new(config: &'a SecurityConfig) -> Self {
113        Self {
114            config,
115            options: ExtractionOptions::default(),
116            progress: OptionalProgress(None),
117        }
118    }
119
120    /// Sets the extraction options.
121    #[must_use]
122    pub fn with_options(mut self, options: ExtractionOptions) -> Self {
123        self.options = options;
124        self
125    }
126
127    /// Reports progress to `progress`.
128    #[must_use]
129    pub fn with_progress(mut self, progress: &'a mut dyn ProgressCallback) -> Self {
130        self.progress = OptionalProgress(Some(progress));
131        self
132    }
133
134    /// Extracts `archive` into `output_dir`; the format is detected.
135    ///
136    /// # Errors
137    ///
138    /// See [`ExtractRequest`].
139    pub fn extract(
140        self,
141        archive: impl AsRef<Path>,
142        output_dir: impl AsRef<Path>,
143    ) -> Result<ExtractionReport> {
144        let Self {
145            config,
146            options,
147            progress,
148        } = self;
149        progress.run(|progress| {
150            extract_staged(output_dir.as_ref(), &options, |dir| {
151                extract_validated(archive.as_ref(), dir, config, &options, progress)
152            })
153        })
154    }
155}
156
157/// Lists the contents of an archive without extracting it.
158///
159/// Holds the [`SecurityConfig`] whose quotas and path rules the listing
160/// enforces, the [`ListOptions`] and an optional [`ProgressCallback`], which
161/// sees one `on_entry_start` / `on_entry_complete` pair per listed entry
162/// (`total` is unknown for TAR) and `on_complete` once after the manifest was
163/// built. Nothing is written to disk.
164///
165/// # Errors
166///
167/// [`list`](Self::list) and [`list_reader`](Self::list_reader) return an error
168/// if:
169/// - the archive cannot be opened or its format is unsupported
170/// - the archive is corrupted
171/// - a quota is exceeded (file count, total size, single file size)
172/// - declared compressed sizes exceed the archive length
173///
174/// A reader source is neither opened nor detected, so a malformed archive fails
175/// as it would from a file. `on_complete` is not called on failure.
176///
177/// # Examples
178///
179/// ```no_run
180/// use exarch_core::ListRequest;
181/// use exarch_core::SecurityConfig;
182///
183/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
184/// let config = SecurityConfig::default();
185/// let manifest = ListRequest::new(&config).list("archive.tar.gz")?;
186/// println!("{} entries", manifest.total_entries());
187/// # Ok(())
188/// # }
189/// ```
190#[derive(Debug)]
191pub struct ListRequest<'a> {
192    config: &'a SecurityConfig,
193    options: ListOptions,
194    progress: OptionalProgress<'a>,
195}
196
197impl<'a> ListRequest<'a> {
198    /// A listing under `config` with default options and no progress callback.
199    #[must_use]
200    pub fn new(config: &'a SecurityConfig) -> Self {
201        Self {
202            config,
203            options: ListOptions::default(),
204            progress: OptionalProgress(None),
205        }
206    }
207
208    /// Sets the listing options.
209    #[must_use]
210    pub const fn with_options(mut self, options: ListOptions) -> Self {
211        self.options = options;
212        self
213    }
214
215    /// Reports progress to `progress`.
216    #[must_use]
217    pub fn with_progress(mut self, progress: &'a mut dyn ProgressCallback) -> Self {
218        self.progress = OptionalProgress(Some(progress));
219        self
220    }
221
222    /// Lists the archive file at `archive`.
223    ///
224    /// # Errors
225    ///
226    /// See [`ListRequest`].
227    pub fn list(self, archive: impl AsRef<Path>) -> Result<ArchiveManifest> {
228        let Self {
229            config,
230            options,
231            progress,
232        } = self;
233        progress.run(|progress| {
234            crate::inspection::list_archive_with_progress(archive, config, options, progress)
235        })
236    }
237
238    /// Lists an archive read from `reader`.
239    ///
240    /// # Errors
241    ///
242    /// See [`ListRequest`].
243    pub fn list_reader(self, reader: ArchiveReader<'_>) -> Result<ArchiveManifest> {
244        let Self {
245            config,
246            options,
247            progress,
248        } = self;
249        progress.run(|progress| {
250            let manifest = reader.list(
251                config,
252                &mut ListPass::strict_with(options.stored_targets).with_progress(progress),
253            )?;
254            progress.on_complete();
255            Ok(manifest)
256        })
257    }
258
259    /// Lists the archive at `archive` and keeps what extraction can reuse.
260    ///
261    /// `config` is the policy the **extraction** will run under. The list pass
262    /// itself runs under the same quotas, path rules, allowlist and decoder
263    /// limits with the flags that only matter once bytes are written (symlinks,
264    /// hardlinks, world-writable files, preserved permissions) turned off, so
265    /// that a listing never admits more than the extraction would. The
266    /// returned [`ListedArchive`] extracts under `config`, so what was listed
267    /// is what is extracted.
268    ///
269    /// `reuse` says where a ZIP archive keeps the output of its structural
270    /// check for the extraction; for a compressed TAR the decoder output is
271    /// spooled instead. See [`ListedArchive`].
272    ///
273    /// The progress callback, if any, sees the list pass's entry events;
274    /// `on_complete` is left to the extraction.
275    ///
276    /// # Errors
277    ///
278    /// See [`ListRequest`].
279    ///
280    /// # Examples
281    ///
282    /// ```
283    /// use exarch_core::DecodeReuse;
284    /// use exarch_core::ListRequest;
285    /// use exarch_core::SecurityConfig;
286    ///
287    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
288    /// # let dir = tempfile::tempdir()?;
289    /// # let archive = dir.path().join("a.tar");
290    /// # let mut tar = tar::Builder::new(Vec::new());
291    /// # let mut header = tar::Header::new_gnu();
292    /// # header.set_size(2);
293    /// # header.set_mode(0o644);
294    /// # tar.append_data(&mut header, "a.txt", &b"hi"[..])?;
295    /// # std::fs::write(&archive, tar.into_inner()?)?;
296    /// let config = SecurityConfig::default();
297    /// let listed = ListRequest::new(&config).for_extraction(&archive, DecodeReuse::default())?;
298    /// assert_eq!(listed.manifest().total_entries(), 1);
299    /// # Ok(())
300    /// # }
301    /// ```
302    pub fn for_extraction(
303        self,
304        archive: impl AsRef<Path>,
305        reuse: DecodeReuse,
306    ) -> Result<ListedArchive> {
307        let Self {
308            config,
309            options,
310            progress,
311        } = self;
312        progress.run(|progress| {
313            ListedArchive::list(archive.as_ref(), config, options, reuse, Some(progress))
314        })
315    }
316}
317
318/// Verifies an archive's security without extracting it.
319///
320/// Holds the [`SecurityConfig`] to validate against, the
321/// [`VerificationOptions`] (whether to also check payload integrity) and an
322/// optional [`ProgressCallback`], which sees one `on_entry_start` /
323/// `on_entry_complete` pair per scanned entry and `on_complete` once when a
324/// report is returned, including one whose status is `Fail`.
325///
326/// # Errors
327///
328/// [`verify`](Self::verify) and [`verify_reader`](Self::verify_reader) return
329/// an error if:
330/// - the archive cannot be opened or its format is unsupported
331/// - the archive structure cannot be read, or declared compressed sizes exceed
332///   the archive length
333/// - an entry name is a path traversal: the listing step rejects it with
334///   [`ArchiveError::PathTraversal`](crate::ArchiveError::PathTraversal) before
335///   a report exists
336/// - integrity is requested and a TAR entry's content fails to decode
337///
338/// Other security violations are reported in
339/// [`VerificationReport::issues`]. `on_complete` is not called on failure.
340///
341/// # Examples
342///
343/// ```no_run
344/// use exarch_core::SecurityConfig;
345/// use exarch_core::VerificationStatus;
346/// use exarch_core::VerifyRequest;
347///
348/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
349/// let config = SecurityConfig::default();
350/// let report = VerifyRequest::new(&config).verify("archive.zip")?;
351/// assert_eq!(report.status(), VerificationStatus::Pass);
352/// # Ok(())
353/// # }
354/// ```
355#[derive(Debug)]
356pub struct VerifyRequest<'a> {
357    config: &'a SecurityConfig,
358    options: VerificationOptions,
359    progress: OptionalProgress<'a>,
360}
361
362impl<'a> VerifyRequest<'a> {
363    /// A verification under `config` with default options and no progress
364    /// callback.
365    #[must_use]
366    pub fn new(config: &'a SecurityConfig) -> Self {
367        Self {
368            config,
369            options: VerificationOptions::default(),
370            progress: OptionalProgress(None),
371        }
372    }
373
374    /// Sets the verification options.
375    #[must_use]
376    pub const fn with_options(mut self, options: VerificationOptions) -> Self {
377        self.options = options;
378        self
379    }
380
381    /// Reports progress to `progress`.
382    #[must_use]
383    pub fn with_progress(mut self, progress: &'a mut dyn ProgressCallback) -> Self {
384        self.progress = OptionalProgress(Some(progress));
385        self
386    }
387
388    /// Verifies the archive file at `archive`.
389    ///
390    /// # Errors
391    ///
392    /// See [`VerifyRequest`].
393    pub fn verify(self, archive: impl AsRef<Path>) -> Result<VerificationReport> {
394        let Self {
395            config,
396            options,
397            progress,
398        } = self;
399        progress.run(|progress| {
400            crate::inspection::verify_archive_with_progress(archive, config, options, progress)
401        })
402    }
403
404    /// Verifies an archive read from `reader`; nothing is written and no
405    /// filesystem path is needed.
406    ///
407    /// # Errors
408    ///
409    /// See [`VerifyRequest`].
410    pub fn verify_reader(self, reader: ArchiveReader<'_>) -> Result<VerificationReport> {
411        let Self {
412            config,
413            options,
414            progress,
415        } = self;
416        progress.run(|progress| {
417            let report = reader.verify(config, options, progress)?;
418            progress.on_complete();
419            Ok(report)
420        })
421    }
422}
423
424/// Extracts an archive read from a reader into an [`EntrySink`].
425///
426/// Every entry passes the validation pipeline of [`ExtractRequest`] and is then
427/// delivered to the sink instead of being written under a directory. See the
428/// [`sink`](crate::sink) module for what the sink may rely on and what it must
429/// do. The optional [`ProgressCallback`] sees the events of a directory
430/// extraction.
431///
432/// A 7z source is read in two phases: everything the file table can refuse
433/// (admission, ratios, quotas, link policy, paths, name lengths) is refused
434/// before the sink sees an entry, then the entries are decoded and delivered in
435/// archive order.
436///
437/// # Errors
438///
439/// [`extract`](Self::extract) returns the errors of [`ExtractRequest`], plus
440/// any error the sink returns: [`ArchiveError::Io`](crate::ArchiveError::Io) if
441/// no entry was delivered yet,
442/// [`ArchiveError::PartialExtraction`](crate::ArchiveError::PartialExtraction)
443/// wrapping it afterwards. A sink that reports [`SinkFull`](crate::SinkFull)
444/// ends the extraction with a
445/// [`QuotaResource::SinkCapacity`](crate::QuotaResource::SinkCapacity) quota
446/// error.
447///
448/// # Examples
449///
450/// ```
451/// use std::io;
452///
453/// use exarch_core::ArchiveReader;
454/// use exarch_core::MemorySink;
455/// use exarch_core::SecurityConfig;
456/// use exarch_core::SinkExtractRequest;
457///
458/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
459/// let mut builder = tar::Builder::new(Vec::new());
460/// let mut header = tar::Header::new_gnu();
461/// header.set_size(2);
462/// header.set_mode(0o644);
463/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
464/// let bytes = builder.into_inner()?;
465///
466/// let mut sink = MemorySink::default();
467/// let config = SecurityConfig::default();
468/// let report = SinkExtractRequest::new(&config)
469///     .extract(ArchiveReader::tar(io::Cursor::new(bytes), None), &mut sink)?;
470/// assert_eq!(report.files_extracted, 1);
471/// # Ok(())
472/// # }
473/// ```
474#[derive(Debug)]
475pub struct SinkExtractRequest<'a> {
476    config: &'a SecurityConfig,
477    options: SinkOptions,
478    progress: OptionalProgress<'a>,
479}
480
481impl<'a> SinkExtractRequest<'a> {
482    /// An extraction into a sink under `config` with default options and no
483    /// progress callback.
484    #[must_use]
485    pub fn new(config: &'a SecurityConfig) -> Self {
486        Self {
487            config,
488            options: SinkOptions::default(),
489            progress: OptionalProgress(None),
490        }
491    }
492
493    /// Sets the sink extraction options.
494    #[must_use]
495    pub const fn with_options(mut self, options: SinkOptions) -> Self {
496        self.options = options;
497        self
498    }
499
500    /// Reports progress to `progress`.
501    #[must_use]
502    pub fn with_progress(mut self, progress: &'a mut dyn ProgressCallback) -> Self {
503        self.progress = OptionalProgress(Some(progress));
504        self
505    }
506
507    /// Extracts `reader` into `sink`.
508    ///
509    /// # Errors
510    ///
511    /// See [`SinkExtractRequest`].
512    pub fn extract<S: EntrySink>(
513        self,
514        reader: ArchiveReader<'_>,
515        sink: &mut S,
516    ) -> Result<ExtractionReport> {
517        let Self {
518            config,
519            options,
520            progress,
521        } = self;
522        progress
523            .run(|progress| extract_to_sink_reusing(reader, sink, config, options, progress, None))
524    }
525}
526
527/// Whether creating an output file may replace one that already exists.
528///
529/// There is no default: the caller states which it means.
530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
531#[non_exhaustive]
532pub enum OutputPolicy {
533    /// Refuse with
534    /// [`ArchiveError::OutputExists`](crate::ArchiveError::OutputExists)
535    /// when anything is at the path.
536    CreateNew,
537    /// Replace a regular file, or a symlink at the path (the link itself, not
538    /// its destination), atomically when the archive is complete.
539    Replace,
540}
541
542closed_enum! {
543    /// Whether a created archive is flushed to stable storage before it is
544    /// reported as written.
545    ///
546    /// `Synced` (the default) flushes the archive file and then its parent
547    /// directory entry, so a published archive survives a crash or power
548    /// loss.
549    ///
550    /// `Unsynced` skips both flushes and is faster, with these hazards:
551    ///
552    /// - After a crash or power loss a [`Replace`](OutputPolicy::Replace)
553    ///   target can be empty or truncated, and a
554    ///   [`CreateNew`](OutputPolicy::CreateNew) file can be empty.
555    /// - Write-back errors (network filesystems, quotas, delayed-allocation
556    ///   `ENOSPC`) are not reported, so an `Ok` result does not mean the bytes
557    ///   reached the disk.
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// use exarch_core::Durability;
563    /// use exarch_core::OutputFile;
564    ///
565    /// assert_eq!(Durability::default(), Durability::Synced);
566    /// let out = OutputFile::replace("scratch.tar").with_durability(Durability::Unsynced);
567    /// assert_eq!(out.durability(), Durability::Unsynced);
568    /// ```
569    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
570    #[non_exhaustive]
571    pub enum Durability {
572        /// Flush the file and its directory entry before reporting success
573        #[default]
574        Synced => "synced",
575
576        /// Skip the flushes; see the type documentation for the hazards
577        Unsynced => "unsynced",
578    }
579}
580
581/// How the archive format of an [`OutputFile`] is chosen.
582#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
583#[non_exhaustive]
584pub enum OutputFormat {
585    /// From the file extension. The ZIP-based extensions that need structure
586    /// exarch does not produce (`.apk`, `.whl`, `.epub`, ...) are refused.
587    #[default]
588    FromExtension,
589    /// The given format, whatever the extension is. This is how a ZIP-based
590    /// extension is written as a plain ZIP.
591    Explicit(CreatableFormat),
592}
593
594/// The archive file a creation writes: its path, whether it may replace an
595/// existing file and how its format is chosen.
596///
597/// The archive is staged in a temporary file in the target's directory (which
598/// must be writable) and renamed into place only when it is complete, so a
599/// failed creation leaves the path as it was. The output must be absent, a
600/// regular file, or a symlink to one (or dangling); a directory, a FIFO or a
601/// device is refused with
602/// [`InvalidConfiguration`](crate::ArchiveError::InvalidConfiguration).
603///
604/// Replacing keeps the permission bits of the file that is replaced (a symlink
605/// is resolved first), never wider than before and without setuid, setgid or
606/// sticky bits; a new file gets `0o666` filtered by the umask. Owner, group,
607/// ACLs and extended attributes of a replaced file are not preserved: the new
608/// file belongs to the creating user and to the group the filesystem gives a
609/// new file in that directory (the directory's group on macOS and BSD), so a
610/// file that was shared through its group can become readable by another group
611/// under the same mode bits.
612///
613/// The staged file and the target are never archived, even when a source
614/// directory contains them. They are recognized by file name and canonical
615/// parent directory, so an alias of the output directory that canonicalization
616/// does not resolve (a bind or `nullfs` mount of it inside a source tree) is
617/// not recognized and the output may be archived into itself. Do not put such
618/// a mount under a source.
619///
620/// A [`ProgressCallback`] that reports
621/// [`is_cancelled`](ProgressCallback::is_cancelled) stops the creation: nothing
622/// is published and a previous output stays as it was. After the archive is
623/// published the parent directory is synced on a best-effort basis (Unix).
624///
625/// # Examples
626///
627/// ```
628/// use exarch_core::OutputFile;
629/// use exarch_core::OutputFormat;
630/// use exarch_core::OutputPolicy;
631/// use exarch_core::formats::detect::CreatableFormat;
632///
633/// let out = OutputFile::replace("backup.tar.gz");
634/// assert_eq!(out.policy(), OutputPolicy::Replace);
635/// assert_eq!(out.format(), OutputFormat::FromExtension);
636///
637/// let out = OutputFile::create_new("bundle.apk").with_format(CreatableFormat::Zip);
638/// assert_eq!(out.format(), OutputFormat::Explicit(CreatableFormat::Zip));
639/// ```
640#[derive(Debug, Clone, PartialEq, Eq)]
641pub struct OutputFile {
642    path: PathBuf,
643    policy: OutputPolicy,
644    format: OutputFormat,
645    durability: Durability,
646}
647
648impl OutputFile {
649    /// An output at `path` that must not exist yet.
650    #[must_use]
651    pub fn create_new(path: impl Into<PathBuf>) -> Self {
652        Self::at(path.into(), OutputPolicy::CreateNew)
653    }
654
655    /// An output at `path` that replaces an existing file.
656    #[must_use]
657    pub fn replace(path: impl Into<PathBuf>) -> Self {
658        Self::at(path.into(), OutputPolicy::Replace)
659    }
660
661    const fn at(path: PathBuf, policy: OutputPolicy) -> Self {
662        Self {
663            path,
664            policy,
665            format: OutputFormat::FromExtension,
666            durability: Durability::Synced,
667        }
668    }
669
670    /// Writes `format` instead of the one the extension names.
671    #[must_use]
672    pub const fn with_format(mut self, format: CreatableFormat) -> Self {
673        self.format = OutputFormat::Explicit(format);
674        self
675    }
676
677    /// Sets whether the archive is flushed to stable storage before success is
678    /// reported.
679    #[must_use]
680    pub const fn with_durability(mut self, durability: Durability) -> Self {
681        self.durability = durability;
682        self
683    }
684
685    /// The output path.
686    #[must_use]
687    pub fn path(&self) -> &Path {
688        &self.path
689    }
690
691    /// Whether an existing file may be replaced.
692    #[must_use]
693    pub const fn policy(&self) -> OutputPolicy {
694        self.policy
695    }
696
697    /// How the format is chosen.
698    #[must_use]
699    pub const fn format(&self) -> OutputFormat {
700        self.format
701    }
702
703    /// Whether the archive is flushed to stable storage.
704    #[must_use]
705    pub const fn durability(&self) -> Durability {
706        self.durability
707    }
708}
709
710/// Creates an archive from files and directories.
711///
712/// Holds the [`CreationConfig`] and an optional [`ProgressCallback`]; the
713/// destination is chosen by the terminal method: a file
714/// ([`create`](Self::create)), a writer ([`write`](Self::write)) or memory
715/// ([`to_bytes`](Self::to_bytes)).
716///
717/// # Errors
718///
719/// All terminals return an error if:
720/// - a source does not exist or cannot be read
721/// - the configuration is invalid
722/// - writing the archive fails
723///
724/// [`create`](Self::create) also returns an error if the output is refused (see
725/// [`OutputFile`]) or its format cannot be determined. Sources are validated
726/// before the output is published, so a failed creation leaves no archive.
727///
728/// # Examples
729///
730/// ```
731/// use exarch_core::CreateRequest;
732/// use exarch_core::CreationConfig;
733/// use exarch_core::OutputFile;
734///
735/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
736/// let dir = tempfile::tempdir()?;
737/// std::fs::write(dir.path().join("a.txt"), b"hello")?;
738///
739/// let config = CreationConfig::default();
740/// let output = dir.path().join("out.tar.gz");
741/// let report = CreateRequest::new(&config).create(
742///     &OutputFile::create_new(&output),
743///     &[dir.path().join("a.txt")],
744/// )?;
745/// assert_eq!(report.files_added, 1);
746/// assert!(output.exists());
747///
748/// let missing = dir.path().join("missing.tar.gz");
749/// assert!(
750///     CreateRequest::new(&config)
751///         .create(
752///             &OutputFile::create_new(&missing),
753///             &[dir.path().join("nope")]
754///         )
755///         .is_err()
756/// );
757/// assert!(!missing.exists());
758/// # Ok(())
759/// # }
760/// ```
761#[derive(Debug)]
762pub struct CreateRequest<'a> {
763    config: &'a CreationConfig,
764    progress: OptionalProgress<'a>,
765}
766
767impl<'a> CreateRequest<'a> {
768    /// A creation under `config` with no progress callback.
769    #[must_use]
770    pub const fn new(config: &'a CreationConfig) -> Self {
771        Self {
772            config,
773            progress: OptionalProgress(None),
774        }
775    }
776
777    /// Reports progress to `progress`.
778    #[must_use]
779    pub fn with_progress(mut self, progress: &'a mut dyn ProgressCallback) -> Self {
780        self.progress = OptionalProgress(Some(progress));
781        self
782    }
783
784    /// Creates the archive at `output` from `sources`.
785    ///
786    /// `CreationReport::bytes_compressed` is the size of the archive file.
787    ///
788    /// # Errors
789    ///
790    /// See [`CreateRequest`].
791    pub fn create<P: AsRef<Path>>(
792        self,
793        output: &OutputFile,
794        sources: &[P],
795    ) -> Result<CreationReport> {
796        let Self { config, progress } = self;
797        let format = resolve_output_format(output)?;
798        let mut staged = StagedOutput::begin(output.path(), output.policy())?;
799        let report = progress.run(|progress| -> Result<CreationReport> {
800            let report = write_staged(&mut staged, format, sources, config, progress)?;
801            check_cancelled(progress)?;
802            Ok(report)
803        })?;
804        staged.commit(output.durability())?;
805        Ok(report)
806    }
807
808    /// Creates the archive from `sources` into `writer`.
809    ///
810    /// The writer fixes the format. `CreationReport::bytes_compressed` is the
811    /// number of bytes written to it.
812    ///
813    /// # Errors
814    ///
815    /// See [`CreateRequest`].
816    ///
817    /// # Examples
818    ///
819    /// ```
820    /// use exarch_core::ArchiveWriter;
821    /// use exarch_core::CreateRequest;
822    /// use exarch_core::CreationConfig;
823    /// use exarch_core::formats::CompressionCodec;
824    ///
825    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
826    /// let src = tempfile::tempdir()?;
827    /// std::fs::write(src.path().join("a.txt"), b"hello")?;
828    ///
829    /// let mut buf = Vec::new();
830    /// let config = CreationConfig::default();
831    /// let report = CreateRequest::new(&config).write(
832    ///     ArchiveWriter::tar(&mut buf, Some(CompressionCodec::Gzip)),
833    ///     &[src.path()],
834    /// )?;
835    /// assert_eq!(report.bytes_compressed, buf.len() as u64);
836    /// # Ok(())
837    /// # }
838    /// ```
839    pub fn write<P: AsRef<Path>>(
840        self,
841        writer: ArchiveWriter<'_>,
842        sources: &[P],
843    ) -> Result<CreationReport> {
844        let Self { config, progress } = self;
845        progress.run(|progress| writer.write(sources, config, progress))
846    }
847
848    /// Creates an archive of `format` from `sources` and returns its bytes.
849    ///
850    /// The whole archive is held in memory, so use [`create`](Self::create) for
851    /// large ones. Because the finished ZIP can be read back, a ZIP result
852    /// carries the same warning as [`create`](Self::create) when default
853    /// extraction would refuse an entry as a zip bomb.
854    ///
855    /// # Errors
856    ///
857    /// See [`CreateRequest`].
858    ///
859    /// # Examples
860    ///
861    /// ```
862    /// use exarch_core::CreateRequest;
863    /// use exarch_core::CreationConfig;
864    /// use exarch_core::formats::detect::CreatableFormat;
865    ///
866    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
867    /// let src = tempfile::tempdir()?;
868    /// std::fs::write(src.path().join("a.txt"), b"hello")?;
869    ///
870    /// let config = CreationConfig::default();
871    /// let (bytes, report) =
872    ///     CreateRequest::new(&config).to_bytes(CreatableFormat::TarGz, &[src.path()])?;
873    /// assert_eq!(report.bytes_compressed, bytes.len() as u64);
874    /// # Ok(())
875    /// # }
876    /// ```
877    pub fn to_bytes<P: AsRef<Path>>(
878        self,
879        format: CreatableFormat,
880        sources: &[P],
881    ) -> Result<(Vec<u8>, CreationReport)> {
882        let mut out = Cursor::new(Vec::new());
883        let mut report = self.write(ArchiveWriter::of_type(&mut out, format), sources)?;
884        if format == CreatableFormat::Zip {
885            warn_on_extraction_ratio(&mut out, &mut report);
886        }
887        Ok((out.into_inner(), report))
888    }
889}
890
891/// Writes the archive of `format` into the staged file, which a ZIP can be
892/// read back from for the extraction-ratio warning.
893fn write_staged<P: AsRef<Path>>(
894    staged: &mut StagedOutput,
895    format: CreatableFormat,
896    sources: &[P],
897    config: &CreationConfig,
898    progress: &mut dyn ProgressCallback,
899) -> Result<CreationReport> {
900    let (file, excluded) = staged.parts();
901    match format.family() {
902        CreationFamily::Tar(codec) => write_tar(file, codec, sources, config, excluded, progress),
903        CreationFamily::Zip => {
904            let (mut report, file) = write_zip(file, sources, config, excluded, progress)?;
905            warn_on_extraction_ratio(file, &mut report);
906            Ok(report)
907        }
908    }
909}