use crate::unpack::media_types;
use std::io;
use std::path::Path;
pub const DEFAULT_ZSTD_LEVEL: i32 = 3;
pub fn pack_files_tar_zstd(
root: &Path,
files: &[&str],
level: i32,
) -> io::Result<(Vec<u8>, String)> {
let encoder = zstd::stream::write::Encoder::new(Vec::new(), level)?;
let mut builder = tar::Builder::new(encoder);
for name in files {
let path = root.join(name);
let mut f = std::fs::File::open(&path).map_err(|e| {
io::Error::new(
e.kind(),
format!("open {} for packing: {e}", path.display()),
)
})?;
builder
.append_file(name, &mut f)
.map_err(|e| io::Error::other(format!("append {} to layer: {e}", path.display())))?;
}
let encoder = builder
.into_inner()
.map_err(|e| io::Error::other(format!("finalize tar: {e}")))?;
let compressed = encoder
.finish()
.map_err(|e| io::Error::other(format!("finalize zstd: {e}")))?;
Ok((compressed, media_types::TAR_ZSTD.to_string()))
}
pub fn pack_dir_tar_zstd(
root: &Path,
exclude_top: &[&str],
level: i32,
) -> io::Result<(Vec<u8>, String)> {
let encoder = zstd::stream::write::Encoder::new(Vec::new(), level)?;
let mut builder = tar::Builder::new(encoder);
builder.follow_symlinks(false);
for entry in sorted_dir_entries(root)? {
let name = entry.file_name();
if name.to_str().is_some_and(|n| exclude_top.contains(&n)) {
continue;
}
append_tree(&mut builder, &entry.path(), Path::new(&name))?;
}
let encoder = builder
.into_inner()
.map_err(|e| io::Error::other(format!("finalize tar: {e}")))?;
let compressed = encoder
.finish()
.map_err(|e| io::Error::other(format!("finalize zstd: {e}")))?;
Ok((compressed, media_types::TAR_ZSTD.to_string()))
}
fn sorted_dir_entries(dir: &Path) -> io::Result<Vec<std::fs::DirEntry>> {
let mut entries = std::fs::read_dir(dir)
.map_err(|e| {
io::Error::new(
e.kind(),
format!("read dir {} for packing: {e}", dir.display()),
)
})?
.collect::<io::Result<Vec<_>>>()
.map_err(|e| {
io::Error::new(
e.kind(),
format!("read dir entry in {} for packing: {e}", dir.display()),
)
})?;
entries.sort_by_key(std::fs::DirEntry::file_name);
Ok(entries)
}
fn append_tree<W: io::Write>(
builder: &mut tar::Builder<W>,
path: &Path,
rel: &Path,
) -> io::Result<()> {
let meta = std::fs::symlink_metadata(path).map_err(|e| {
io::Error::new(
e.kind(),
format!("stat {} for packing: {e}", path.display()),
)
})?;
builder
.append_path_with_name(path, rel)
.map_err(|e| io::Error::other(format!("append {} to layer: {e}", path.display())))?;
if meta.is_dir() {
for entry in sorted_dir_entries(path)? {
let name = entry.file_name();
append_tree(builder, &entry.path(), &rel.join(&name))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::unpack::LayerUnpacker;
#[tokio::test]
async fn pack_then_unpack_roundtrips_files_flat() {
let src = tempfile::tempdir().unwrap();
std::fs::write(src.path().join("disk.img"), b"DISK-CONTENT").unwrap();
std::fs::write(src.path().join("hardware-model.bin"), b"HWMODEL").unwrap();
std::fs::write(src.path().join("aux.img"), b"AUXDATA").unwrap();
let (bytes, media_type) = pack_files_tar_zstd(
src.path(),
&["disk.img", "hardware-model.bin", "aux.img"],
DEFAULT_ZSTD_LEVEL,
)
.unwrap();
assert_eq!(media_type, media_types::TAR_ZSTD);
assert!(!bytes.is_empty());
let out = tempfile::tempdir().unwrap();
let mut unpacker = LayerUnpacker::new(out.path().to_path_buf());
unpacker
.unpack_layers(&[(bytes, media_type)])
.await
.unwrap();
assert_eq!(
std::fs::read(out.path().join("disk.img")).unwrap(),
b"DISK-CONTENT"
);
assert_eq!(
std::fs::read(out.path().join("hardware-model.bin")).unwrap(),
b"HWMODEL"
);
assert_eq!(
std::fs::read(out.path().join("aux.img")).unwrap(),
b"AUXDATA"
);
}
#[test]
fn missing_file_is_an_error() {
let src = tempfile::tempdir().unwrap();
let err = pack_files_tar_zstd(src.path(), &["nope.img"], DEFAULT_ZSTD_LEVEL).unwrap_err();
assert!(err.to_string().contains("nope.img"));
}
#[cfg(unix)]
fn build_fixture_tree(root: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
std::fs::write(root.join("real"), b"REAL-TOOL-BYTES").unwrap();
std::fs::create_dir(root.join("bin")).unwrap();
std::fs::write(root.join("bin/runme"), b"#!/bin/sh\nexit 0\n").unwrap();
std::fs::set_permissions(
root.join("bin/runme"),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
std::fs::create_dir_all(root.join("nested/inner")).unwrap();
std::fs::write(root.join("nested/inner/data.txt"), b"nested-data").unwrap();
std::fs::write(root.join("nested/.ready"), b"not-top-level").unwrap();
std::fs::create_dir(root.join("emptydir")).unwrap();
std::fs::create_dir(root.join("opt")).unwrap();
std::os::unix::fs::symlink("../real", root.join("opt/tool")).unwrap();
std::os::unix::fs::symlink("/abs/target/file", root.join("abslink")).unwrap();
std::fs::create_dir(root.join(".build")).unwrap();
std::fs::write(root.join(".build/stamp"), b"stamp").unwrap();
std::fs::write(root.join(".ready"), b"ready").unwrap();
}
#[cfg(unix)]
#[tokio::test]
async fn pack_dir_then_unpack_roundtrips_tree() {
use std::os::unix::fs::PermissionsExt;
let src = tempfile::tempdir().unwrap();
build_fixture_tree(src.path());
let (bytes, media_type) =
pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();
assert_eq!(media_type, media_types::TAR_ZSTD);
assert!(!bytes.is_empty());
let out = tempfile::tempdir().unwrap();
let mut unpacker = LayerUnpacker::new(out.path().to_path_buf());
unpacker
.unpack_layers(&[(bytes, media_type)])
.await
.unwrap();
assert_eq!(
std::fs::read(out.path().join("real")).unwrap(),
b"REAL-TOOL-BYTES"
);
assert_eq!(
std::fs::read(out.path().join("bin/runme")).unwrap(),
b"#!/bin/sh\nexit 0\n"
);
assert_eq!(
std::fs::read(out.path().join("nested/inner/data.txt")).unwrap(),
b"nested-data"
);
let mode = std::fs::metadata(out.path().join("bin/runme"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o755, "exec bits lost: {mode:o}");
let tool = out.path().join("opt/tool");
assert!(std::fs::symlink_metadata(&tool).unwrap().is_symlink());
assert_eq!(
std::fs::read_link(&tool).unwrap(),
std::path::PathBuf::from("../real")
);
let abslink = out.path().join("abslink");
assert!(std::fs::symlink_metadata(&abslink).unwrap().is_symlink());
assert_eq!(
std::fs::read_link(&abslink).unwrap(),
std::path::PathBuf::from("abs/target/file")
);
assert!(!out.path().join(".build").exists());
assert!(!out.path().join(".ready").exists());
assert_eq!(
std::fs::read(out.path().join("nested/.ready")).unwrap(),
b"not-top-level"
);
assert!(out.path().join("emptydir").is_dir());
}
#[cfg(unix)]
#[test]
fn pack_dir_stores_verbatim_symlink_targets_and_relative_names() {
use std::path::{Path, PathBuf};
let src = tempfile::tempdir().unwrap();
build_fixture_tree(src.path());
let (bytes, _) =
pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();
let decoder = zstd::stream::read::Decoder::new(std::io::Cursor::new(&bytes[..])).unwrap();
let mut archive = tar::Archive::new(decoder);
let mut names: Vec<PathBuf> = Vec::new();
let mut abs_target: Option<PathBuf> = None;
let mut rel_target: Option<PathBuf> = None;
for entry in archive.entries().unwrap() {
let entry = entry.unwrap();
let path = entry.path().unwrap().to_path_buf();
assert!(
!path.to_string_lossy().starts_with("./") && path.is_relative(),
"entry not plain-relative: {}",
path.display()
);
if path == Path::new("abslink") {
assert_eq!(entry.header().entry_type(), tar::EntryType::Symlink);
abs_target = entry.link_name().unwrap().map(|t| t.to_path_buf());
}
if path == Path::new("opt/tool") {
assert_eq!(entry.header().entry_type(), tar::EntryType::Symlink);
rel_target = entry.link_name().unwrap().map(|t| t.to_path_buf());
}
names.push(path);
}
assert_eq!(abs_target.unwrap(), PathBuf::from("/abs/target/file"));
assert_eq!(rel_target.unwrap(), PathBuf::from("../real"));
assert!(names.contains(&PathBuf::from("emptydir")));
assert!(!names.iter().any(|p| p.starts_with(".build")));
assert!(!names.contains(&PathBuf::from(".ready")));
assert!(names.contains(&PathBuf::from("nested/.ready")));
}
#[cfg(unix)]
#[test]
fn pack_dir_digest_is_deterministic() {
use sha2::{Digest, Sha256};
let src = tempfile::tempdir().unwrap();
build_fixture_tree(src.path());
let (first, _) =
pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();
let (second, _) =
pack_dir_tar_zstd(src.path(), &[".build", ".ready"], DEFAULT_ZSTD_LEVEL).unwrap();
assert_eq!(
hex::encode(Sha256::digest(&first)),
hex::encode(Sha256::digest(&second)),
"packing the same tree twice must yield an identical digest"
);
assert_eq!(first, second);
}
#[test]
fn pack_dir_missing_root_is_an_error() {
let src = tempfile::tempdir().unwrap();
let missing = src.path().join("does-not-exist");
let err = pack_dir_tar_zstd(&missing, &[], DEFAULT_ZSTD_LEVEL).unwrap_err();
assert!(err.to_string().contains("does-not-exist"));
}
}