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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
use flate2::{write::GzEncoder, Compression};
use humansize::{make_format, DECIMAL};
use std::{
collections::hash_map::DefaultHasher,
fmt,
fs::File,
hash::Hasher,
io::{copy, BufReader, Seek, SeekFrom},
};
use tar::Archive;
use tempfile::NamedTempFile;
/// The compression level to use when compressing files (0-9)
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum CompressionLevel {
/// No compression (0)
None,
/// Fast compression (1)
Fast,
/// Default compression (6)
Default,
/// Maximum compression (9)
Maximum,
/// Custom compression level (0-9)
Custom(u32),
}
impl AsRef<CompressionLevel> for CompressionLevel {
fn as_ref(&self) -> &CompressionLevel {
self
}
}
impl From<&CompressionLevel> for u32 {
fn from(value: &CompressionLevel) -> Self {
use CompressionLevel::{Custom, Default, Fast, Maximum, None};
match value {
None => 0,
Fast => 1,
Default => 6,
Maximum => 9,
Custom(level) => *level,
}
}
}
impl From<CompressionLevel> for u32 {
fn from(value: CompressionLevel) -> Self {
use CompressionLevel::{Custom, Default, Fast, Maximum, None};
match value {
None => 0,
Fast => 1,
Default => 6,
Maximum => 9,
Custom(level) => level,
}
}
}
impl TryFrom<CompressionLevel> for Compression {
type Error = String;
fn try_from(value: CompressionLevel) -> Result<Self, Self::Error> {
use CompressionLevel::{Custom, Default, Fast, Maximum, None};
match value {
None => Ok(Compression::none()),
Fast => Ok(Compression::fast()),
Default => Ok(Compression::default()),
Maximum => Ok(Compression::best()),
Custom(level) => {
if level > 9 {
Err(format!(
"Invalid compression level: {level}, must be between 0 and 9"
))
} else {
Ok(Compression::new(level))
}
}
}
}
}
impl TryFrom<&CompressionLevel> for Compression {
type Error = String;
fn try_from(value: &CompressionLevel) -> Result<Self, Self::Error> {
use CompressionLevel::{Custom, Default, Fast, Maximum, None};
match value {
None => Ok(Compression::none()),
Fast => Ok(Compression::fast()),
Default => Ok(Compression::default()),
Maximum => Ok(Compression::best()),
Custom(level) => {
if *level > 9 {
Err(format!(
"Invalid compression level: {level}, must be between 0 and 9"
))
} else {
Ok(Compression::new(*level))
}
}
}
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ArchiveInfo {
input_size: u64,
output_size: u64,
ratio: f64,
}
impl ArchiveInfo {
/// Get the input size without formatting
#[must_use]
pub fn input_size(&self) -> u64 {
self.input_size
}
/// Get the input size in a human readable format
///
/// # Example
///
/// ```
/// use comprexor::ArchiveInfo;
///
/// let archive_data = ArchiveInfo {
/// input_size: 1000,
/// output_size: 1000,
/// ratio: 1.0,
/// };
///
/// assert_eq!(archive_data.input_size_formatted(), "1.0 kB");
/// ```
#[must_use]
pub fn input_size_formatted(&self) -> String {
let formatter = make_format(DECIMAL);
formatter(self.input_size)
}
/// Get the output size without formatting
#[must_use]
pub fn output_size(&self) -> u64 {
self.output_size
}
/// Get the output size in a human readable format
///
/// # Example
///
/// ```
/// use comprexor::ArchiveInfo;
///
/// let archive_data = ArchiveInfo {
/// input_size: 1000,
/// output_size: 1000,
/// ratio: 1.0,
/// };
///
/// assert_eq!(archive_data.output_size_formatted(), "1.0 kB");
/// ```
#[must_use]
pub fn output_size_formatted(&self) -> String {
let formatter = make_format(DECIMAL);
formatter(self.output_size)
}
/// Get the ratio without formatting
#[must_use]
pub fn ratio(&self) -> f64 {
self.ratio
}
/// Get the ratio formatted to the given number of decimals
///
/// # Example
///
/// ```
/// use comprexor::ArchiveInfo;
///
/// let archive_data = ArchiveInfo {
/// input_size: 1000,
/// output_size: 1000,
/// ratio: 1.0,
/// };
///
/// assert_eq!(archive_data.ratio_formatted(5), "1.00000");
/// assert_eq!(archive_data.ratio_formatted(2), "1.00");
/// ```
#[must_use]
pub fn ratio_formatted(&self, num_decimals: u8) -> String {
format!(
"{:.decimals$}",
self.ratio,
decimals = num_decimals as usize
)
}
}
trait ArchiveExt {
fn gen_hashed_name<T>(input: &T) -> String
where
T: std::hash::Hash + fmt::Display,
{
let mut hasher = DefaultHasher::new();
input.hash(&mut hasher);
format!("{}-{}", hasher.finish(), "tar-gen.tar")
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash)]
pub struct Compressor<'a> {
input: &'a str,
output: &'a str,
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash)]
pub struct Extractor<'a> {
input: &'a str,
output: &'a str,
}
impl<'a> ArchiveExt for Compressor<'a> {}
impl<'a> ArchiveExt for Extractor<'a> {}
impl<'a> Extractor<'a> {
#[must_use]
/// Create a new extractor with the given input and output
///
/// # Example
/// ```
/// use comprexor::Extractor;
///
/// let extractor = Extractor::new("./compacted-archive.tar.gz", "./output-folder-or-file");
/// extractor.extract().unwrap();
/// ```
pub fn new(input: &'a str, output: &'a str) -> Extractor<'a> {
Self { input, output }
}
/// Decompress the input file to the output file
///
/// # Example
///
/// ```
/// use comprexor::Extractor;
///
/// let extractor = Extractor::new("./compacted-archive.tar.gz", "./output-folder-or-file");
/// extractor.extract().unwrap();
/// ```
///
/// # Errors
///
/// This function will return an error if the input file is not a valid gzip file or something goes wrong while decompressing
pub fn extract(&self) -> Result<ArchiveInfo, std::io::Error> {
let archive_data = self.extract_internal()?;
Ok(archive_data)
}
fn extract_internal(&self) -> Result<ArchiveInfo, std::io::Error> {
let input_file = BufReader::new(std::fs::File::open(self.input)?);
let input_size = std::fs::metadata(self.input)?.len();
let mut tmpfile = tempfile::tempfile()?;
let mut decoder = flate2::read::GzDecoder::new(input_file);
copy(&mut decoder, &mut tmpfile)?;
tmpfile.seek(SeekFrom::Start(0))?;
let output_size = tmpfile.metadata()?.len();
let mut archive = Archive::new(tmpfile);
archive.unpack(self.output)?;
Ok(ArchiveInfo {
input_size,
output_size,
ratio: output_size as f64 / input_size as f64,
})
}
}
impl<'a> Compressor<'a> {
#[must_use]
/// Creates a new compressor with the given input and output
///
/// # Example
///
/// ```
/// use comprexor::{CompressionLevel, Compressor};
///
/// let compressor = Compressor::new("./folder-or-file-to-compress", "./compacted-archive.tar.gz");
/// compressor.compress(CompressionLevel::Maximum).unwrap();
/// ```
pub fn new(input: &'a str, output: &'a str) -> Compressor<'a> {
Self { input, output }
}
/// Compress the input file or folder to the output location
///
/// You can choose the compression level with the `CompressionLevel` enum
///
/// The compression level can be:
///
/// - `CompressionLevel::None`
/// - `CompressionLevel::Fast`
/// - `CompressionLevel::Default`
/// - `CompressionLevel::Maximum`
/// - `CompressionLevel::Custom` (you can specify the compression level between 0 and 9)
///
/// # Example
///
/// ```
/// use comprexor::{CompressionLevel, Compressor};
///
/// let compressor = Compressor::new("./folder-or-file-to-compress", "./compacted-archive.tar.gz");
/// compressor.compress(CompressionLevel::Maximum).unwrap();
/// ```
///
/// # Errors
///
/// This function will return an error if the input file is not a valid gzip file or something goes wrong while compressing
pub fn compress<T>(&self, level: T) -> Result<ArchiveInfo, std::io::Error>
where
T: AsRef<CompressionLevel>,
{
let archive_data = self.compress_with_tar(level.as_ref())?;
Ok(archive_data)
}
fn compress_with_tar(&self, level: &CompressionLevel) -> Result<ArchiveInfo, std::io::Error> {
let mut tmpfile = NamedTempFile::new()?;
let mut tar = tar::Builder::new(tmpfile.reopen()?);
if std::fs::metadata(self.input)?.is_dir() {
let folder_name = std::path::Path::new(self.input)
.file_name()
.ok_or(std::io::Error::new(
std::io::ErrorKind::Other,
"Could not get file name from input",
))?
.to_str()
.ok_or(std::io::Error::new(
std::io::ErrorKind::Other,
"Could not convert file name to str",
))?;
tar.append_dir_all(folder_name, self.input)?;
} else if std::fs::metadata(self.input)?.is_file()
|| std::fs::metadata(self.input)?.is_symlink()
{
let mut file = std::fs::File::open(self.input)?;
tar.append_file(self.input, &mut file)?;
} else {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Input is neither a file, symlink or a directory",
));
}
tar.finish()?;
tmpfile.seek(SeekFrom::Start(0))?;
let archive_data = self.compress_internal(&mut tmpfile.reopen()?, level)?;
// By closing the `TempPath` explicitly, we can check that it has
// been deleted successfully. If we don't close it explicitly, the
// file will still be deleted when `file` goes out of scope, but we
// won't know whether deleting the file succeeded.
tmpfile.close()?;
Ok(archive_data)
}
fn compress_internal(
&self,
input_file: &mut File,
level: &CompressionLevel,
) -> Result<ArchiveInfo, std::io::Error> {
let input_size = input_file.metadata()?.len();
let output_file = std::fs::File::create(self.output)?;
let mut encoder = GzEncoder::new(
output_file,
level
.try_into()
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?,
);
copy(input_file, &mut encoder)?;
encoder.finish()?;
let output_size = std::fs::metadata(self.output)?.len();
Ok(ArchiveInfo {
input_size,
output_size,
ratio: input_size as f64 / output_size as f64,
})
}
}