file_rotate/
compression.rs

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
//! Compression - configuration and implementation
use flate2::write::GzEncoder;
use std::{
    fs::{self, File, OpenOptions},
    io,
    path::{Path, PathBuf},
};

/// Compression mode - when to compress files.
#[derive(Debug, Clone)]
pub enum Compression {
    /// No compression
    None,
    /// Look for files to compress when rotating.
    /// First argument: How many files to keep uncompressed (excluding the original file)
    OnRotate(usize),
}

pub(crate) fn compress(path: &Path) -> io::Result<()> {
    let dest_path = PathBuf::from(format!("{}.gz", path.display()));

    let mut src_file = File::open(path)?;
    let dest_file = OpenOptions::new()
        .write(true)
        .create(true)
        .append(false)
        .open(&dest_path)?;

    assert!(path.exists());
    assert!(dest_path.exists());
    let mut encoder = GzEncoder::new(dest_file, flate2::Compression::default());
    io::copy(&mut src_file, &mut encoder)?;

    fs::remove_file(path)?;

    Ok(())
}