use anyhow::{Context, Result};
use flate2::{write::GzEncoder, Compression};
use std::fs;
use std::path::PathBuf;
use tar::Builder;
use super::types::{CompileResult, MANIFEST_FILENAME};
pub fn create_package_archive(compile_result: &CompileResult, output: &PathBuf) -> Result<()> {
let output_file = fs::File::create(output)
.with_context(|| format!("Failed to create output file: {:?}", output))?;
let gz_encoder = GzEncoder::new(output_file, Compression::default());
let mut tar_builder = Builder::new(gz_encoder);
let manifest_json = serde_json::to_string_pretty(&compile_result.manifest)
.context("Failed to serialize manifest to JSON")?;
let manifest_bytes = manifest_json.as_bytes();
let mut header = tar::Header::new_gnu();
header.set_size(manifest_bytes.len() as u64);
header.set_cksum();
tar_builder
.append_data(&mut header, MANIFEST_FILENAME, manifest_bytes)
.context("Failed to add manifest.json to archive")?;
let archive_so_path = &compile_result.manifest.library.filename;
tar_builder
.append_file(
archive_so_path,
&mut fs::File::open(&compile_result.so_path)?,
)
.context("Failed to add .so file to archive")?;
tar_builder
.finish()
.context("Failed to finalize package archive")?;
Ok(())
}