Files

46 lines
1.7 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::Write;
use flate2::Compression;
use flate2::write::GzEncoder;
/// A .tar.gz of regular files (path, contents, executable).
pub fn targz(files: &[(&str, &[u8], bool)]) -> Vec<u8> {
let mut b = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::fast()));
for (path, data, exec) in files {
let mut h = tar::Header::new_gnu();
h.set_size(data.len() as u64);
h.set_mode(if *exec { 0o755 } else { 0o644 });
h.set_entry_type(tar::EntryType::Regular);
b.append_data(&mut h, path, *data).unwrap();
}
b.into_inner().unwrap().finish().unwrap()
}
/// A .tar.gz with one raw entry whose name and type the tar crate would not let us write.
pub fn raw_targz(name: &[u8], kind: tar::EntryType, data: &[u8], link: &[u8]) -> Vec<u8> {
let mut h = tar::Header::new_old();
{
let old = h.as_old_mut();
old.name[..name.len()].copy_from_slice(name);
old.linkname[..link.len()].copy_from_slice(link);
}
h.set_size(data.len() as u64);
h.set_mode(0o644);
h.set_entry_type(kind);
h.set_cksum();
let mut tarball = Vec::new();
tarball.extend_from_slice(h.as_bytes());
tarball.extend_from_slice(data);
tarball.resize(tarball.len().div_ceil(512) * 512, 0);
tarball.extend_from_slice(&[0u8; 1024]);
let mut gz = GzEncoder::new(Vec::new(), Compression::fast());
gz.write_all(&tarball).unwrap();
gz.finish().unwrap()
}