file_rotate/
compression.rs

1//! Compression - configuration and implementation
2use flate2::write::GzEncoder;
3use std::{
4    fs::{self, File, OpenOptions},
5    io,
6    path::{Path, PathBuf},
7};
8
9/// Compression mode - when to compress files.
10#[derive(Debug, Clone)]
11pub enum Compression {
12    /// No compression
13    None,
14    /// Look for files to compress when rotating.
15    /// First argument: How many files to keep uncompressed (excluding the original file)
16    OnRotate(usize),
17}
18
19pub(crate) fn compress(path: &Path) -> io::Result<()> {
20    let dest_path = PathBuf::from(format!("{}.gz", path.display()));
21
22    let mut src_file = File::open(path)?;
23    let dest_file = OpenOptions::new()
24        .write(true)
25        .create(true)
26        .append(false)
27        .open(&dest_path)?;
28
29    assert!(path.exists());
30    assert!(dest_path.exists());
31    let mut encoder = GzEncoder::new(dest_file, flate2::Compression::default());
32    io::copy(&mut src_file, &mut encoder)?;
33
34    fs::remove_file(path)?;
35
36    Ok(())
37}