refactor: upgrade crates and restructure project
This commit is contained in:
1 parent
ea093c044f
commit
47dad69321
80 files changed
+6094
-6125
No files matched your search
@@ -0,0 +1,51 @@
|
||||
pub mod mods;
|
||||
pub mod resource_packs;
|
||||
pub mod shaders;
|
||||
pub mod worlds;
|
||||
|
||||
pub use mods::{scan_mods, toggle_entry, ContentEntry};
|
||||
pub use resource_packs::scan_resource_packs;
|
||||
pub use shaders::scan_shaders;
|
||||
pub use worlds::scan_worlds;
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
/// Determine enabled/disabled state and file stem from a filename.
|
||||
///
|
||||
/// Given the file extension (e.g. ".jar", ".zip") and the file name, returns
|
||||
/// `Some((enabled, file_stem))` or `None` if the file doesn't match.
|
||||
pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> {
|
||||
let disabled_ext = format!("{ext}.disabled");
|
||||
if let Some(stem) = file_name.strip_suffix(&disabled_ext) {
|
||||
Some((false, stem.to_string()))
|
||||
} else if let Some(stem) = file_name.strip_suffix(ext) {
|
||||
Some((true, stem.to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// For directories: check if the name ends in `.disabled`.
|
||||
pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
|
||||
if let Some(stem) = file_name.strip_suffix(".disabled") {
|
||||
(false, stem.to_string())
|
||||
} else {
|
||||
(true, file_name.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read icon bytes from a zip archive (pack.png).
|
||||
pub(crate) fn read_icon_from_zip(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<Vec<u8>> {
|
||||
let mut entry = archive.by_name("pack.png").ok()?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf).ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
/// Open a zip file and return the archive handle.
|
||||
pub(crate) fn open_zip(path: &std::path::Path) -> Option<zip::ZipArchive<std::fs::File>> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
zip::ZipArchive::new(file).ok()
|
||||
}
|
||||
@@ -3,10 +3,20 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
type IconCell = (u8, u8, u8, u8, u8, u8);
|
||||
/// A single icon cell representing two vertically stacked pixels using the "▄" half-block.
|
||||
/// `bg_*` = top pixel (background color), `fg_*` = bottom pixel (foreground color).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct IconCell {
|
||||
pub bg_r: u8,
|
||||
pub bg_g: u8,
|
||||
pub bg_b: u8,
|
||||
pub fg_r: u8,
|
||||
pub fg_g: u8,
|
||||
pub fg_b: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ModEntry {
|
||||
pub struct ContentEntry {
|
||||
pub file_stem: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
@@ -19,14 +29,28 @@ pub struct ModEntry {
|
||||
#[derive(Deserialize, Default)]
|
||||
struct FabricModJson {
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
description: String,
|
||||
#[serde(default)]
|
||||
pub icon: String,
|
||||
icon: serde_json::Value,
|
||||
}
|
||||
|
||||
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
impl FabricModJson {
|
||||
fn icon_path(&self) -> String {
|
||||
match &self.icon {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
serde_json::Value::Object(map) => map
|
||||
.values()
|
||||
.find_map(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let mods_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
@@ -46,25 +70,20 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let (enabled, file_stem) = if file_name.ends_with(".jar") {
|
||||
(true, file_name.trim_end_matches(".jar").to_string())
|
||||
} else if file_name.ends_with(".jar.disabled") {
|
||||
(
|
||||
false,
|
||||
file_name.trim_end_matches(".jar.disabled").to_string(),
|
||||
)
|
||||
} else {
|
||||
let Some((enabled, file_stem)) = super::parse_enabled_stem(&file_name, ".jar") else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let (name, description, icon_bytes) = read_mod_metadata(&path);
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||
.or_else(|| Some(fallback_icon()));
|
||||
|
||||
entries.push(ModEntry {
|
||||
file_stem: file_stem.clone(),
|
||||
name: if name.is_empty() { file_stem } else { name },
|
||||
let display_name = if name.is_empty() { file_stem.clone() } else { name };
|
||||
entries.push(ContentEntry {
|
||||
file_stem,
|
||||
name: display_name,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
@@ -73,7 +92,7 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
});
|
||||
}
|
||||
|
||||
entries.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
entries
|
||||
}
|
||||
|
||||
@@ -104,9 +123,49 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
||||
fn read_fabric_meta(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String)> {
|
||||
let entry = archive.by_name("fabric.mod.json").ok()?;
|
||||
let data: FabricModJson = serde_json::from_reader(entry).ok()?;
|
||||
Some((data.name, data.description, data.icon))
|
||||
let mut entry = archive.by_name("fabric.mod.json").ok()?;
|
||||
let mut raw = String::new();
|
||||
entry.read_to_string(&mut raw).ok()?;
|
||||
// Some mods have literal newlines in JSON strings — sanitize them
|
||||
let sanitized = sanitize_json_strings(&raw);
|
||||
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
|
||||
let icon = data.icon_path();
|
||||
Some((data.name, data.description, icon))
|
||||
}
|
||||
|
||||
/// Replace literal control characters inside JSON string values with escaped versions.
|
||||
fn sanitize_json_strings(input: &str) -> String {
|
||||
let mut result = String::with_capacity(input.len());
|
||||
let mut in_string = false;
|
||||
let mut escape_next = false;
|
||||
|
||||
for ch in input.chars() {
|
||||
if escape_next {
|
||||
result.push(ch);
|
||||
escape_next = false;
|
||||
continue;
|
||||
}
|
||||
if ch == '\\' && in_string {
|
||||
result.push(ch);
|
||||
escape_next = true;
|
||||
continue;
|
||||
}
|
||||
if ch == '"' {
|
||||
in_string = !in_string;
|
||||
result.push(ch);
|
||||
continue;
|
||||
}
|
||||
if in_string && ch == '\n' {
|
||||
result.push_str("\\n");
|
||||
} else if in_string && ch == '\r' {
|
||||
result.push_str("\\r");
|
||||
} else if in_string && ch == '\t' {
|
||||
result.push_str("\\t");
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
|
||||
@@ -137,7 +196,7 @@ pub(crate) fn make_icon_pixels(
|
||||
let bottom_y = (u32::from(row) * 2 + 1).min(rgb.height().saturating_sub(1));
|
||||
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
|
||||
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
|
||||
cols.push((br, bg, bb, tr, tg, tb));
|
||||
cols.push(IconCell { bg_r: br, bg_g: bg, bg_b: bb, fg_r: tr, fg_g: tg, fg_b: tb });
|
||||
}
|
||||
rows.push(cols);
|
||||
}
|
||||
@@ -145,7 +204,19 @@ pub(crate) fn make_icon_pixels(
|
||||
Some(rows)
|
||||
}
|
||||
|
||||
pub fn toggle_mod(entry: &ModEntry) -> Result<(), std::io::Error> {
|
||||
/// 6x3 fallback icon showing a "?" pattern for mods without icons.
|
||||
fn fallback_icon() -> Vec<Vec<IconCell>> {
|
||||
let b = IconCell { bg_r: 50, bg_g: 50, bg_b: 50, fg_r: 50, fg_g: 50, fg_b: 50 };
|
||||
let tb = IconCell { bg_r: 50, bg_g: 50, bg_b: 50, fg_r: 130, fg_g: 130, fg_b: 130 };
|
||||
let bt = IconCell { bg_r: 130, bg_g: 130, bg_b: 130, fg_r: 50, fg_g: 50, fg_b: 50 };
|
||||
vec![
|
||||
vec![b, tb, tb, tb, tb, b],
|
||||
vec![b, b, b, bt, bt, b],
|
||||
vec![b, b, bt, bt, b, b],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
||||
let file_name = match entry.path.file_name().and_then(|name| name.to_str()) {
|
||||
Some(name) => name,
|
||||
None => return Ok(()),
|
||||
@@ -234,13 +305,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_mod_enable() {
|
||||
fn toggle_entry_enable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let disabled_path = dir.join("mymod.jar.disabled");
|
||||
std::fs::write(&disabled_path, b"PK\x03\x04").unwrap();
|
||||
|
||||
let entry = ModEntry {
|
||||
let entry = ContentEntry {
|
||||
file_stem: "mymod".to_string(),
|
||||
name: "mymod".to_string(),
|
||||
description: String::new(),
|
||||
@@ -250,19 +321,19 @@ mod tests {
|
||||
icon_lines: None,
|
||||
};
|
||||
|
||||
toggle_mod(&entry).unwrap();
|
||||
toggle_entry(&entry).unwrap();
|
||||
assert!(!disabled_path.exists());
|
||||
assert!(dir.join("mymod.jar").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_mod_disable() {
|
||||
fn toggle_entry_disable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let enabled_path = dir.join("mymod.jar");
|
||||
std::fs::write(&enabled_path, b"PK\x03\x04").unwrap();
|
||||
|
||||
let entry = ModEntry {
|
||||
let entry = ContentEntry {
|
||||
file_stem: "mymod".to_string(),
|
||||
name: "mymod".to_string(),
|
||||
description: String::new(),
|
||||
@@ -272,7 +343,7 @@ mod tests {
|
||||
icon_lines: None,
|
||||
};
|
||||
|
||||
toggle_mod(&entry).unwrap();
|
||||
toggle_entry(&entry).unwrap();
|
||||
assert!(!enabled_path.exists());
|
||||
assert!(dir.join("mymod.jar.disabled").exists());
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::mods::{make_icon_pixels, ModEntry};
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub(crate) struct PackMcMeta {
|
||||
@@ -38,7 +37,7 @@ pub(crate) fn extract_description(value: &serde_json::Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let packs_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
@@ -60,18 +59,9 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Mod
|
||||
|
||||
let is_dir = path.is_dir();
|
||||
let (enabled, file_stem) = if is_dir {
|
||||
if file_name.ends_with(".disabled") {
|
||||
(false, file_name.trim_end_matches(".disabled").to_string())
|
||||
} else {
|
||||
(true, file_name.clone())
|
||||
}
|
||||
} else if file_name.ends_with(".zip") {
|
||||
(true, file_name.trim_end_matches(".zip").to_string())
|
||||
} else if file_name.ends_with(".zip.disabled") {
|
||||
(
|
||||
false,
|
||||
file_name.trim_end_matches(".zip.disabled").to_string(),
|
||||
)
|
||||
super::parse_enabled_stem_dir(&file_name)
|
||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||
pair
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
@@ -86,9 +76,10 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Mod
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
|
||||
|
||||
entries.push(ModEntry {
|
||||
file_stem: file_stem.clone(),
|
||||
name: if name.is_empty() { file_stem } else { name },
|
||||
let display_name = if name.is_empty() { file_stem.clone() } else { name };
|
||||
entries.push(ContentEntry {
|
||||
file_stem,
|
||||
name: display_name,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
@@ -97,72 +88,36 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Mod
|
||||
});
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
entries
|
||||
}
|
||||
|
||||
fn read_pack_metadata_from_zip(zip_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
||||
let file = match std::fs::File::open(zip_path) {
|
||||
Ok(f) => f,
|
||||
Err(_) => return (String::new(), String::new(), None),
|
||||
let Some(mut archive) = super::open_zip(zip_path) else {
|
||||
return (String::new(), String::new(), None);
|
||||
};
|
||||
|
||||
let mut archive = match zip::ZipArchive::new(file) {
|
||||
Ok(a) => a,
|
||||
Err(_) => return (String::new(), String::new(), None),
|
||||
};
|
||||
|
||||
let description = read_pack_description(&mut archive);
|
||||
|
||||
let icon_bytes = {
|
||||
let mut buf = Vec::new();
|
||||
match archive.by_name("pack.png") {
|
||||
Ok(mut entry) => {
|
||||
if entry.read_to_end(&mut buf).is_ok() {
|
||||
Some(buf)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
};
|
||||
|
||||
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
||||
(String::new(), description, icon_bytes)
|
||||
}
|
||||
|
||||
fn read_pack_description(archive: &mut zip::ZipArchive<std::fs::File>) -> String {
|
||||
let entry = match archive.by_name("pack.mcmeta") {
|
||||
Ok(e) => e,
|
||||
Err(_) => return String::new(),
|
||||
};
|
||||
|
||||
let meta: PackMcMeta = match serde_json::from_reader(entry) {
|
||||
Ok(m) => m,
|
||||
Err(_) => return String::new(),
|
||||
};
|
||||
|
||||
extract_description(&meta.pack.description)
|
||||
archive
|
||||
.by_name("pack.mcmeta")
|
||||
.ok()
|
||||
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
||||
.map(|meta| extract_description(&meta.pack.description))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option<Vec<u8>>) {
|
||||
let actual_dir = dir.to_path_buf();
|
||||
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
|
||||
.ok()
|
||||
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
||||
.map(|meta| extract_description(&meta.pack.description))
|
||||
.unwrap_or_default();
|
||||
|
||||
let description = {
|
||||
let mcmeta_path = actual_dir.join("pack.mcmeta");
|
||||
match std::fs::read_to_string(&mcmeta_path) {
|
||||
Ok(content) => match serde_json::from_str::<PackMcMeta>(&content) {
|
||||
Ok(meta) => extract_description(&meta.pack.description),
|
||||
Err(_) => String::new(),
|
||||
},
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
};
|
||||
|
||||
let icon_bytes = {
|
||||
let icon_path = actual_dir.join("pack.png");
|
||||
std::fs::read(&icon_path).ok()
|
||||
};
|
||||
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
|
||||
|
||||
(String::new(), description, icon_bytes)
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use super::mods::{make_icon_pixels, ModEntry};
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
use super::resource_packs::{extract_description, PackMcMeta};
|
||||
|
||||
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let shaders_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
@@ -26,18 +25,9 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry>
|
||||
|
||||
let is_dir = path.is_dir();
|
||||
let (enabled, file_stem) = if is_dir {
|
||||
if file_name.ends_with(".disabled") {
|
||||
(false, file_name.trim_end_matches(".disabled").to_string())
|
||||
} else {
|
||||
(true, file_name.clone())
|
||||
}
|
||||
} else if file_name.ends_with(".zip") {
|
||||
(true, file_name.trim_end_matches(".zip").to_string())
|
||||
} else if file_name.ends_with(".zip.disabled") {
|
||||
(
|
||||
false,
|
||||
file_name.trim_end_matches(".zip.disabled").to_string(),
|
||||
)
|
||||
super::parse_enabled_stem_dir(&file_name)
|
||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||
pair
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
@@ -52,9 +42,9 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry>
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
|
||||
|
||||
entries.push(ModEntry {
|
||||
file_stem: file_stem.clone(),
|
||||
name: file_stem,
|
||||
entries.push(ContentEntry {
|
||||
name: file_stem.clone(),
|
||||
file_stem,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
@@ -63,54 +53,30 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry>
|
||||
});
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
entries
|
||||
}
|
||||
|
||||
fn read_shader_metadata_from_zip(zip_path: &Path) -> (String, Option<Vec<u8>>) {
|
||||
let file = match std::fs::File::open(zip_path) {
|
||||
Ok(f) => f,
|
||||
Err(_) => return (String::new(), None),
|
||||
let Some(mut archive) = super::open_zip(zip_path) else {
|
||||
return (String::new(), None);
|
||||
};
|
||||
|
||||
let mut archive = match zip::ZipArchive::new(file) {
|
||||
Ok(a) => a,
|
||||
Err(_) => return (String::new(), None),
|
||||
};
|
||||
|
||||
let description = match archive.by_name("pack.mcmeta") {
|
||||
Ok(entry) => match serde_json::from_reader::<_, PackMcMeta>(entry) {
|
||||
Ok(meta) => extract_description(&meta.pack.description),
|
||||
Err(_) => String::new(),
|
||||
},
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
|
||||
let icon_bytes = {
|
||||
let mut buf = Vec::new();
|
||||
match archive.by_name("pack.png") {
|
||||
Ok(mut entry) => {
|
||||
if entry.read_to_end(&mut buf).is_ok() {
|
||||
Some(buf)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
};
|
||||
|
||||
let description = archive
|
||||
.by_name("pack.mcmeta")
|
||||
.ok()
|
||||
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
||||
.map(|meta| extract_description(&meta.pack.description))
|
||||
.unwrap_or_default();
|
||||
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
||||
(description, icon_bytes)
|
||||
}
|
||||
|
||||
fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
|
||||
let description = match std::fs::read_to_string(dir.join("pack.mcmeta")) {
|
||||
Ok(content) => match serde_json::from_str::<PackMcMeta>(&content) {
|
||||
Ok(meta) => extract_description(&meta.pack.description),
|
||||
Err(_) => String::new(),
|
||||
},
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
|
||||
.ok()
|
||||
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
||||
.map(|meta| extract_description(&meta.pack.description))
|
||||
.unwrap_or_default();
|
||||
|
||||
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use std::path::Path;
|
||||
|
||||
use super::mods::{make_icon_pixels, ModEntry};
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
|
||||
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let saves_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
@@ -26,21 +26,19 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let (enabled, file_stem) = if file_name.ends_with(".disabled") {
|
||||
(false, file_name.trim_end_matches(".disabled").to_string())
|
||||
} else {
|
||||
(true, file_name.clone())
|
||||
};
|
||||
let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name);
|
||||
|
||||
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 12, 6));
|
||||
|
||||
entries.push(ModEntry {
|
||||
file_stem: file_stem.clone(),
|
||||
name: file_stem,
|
||||
description: String::new(),
|
||||
let description = world_description(&path);
|
||||
|
||||
entries.push(ContentEntry {
|
||||
name: file_stem.clone(),
|
||||
file_stem,
|
||||
description,
|
||||
enabled,
|
||||
icon_bytes,
|
||||
path,
|
||||
@@ -48,10 +46,85 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
|
||||
});
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||
entries
|
||||
}
|
||||
|
||||
fn world_description(world_dir: &Path) -> String {
|
||||
let level_dat = world_dir.join("level.dat");
|
||||
|
||||
let created = world_dir
|
||||
.metadata()
|
||||
.ok()
|
||||
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs());
|
||||
|
||||
let modified = level_dat
|
||||
.metadata()
|
||||
.ok()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs());
|
||||
|
||||
let dir_size = dir_size_approx(world_dir);
|
||||
|
||||
let mut lines = Vec::new();
|
||||
|
||||
if let Some(secs) = created {
|
||||
if let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
||||
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(secs) = modified {
|
||||
if let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
||||
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
}
|
||||
|
||||
if dir_size > 0 {
|
||||
lines.push(format!("Size: {}", format_size(dir_size)));
|
||||
}
|
||||
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn dir_size_approx(path: &Path) -> u64 {
|
||||
let mut total = 0u64;
|
||||
if let Ok(rd) = std::fs::read_dir(path) {
|
||||
for entry in rd.flatten() {
|
||||
if let Ok(meta) = entry.metadata() {
|
||||
if meta.is_file() {
|
||||
total += meta.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check region folder too (main chunk data)
|
||||
let region = path.join("region");
|
||||
if let Ok(rd) = std::fs::read_dir(region) {
|
||||
for entry in rd.flatten() {
|
||||
if let Ok(meta) = entry.metadata() {
|
||||
total += meta.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn format_size(bytes: u64) -> String {
|
||||
if bytes < 1024 {
|
||||
format!("{} B", bytes)
|
||||
} else if bytes < 1024 * 1024 {
|
||||
format!("{:.1} KB", bytes as f64 / 1024.0)
|
||||
} else if bytes < 1024 * 1024 * 1024 {
|
||||
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
|
||||
} else {
|
||||
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
+99
-15
@@ -2,17 +2,38 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::instance::models::InstanceConfig;
|
||||
|
||||
const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.png");
|
||||
const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.svg");
|
||||
|
||||
pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
||||
dirs_next::data_dir().map(|d| {
|
||||
d.join("applications")
|
||||
.join(format!("mcl-{}.desktop", sanitize(name)))
|
||||
})
|
||||
let sanitized = sanitize(name);
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
dirs_next::data_dir().map(|d| {
|
||||
d.join("applications")
|
||||
.join(format!("mcl-{sanitized}.desktop"))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.bat")))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.command")))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
let _ = sanitized;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn icon_path() -> Option<PathBuf> {
|
||||
dirs_next::data_dir().map(|d| d.join("mcl").join("icon.png"))
|
||||
dirs_next::data_dir().map(|d| d.join("mcl").join("icon.svg"))
|
||||
}
|
||||
|
||||
fn ensure_icon() -> Option<PathBuf> {
|
||||
@@ -38,7 +59,7 @@ pub fn exists(name: &str) -> bool {
|
||||
|
||||
pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
||||
let path = desktop_path(&config.name)
|
||||
.ok_or_else(|| std::io::Error::other("cannot resolve data directory"))?;
|
||||
.ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?;
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
@@ -47,6 +68,14 @@ pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
||||
let icon = ensure_icon();
|
||||
let content = build_content(&config.name, icon.as_deref());
|
||||
std::fs::write(&path, content)?;
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let perms = std::fs::Permissions::from_mode(0o755);
|
||||
std::fs::set_permissions(&path, perms)?;
|
||||
}
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -80,6 +109,32 @@ pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()
|
||||
}
|
||||
|
||||
fn build_content(name: &str, icon: Option<&Path>) -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
build_linux_desktop(name, icon)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = icon;
|
||||
build_windows_shortcut(name)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = icon;
|
||||
build_macos_command(name)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
let _ = (name, icon);
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("[Desktop Entry]\n");
|
||||
out.push_str("Version=1.0\n");
|
||||
@@ -95,6 +150,25 @@ fn build_content(name: &str, icon: Option<&Path>) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn build_windows_shortcut(name: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("@echo off\r\n");
|
||||
out.push_str(&format!("title Minecraft - {name}\r\n"));
|
||||
out.push_str(&format!("mcl instance launch \"{name}\"\r\n"));
|
||||
out.push_str("pause\r\n");
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn build_macos_command(name: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("#!/bin/bash\n");
|
||||
out.push_str(&format!("# Launch Minecraft instance: {name}\n"));
|
||||
out.push_str(&format!("mcl instance launch \"{name}\"\n"));
|
||||
out
|
||||
}
|
||||
|
||||
fn sanitize(name: &str) -> String {
|
||||
name.chars()
|
||||
.map(|c| {
|
||||
@@ -123,20 +197,30 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_content_with_icon() {
|
||||
let icon = PathBuf::from("/home/user/icon.png");
|
||||
let content = build_content("TestPack", Some(&icon));
|
||||
fn desktop_path_returns_some() {
|
||||
let path = desktop_path("TestPack");
|
||||
// On CI or minimal environments this may be None, but on most systems it should work
|
||||
if let Some(p) = path {
|
||||
let name = p.file_name().unwrap().to_str().unwrap();
|
||||
assert!(name.contains("TestPack"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn build_content_linux() {
|
||||
let content = build_content("TestPack", None);
|
||||
assert!(content.contains("Name=Minecraft - TestPack"));
|
||||
assert!(content.contains("Exec=mcl instance launch \"TestPack\""));
|
||||
assert!(content.contains("Icon=/home/user/icon.png"));
|
||||
assert!(content.contains("Terminal=true"));
|
||||
assert!(content.contains("Categories=Game;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_content_without_icon() {
|
||||
let content = build_content("TestPack", None);
|
||||
assert!(content.contains("Name=Minecraft - TestPack"));
|
||||
assert!(!content.contains("Icon="));
|
||||
#[cfg(target_os = "linux")]
|
||||
fn build_content_linux_with_icon() {
|
||||
let icon = PathBuf::from("/tmp/icon.png");
|
||||
let content = build_content("TestPack", Some(&icon));
|
||||
assert!(content.contains("Icon=/tmp/icon.png"));
|
||||
}
|
||||
}
|
||||
+52
-104
@@ -71,31 +71,31 @@ struct LoaderLibrary {
|
||||
}
|
||||
|
||||
fn lib_allowed(lib: &MetaLibrary) -> bool {
|
||||
let rules = match &lib.rules {
|
||||
Some(r) => r,
|
||||
None => return true,
|
||||
let Some(rules) = &lib.rules else {
|
||||
return true;
|
||||
};
|
||||
let current_os = match std::env::consts::OS {
|
||||
"macos" => "osx",
|
||||
other => other,
|
||||
};
|
||||
let mut allowed = false;
|
||||
let mut dominated = false;
|
||||
for rule in rules {
|
||||
let matches = match &rule.os {
|
||||
Some(os) => os.name.as_deref().map(|n| n == current_os).unwrap_or(true),
|
||||
None => true,
|
||||
};
|
||||
if !matches {
|
||||
let matches_os = rule
|
||||
.os
|
||||
.as_ref()
|
||||
.and_then(|os| os.name.as_deref())
|
||||
.is_none_or(|n| n == current_os);
|
||||
if !matches_os {
|
||||
continue;
|
||||
}
|
||||
if rule.action == "disallow" {
|
||||
return false;
|
||||
}
|
||||
if rule.action == "allow" {
|
||||
allowed = true;
|
||||
dominated = true;
|
||||
match rule.action.as_str() {
|
||||
"disallow" => return false,
|
||||
"allow" => return true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
allowed
|
||||
!dominated
|
||||
}
|
||||
|
||||
pub async fn launch(
|
||||
@@ -114,7 +114,7 @@ pub async fn launch(
|
||||
if !meta_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(meta_path.display().to_string()));
|
||||
}
|
||||
let meta: MetaJson = serde_json::from_slice(&std::fs::read(&meta_path)?)?;
|
||||
let meta: MetaJson = serde_json::from_slice(&tokio::fs::read(&meta_path).await?)?;
|
||||
|
||||
let lib_dir = meta_dir.join("libraries");
|
||||
let mut classpath: Vec<PathBuf> = meta
|
||||
@@ -130,98 +130,46 @@ pub async fn launch(
|
||||
})
|
||||
.collect();
|
||||
|
||||
let main_class = match config.loader {
|
||||
ModLoader::Vanilla => meta.main_class.clone(),
|
||||
ModLoader::Fabric => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("fabric-{}-{}.json", config.game_version, lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
profile_path.display().to_string(),
|
||||
));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_filename = match config.loader {
|
||||
ModLoader::Vanilla => None,
|
||||
ModLoader::Fabric => Some(format!("fabric-{}-{}.json", config.game_version, lv)),
|
||||
ModLoader::Quilt => Some(format!("quilt-{}-{}.json", config.game_version, lv)),
|
||||
ModLoader::Forge => Some(format!("forge-{}-{}.json", config.game_version, lv)),
|
||||
ModLoader::NeoForge => Some(format!("neoforge-{}.json", lv)),
|
||||
};
|
||||
|
||||
let main_class = if let Some(filename) = profile_filename {
|
||||
let profile_path = meta_dir.join("loader-profiles").join(&filename);
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
profile_path.display().to_string(),
|
||||
));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&tokio::fs::read(&profile_path).await?)?;
|
||||
|
||||
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
|
||||
let local_lib_dir = minecraft_dir.join("libraries");
|
||||
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
if has_local_libs {
|
||||
let in_meta = lib_dir.join(&p);
|
||||
let in_local = local_lib_dir.join(&p);
|
||||
if in_meta.exists() {
|
||||
classpath.push(in_meta);
|
||||
} else if in_local.exists() {
|
||||
classpath.push(in_local);
|
||||
}
|
||||
} else {
|
||||
classpath.push(lib_dir.join(p));
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
ModLoader::Quilt => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("quilt-{}-{}.json", config.game_version, lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
profile_path.display().to_string(),
|
||||
));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
classpath.push(lib_dir.join(p));
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
ModLoader::Forge => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("forge-{}-{}.json", config.game_version, lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
profile_path.display().to_string(),
|
||||
));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
let forge_lib_dir = minecraft_dir.join("libraries");
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
let in_meta = lib_dir.join(&p);
|
||||
let in_forge = forge_lib_dir.join(&p);
|
||||
if in_meta.exists() {
|
||||
classpath.push(in_meta);
|
||||
} else if in_forge.exists() {
|
||||
classpath.push(in_forge);
|
||||
}
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
ModLoader::NeoForge => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("neoforge-{}.json", lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
profile_path.display().to_string(),
|
||||
));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
let neo_lib_dir = minecraft_dir.join("libraries");
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
let in_meta = lib_dir.join(&p);
|
||||
let in_neo = neo_lib_dir.join(&p);
|
||||
if in_meta.exists() {
|
||||
classpath.push(in_meta);
|
||||
} else if in_neo.exists() {
|
||||
classpath.push(in_neo);
|
||||
}
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
profile.main_class
|
||||
} else {
|
||||
meta.main_class.clone()
|
||||
};
|
||||
|
||||
classpath.push(
|
||||
|
||||
@@ -1,542 +0,0 @@
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::fabric;
|
||||
use crate::net::forge;
|
||||
use crate::net::mojang;
|
||||
use crate::net::neoforge;
|
||||
use crate::net::quilt;
|
||||
use crate::net::{HttpClient, NetError};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GameVersion {
|
||||
pub id: String,
|
||||
pub stable: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ModLoaderInstaller: Send + Sync {
|
||||
/// Returns the ModLoader variant this installer handles.
|
||||
fn loader_type(&self) -> ModLoader;
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError>;
|
||||
|
||||
/// Returns available loader versions for the given Minecraft version.
|
||||
/// For Vanilla, returns a single placeholder entry.
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError>;
|
||||
|
||||
/// Downloads and installs the loader into the given instance directory.
|
||||
/// For Vanilla, this is a no-op since Minecraft files are downloaded separately.
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError>;
|
||||
}
|
||||
|
||||
pub struct VanillaInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for VanillaInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Vanilla
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
let manifest = match mojang::fetch_version_manifest(client).await {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(manifest
|
||||
.versions
|
||||
.into_iter()
|
||||
.map(|version| GameVersion {
|
||||
id: version.id,
|
||||
stable: version.version_type == "release",
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
_client: &HttpClient,
|
||||
_game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
Ok(vec!["vanilla".to_string()])
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
_client: &HttpClient,
|
||||
_game_version: &str,
|
||||
_loader_version: &str,
|
||||
_instance_dir: &Path,
|
||||
_meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
// Vanilla: no loader to install; Minecraft files downloaded by Mojang API separately
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FabricInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for FabricInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Fabric
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
fabric::fetch_fabric_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
let loader_versions = match fabric::fetch_fabric_versions(client, game_version).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
Ok(loader_versions
|
||||
.into_iter()
|
||||
.map(|lv| lv.loader.version)
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
_instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let profile = match fabric::fetch_fabric_profile(client, game_version, loader_version).await
|
||||
{
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
match fabric::download_fabric_libraries(client, &profile, meta_dir).await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
let profiles_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profiles_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path =
|
||||
profiles_dir.join(format!("fabric-{}-{}.json", game_version, loader_version));
|
||||
match serde_json::to_string_pretty(&profile) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save Fabric profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to serialize Fabric profile: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ForgeInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for ForgeInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Forge
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
forge::fetch_forge_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
forge::fetch_forge_versions(client, game_version).await
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
|
||||
|
||||
match forge::download_forge_installer(client, game_version, loader_version, &installer_jar)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
let java_path = crate::net::detect_java_path();
|
||||
match forge::run_forge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
||||
tracing::error!(
|
||||
"Failed to remove Forge installer JAR {}: {}",
|
||||
installer_jar.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
|
||||
let forge_ver_json = instance_dir
|
||||
.join(".minecraft")
|
||||
.join("versions")
|
||||
.join(format!("{}-forge-{}", game_version, loader_version))
|
||||
.join(format!("{}-forge-{}.json", game_version, loader_version));
|
||||
if forge_ver_json.exists() {
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ForgeVersionJson {
|
||||
main_class: String,
|
||||
#[serde(default)]
|
||||
libraries: Vec<ForgeVersionLib>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ForgeVersionLib {
|
||||
name: String,
|
||||
}
|
||||
match std::fs::read(&forge_ver_json)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<ForgeVersionJson>(&b).ok())
|
||||
{
|
||||
Some(forge_ver) => {
|
||||
let profile_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profile_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path = profile_dir
|
||||
.join(format!("forge-{}-{}.json", game_version, loader_version));
|
||||
let libs: Vec<serde_json::Value> = forge_ver
|
||||
.libraries
|
||||
.iter()
|
||||
.map(|l| serde_json::json!({"name": l.name}))
|
||||
.collect();
|
||||
let json_val = serde_json::json!({
|
||||
"mainClass": forge_ver.main_class,
|
||||
"libraries": libs
|
||||
});
|
||||
match serde_json::to_string_pretty(&json_val) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save Forge profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to serialize Forge profile: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
}
|
||||
None => tracing::warn!(
|
||||
"Could not read Forge version JSON at {}",
|
||||
forge_ver_json.display()
|
||||
),
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"Forge version JSON not found at {} — profile not saved",
|
||||
forge_ver_json.display()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct QuiltInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for QuiltInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Quilt
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
quilt::fetch_quilt_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
let loader_versions = match quilt::fetch_quilt_versions(client, game_version).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
Ok(loader_versions
|
||||
.into_iter()
|
||||
.map(|lv| lv.loader.version)
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
_instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let profile = match quilt::fetch_quilt_profile(client, game_version, loader_version).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
match quilt::download_quilt_libraries(client, &profile, meta_dir).await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
let profiles_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profiles_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path =
|
||||
profiles_dir.join(format!("quilt-{}-{}.json", game_version, loader_version));
|
||||
match serde_json::to_string_pretty(&profile) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save Quilt profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to serialize Quilt profile: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NeoForgeInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::NeoForge
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
neoforge::fetch_neoforge_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
neoforge::fetch_neoforge_versions(client, game_version).await
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
_game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(".minecraft")
|
||||
.join("neoforge-installer.jar");
|
||||
|
||||
match neoforge::download_neoforge_installer(client, loader_version, &installer_jar).await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
let java_path = crate::net::detect_java_path();
|
||||
match neoforge::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
||||
tracing::error!(
|
||||
"Failed to remove NeoForge installer JAR {}: {}",
|
||||
installer_jar.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
|
||||
let neo_ver_json = instance_dir
|
||||
.join(".minecraft")
|
||||
.join("versions")
|
||||
.join(format!("neoforge-{}", loader_version))
|
||||
.join(format!("neoforge-{}.json", loader_version));
|
||||
if neo_ver_json.exists() {
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ForgeVersionJson {
|
||||
main_class: String,
|
||||
#[serde(default)]
|
||||
libraries: Vec<ForgeVersionLib>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ForgeVersionLib {
|
||||
name: String,
|
||||
}
|
||||
match std::fs::read(&neo_ver_json)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<ForgeVersionJson>(&b).ok())
|
||||
{
|
||||
Some(neo_ver) => {
|
||||
let profile_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profile_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path =
|
||||
profile_dir.join(format!("neoforge-{}.json", loader_version));
|
||||
let libs: Vec<serde_json::Value> = neo_ver
|
||||
.libraries
|
||||
.iter()
|
||||
.map(|l| serde_json::json!({"name": l.name}))
|
||||
.collect();
|
||||
let json_val = serde_json::json!({
|
||||
"mainClass": neo_ver.main_class,
|
||||
"libraries": libs
|
||||
});
|
||||
match serde_json::to_string_pretty(&json_val) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save NeoForge profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to serialize NeoForge profile: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
}
|
||||
None => tracing::warn!(
|
||||
"Could not read NeoForge version JSON at {}",
|
||||
neo_ver_json.display()
|
||||
),
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"NeoForge version JSON not found at {} — profile not saved",
|
||||
neo_ver_json.display()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + Sync> {
|
||||
match loader {
|
||||
ModLoader::Vanilla => Box::new(VanillaInstaller),
|
||||
ModLoader::Fabric => Box::new(FabricInstaller),
|
||||
ModLoader::Forge => Box::new(ForgeInstaller),
|
||||
ModLoader::NeoForge => Box::new(NeoForgeInstaller),
|
||||
ModLoader::Quilt => Box::new(QuiltInstaller),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_vanilla_factory() {
|
||||
let installer = get_installer(ModLoader::Vanilla);
|
||||
assert_eq!(installer.loader_type(), ModLoader::Vanilla);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_vanilla_get_versions() {
|
||||
let client = HttpClient::new();
|
||||
let installer = VanillaInstaller;
|
||||
match installer.get_versions(&client, "1.20.1").await {
|
||||
Ok(versions) => {
|
||||
assert!(!versions.is_empty());
|
||||
assert_eq!(versions[0], "vanilla");
|
||||
}
|
||||
Err(e) => panic!("get_versions failed: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_vanilla_install_noop() {
|
||||
let client = HttpClient::new();
|
||||
let installer = VanillaInstaller;
|
||||
let tmp = std::env::temp_dir().join("mcl_test_vanilla_install");
|
||||
let meta = std::env::temp_dir().join("mcl_test_meta");
|
||||
match installer
|
||||
.install(&client, "1.20.1", "vanilla", &tmp, &meta)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
Err(e) => panic!("install failed: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_vanilla_get_game_versions() {
|
||||
let client = HttpClient::new();
|
||||
let installer = VanillaInstaller;
|
||||
match installer.get_game_versions(&client).await {
|
||||
Ok(versions) => {
|
||||
assert!(!versions.is_empty());
|
||||
assert!(versions.iter().any(|version| version.id == "1.20.1"));
|
||||
}
|
||||
Err(e) => panic!("get_game_versions failed: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{fabric as fabric_api, HttpClient, NetError};
|
||||
|
||||
pub struct FabricInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for FabricInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Fabric
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
fabric_api::fetch_fabric_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
let loader_versions = fabric_api::fetch_fabric_versions(client, game_version).await?;
|
||||
Ok(loader_versions
|
||||
.into_iter()
|
||||
.map(|lv| lv.loader.version)
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
_instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let profile =
|
||||
fabric_api::fetch_fabric_profile(client, game_version, loader_version).await?;
|
||||
fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?;
|
||||
|
||||
super::save_profile_json(
|
||||
meta_dir,
|
||||
&format!("fabric-{game_version}-{loader_version}.json"),
|
||||
&profile,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{forge as forge_api, HttpClient, NetError};
|
||||
|
||||
pub struct ForgeInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for ForgeInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Forge
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
forge_api::fetch_forge_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
forge_api::fetch_forge_versions(client, game_version).await
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
|
||||
|
||||
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
|
||||
.await?;
|
||||
|
||||
let java_path = crate::config::SETTINGS
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(crate::net::detect_java_path);
|
||||
if let Err(e) =
|
||||
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
|
||||
{
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
||||
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
|
||||
}
|
||||
|
||||
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn save_forge_profile(
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
) -> Result<(), NetError> {
|
||||
let version_dir_name = format!("{game_version}-forge-{loader_version}");
|
||||
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
|
||||
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
mod vanilla;
|
||||
mod fabric;
|
||||
mod forge;
|
||||
mod neoforge;
|
||||
mod quilt;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{HttpClient, NetError};
|
||||
|
||||
pub use vanilla::VanillaInstaller;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GameVersion {
|
||||
pub id: String,
|
||||
pub stable: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ModLoaderInstaller: Send + Sync {
|
||||
fn loader_type(&self) -> ModLoader;
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError>;
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError>;
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError>;
|
||||
}
|
||||
|
||||
/// Save a serializable loader profile JSON to `meta_dir/loader-profiles/<filename>`.
|
||||
pub(crate) fn save_profile_json(
|
||||
meta_dir: &Path,
|
||||
filename: &str,
|
||||
profile: &impl serde::Serialize,
|
||||
) -> Result<(), NetError> {
|
||||
let profiles_dir = meta_dir.join("loader-profiles");
|
||||
std::fs::create_dir_all(&profiles_dir)?;
|
||||
let profile_path = profiles_dir.join(filename);
|
||||
let json = serde_json::to_string_pretty(profile)
|
||||
.map_err(|e| NetError::Parse(format!("Failed to serialize profile {filename}: {e}")))?;
|
||||
std::fs::write(&profile_path, &json)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a Forge/NeoForge version JSON installed by the Java installer, extract
|
||||
/// mainClass + libraries, and save a simplified profile to `meta_dir/loader-profiles/`.
|
||||
pub(crate) fn save_installer_profile(
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
version_dir_name: &str,
|
||||
profile_filename: &str,
|
||||
) -> Result<(), NetError> {
|
||||
let ver_json_path = instance_dir
|
||||
.join(".minecraft")
|
||||
.join("versions")
|
||||
.join(version_dir_name)
|
||||
.join(format!("{version_dir_name}.json"));
|
||||
|
||||
if !ver_json_path.exists() {
|
||||
return Err(NetError::Parse(format!(
|
||||
"Version JSON not found at {}",
|
||||
ver_json_path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct InstallerVersionJson {
|
||||
main_class: String,
|
||||
#[serde(default)]
|
||||
libraries: Vec<InstallerLib>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct InstallerLib {
|
||||
name: String,
|
||||
}
|
||||
|
||||
let raw = std::fs::read(&ver_json_path)?;
|
||||
let ver: InstallerVersionJson = serde_json::from_slice(&raw)
|
||||
.map_err(|e| NetError::Parse(format!("Invalid version JSON at {}: {e}", ver_json_path.display())))?;
|
||||
|
||||
let libs: Vec<serde_json::Value> = ver
|
||||
.libraries
|
||||
.iter()
|
||||
.map(|l| serde_json::json!({"name": l.name}))
|
||||
.collect();
|
||||
let json_val = serde_json::json!({
|
||||
"mainClass": ver.main_class,
|
||||
"libraries": libs
|
||||
});
|
||||
|
||||
save_profile_json(meta_dir, profile_filename, &json_val)
|
||||
}
|
||||
|
||||
pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + Sync> {
|
||||
match loader {
|
||||
ModLoader::Vanilla => Box::new(vanilla::VanillaInstaller),
|
||||
ModLoader::Fabric => Box::new(fabric::FabricInstaller),
|
||||
ModLoader::Forge => Box::new(forge::ForgeInstaller),
|
||||
ModLoader::NeoForge => Box::new(neoforge::NeoForgeInstaller),
|
||||
ModLoader::Quilt => Box::new(quilt::QuiltInstaller),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_vanilla_factory() {
|
||||
let installer = get_installer(ModLoader::Vanilla);
|
||||
assert_eq!(installer.loader_type(), ModLoader::Vanilla);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_vanilla_get_versions() {
|
||||
let client = HttpClient::new();
|
||||
let installer = VanillaInstaller;
|
||||
let versions = installer.get_versions(&client, "1.20.1").await.unwrap();
|
||||
assert!(!versions.is_empty());
|
||||
assert_eq!(versions[0], "vanilla");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_vanilla_install_noop() {
|
||||
let client = HttpClient::new();
|
||||
let installer = VanillaInstaller;
|
||||
let tmp = std::env::temp_dir().join("mcl_test_vanilla_install");
|
||||
let meta = std::env::temp_dir().join("mcl_test_meta");
|
||||
installer
|
||||
.install(&client, "1.20.1", "vanilla", &tmp, &meta)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "hits live Mojang API"]
|
||||
async fn test_vanilla_get_game_versions() {
|
||||
let client = HttpClient::new();
|
||||
let installer = VanillaInstaller;
|
||||
let versions = installer.get_game_versions(&client).await.unwrap();
|
||||
assert!(!versions.is_empty());
|
||||
assert!(versions.iter().any(|v| v.id == "1.20.1"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{neoforge as neoforge_api, HttpClient, NetError};
|
||||
|
||||
pub struct NeoForgeInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::NeoForge
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
neoforge_api::fetch_neoforge_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
neoforge_api::fetch_neoforge_versions(client, game_version).await
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
_game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(".minecraft")
|
||||
.join("neoforge-installer.jar");
|
||||
|
||||
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
|
||||
|
||||
let java_path = crate::config::SETTINGS
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(crate::net::detect_java_path);
|
||||
if let Err(e) =
|
||||
neoforge_api::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await
|
||||
{
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
||||
tracing::warn!("Failed to remove NeoForge installer JAR: {}", e);
|
||||
}
|
||||
|
||||
save_neoforge_profile(instance_dir, meta_dir, loader_version)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn save_neoforge_profile(instance_dir: &Path, meta_dir: &Path, loader_version: &str) -> Result<(), NetError> {
|
||||
let version_dir_name = format!("neoforge-{loader_version}");
|
||||
let profile_filename = format!("neoforge-{loader_version}.json");
|
||||
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{quilt as quilt_api, HttpClient, NetError};
|
||||
|
||||
pub struct QuiltInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for QuiltInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Quilt
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
quilt_api::fetch_quilt_game_versions(client).await
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
let loader_versions = quilt_api::fetch_quilt_versions(client, game_version).await?;
|
||||
Ok(loader_versions
|
||||
.into_iter()
|
||||
.map(|lv| lv.loader.version)
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
_instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let profile =
|
||||
quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
|
||||
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
|
||||
|
||||
super::save_profile_json(
|
||||
meta_dir,
|
||||
&format!("quilt-{game_version}-{loader_version}.json"),
|
||||
&profile,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{GameVersion, ModLoaderInstaller};
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::{mojang, HttpClient, NetError};
|
||||
|
||||
pub struct VanillaInstaller;
|
||||
|
||||
#[async_trait]
|
||||
impl ModLoaderInstaller for VanillaInstaller {
|
||||
fn loader_type(&self) -> ModLoader {
|
||||
ModLoader::Vanilla
|
||||
}
|
||||
|
||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||
let manifest = mojang::fetch_version_manifest(client).await?;
|
||||
Ok(manifest
|
||||
.versions
|
||||
.into_iter()
|
||||
.map(|v| GameVersion {
|
||||
id: v.id,
|
||||
stable: v.version_type == "release",
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn get_versions(
|
||||
&self,
|
||||
_client: &HttpClient,
|
||||
_game_version: &str,
|
||||
) -> Result<Vec<String>, NetError> {
|
||||
Ok(vec!["vanilla".to_owned()])
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
_client: &HttpClient,
|
||||
_game_version: &str,
|
||||
_loader_version: &str,
|
||||
_instance_dir: &Path,
|
||||
_meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+33
-168
@@ -43,59 +43,27 @@ impl InstanceManager {
|
||||
loader: ModLoader,
|
||||
loader_version: Option<&str>,
|
||||
) -> Result<InstanceConfig, InstanceError> {
|
||||
match validate_name(name) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Invalid instance name '{}': {}", name, e);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
validate_name(name)?;
|
||||
|
||||
let instance_dir = self.instances_dir.join(name);
|
||||
let instance_json = instance_dir.join("instance.json");
|
||||
|
||||
if instance_json.exists() {
|
||||
tracing::error!("Instance '{}' already exists", name);
|
||||
return Err(InstanceError::AlreadyExists(name.to_string()));
|
||||
}
|
||||
|
||||
if instance_dir.exists() && !instance_json.exists() {
|
||||
match std::fs::remove_dir_all(&instance_dir) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Failed to remove partial instance directory '{}': {}",
|
||||
instance_dir.display(),
|
||||
e
|
||||
);
|
||||
return Err(InstanceError::Io(e));
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&instance_dir)?;
|
||||
}
|
||||
|
||||
match std::fs::create_dir_all(&instance_dir) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to create instance directory: {}", e);
|
||||
return Err(InstanceError::Io(e));
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(&instance_dir)?;
|
||||
|
||||
let result = self
|
||||
.create_inner(name, game_version, loader, loader_version, &instance_dir)
|
||||
.await;
|
||||
|
||||
if result.is_err() {
|
||||
match std::fs::remove_dir_all(&instance_dir) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"Failed to clean up partial instance directory '{}': {}",
|
||||
instance_dir.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&instance_dir);
|
||||
}
|
||||
|
||||
result
|
||||
@@ -111,24 +79,12 @@ impl InstanceManager {
|
||||
) -> Result<InstanceConfig, InstanceError> {
|
||||
let minecraft_dir = instance_dir.join(".minecraft");
|
||||
for subdir in &["mods", "config", "resourcepacks", "shaderpacks", "saves"] {
|
||||
match std::fs::create_dir_all(minecraft_dir.join(subdir)) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to create directory: {}", e);
|
||||
return Err(InstanceError::Io(e));
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(minecraft_dir.join(subdir))?;
|
||||
}
|
||||
|
||||
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
|
||||
if !launcher_profiles_path.exists() {
|
||||
match std::fs::write(&launcher_profiles_path, "{}") {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to create launcher_profiles.json: {}", e);
|
||||
return Err(InstanceError::Io(e));
|
||||
}
|
||||
}
|
||||
std::fs::write(&launcher_profiles_path, "{}")?;
|
||||
}
|
||||
|
||||
for meta_subdir in &[
|
||||
@@ -137,47 +93,26 @@ impl InstanceManager {
|
||||
self.meta_dir.join("assets").join("objects"),
|
||||
self.meta_dir.join("assets").join("indexes"),
|
||||
] {
|
||||
match std::fs::create_dir_all(meta_subdir) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to create meta directory: {}", e);
|
||||
return Err(InstanceError::Io(e));
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(meta_subdir)?;
|
||||
}
|
||||
|
||||
let manifest = match crate::net::mojang::fetch_version_manifest(&self.client).await {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
return Err(InstanceError::Download(e));
|
||||
}
|
||||
};
|
||||
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
|
||||
|
||||
let version_entry = match manifest.versions.iter().find(|v| v.id == game_version) {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
let msg = format!("Minecraft version '{}' not found in manifest", game_version);
|
||||
tracing::error!("{}", msg);
|
||||
return Err(InstanceError::InvalidName(msg));
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
"Minecraft version '{}' not found in manifest",
|
||||
game_version
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let version_meta =
|
||||
match crate::net::mojang::fetch_version_meta(&self.client, version_entry).await {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
return Err(InstanceError::Download(e));
|
||||
}
|
||||
};
|
||||
crate::net::mojang::fetch_version_meta(&self.client, version_entry).await?;
|
||||
|
||||
match crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
return Err(InstanceError::Download(e));
|
||||
}
|
||||
}
|
||||
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
|
||||
.await?;
|
||||
|
||||
let meta_json_path = self
|
||||
.meta_dir
|
||||
@@ -195,36 +130,23 @@ impl InstanceManager {
|
||||
}
|
||||
}
|
||||
|
||||
match crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
return Err(InstanceError::Download(e));
|
||||
}
|
||||
}
|
||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir)
|
||||
.await?;
|
||||
|
||||
match crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
return Err(InstanceError::Download(e));
|
||||
}
|
||||
}
|
||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
|
||||
let installer = crate::instance::loader::get_installer(loader);
|
||||
let effective_loader_version = match loader_version {
|
||||
Some(v) => v,
|
||||
None if loader == ModLoader::Vanilla => "vanilla",
|
||||
None => {
|
||||
tracing::error!("No loader version provided for {} loader", loader);
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
"A loader version is required for {}",
|
||||
loader
|
||||
)));
|
||||
}
|
||||
};
|
||||
match installer
|
||||
installer
|
||||
.install(
|
||||
&self.client,
|
||||
game_version,
|
||||
@@ -232,13 +154,7 @@ impl InstanceManager {
|
||||
instance_dir,
|
||||
&self.meta_dir,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
return Err(InstanceError::Download(e));
|
||||
}
|
||||
}
|
||||
.await?;
|
||||
|
||||
let config = InstanceConfig {
|
||||
name: name.to_string(),
|
||||
@@ -254,13 +170,7 @@ impl InstanceManager {
|
||||
resolution: None,
|
||||
};
|
||||
|
||||
match self.save(&config) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to save instance config: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
self.save(&config)?;
|
||||
|
||||
crate::tui::progress::clear();
|
||||
Ok(config)
|
||||
@@ -271,18 +181,11 @@ impl InstanceManager {
|
||||
if !instance_dir.exists() {
|
||||
return Err(InstanceError::NotFound(name.to_string()));
|
||||
}
|
||||
match std::fs::remove_dir_all(&instance_dir) {
|
||||
Ok(_) => {
|
||||
if let Err(e) = crate::instance::desktop::remove(name) {
|
||||
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to delete instance '{}': {}", name, e);
|
||||
Err(InstanceError::Io(e))
|
||||
}
|
||||
std::fs::remove_dir_all(&instance_dir)?;
|
||||
if let Err(e) = crate::instance::desktop::remove(name) {
|
||||
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
|
||||
@@ -360,58 +263,23 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub fn load_one(&self, name: &str) -> Result<InstanceConfig, InstanceError> {
|
||||
match validate_name(name) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Invalid instance name '{}': {}", name, e);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
validate_name(name)?;
|
||||
|
||||
let config_path = self.instances_dir.join(name).join("instance.json");
|
||||
if !config_path.exists() {
|
||||
tracing::error!("Instance '{}' not found", name);
|
||||
return Err(InstanceError::NotFound(name.to_string()));
|
||||
}
|
||||
|
||||
let contents = match std::fs::read_to_string(&config_path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read {}: {}", config_path.display(), e);
|
||||
return Err(InstanceError::Io(e));
|
||||
}
|
||||
};
|
||||
|
||||
match serde_json::from_str::<InstanceConfig>(&contents) {
|
||||
Ok(config) => Ok(config),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to parse {}: {}", config_path.display(), e);
|
||||
Err(InstanceError::Json(e))
|
||||
}
|
||||
}
|
||||
let contents = std::fs::read_to_string(&config_path)?;
|
||||
Ok(serde_json::from_str::<InstanceConfig>(&contents)?)
|
||||
}
|
||||
|
||||
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
|
||||
let instance_dir = self.instances_dir.join(&instance.name);
|
||||
let config_path = instance_dir.join("instance.json");
|
||||
let json = match serde_json::to_string_pretty(instance) {
|
||||
Ok(j) => j,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to serialize instance config: {}", e);
|
||||
return Err(InstanceError::Json(e));
|
||||
}
|
||||
};
|
||||
match std::fs::write(&config_path, &json) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Failed to write instance config to {}: {}",
|
||||
config_path.display(),
|
||||
e
|
||||
);
|
||||
Err(InstanceError::Io(e))
|
||||
}
|
||||
}
|
||||
let json = serde_json::to_string_pretty(instance)?;
|
||||
std::fs::write(&config_path, &json)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
|
||||
@@ -428,7 +296,7 @@ fn validate_name(name: &str) -> Result<(), InstanceError> {
|
||||
name
|
||||
)));
|
||||
}
|
||||
if name.contains('/') || name.contains('\\') || name.contains('.') {
|
||||
if name.contains('/') || name.contains('\\') || name.starts_with('.') {
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
"Name contains invalid characters: {:?}",
|
||||
name
|
||||
@@ -502,10 +370,7 @@ mod tests {
|
||||
resolution: None,
|
||||
};
|
||||
|
||||
match manager.save(&config) {
|
||||
Ok(_) => {}
|
||||
Err(e) => panic!("save failed: {}", e),
|
||||
}
|
||||
manager.save(&config).expect("save failed");
|
||||
|
||||
let all = manager.load_all();
|
||||
assert_eq!(all.len(), 1);
|
||||
|
||||
+4
-10
@@ -1,21 +1,15 @@
|
||||
pub mod content;
|
||||
pub mod desktop;
|
||||
pub mod import;
|
||||
pub mod launch;
|
||||
pub mod loader;
|
||||
pub mod desktop;
|
||||
pub mod log_files;
|
||||
pub mod manager;
|
||||
pub mod models;
|
||||
pub mod mods;
|
||||
pub mod resource_packs;
|
||||
pub mod screenshots;
|
||||
pub mod shaders;
|
||||
pub mod worlds;
|
||||
pub mod import;
|
||||
|
||||
pub use content::{scan_mods, toggle_entry, ContentEntry, scan_resource_packs, scan_shaders, scan_worlds};
|
||||
pub use launch::LaunchError;
|
||||
pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};
|
||||
pub use manager::{InstanceError, InstanceManager};
|
||||
pub use models::{InstanceConfig, ModLoader};
|
||||
pub use mods::{scan_mods, toggle_mod, ModEntry};
|
||||
pub use resource_packs::scan_resource_packs;
|
||||
pub use shaders::scan_shaders;
|
||||
pub use worlds::scan_worlds;
|
||||
+7
-22
@@ -2,7 +2,7 @@ use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ModLoader {
|
||||
Vanilla,
|
||||
@@ -43,15 +43,6 @@ pub struct InstanceConfig {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_modloader_display() {
|
||||
assert_eq!(ModLoader::Vanilla.to_string(), "Vanilla");
|
||||
assert_eq!(ModLoader::Fabric.to_string(), "Fabric");
|
||||
assert_eq!(ModLoader::Forge.to_string(), "Forge");
|
||||
assert_eq!(ModLoader::NeoForge.to_string(), "NeoForge");
|
||||
assert_eq!(ModLoader::Quilt.to_string(), "Quilt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_instance_config_roundtrip() {
|
||||
let config = InstanceConfig {
|
||||
@@ -67,17 +58,11 @@ mod tests {
|
||||
jvm_args: vec![],
|
||||
resolution: Some((1920, 1080)),
|
||||
};
|
||||
match serde_json::to_string_pretty(&config) {
|
||||
Ok(json) => match serde_json::from_str::<InstanceConfig>(&json) {
|
||||
Ok(parsed) => {
|
||||
assert_eq!(parsed.name, config.name);
|
||||
assert_eq!(parsed.game_version, config.game_version);
|
||||
assert_eq!(parsed.loader, config.loader);
|
||||
assert_eq!(parsed.resolution, config.resolution);
|
||||
}
|
||||
Err(e) => panic!("Deserialization failed: {}", e),
|
||||
},
|
||||
Err(e) => panic!("Serialization failed: {}", e),
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&config).expect("serialize");
|
||||
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
|
||||
assert_eq!(parsed.name, config.name);
|
||||
assert_eq!(parsed.game_version, config.game_version);
|
||||
assert_eq!(parsed.loader, config.loader);
|
||||
assert_eq!(parsed.resolution, config.resolution);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user