1use std::path::Path;
2
3use thiserror::Error;
4
5#[cfg(feature = "bzip")]
6pub use crate::bzip2::Bzip2;
7
8#[cfg(feature = "gzip")]
9pub use crate::gzip::Gzip;
10
11#[cfg(feature = "tar")]
12pub use crate::tar::Tar;
13
14#[cfg(feature = "xz")]
15pub use crate::xz::Xz;
16
17#[cfg(feature = "zip")]
18pub use crate::zip::Zip;
19
20#[cfg(feature = "bzip")]
21mod bzip2;
22
23#[cfg(feature = "gzip")]
24mod gzip;
25
26#[cfg(feature = "tar")]
27mod tar;
28
29#[cfg(feature = "xz")]
30mod xz;
31
32#[cfg(feature = "zip")]
33mod zip;
34
35#[derive(Error, Debug)]
36pub enum ArchiverError {
37 #[error("{0}")]
38 Io(#[from] std::io::Error),
39 #[error("File Not Found")]
40 NotFound,
41}
42
43type Result<T> = std::result::Result<T, ArchiverError>;
44
45pub trait Archive {
46 fn contains(&mut self, file: String) -> Result<bool>;
47
48 fn extract(&mut self, destination: &Path) -> Result<()>;
49
50 fn extract_single(&mut self, target: &Path, file: String) -> Result<()>;
51
52 fn files(&mut self) -> Result<Vec<String>>;
53
54 fn walk(&mut self, f: Box<dyn Fn(String) -> Option<String>>) -> Result<()>;
55}
56
57pub trait Compressed: std::io::Read {
58 fn decompress(&mut self, target: &Path) -> Result<()>;
59}
60
61pub fn open(path: &Path) -> std::io::Result<Box<dyn Archive>> {
62 use std::fs::File;
63 use std::io::{Error, ErrorKind, Read, Seek, SeekFrom};
64
65 let mut file = File::open(&path)?;
66 let mut buffer = [0u8; 2];
67 file.read(&mut buffer)?;
68 file.seek(SeekFrom::Start(0))?;
69
70 match buffer {
71 #[cfg(all(feature = "bzip", feature = "tar"))]
72 [0x42, 0x5A] => Ok(Box::new(Tar::new(Bzip2::new(file)?)?)), #[cfg(all(feature = "gzip", feature = "tar"))]
74 [0x1F, 0x8B] => Ok(Box::new(Tar::new(Gzip::new(file)?)?)), #[cfg(all(feature = "xz", feature = "tar"))]
76 [0xFD, 0x37] => Ok(Box::new(Tar::new(Xz::new(file)?)?)), #[cfg(feature = "zip")]
78 [0x50, 0x4B] => Ok(Box::new(Zip::new(file)?)), _ => Err(Error::from(ErrorKind::InvalidData))?,
80 }
81}