Skip to main content

exarch_core/formats/
detect.rs

1//! Archive format detection.
2
3use std::path::Path;
4use std::str::FromStr;
5
6use crate::ArchiveError;
7use crate::ConfigProblem;
8use crate::ConfigSetting;
9use crate::Result;
10use crate::closed_enum::ClosedEnum;
11use crate::closed_enum::closed_enum;
12use crate::formats::compression::CompressionCodec;
13use crate::formats::sevenz::SEVENZ_MAGIC;
14
15/// Number of bytes to read for magic-byte detection: one full TAR header block,
16/// so the USTAR signature at offset 257 and the checksum field at 148 are both
17/// available. All other signatures fit within the first 6 bytes.
18const MAGIC_READ_LEN: usize = 512;
19
20const TAR_BLOCK_LEN: usize = 512;
21const USTAR_MAGIC_OFFSET: usize = 257;
22const TAR_CKSUM_FIELD: std::ops::Range<usize> = 148..156;
23
24/// Magic byte signatures for each supported archive format.
25///
26/// Each entry is `(offset, signature, ArchiveType)`.
27///
28/// ZIP has three recognized openers: local-file header (`PK\x03\x04`), EOCD
29/// (`PK\x05\x06` — valid empty ZIP), and split-archive marker (`PK\x07\x08`).
30const MAGIC_SIGNATURES: &[(usize, &[u8], ArchiveType)] = &[
31    (0, b"\x1f\x8b", ArchiveType::TarGz),
32    (0, b"\x28\xb5\x2f\xfd", ArchiveType::TarZst),
33    (0, b"\x42\x5a\x68", ArchiveType::TarBz2),
34    (0, b"\x50\x4b\x03\x04", ArchiveType::Zip),
35    (0, b"\x50\x4b\x05\x06", ArchiveType::Zip),
36    (0, b"\x50\x4b\x07\x08", ArchiveType::Zip),
37    (0, &SEVENZ_MAGIC, ArchiveType::SevenZ),
38    (0, b"\xfd\x37\x7a\x58\x5a\x00", ArchiveType::TarXz),
39    (257, b"ustar", ArchiveType::Tar),
40];
41
42/// File extensions that wrap a ZIP container with extra structure.
43///
44/// Signing, manifests, and ordering rules sit on top of the ZIP bytes
45/// for these formats. Extraction treats them as ZIP; creation is
46/// rejected separately in `api::reject_zip_family_creation`. Kept as a
47/// single source of truth so the two call sites don't drift.
48pub const ZIP_FAMILY_ALIASES: &[&str] = &[
49    "jar", "war", "ear", "nar", "nbm", "apk", "aab", "ipa", "appx", "msix", "whl", "vsix", "xpi",
50    "epub",
51];
52
53/// Returns true if `ext` (case-insensitive) names a ZIP-family alias.
54/// Plain `.zip` is deliberately *not* included - callers can test it
55/// separately when they need to distinguish "bare ZIP" from "ZIP under
56/// another name".
57pub(crate) fn is_zip_family_alias(ext: &str) -> bool {
58    ZIP_FAMILY_ALIASES
59        .iter()
60        .any(|alias| ext.eq_ignore_ascii_case(alias))
61}
62
63closed_enum! {
64    /// Supported archive formats.
65    ///
66    /// `#[non_exhaustive]` so support for a new archive format is not a
67    /// breaking change for downstream matches.
68    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
69    #[non_exhaustive]
70    pub enum ArchiveType {
71        /// Tar archive (uncompressed).
72        Tar => "Tar",
73        /// Gzip-compressed tar archive.
74        TarGz => "TarGz",
75        /// Bzip2-compressed tar archive.
76        TarBz2 => "TarBz2",
77        /// XZ-compressed tar archive.
78        TarXz => "TarXz",
79        /// Zstd-compressed tar archive.
80        TarZst => "TarZst",
81        /// ZIP archive.
82        Zip => "Zip",
83        /// 7z archive.
84        SevenZ => "SevenZ",
85    }
86}
87
88closed_enum! {
89    /// Archive formats exarch can create.
90    ///
91    /// The subset of [`ArchiveType`] with a writer: 7z can be read but not
92    /// created, so it is absent here and a creation API cannot be asked for it.
93    ///
94    /// # Examples
95    ///
96    /// ```
97    /// use exarch_core::formats::detect::ArchiveType;
98    /// use exarch_core::formats::detect::CreatableFormat;
99    ///
100    /// assert_eq!(ArchiveType::from(CreatableFormat::TarGz), ArchiveType::TarGz);
101    /// assert_eq!(
102    ///     CreatableFormat::try_from(ArchiveType::Zip).unwrap(),
103    ///     CreatableFormat::Zip
104    /// );
105    /// assert!(CreatableFormat::try_from(ArchiveType::SevenZ).is_err());
106    /// ```
107    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
108    #[non_exhaustive]
109    pub enum CreatableFormat {
110        /// Tar archive (uncompressed).
111        Tar => "Tar",
112        /// Gzip-compressed tar archive.
113        TarGz => "TarGz",
114        /// Bzip2-compressed tar archive.
115        TarBz2 => "TarBz2",
116        /// XZ-compressed tar archive.
117        TarXz => "TarXz",
118        /// Zstd-compressed tar archive.
119        TarZst => "TarZst",
120        /// ZIP archive.
121        Zip => "Zip",
122    }
123}
124
125closed_enum! {
126    /// Archive formats exarch can read but not create.
127    ///
128    /// Together with [`CreatableFormat`] it partitions [`ArchiveType`], so a
129    /// refusal to create a format names a value that cannot be a creatable one.
130    ///
131    /// # Examples
132    ///
133    /// ```
134    /// use exarch_core::formats::detect::ExtractOnlyFormat;
135    ///
136    /// assert_eq!(ExtractOnlyFormat::SevenZ.extension(), "7z");
137    /// ```
138    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
139    #[non_exhaustive]
140    pub enum ExtractOnlyFormat {
141        /// 7z archive.
142        SevenZ => "SevenZ",
143    }
144}
145
146impl ExtractOnlyFormat {
147    /// The canonical file extension, without a leading dot.
148    #[must_use]
149    pub const fn extension(self) -> &'static str {
150        match self {
151            Self::SevenZ => "7z",
152        }
153    }
154
155    fn not_creatable(self) -> ArchiveError {
156        ArchiveError::InvalidConfiguration {
157            setting: ConfigSetting::CreationFormat,
158            problem: ConfigProblem::NotCreatable { format: self },
159        }
160    }
161}
162
163/// How a [`CreatableFormat`] is written: a TAR stream with an optional codec,
164/// or a ZIP container.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub(crate) enum CreationFamily {
167    Tar(Option<CompressionCodec>),
168    Zip,
169}
170
171impl CreatableFormat {
172    /// The TAR format for a stream compressed with `codec`, or plain TAR.
173    pub(crate) const fn tar_with(codec: Option<CompressionCodec>) -> Self {
174        match codec {
175            None => Self::Tar,
176            Some(CompressionCodec::Gzip) => Self::TarGz,
177            Some(CompressionCodec::Bzip2) => Self::TarBz2,
178            Some(CompressionCodec::Xz) => Self::TarXz,
179            Some(CompressionCodec::Zstd) => Self::TarZst,
180        }
181    }
182
183    /// Groups this format by the writer that handles it.
184    pub(crate) const fn family(self) -> CreationFamily {
185        match self {
186            Self::Tar => CreationFamily::Tar(None),
187            Self::TarGz => CreationFamily::Tar(Some(CompressionCodec::Gzip)),
188            Self::TarBz2 => CreationFamily::Tar(Some(CompressionCodec::Bzip2)),
189            Self::TarXz => CreationFamily::Tar(Some(CompressionCodec::Xz)),
190            Self::TarZst => CreationFamily::Tar(Some(CompressionCodec::Zstd)),
191            Self::Zip => CreationFamily::Zip,
192        }
193    }
194}
195
196impl From<CreatableFormat> for ArchiveType {
197    fn from(format: CreatableFormat) -> Self {
198        match format {
199            CreatableFormat::Tar => Self::Tar,
200            CreatableFormat::TarGz => Self::TarGz,
201            CreatableFormat::TarBz2 => Self::TarBz2,
202            CreatableFormat::TarXz => Self::TarXz,
203            CreatableFormat::TarZst => Self::TarZst,
204            CreatableFormat::Zip => Self::Zip,
205        }
206    }
207}
208
209impl TryFrom<ArchiveType> for CreatableFormat {
210    type Error = ArchiveError;
211
212    /// # Errors
213    ///
214    /// Returns [`ArchiveError::InvalidConfiguration`] with
215    /// [`ConfigProblem::NotCreatable`] for 7z, which cannot be created.
216    fn try_from(format: ArchiveType) -> Result<Self> {
217        match format {
218            ArchiveType::Tar => Ok(Self::Tar),
219            ArchiveType::TarGz => Ok(Self::TarGz),
220            ArchiveType::TarBz2 => Ok(Self::TarBz2),
221            ArchiveType::TarXz => Ok(Self::TarXz),
222            ArchiveType::TarZst => Ok(Self::TarZst),
223            ArchiveType::Zip => Ok(Self::Zip),
224            ArchiveType::SevenZ => Err(ExtractOnlyFormat::SevenZ.not_creatable()),
225        }
226    }
227}
228
229impl FromStr for CreatableFormat {
230    type Err = ArchiveError;
231
232    /// Parses the string form shared with [`ArchiveType::as_str`].
233    ///
234    /// # Errors
235    ///
236    /// [`ArchiveError::InvalidConfiguration`] naming
237    /// [`ConfigSetting::CreationFormat`]: [`ConfigProblem::NotCreatable`] for
238    /// the spelling of a format that can only be read, and
239    /// [`ConfigProblem::NotOneOf`] listing the creatable formats for any other
240    /// string.
241    ///
242    /// # Examples
243    ///
244    /// ```
245    /// use exarch_core::formats::detect::CreatableFormat;
246    ///
247    /// assert_eq!(
248    ///     "Zip".parse::<CreatableFormat>().unwrap(),
249    ///     CreatableFormat::Zip
250    /// );
251    /// let err = "SevenZ".parse::<CreatableFormat>().unwrap_err();
252    /// assert_eq!(
253    ///     err.to_string(),
254    ///     "invalid configuration: 7z archive creation is not supported"
255    /// );
256    /// ```
257    fn from_str(value: &str) -> Result<Self> {
258        if let Some(format) = ExtractOnlyFormat::ALL
259            .iter()
260            .find(|format| format.as_str() == value)
261        {
262            return Err(format.not_creatable());
263        }
264        <Self as ClosedEnum>::parse_for(ConfigSetting::CreationFormat, value)
265    }
266}
267
268/// How an [`ArchiveType`] is read: a TAR stream with an optional codec, or a
269/// container format with its own handler.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub(crate) enum FormatFamily {
272    Tar(Option<CompressionCodec>),
273    Seekable(crate::SeekableFormat),
274}
275
276impl ArchiveType {
277    /// The TAR type for a stream compressed with `codec`, or plain TAR.
278    pub(crate) const fn tar_with(codec: Option<CompressionCodec>) -> Self {
279        match codec {
280            None => Self::Tar,
281            Some(CompressionCodec::Gzip) => Self::TarGz,
282            Some(CompressionCodec::Bzip2) => Self::TarBz2,
283            Some(CompressionCodec::Xz) => Self::TarXz,
284            Some(CompressionCodec::Zstd) => Self::TarZst,
285        }
286    }
287
288    /// The canonical file extension for this type, without a leading dot.
289    ///
290    /// Extension detection maps the result back to the same type.
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// use exarch_core::formats::detect::ArchiveType;
296    ///
297    /// assert_eq!(ArchiveType::TarGz.extension(), "tar.gz");
298    /// assert_eq!(ArchiveType::SevenZ.extension(), "7z");
299    /// ```
300    #[must_use]
301    pub const fn extension(self) -> &'static str {
302        match self {
303            Self::Tar => "tar",
304            Self::TarGz => "tar.gz",
305            Self::TarBz2 => "tar.bz2",
306            Self::TarXz => "tar.xz",
307            Self::TarZst => "tar.zst",
308            Self::Zip => "zip",
309            Self::SevenZ => "7z",
310        }
311    }
312
313    /// Whether this type is a TAR stream, with or without a compression codec.
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// use exarch_core::formats::detect::ArchiveType;
319    ///
320    /// assert!(ArchiveType::TarZst.is_tar());
321    /// assert!(!ArchiveType::Zip.is_tar());
322    /// ```
323    #[must_use]
324    pub const fn is_tar(self) -> bool {
325        match self.family() {
326            FormatFamily::Tar(_) => true,
327            FormatFamily::Seekable(_) => false,
328        }
329    }
330
331    /// Groups this type by the reader that handles it.
332    pub(crate) const fn family(self) -> FormatFamily {
333        match self {
334            Self::Tar => FormatFamily::Tar(None),
335            Self::TarGz => FormatFamily::Tar(Some(CompressionCodec::Gzip)),
336            Self::TarBz2 => FormatFamily::Tar(Some(CompressionCodec::Bzip2)),
337            Self::TarXz => FormatFamily::Tar(Some(CompressionCodec::Xz)),
338            Self::TarZst => FormatFamily::Tar(Some(CompressionCodec::Zstd)),
339            Self::Zip => FormatFamily::Seekable(crate::SeekableFormat::Zip),
340            Self::SevenZ => FormatFamily::Seekable(crate::SeekableFormat::SevenZ),
341        }
342    }
343}
344
345/// Detects the archive type from a file path using two-phase detection.
346///
347/// This function is for **reading** existing archives. For creating archives,
348/// use `detect_format_from_extension` directly so that stale on-disk bytes
349/// do not override the user's intended output format.
350///
351/// **Phase 1 — extension:** maps the file extension to an [`ArchiveType`] using
352/// the same rules as before. `.gz` is only accepted when the stem ends with
353/// `.tar`, compared case-insensitively (e.g. `archive.tar.gz`,
354/// `ARCHIVE.TAR.GZ`); a bare `archive.gz` is not a recognised extension.
355///
356/// **Phase 2 — magic bytes:** when extension detection fails (unrecognised or
357/// missing extension), the function reads up to the first 512 bytes of the file
358/// and matches against known magic-byte signatures. If the file is not readable
359/// (does not exist, is a directory, I/O error), phase 2 is silently skipped and
360/// [`ArchiveError::UnknownFormat`] is returned.
361///
362/// Additionally, if extension detection succeeds but magic-byte inspection
363/// identifies a *different* known format, the magic-byte result takes
364/// precedence. This covers the common case where a file was renamed or given
365/// the wrong extension.
366///
367/// **Precedence between signatures:** a ZIP or 7z magic at offset 0 always
368/// wins, and so do gzip, xz and zstd magics: no valid UTF-8 member name starts
369/// with them, while a gzip header can carry a whole ustar block in its extra
370/// field. Only `BZh` can open a member name, so a checksum-valid ustar header
371/// whose leading bytes are not a complete bzip2 stream header (`BZh`, a level
372/// digit, then the block or end-of-stream marker) is read as a plain TAR. An
373/// input that is valid under both readings keeps its compression view, as in
374/// bsdtar and `CPython`.
375///
376/// **Note on compression signatures:** magic-byte detection maps GZ, BZ2, XZ,
377/// and Zstd signatures to their `Tar*` variants because those are the only
378/// archive-level formats this library handles for those compression schemes.
379/// A bare single-file gzip/bz2/xz/zstd stream (not wrapping a tar) will
380/// succeed detection but fail at extraction with a tar-parse error. When the
381/// file has an unrelated extension (e.g. `.dat`), magic-byte fallback still
382/// returns the `Tar*` guess — callers should be aware that
383/// compressed-but-not-tar streams will surface errors at decode time rather
384/// than at detection.
385///
386/// # Errors
387///
388/// Returns [`ArchiveError::UnknownFormat`] when neither phase can determine the
389/// format.
390pub fn detect_format(path: &Path) -> Result<ArchiveType> {
391    let ext_result = detect_format_from_extension(path);
392
393    match ext_result {
394        Ok(ext_type) => {
395            // Extension matched. Read magic bytes to verify; if they point to
396            // a different known format, trust the bytes over the name.
397            if let Some(magic_type) = detect_format_from_magic(path)
398                && magic_type != ext_type
399            {
400                return Ok(magic_type);
401            }
402            Ok(ext_type)
403        }
404        Err(_) => {
405            // Extension gave no conclusive result — fall back to magic bytes.
406            detect_format_from_magic(path).ok_or_else(|| ArchiveError::UnknownFormat {
407                path: path.to_path_buf(),
408            })
409        }
410    }
411}
412
413/// Extension-only detection used for archive **creation**.
414///
415/// Magic-byte inspection is intentionally skipped here: the output file may not
416/// exist yet, or it may contain stale bytes from a previous run that must not
417/// override the caller's chosen format.
418pub(crate) fn detect_format_from_extension(path: &Path) -> Result<ArchiveType> {
419    let extension =
420        path.extension()
421            .and_then(|e| e.to_str())
422            .ok_or_else(|| ArchiveError::UnknownFormat {
423                path: path.to_path_buf(),
424            })?;
425
426    let ext_lower = extension.to_ascii_lowercase();
427    match ext_lower.as_str() {
428        "tar" => Ok(ArchiveType::Tar),
429        "tgz" => Ok(ArchiveType::TarGz),
430        "gz" => {
431            if let Some(stem) = path.file_stem()
432                && stem
433                    .as_encoded_bytes()
434                    .last_chunk::<4>()
435                    .is_some_and(|tail| tail.eq_ignore_ascii_case(b".tar"))
436            {
437                Ok(ArchiveType::TarGz)
438            } else {
439                Err(ArchiveError::UnknownFormat {
440                    path: path.to_path_buf(),
441                })
442            }
443        }
444        "bz2" | "tbz" | "tbz2" => Ok(ArchiveType::TarBz2),
445        "xz" | "txz" => Ok(ArchiveType::TarXz),
446        "zst" | "tzst" => Ok(ArchiveType::TarZst),
447        "zip" => Ok(ArchiveType::Zip),
448        "7z" => Ok(ArchiveType::SevenZ),
449        // JVM artifacts, app bundles, Python wheels, IDE/browser
450        // extensions, EPUBs - all ZIP under the hood, so they extract
451        // through the same path. See `ZIP_FAMILY_ALIASES` for the list.
452        ext if is_zip_family_alias(ext) => Ok(ArchiveType::Zip),
453        _ => Err(ArchiveError::UnknownFormat {
454            path: path.to_path_buf(),
455        }),
456    }
457}
458
459/// Reads up to [`MAGIC_READ_LEN`] bytes from the beginning of `path` and
460/// matches them against [`MAGIC_SIGNATURES`].
461///
462/// Uses a read loop to handle short reads (interrupted syscalls, FUSE mounts,
463/// network filesystems) so the USTAR check at offset 257 is always reliable.
464///
465/// Returns `None` if the file cannot be read or no signature matches.
466fn detect_format_from_magic(path: &Path) -> Option<ArchiveType> {
467    let mut file = std::fs::File::open(path).ok()?;
468    let header = peek_header(&mut file).ok()?;
469    match_signature(header.as_slice())
470}
471
472/// The leading bytes of a source, as many as [`MAGIC_READ_LEN`] allows.
473pub(crate) struct Header {
474    buf: [u8; MAGIC_READ_LEN],
475    filled: usize,
476}
477
478impl Header {
479    /// The bytes that were actually read.
480    pub(crate) fn as_slice(&self) -> &[u8] {
481        &self.buf[..self.filled]
482    }
483}
484
485/// Reads up to [`MAGIC_READ_LEN`] bytes from `reader`, looping over short
486/// reads and `Interrupted` until the buffer is full or the source ends.
487///
488/// # Errors
489///
490/// Returns the first read error other than `Interrupted`.
491pub(crate) fn peek_header<R: std::io::Read + ?Sized>(reader: &mut R) -> std::io::Result<Header> {
492    let mut header = Header {
493        buf: [0; MAGIC_READ_LEN],
494        filled: 0,
495    };
496    while header.filled < MAGIC_READ_LEN {
497        match reader.read(&mut header.buf[header.filled..]) {
498            Ok(0) => break,
499            Ok(n) => header.filled += n,
500            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
501            Err(e) => return Err(e),
502        }
503    }
504    Ok(header)
505}
506
507/// Whether `header` opens with a TAR header block: `ustar` at offset 257 and a
508/// checksum field that matches the tar reader's own rule (unsigned byte sum
509/// with the checksum field counted as spaces).
510fn is_ustar_header(header: &[u8]) -> bool {
511    let Some(block) = header.first_chunk::<TAR_BLOCK_LEN>() else {
512        return false;
513    };
514    if !block[USTAR_MAGIC_OFFSET..].starts_with(b"ustar") {
515        return false;
516    }
517    let sum: u32 = block
518        .iter()
519        .enumerate()
520        .map(|(i, &b)| {
521            if TAR_CKSUM_FIELD.contains(&i) {
522                u32::from(b' ')
523            } else {
524                u32::from(b)
525            }
526        })
527        .sum();
528    tar::Header::from_byte_slice(block)
529        .cksum()
530        .is_ok_and(|stored| stored == sum)
531}
532
533/// Whether `header` opens with a complete bzip2 stream header: `BZh`, a level
534/// digit, then the first block magic or the end-of-stream marker.
535fn is_bzip2_stream_start(header: &[u8]) -> bool {
536    const BLOCK_MAGIC: &[u8; 6] = b"1AY&SY";
537    const END_MAGIC: &[u8; 6] = &[0x17, 0x72, 0x45, 0x38, 0x50, 0x90];
538    header.starts_with(b"BZh")
539        && header
540            .get(3)
541            .is_some_and(|level| (b'1'..=b'9').contains(level))
542        && header
543            .get(4..10)
544            .is_some_and(|marker| marker == BLOCK_MAGIC || marker == END_MAGIC)
545}
546
547/// Matches `header` against [`MAGIC_SIGNATURES`]; the first entry in table
548/// order wins, so an offset-0 magic beats the `ustar` signature at 257.
549///
550/// The one exception is a bzip2 magic that is not a complete bzip2 stream
551/// header: a checksum-valid ustar header outranks it, because a TAR member name
552/// can start with `BZh`. Input valid under both readings, and every other
553/// magic, keeps the offset-0 view.
554///
555/// The one signature table behind path, seekable and streaming detection.
556pub(crate) fn match_signature(header: &[u8]) -> Option<ArchiveType> {
557    let table_match = MAGIC_SIGNATURES
558        .iter()
559        .find(|&&(offset, sig, _)| {
560            offset
561                .checked_add(sig.len())
562                .and_then(|end| header.get(offset..end))
563                .is_some_and(|window| window == sig)
564        })
565        .map(|&(_, _, archive_type)| archive_type);
566    match table_match {
567        Some(ArchiveType::TarBz2) if !is_bzip2_stream_start(header) && is_ustar_header(header) => {
568            Some(ArchiveType::Tar)
569        }
570        _ => table_match,
571    }
572}
573
574#[cfg(test)]
575#[allow(clippy::unwrap_used)]
576mod tests {
577    use super::*;
578    use std::assert_matches;
579    use std::path::PathBuf;
580
581    #[test]
582    fn a_creatable_format_parses_from_its_name() {
583        for &format in CreatableFormat::ALL {
584            assert_eq!(format.as_str().parse::<CreatableFormat>().unwrap(), format);
585        }
586    }
587
588    #[test]
589    fn an_unknown_creation_format_lists_the_creatable_formats_only() {
590        for text in ["zip", "ZIP", "tar.gz", "bogus", "", "7z"] {
591            let err = text.parse::<CreatableFormat>().unwrap_err();
592            assert_eq!(
593                err.to_string(),
594                "invalid configuration: creation format is not one of the allowed values: \
595                 Tar, TarGz, TarBz2, TarXz, TarZst, Zip",
596                "{text:?}"
597            );
598        }
599    }
600
601    #[test]
602    fn an_extract_only_format_is_not_creatable() {
603        let from_name = "SevenZ".parse::<CreatableFormat>().unwrap_err();
604        let from_type = CreatableFormat::try_from(ArchiveType::SevenZ).unwrap_err();
605        for err in [from_name, from_type] {
606            assert_matches!(
607                err,
608                ArchiveError::InvalidConfiguration {
609                    setting: ConfigSetting::CreationFormat,
610                    problem: ConfigProblem::NotCreatable {
611                        format: ExtractOnlyFormat::SevenZ
612                    },
613                }
614            );
615        }
616    }
617
618    #[test]
619    fn creatable_and_extract_only_formats_partition_the_archive_types() {
620        let mut names: Vec<&str> = CreatableFormat::NAMES
621            .iter()
622            .chain(ExtractOnlyFormat::NAMES)
623            .copied()
624            .collect();
625        names.sort_unstable();
626        let mut all: Vec<&str> = ArchiveType::NAMES.to_vec();
627        all.sort_unstable();
628        assert_eq!(names, all);
629    }
630
631    #[test]
632    fn test_archive_type_as_str_matches_display_and_is_unique() {
633        let names: Vec<&str> = ArchiveType::ALL.iter().map(|t| t.as_str()).collect();
634        assert_eq!(
635            names,
636            ["Tar", "TarGz", "TarBz2", "TarXz", "TarZst", "Zip", "SevenZ"]
637        );
638        for t in ArchiveType::ALL {
639            assert_eq!(t.to_string(), t.as_str());
640        }
641    }
642
643    #[test]
644    fn test_archive_type_extension_round_trips_through_detection() {
645        for &t in ArchiveType::ALL {
646            let name = format!("archive.{}", t.extension());
647            assert_eq!(detect_format_from_extension(Path::new(&name)).unwrap(), t);
648        }
649    }
650
651    #[test]
652    fn test_creatable_format_round_trips_through_archive_type() {
653        for &format in CreatableFormat::ALL {
654            let archive_type = ArchiveType::from(format);
655            assert_eq!(CreatableFormat::try_from(archive_type).unwrap(), format);
656            assert_eq!(archive_type.as_str(), format.as_str());
657        }
658        assert_eq!(CreatableFormat::ALL.len(), ArchiveType::ALL.len() - 1);
659        assert_matches!(
660            CreatableFormat::try_from(ArchiveType::SevenZ),
661            Err(ArchiveError::InvalidConfiguration { .. })
662        );
663    }
664
665    #[test]
666    fn test_family_maps_tar_codecs() {
667        assert_eq!(ArchiveType::Tar.family(), FormatFamily::Tar(None));
668        assert_eq!(
669            ArchiveType::TarGz.family(),
670            FormatFamily::Tar(Some(CompressionCodec::Gzip))
671        );
672        assert_eq!(
673            ArchiveType::TarBz2.family(),
674            FormatFamily::Tar(Some(CompressionCodec::Bzip2))
675        );
676        assert_eq!(
677            ArchiveType::TarXz.family(),
678            FormatFamily::Tar(Some(CompressionCodec::Xz))
679        );
680        assert_eq!(
681            ArchiveType::TarZst.family(),
682            FormatFamily::Tar(Some(CompressionCodec::Zstd))
683        );
684        assert_eq!(
685            ArchiveType::Zip.family(),
686            FormatFamily::Seekable(crate::SeekableFormat::Zip)
687        );
688        assert_eq!(
689            ArchiveType::SevenZ.family(),
690            FormatFamily::Seekable(crate::SeekableFormat::SevenZ)
691        );
692    }
693
694    #[test]
695    fn test_detect_tar() {
696        let path = PathBuf::from("archive.tar");
697        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
698    }
699
700    #[test]
701    fn test_detect_tar_gz_still_works() {
702        let path = PathBuf::from("archive.tar.gz");
703        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarGz);
704
705        let path2 = PathBuf::from("archive.tgz");
706        assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarGz);
707    }
708
709    #[test]
710    fn test_detect_tar_gz_stem_is_case_insensitive() {
711        for name in ["a.TAR.gz", "a.Tar.GZ", "A.TAR.GZ"] {
712            assert_eq!(
713                detect_format(&PathBuf::from(name)).unwrap(),
714                ArchiveType::TarGz,
715                "{name}"
716            );
717        }
718    }
719
720    #[test]
721    fn test_detect_bare_dot_tar_gz_still_matches() {
722        assert_eq!(
723            detect_format_from_extension(Path::new(".tar.gz")).unwrap(),
724            ArchiveType::TarGz
725        );
726    }
727
728    #[test]
729    fn test_detect_bare_gz_returns_unknown_format() {
730        let path = PathBuf::from("archive.gz");
731        assert_matches!(
732            detect_format(&path),
733            Err(ArchiveError::UnknownFormat { .. })
734        );
735    }
736
737    #[test]
738    fn test_detect_bare_gz_error_carries_path() {
739        let path = PathBuf::from("archive.gz");
740        let err = detect_format(&path).unwrap_err();
741        assert_matches!(
742            err,
743            ArchiveError::UnknownFormat { path: ref p } if p == &PathBuf::from("archive.gz")
744        );
745    }
746
747    #[test]
748    fn test_detect_tar_bz2() {
749        let path = PathBuf::from("archive.tar.bz2");
750        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarBz2);
751
752        let path2 = PathBuf::from("archive.tbz");
753        assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarBz2);
754
755        let path3 = PathBuf::from("archive.tbz2");
756        assert_eq!(detect_format(&path3).unwrap(), ArchiveType::TarBz2);
757    }
758
759    #[test]
760    fn test_detect_tar_xz() {
761        let path = PathBuf::from("archive.tar.xz");
762        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarXz);
763
764        let path2 = PathBuf::from("archive.txz");
765        assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarXz);
766    }
767
768    #[test]
769    fn test_detect_tar_zst() {
770        let path = PathBuf::from("archive.tar.zst");
771        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarZst);
772
773        let path2 = PathBuf::from("archive.tzst");
774        assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarZst);
775    }
776
777    #[test]
778    fn test_detect_zip() {
779        let path = PathBuf::from("archive.zip");
780        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
781    }
782
783    #[test]
784    fn test_detect_zip_family_extensions() {
785        // Each of these is a ZIP underneath and should resolve to
786        // ArchiveType::Zip so the existing extractor picks it up. Upper-case
787        // variants cover Windows-authored filenames. Driving off
788        // ZIP_FAMILY_ALIASES keeps the test from drifting if the list changes.
789        for ext in ZIP_FAMILY_ALIASES {
790            let path = PathBuf::from(format!("archive.{ext}"));
791            assert_eq!(
792                detect_format(&path).unwrap(),
793                ArchiveType::Zip,
794                "{ext} should detect as ZIP",
795            );
796
797            let upper = PathBuf::from(format!("archive.{}", ext.to_ascii_uppercase()));
798            assert_eq!(
799                detect_format(&upper).unwrap(),
800                ArchiveType::Zip,
801                "{ext} uppercase should detect as ZIP",
802            );
803        }
804    }
805
806    #[test]
807    fn test_detect_7z() {
808        let path = PathBuf::from("archive.7z");
809        assert_eq!(detect_format(&path).unwrap(), ArchiveType::SevenZ);
810    }
811
812    #[test]
813    fn test_detect_7z_case_insensitive() {
814        let path = PathBuf::from("ARCHIVE.7Z");
815        assert_eq!(detect_format(&path).unwrap(), ArchiveType::SevenZ);
816
817        let path2 = PathBuf::from("Archive.7Z");
818        assert_eq!(detect_format(&path2).unwrap(), ArchiveType::SevenZ);
819    }
820
821    #[test]
822    fn test_detect_unknown_format() {
823        let path = PathBuf::from("archive.rar");
824        assert_matches!(
825            detect_format(&path),
826            Err(ArchiveError::UnknownFormat { .. })
827        );
828    }
829
830    #[test]
831    fn test_detect_unknown_format_error_carries_path() {
832        let path = PathBuf::from("archive.rar");
833        let err = detect_format(&path).unwrap_err();
834        assert_matches!(
835            err,
836            ArchiveError::UnknownFormat { path: ref p } if p == &PathBuf::from("archive.rar")
837        );
838    }
839
840    #[test]
841    fn test_archive_type_sevenz_equality() {
842        assert_eq!(ArchiveType::SevenZ, ArchiveType::SevenZ);
843        assert_ne!(ArchiveType::SevenZ, ArchiveType::Zip);
844    }
845
846    #[test]
847    fn test_archive_type_sevenz_debug() {
848        let format = ArchiveType::SevenZ;
849        let debug_str = format!("{format:?}");
850        assert_eq!(debug_str, "SevenZ");
851    }
852
853    // --- magic-bytes tests ---
854
855    fn write_magic_file(dir: &tempfile::TempDir, name: &str, header: &[u8]) -> PathBuf {
856        let path = dir.path().join(name);
857        // Pad to MAGIC_READ_LEN so TAR USTAR offset tests work.
858        let mut data = vec![0u8; MAGIC_READ_LEN];
859        let n = header.len().min(data.len());
860        data[..n].copy_from_slice(&header[..n]);
861        std::fs::write(&path, &data).unwrap();
862        path
863    }
864
865    fn write_magic_file_at_offset(
866        dir: &tempfile::TempDir,
867        name: &str,
868        offset: usize,
869        sig: &[u8],
870    ) -> PathBuf {
871        let path = dir.path().join(name);
872        let mut data = vec![0u8; MAGIC_READ_LEN];
873        let end = offset + sig.len();
874        if end <= data.len() {
875            data[offset..end].copy_from_slice(sig);
876        }
877        std::fs::write(&path, &data).unwrap();
878        path
879    }
880
881    #[test]
882    fn test_magic_zip_no_extension() {
883        let dir = tempfile::tempdir().unwrap();
884        let path = write_magic_file(&dir, "data", b"\x50\x4b\x03\x04");
885        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
886    }
887
888    #[test]
889    fn test_magic_gzip_no_extension() {
890        let dir = tempfile::tempdir().unwrap();
891        let path = write_magic_file(&dir, "data", b"\x1f\x8b\x00");
892        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarGz);
893    }
894
895    #[test]
896    fn test_magic_bz2_no_extension() {
897        let dir = tempfile::tempdir().unwrap();
898        let path = write_magic_file(&dir, "data", b"\x42\x5a\x68");
899        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarBz2);
900    }
901
902    #[test]
903    fn test_magic_xz_no_extension() {
904        let dir = tempfile::tempdir().unwrap();
905        let path = write_magic_file(&dir, "data", b"\xfd\x37\x7a\x58\x5a\x00");
906        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarXz);
907    }
908
909    #[test]
910    fn test_magic_zstd_no_extension() {
911        let dir = tempfile::tempdir().unwrap();
912        let path = write_magic_file(&dir, "data", b"\x28\xb5\x2f\xfd");
913        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarZst);
914    }
915
916    #[test]
917    fn test_magic_sevenz_no_extension() {
918        let dir = tempfile::tempdir().unwrap();
919        let path = write_magic_file(&dir, "data", b"\x37\x7a\xbc\xaf\x27\x1c");
920        assert_eq!(detect_format(&path).unwrap(), ArchiveType::SevenZ);
921    }
922
923    #[test]
924    fn test_magic_tar_ustar_no_extension() {
925        let dir = tempfile::tempdir().unwrap();
926        let path = write_magic_file_at_offset(&dir, "data", 257, b"ustar");
927        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
928    }
929
930    #[test]
931    fn test_magic_wins_over_wrong_extension() {
932        // File named .zip but contains gzip magic bytes.
933        let dir = tempfile::tempdir().unwrap();
934        let path = write_magic_file(&dir, "archive.zip", b"\x1f\x8b\x00");
935        assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarGz);
936    }
937
938    #[test]
939    fn test_extension_wins_when_no_magic_mismatch() {
940        // File named .zip whose first bytes are not a recognised signature —
941        // extension result stands.
942        let dir = tempfile::tempdir().unwrap();
943        let path = dir.path().join("archive.zip");
944        std::fs::write(&path, b"\x00\x00\x00\x00").unwrap();
945        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
946    }
947
948    #[test]
949    fn test_nonexistent_file_without_extension_returns_unknown() {
950        let path = PathBuf::from("/nonexistent/path/to/archive");
951        assert_matches!(
952            detect_format(&path),
953            Err(ArchiveError::UnknownFormat { .. })
954        );
955    }
956
957    #[test]
958    fn test_nonexistent_file_with_known_extension_uses_extension() {
959        // For a nonexistent file the magic-read silently fails, so extension
960        // wins.
961        let path = PathBuf::from("/nonexistent/archive.zip");
962        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
963    }
964
965    // S1: empty ZIP (EOCD magic) and split-archive marker must be detected.
966    #[test]
967    fn test_magic_empty_zip_eocd_no_extension() {
968        let dir = tempfile::tempdir().unwrap();
969        let path = write_magic_file(&dir, "empty", b"\x50\x4b\x05\x06");
970        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
971    }
972
973    #[test]
974    fn test_magic_split_zip_no_extension() {
975        let dir = tempfile::tempdir().unwrap();
976        let path = write_magic_file(&dir, "split", b"\x50\x4b\x07\x08");
977        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
978    }
979
980    // S3: USTAR detection must work even when the file is exactly 262 bytes
981    // with no extra padding — exercises the read loop for a file that is
982    // exactly at the boundary and has no trailing zero padding beyond
983    // offset 262.
984    #[test]
985    fn test_magic_tar_ustar_exact_boundary_file() {
986        let dir = tempfile::tempdir().unwrap();
987        let path = dir.path().join("minimal.tar");
988        // Write exactly 262 bytes: zeros everywhere except "ustar" at offset
989        // 257.
990        let mut data = vec![0u8; MAGIC_READ_LEN];
991        data[257..262].copy_from_slice(b"ustar");
992        std::fs::write(&path, &data).unwrap();
993        // Extension matches too — verify magic agrees.
994        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
995    }
996
997    // S3: a file shorter than 262 bytes but with USTAR at offset 257 must still
998    // be detected (file is 262 bytes minimum by construction, but 263 bytes
999    // with one extra zero also works; test a file that is exactly the USTAR
1000    // minimum).
1001    #[test]
1002    fn test_magic_tar_ustar_minimal_263_byte_file() {
1003        let dir = tempfile::tempdir().unwrap();
1004        let path = dir.path().join("data");
1005        let mut data = vec![0u8; 263];
1006        data[257..262].copy_from_slice(b"ustar");
1007        std::fs::write(&path, &data).unwrap();
1008        assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
1009    }
1010
1011    #[test]
1012    fn match_signature_prefers_offset_zero_magic_over_ustar() {
1013        let mut header = [0u8; MAGIC_READ_LEN];
1014        header[257..262].copy_from_slice(b"ustar");
1015        assert_eq!(match_signature(&header), Some(ArchiveType::Tar));
1016        header[..4].copy_from_slice(b"PK\x03\x04");
1017        assert_eq!(match_signature(&header), Some(ArchiveType::Zip));
1018    }
1019
1020    fn sealed_block(name: &[u8]) -> [u8; TAR_BLOCK_LEN] {
1021        let mut header = tar::Header::new_ustar();
1022        header.as_old_mut().name[..name.len()].copy_from_slice(name);
1023        header.set_size(0);
1024        header.set_cksum();
1025        *header.as_bytes()
1026    }
1027
1028    #[test]
1029    fn is_ustar_header_accepts_only_a_sealed_block() {
1030        let block = sealed_block(b"a.txt");
1031        assert!(is_ustar_header(&block));
1032
1033        let mut off_by_one = block;
1034        off_by_one[0] ^= 1;
1035        assert!(!is_ustar_header(&off_by_one));
1036
1037        let mut non_numeric = block;
1038        non_numeric[TAR_CKSUM_FIELD].copy_from_slice(b"xxxxxxx\0");
1039        assert!(!is_ustar_header(&non_numeric));
1040
1041        assert!(!is_ustar_header(&block[..TAR_BLOCK_LEN - 1]));
1042        assert!(!is_ustar_header(&[]));
1043
1044        let mut v7 = sealed_block(b"a.txt");
1045        v7[USTAR_MAGIC_OFFSET..USTAR_MAGIC_OFFSET + 5].fill(0);
1046        assert!(!is_ustar_header(&v7));
1047    }
1048
1049    #[test]
1050    fn only_a_bzip2_looking_name_loses_to_a_sealed_ustar_block() {
1051        let cases: [(&[u8], Option<ArchiveType>); 8] = [
1052            (b"BZhfoo.txt", Some(ArchiveType::Tar)),
1053            (b"BZh91AY&SYfoo", Some(ArchiveType::TarBz2)),
1054            (b"\x1f\x8bfoo", Some(ArchiveType::TarGz)),
1055            (b"\x28\xb5\x2f\xfdfoo", Some(ArchiveType::TarZst)),
1056            (b"\xfd7zXZ\0foo", Some(ArchiveType::TarXz)),
1057            (b"PK\x03\x04foo", Some(ArchiveType::Zip)),
1058            (b"7z\xbc\xaf\x27\x1cfoo", Some(ArchiveType::SevenZ)),
1059            (b"plain.txt", Some(ArchiveType::Tar)),
1060        ];
1061        for (name, expected) in cases {
1062            assert_eq!(match_signature(&sealed_block(name)), expected, "{name:?}");
1063        }
1064    }
1065
1066    #[test]
1067    fn a_v7_tar_with_a_gzip_magic_name_stays_gzip() {
1068        let mut block = sealed_block(b"\x1f\x8bfoo");
1069        block[USTAR_MAGIC_OFFSET..USTAR_MAGIC_OFFSET + 5].fill(0);
1070        assert_eq!(match_signature(&block), Some(ArchiveType::TarGz));
1071    }
1072
1073    #[test]
1074    fn match_signature_handles_short_and_empty_headers() {
1075        assert_eq!(match_signature(&[]), None);
1076        assert_eq!(match_signature(b"\x1f"), None);
1077        assert_eq!(match_signature(b"\x1f\x8b"), Some(ArchiveType::TarGz));
1078        assert_eq!(match_signature(&[0; 261]), None);
1079    }
1080}