fn make_package_json(wm_class: &Option<String>) -> String {
if let Some(wm_class) = wm_class {
format!(r#"{{"main": "index.js", "name": "{wm_class}"}}"#)
} else {
r#"{"main": "index.js"}"#.to_string()
}
}
#[derive(Debug, Default)]
pub struct Asar {
pub id: String,
pub template: String,
pub wm_class: Option<String>,
pub mod_entrypoint: String,
pub profile_dir: Option<String>,
}
impl Asar {
pub fn new() -> Self {
Self::default()
}
pub fn get_path(&self) -> Option<std::path::PathBuf> {
(!self.id.is_empty()).then(|| crate::paths::asar_cache_path(&self.id))
}
#[cfg(feature = "uuid")]
pub fn with_uuid(mut self) -> Self {
self.id = uuid::Uuid::new_v4().to_string();
std::env::set_var("MODLOADER_ASAR_ID", self.id.clone());
self
}
pub fn with_id(mut self, id: &str) -> Self {
self.id = id.to_string();
std::env::set_var("MODLOADER_ASAR_ID", id);
self
}
pub fn with_template(mut self, template: &str) -> Self {
self.template = template.to_string();
self
}
pub fn with_mod_entrypoint(mut self, mod_entrypoint: &str) -> Self {
self.mod_entrypoint = mod_entrypoint.to_string();
std::env::set_var("MODLOADER_MOD_ENTRYPOINT", mod_entrypoint);
self
}
pub fn with_wm_class(mut self, wm_class: &str) -> Self {
self.wm_class = Some(wm_class.to_string());
std::env::set_var("MODLOADER_WM_CLASS", wm_class);
self
}
pub fn with_profile_dir(mut self, profile_dir: &str) -> Self {
self.profile_dir = Some(profile_dir.to_string());
std::env::set_var("MODLOADER_PROFILE_DIR", profile_dir);
self
}
pub fn create(&self) -> Result<std::path::PathBuf, String> {
use crate::paths::asar_cache_path;
let asar_path = asar_cache_path(&self.id);
let mut asar = asar::AsarWriter::new();
asar.write_file("index.js", self.template.clone(), false)
.map_err(|e| format!("Failed to write index.js: {e}"))?;
asar.write_file("package.json", make_package_json(&self.wm_class), false)
.map_err(|e| format!("Failed to write package.json: {e}"))?;
let file = std::fs::File::create(&asar_path)
.map_err(|e| format!("Failed to create file at {}: {e}", asar_path.display()))?;
asar.finalize(file)
.map_err(|e| format!("Failed to write asar to disk with error: {e}"))?;
Ok(asar_path)
}
}