feat: add instance management with CRUD and JSON persistence

This commit is contained in:
objz committed 2025-07-05 15:52:33 +02:00
1 parent 8d8cf4805e
commit b10c4c4973
4 files changed
+787

No files matched your search

+329
View File
@@ -0,0 +1,329 @@
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::neoforge;
use crate::net::quilt;
use crate::net::{HttpClient, NetError};
#[async_trait]
pub trait ModLoaderInstaller: Send + Sync {
/// Returns the ModLoader variant this installer handles.
fn loader_type(&self) -> ModLoader;
/// 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,
) -> Result<(), NetError>;
}
pub struct VanillaInstaller;
#[async_trait]
impl ModLoaderInstaller for VanillaInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Vanilla
}
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,
) -> 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_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,
) -> 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, instance_dir).await {
Ok(()) => {}
Err(e) => {
return Err(e);
}
}
Ok(())
}
}
pub struct ForgeInstaller;
#[async_trait]
impl ModLoaderInstaller for ForgeInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Forge
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
match forge::fetch_forge_versions(client, game_version).await {
Ok(v) => Ok(v),
Err(e) => {
Err(e)
}
}
}
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_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 = forge::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
);
}
Ok(())
}
}
pub struct QuiltInstaller;
#[async_trait]
impl ModLoaderInstaller for QuiltInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Quilt
}
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,
) -> 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, instance_dir).await {
Ok(()) => {}
Err(e) => {
return Err(e);
}
}
Ok(())
}
}
pub struct NeoForgeInstaller;
#[async_trait]
impl ModLoaderInstaller for NeoForgeInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::NeoForge
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
match neoforge::fetch_neoforge_versions(client, game_version).await {
Ok(v) => Ok(v),
Err(e) => {
Err(e)
}
}
}
async fn install(
&self,
client: &HttpClient,
_game_version: &str,
loader_version: &str,
instance_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 = neoforge::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
);
}
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) => assert!(false, "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");
match installer.install(&client, "1.20.1", "vanilla", &tmp).await {
Ok(()) => {}
Err(e) => assert!(false, "install failed: {}", e),
}
}
}
+359
View File
@@ -0,0 +1,359 @@
use std::path::PathBuf;
use chrono::Utc;
use thiserror::Error;
use crate::instance::models::{InstanceConfig, ModLoader};
#[derive(Debug, Error)]
pub enum InstanceError {
#[error("Instance '{0}' already exists")]
AlreadyExists(String),
#[error("Instance '{0}' not found")]
NotFound(String),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("Download error: {0}")]
Download(#[from] crate::net::NetError),
#[error("Invalid instance name: {0}")]
InvalidName(String),
}
pub struct InstanceManager {
pub instances_dir: PathBuf,
client: crate::net::HttpClient,
}
impl InstanceManager {
pub fn new(instances_dir: impl Into<PathBuf>) -> Self {
InstanceManager {
instances_dir: instances_dir.into(),
client: crate::net::HttpClient::new(),
}
}
pub async fn create(
&self,
name: &str,
game_version: &str,
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);
}
}
let instance_dir = self.instances_dir.join(name);
if instance_dir.exists() {
tracing::error!("Instance '{}' already exists", name);
return Err(InstanceError::AlreadyExists(name.to_string()));
}
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));
}
}
}
let manifest = match crate::net::mojang::fetch_version_manifest(&self.client).await {
Ok(m) => m,
Err(e) => {
return Err(InstanceError::Download(e));
}
};
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));
}
};
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));
}
};
match crate::net::mojang::download_client_jar(&self.client, &version_meta, &instance_dir).await {
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
match crate::net::mojang::download_libraries(&self.client, &version_meta, &instance_dir).await {
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
match crate::net::mojang::download_assets(&self.client, &version_meta, &instance_dir).await {
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
let installer = crate::instance::loader::get_installer(loader);
let effective_loader_version = loader_version.unwrap_or("latest");
match installer
.install(&self.client, game_version, effective_loader_version, &instance_dir)
.await
{
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
let config = InstanceConfig {
name: name.to_string(),
game_version: game_version.to_string(),
loader,
loader_version: loader_version.map(String::from),
created: Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: vec![],
resolution: None,
};
match self.save(&config) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to save instance config: {}", e);
return Err(e);
}
}
crate::tui::progress::clear();
Ok(config)
}
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
let instance_dir = self.instances_dir.join(name);
if !instance_dir.exists() {
return Err(InstanceError::NotFound(name.to_string()));
}
match std::fs::remove_dir_all(&instance_dir) {
Ok(_) => Ok(()),
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
Err(InstanceError::Io(e))
}
}
}
pub fn load_all(&self) -> Vec<InstanceConfig> {
let mut instances = vec![];
let read_dir = match std::fs::read_dir(&self.instances_dir) {
Ok(rd) => rd,
Err(e) => {
tracing::error!("Failed to read instances directory: {}", e);
return instances;
}
};
for entry in read_dir {
let entry = match entry {
Ok(e) => e,
Err(e) => {
tracing::error!("Failed to read directory entry: {}", e);
continue;
}
};
let config_path = entry.path().join("instance.json");
if !config_path.exists() {
continue;
}
let contents = match std::fs::read_to_string(&config_path) {
Ok(c) => c,
Err(e) => {
tracing::error!("Failed to read {}: {}", config_path.display(), e);
continue;
}
};
match serde_json::from_str::<InstanceConfig>(&contents) {
Ok(config) => instances.push(config),
Err(e) => {
tracing::error!("Failed to parse {}: {}", config_path.display(), e);
}
}
}
instances
}
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);
}
}
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))
}
}
}
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))
}
}
}
}
fn validate_name(name: &str) -> Result<(), InstanceError> {
if name.is_empty() || name.len() > 64 {
return Err(InstanceError::InvalidName(format!(
"Name must be 1-64 chars, got: {:?}",
name
)));
}
if name.contains('/') || name.contains('\\') || name.contains('.') {
return Err(InstanceError::InvalidName(format!(
"Name contains invalid characters: {:?}",
name
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::instance::models::ModLoader;
use std::path::PathBuf;
fn test_manager() -> (InstanceManager, PathBuf) {
let tmp = std::env::temp_dir().join(format!("mcl_test_{}", uuid_like()));
std::fs::create_dir_all(&tmp).ok();
(InstanceManager::new(tmp.clone()), tmp)
}
fn uuid_like() -> String {
format!(
"{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
)
}
#[test]
fn test_validate_name_valid() {
assert!(validate_name("my-instance").is_ok());
assert!(validate_name("test_world").is_ok());
}
#[test]
fn test_validate_name_invalid() {
assert!(validate_name("").is_err());
assert!(validate_name("path/traversal").is_err());
assert!(validate_name(".hidden").is_err());
}
#[test]
fn test_delete_nonexistent() {
let (manager, tmp) = test_manager();
let result = manager.delete("ghost-instance");
assert!(matches!(result, Err(InstanceError::NotFound(_))));
std::fs::remove_dir_all(&tmp).ok();
}
#[test]
fn test_save_and_load_all() {
let (manager, tmp) = test_manager();
let instance_dir = tmp.join("test-save");
std::fs::create_dir_all(&instance_dir).ok();
let config = InstanceConfig {
name: "test-save".to_string(),
game_version: "1.20.1".to_string(),
loader: ModLoader::Vanilla,
loader_version: None,
created: chrono::Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: vec![],
resolution: None,
};
match manager.save(&config) {
Ok(_) => {}
Err(e) => assert!(false, "save failed: {}", e),
}
let all = manager.load_all();
assert_eq!(all.len(), 1);
assert_eq!(all[0].name, "test-save");
assert_eq!(all[0].game_version, "1.20.1");
std::fs::remove_dir_all(&tmp).ok();
}
#[test]
fn test_load_one_not_found() {
let (manager, tmp) = test_manager();
let result = manager.load_one("ghost-instance");
assert!(matches!(result, Err(InstanceError::NotFound(_))));
std::fs::remove_dir_all(&tmp).ok();
}
}
+7
View File
@@ -0,0 +1,7 @@
pub mod manager;
pub mod loader;
pub mod models;
pub use manager::{InstanceError, InstanceManager};
pub use loader::{get_installer, ModLoaderInstaller, VanillaInstaller};
pub use models::{InstanceConfig, InstanceState, ModLoader};
+92
View File
@@ -0,0 +1,92 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModLoader {
Vanilla,
Fabric,
Forge,
NeoForge,
Quilt,
}
impl fmt::Display for ModLoader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ModLoader::Vanilla => write!(f, "Vanilla"),
ModLoader::Fabric => write!(f, "Fabric"),
ModLoader::Forge => write!(f, "Forge"),
ModLoader::NeoForge => write!(f, "NeoForge"),
ModLoader::Quilt => write!(f, "Quilt"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstanceConfig {
pub name: String,
pub game_version: String,
pub loader: ModLoader,
pub loader_version: Option<String>,
pub created: DateTime<Utc>,
pub last_played: Option<DateTime<Utc>>,
pub java_path: Option<String>,
pub memory_max: Option<String>,
pub memory_min: Option<String>,
pub jvm_args: Vec<String>,
pub resolution: Option<(u32, u32)>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InstanceState {
Ready,
Downloading,
Running,
Error(String),
}
#[cfg(test)]
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 {
name: "test".to_string(),
game_version: "1.20.1".to_string(),
loader: ModLoader::Fabric,
loader_version: Some("0.15.0".to_string()),
created: Utc::now(),
last_played: None,
java_path: None,
memory_max: Some("4G".to_string()),
memory_min: Some("512M".to_string()),
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) => assert!(false, "Deserialization failed: {}", e),
},
Err(e) => assert!(false, "Serialization failed: {}", e),
}
}
}