Replace in-place compression

Compress gzip files to a temporary file first and then do an atomic
rename.
This commit is contained in:
KARASZI István 2021-01-07 16:50:13 +01:00
parent fa40c6e3d4
commit 956adfc90a
3 changed files with 12 additions and 2 deletions

View file

@ -1,19 +1,27 @@
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use std::fs::{create_dir_all, File};
use std::fs::{create_dir_all, rename, File};
use std::path::Path;
use tar::{Builder, Archive};
use uuid::Uuid;
use crate::error::Error;
pub fn to_tar_gz(src: &Path, dest: &Path) -> Result<(), Error> {
let f = File::create(dest)?;
let file_name = format!(".{}", Uuid::new_v4().to_urn());
let p = dest.with_file_name(file_name);
let tmp_dest = p.as_path();
let f = File::create(tmp_dest)?;
let gz_encoder = GzEncoder::new(f, Compression::default());
let mut tar_encoder = Builder::new(gz_encoder);
tar_encoder.append_dir_all(".", src)?;
let gz_encoder = tar_encoder.into_inner()?;
gz_encoder.finish()?;
rename(tmp_dest, dest)?;
Ok(())
}