使用 Tarballs

解压缩 一个 tarball

flate2-badge tar-badge cat-compression-badge

解压缩(GzDecoder)和提取(Archive::unpack)当前工作目录中的压缩包archive.tar.gz的所有文件,并放在同一位置。

extern crate flate2;
extern crate tar;

use std::fs::File;
use flate2::read::GzDecoder;
use tar::Archive;

fn main() -> Result<(), std::io::Error> {
    let path = "archive.tar.gz";

    let tar_gz = File::open(path)?;
    let tar = GzDecoder::new(tar_gz);
    let mut archive = Archive::new(tar);
    archive.unpack(".")?;

    Ok(())
}

将目录压缩为一个 tarball

flate2-badge tar-badge cat-compression-badge

/var/log目录压缩,为archive.tar.gz

创建一个File,包进GzEncoder,在包入tar::Builder

  • Builder::append_dir_all递归添加/var/log目录中的内容,归档到backup/logs路径下。
  • GzEncoder负责在数据写入archive.tar.gz之前,透明地压缩数据。
extern crate tar;
extern crate flate2;

use std::fs::File;
use flate2::Compression;
use flate2::write::GzEncoder;

fn main() -> Result<(), std::io::Error> {
    let tar_gz = File::create("archive.tar.gz")?;
    let enc = GzEncoder::new(tar_gz, Compression::default());
    let mut tar = tar::Builder::new(enc);
    tar.append_dir_all("backup/logs", "/var/log")?;
    Ok(())
}

从路径中删除前缀时,解压缩一个 tarball

flate2-badge tar-badge cat-compression-badge

迭代Archive::entries。使用Path::strip_prefix删除指定的路径前缀(bundle/logs)。最后,通过Entry::unpack,提取出tar::Entry - 压缩中的项。

# #[macro_use]
# extern crate error_chain;
extern crate flate2;
extern crate tar;

use std::fs::File;
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
#
# error_chain! {
#   foreign_links {
#     Io(std::io::Error);
#     StripPrefixError(::std::path::StripPrefixError);
#   }
# }

fn main() -> Result<()> {
    let file = File::open("archive.tar.gz")?;
    let mut archive = Archive::new(GzDecoder::new(file));
    let prefix = "bundle/logs";

    println!("Extracted the following files:");
    archive
        .entries()?
        .filter_map(|e| e.ok())
        .map(|mut entry| -> Result<PathBuf> {
            let path = entry.path()?.strip_prefix(prefix)?.to_owned();
            entry.unpack(&path)?;
            Ok(path)
        })
        .filter_map(|e| e.ok())
        .for_each(|x| println!("> {}", x.display()));

    Ok(())
}