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