Created
April 13, 2022 03:47
-
-
Save sibu-github/699157fae82f3118b1505a92850354c5 to your computer and use it in GitHub Desktop.
Compress & decompress tarball
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use flate2::read::GzDecoder; | |
use flate2::write::GzEncoder; | |
use flate2::Compression; | |
use std::fs::File; | |
use tar::Archive; | |
const TEST_DIR: &str = "test"; | |
const TAR_FILE_NM: &str = "test.tar.gz"; | |
// compress input directory into a _.tar.gz file | |
// compressing and gzip encoding | |
fn compress(input_dir_nm: &str, target_file_nm: &str) -> Result<(), Box<dyn std::error::Error>> { | |
// create target file | |
let target_file = File::create(target_file_nm)?; | |
// create gz encoder | |
let encoder = GzEncoder::new(target_file, Compression::default()); | |
// create tar builder | |
let mut builder = tar::Builder::new(encoder); | |
// append the target directory and all of its content recursively | |
builder.append_dir_all(input_dir_nm, input_dir_nm)?; | |
Ok(()) | |
} | |
// decompress a _.tar.gz file | |
fn decompress(input_file_nm: &str, target_path: &str) -> Result<(), Box<dyn std::error::Error>> { | |
let file = File::open(input_file_nm)?; | |
let decoder = GzDecoder::new(file); | |
let mut archive = Archive::new(decoder); | |
archive.unpack(target_path)?; | |
Ok(()) | |
} | |
fn main() { | |
println!("Starting to compress the directory {TEST_DIR} into {TAR_FILE_NM}"); | |
// compress directory | |
compress(TEST_DIR, TAR_FILE_NM).unwrap(); | |
println!("Starting to decompress the {TAR_FILE_NM}"); | |
// decompress the tar file | |
decompress(TAR_FILE_NM, ".").unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment