s2mod-packer 0.1.0

Pack/unpack .s2mod Content Pack archives for OpenStranded
Documentation
// s2mod-packer – pack/unpack .s2mod Content Pack archives for OpenStranded
// Copyright (C) 2025  s2mod-packer contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! .s2mod package reading and writing.

use std::fs;
use std::io::{Read, Write};
use std::path::Path;

use zip::write::FileOptions;
use zip::ZipWriter;

use crate::manifest::ContentPackManifest;

/// Errors that can occur when working with .s2mod packages
#[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)
    }
}

/// A loaded .s2mod package
pub struct S2ModPackage {
    /// Parsed manifest
    pub manifest: ContentPackManifest,
}

impl S2ModPackage {
    /// Open a .s2mod zip archive and read its manifest
    pub fn open(path: &Path) -> Result<Self, PackageError> {
        let file = fs::File::open(path)?;
        let mut archive = zip::ZipArchive::new(file)?;

        // Read manifest.toml
        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 })
    }

    /// Open a .s2mod from an unpacked directory
    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 })
    }

    /// Extract a .s2mod zip archive into a directory.
    ///
    /// Reads the zip archive at `zip_path` and writes all entries to `dst_dir`.
    /// Uses `mangled_name` to prevent path traversal attacks.
    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(())
    }

    /// Get a reference to the manifest
    pub fn manifest(&self) -> &ContentPackManifest {
        &self.manifest
    }

    // ── Packing ────────────────────────────────────────────

    /// Pack a directory as a .s2mod zip archive.
    ///
    /// `src_dir` must contain a `manifest.toml` and all content files.
    /// The zip is written to `dst_path`.
    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);

        // Verify manifest exists
        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(())
    }

    /// Pack a directory as an unpacked .s2mod directory.
    ///
    /// Copies `src_dir` contents (including `manifest.toml`) to `dst_dir`.
    /// This produces the same content as a .s2mod would contain, just as
    /// a plain directory.
    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(())
    }

    /// Recursively add all files from a directory into a zip archive.
    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(())
    }
}

/// Recursively copy a directory tree.
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() {
        // Create a temporary source directory with manifest.toml + a dummy file
        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();

        // Pack to zip
        let zip_path = tmp.path().join("output.s2mod");
        S2ModPackage::pack_to_zip(&src, &zip_path).unwrap();
        assert!(zip_path.exists());

        // Re-open and verify
        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();

        // Pack to zip
        let zip_path = tmp.path().join("test.s2mod");
        S2ModPackage::pack_to_zip(&src, &zip_path).unwrap();

        // Unpack to directory
        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");

        // Verify it can be opened as a dir package
        let pkg = S2ModPackage::from_dir(&dst).unwrap();
        assert_eq!(pkg.manifest().pack.name, "dir-pack");
    }
}