use std::fs;
use std::io::{Read, Write};
use std::path::Path;
use zip::write::FileOptions;
use zip::ZipWriter;
use crate::manifest::ContentPackManifest;
#[derive(Debug)]
pub enum PackageError {
Io(std::io::Error),
Zip(zip::result::ZipError),
Manifest(toml::de::Error),
InvalidPath(String),
}
impl std::fmt::Display for PackageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(e) => write!(f, "IO: {e}"),
Self::Zip(e) => write!(f, "Zip: {e}"),
Self::Manifest(e) => write!(f, "Manifest: {e}"),
Self::InvalidPath(p) => write!(f, "Invalid path: {p}"),
}
}
}
impl std::error::Error for PackageError {}
impl From<std::io::Error> for PackageError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl From<zip::result::ZipError> for PackageError {
fn from(e: zip::result::ZipError) -> Self {
Self::Zip(e)
}
}
impl From<toml::de::Error> for PackageError {
fn from(e: toml::de::Error) -> Self {
Self::Manifest(e)
}
}
pub struct S2ModPackage {
pub manifest: ContentPackManifest,
}
impl S2ModPackage {
pub fn open(path: &Path) -> Result<Self, PackageError> {
let file = fs::File::open(path)?;
let mut archive = zip::ZipArchive::new(file)?;
let manifest_str = {
let mut file = archive
.by_name("manifest.toml")
.map_err(|_| PackageError::InvalidPath("manifest.toml not found in archive".into()))?;
let mut content = String::new();
std::io::Read::read_to_string(&mut file, &mut content)?;
content
};
let manifest = ContentPackManifest::from_toml(&manifest_str)?;
Ok(S2ModPackage { manifest })
}
pub fn from_dir(path: &Path) -> Result<Self, PackageError> {
let manifest_path = path.join("manifest.toml");
let manifest_str = fs::read_to_string(&manifest_path)?;
let manifest = ContentPackManifest::from_toml(&manifest_str)?;
Ok(S2ModPackage { manifest })
}
pub fn unpack_to_dir(zip_path: &Path, dst_dir: &Path) -> Result<(), PackageError> {
let file = fs::File::open(zip_path)?;
let mut archive = zip::ZipArchive::new(file)?;
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
let outpath = dst_dir.join(entry.mangled_name());
if entry.is_dir() {
fs::create_dir_all(&outpath)?;
} else {
if let Some(parent) = outpath.parent() {
fs::create_dir_all(parent)?;
}
let mut outfile = fs::File::create(&outpath)?;
std::io::copy(&mut entry, &mut outfile)?;
}
}
Ok(())
}
pub fn manifest(&self) -> &ContentPackManifest {
&self.manifest
}
pub fn pack_to_zip(src_dir: &Path, dst_path: &Path) -> Result<(), PackageError> {
let file = fs::File::create(dst_path)?;
let mut zip = ZipWriter::new(file);
if !src_dir.join("manifest.toml").exists() {
return Err(PackageError::InvalidPath(
"manifest.toml not found in source directory".into(),
));
}
Self::add_dir_recursive(&mut zip, src_dir, src_dir)?;
zip.finish()?;
Ok(())
}
pub fn pack_to_dir(src_dir: &Path, dst_dir: &Path) -> Result<(), PackageError> {
if !src_dir.join("manifest.toml").exists() {
return Err(PackageError::InvalidPath(
"manifest.toml not found in source directory".into(),
));
}
copy_dir_recursive(src_dir, dst_dir)?;
Ok(())
}
fn add_dir_recursive(
zip: &mut ZipWriter<fs::File>,
base: &Path,
dir: &Path,
) -> Result<(), PackageError> {
let options: FileOptions<'static, ()> = FileOptions::default()
.compression_method(zip::CompressionMethod::Deflated);
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
Self::add_dir_recursive(zip, base, &path)?;
} else {
let relative = path
.strip_prefix(base)
.map_err(|_| PackageError::InvalidPath("path prefix error".into()))?;
let name = relative.to_string_lossy().replace('\\', "/");
zip.start_file(&name, options)?;
let mut data = Vec::new();
fs::File::open(&path)?.read_to_end(&mut data)?;
zip.write_all(&data)?;
}
}
Ok(())
}
}
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), PackageError> {
fs::create_dir_all(dst)?;
for entry in fs::read_dir(src)? {
let entry = entry?;
let path = entry.path();
let dst_path = dst.join(entry.file_name());
if path.is_dir() {
copy_dir_recursive(&path, &dst_path)?;
} else {
fs::copy(&path, &dst_path)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::manifest::*;
use std::fs;
#[test]
fn test_pack_and_reopen_zip() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
fs::create_dir_all(&src).unwrap();
let mut manifest = ContentPackManifest::new("test-pack", "test-pack");
manifest.pack.version = "0.1.0".to_string();
manifest.pack.description = "Test pack".to_string();
let manifest_toml = manifest.to_toml().unwrap();
fs::write(src.join("manifest.toml"), &manifest_toml).unwrap();
fs::write(src.join("hello.txt"), "world").unwrap();
fs::create_dir_all(src.join("sub")).unwrap();
fs::write(src.join("sub").join("nested.txt"), "nested").unwrap();
let zip_path = tmp.path().join("output.s2mod");
S2ModPackage::pack_to_zip(&src, &zip_path).unwrap();
assert!(zip_path.exists());
let pkg = S2ModPackage::open(&zip_path).unwrap();
assert_eq!(pkg.manifest().pack.name, "test-pack");
}
#[test]
fn test_unpack_to_dir() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
fs::create_dir_all(&src).unwrap();
let manifest = ContentPackManifest::new("unpack-test", "unpack-test");
let manifest_toml = manifest.to_toml().unwrap();
fs::write(src.join("manifest.toml"), &manifest_toml).unwrap();
fs::write(src.join("data.txt"), "hello").unwrap();
fs::create_dir_all(src.join("sub")).unwrap();
fs::write(src.join("sub").join("nested.txt"), "nested").unwrap();
let zip_path = tmp.path().join("test.s2mod");
S2ModPackage::pack_to_zip(&src, &zip_path).unwrap();
let dst = tmp.path().join("unpacked");
S2ModPackage::unpack_to_dir(&zip_path, &dst).unwrap();
assert!(dst.join("manifest.toml").exists(), "manifest");
assert!(dst.join("data.txt").exists(), "data.txt");
assert!(dst.join("sub").join("nested.txt").exists(), "sub/nested.txt");
assert_eq!(fs::read_to_string(dst.join("data.txt")).unwrap(), "hello");
}
#[test]
fn test_pack_to_dir() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
let dst = tmp.path().join("dst");
fs::create_dir_all(&src).unwrap();
let manifest = ContentPackManifest::new("dir-pack", "dir-pack");
let manifest_toml = manifest.to_toml().unwrap();
fs::write(src.join("manifest.toml"), &manifest_toml).unwrap();
fs::write(src.join("data.bin"), b"some bytes").unwrap();
S2ModPackage::pack_to_dir(&src, &dst).unwrap();
assert!(dst.join("manifest.toml").exists());
assert!(dst.join("data.bin").exists());
assert_eq!(fs::read(dst.join("data.bin")).unwrap(), b"some bytes");
let pkg = S2ModPackage::from_dir(&dst).unwrap();
assert_eq!(pkg.manifest().pack.name, "dir-pack");
}
}