feat(content): add managed content metadata layout

This commit is contained in:
objz committed 2026-07-25 12:14:30 +02:00
1 parent a05b030862
commit fbf8142ea0
46 files changed
+2403 -165

No files matched your search

Generated
+14 -1
View File
@@ -3240,6 +3240,8 @@ dependencies = [
"rstest", "rstest",
"serde", "serde",
"serde_json", "serde_json",
"sha1 0.10.7",
"sha2",
"tachyonfx", "tachyonfx",
"tempfile", "tempfile",
"thiserror 2.0.18", "thiserror 2.0.18",
@@ -3524,6 +3526,17 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]] [[package]]
name = "sha1" name = "sha1"
version = "0.11.0" version = "0.11.0"
@@ -5277,7 +5290,7 @@ dependencies = [
"memchr", "memchr",
"pbkdf2", "pbkdf2",
"ppmd-rust", "ppmd-rust",
"sha1", "sha1 0.11.0",
"time", "time",
"typed-path", "typed-path",
"zeroize", "zeroize",
+2
View File
@@ -36,6 +36,8 @@ ratatui-textarea = { version = "0.9.1", features = ["crossterm"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] } reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
serde = { version = "1.0.217", features = ["derive"] } serde = { version = "1.0.217", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
sha1 = "0.10"
sha2 = "0.10"
toml = "1.1.2" toml = "1.1.2"
tachyonfx = "0.25" tachyonfx = "0.25"
throbber-widgets-tui = "0.11" throbber-widgets-tui = "0.11"
+11
View File
@@ -23,3 +23,14 @@ error_fly_out_ms = 300
# don’t let this blow up endlessly # don’t let this blow up endlessly
max_error_events = 50 max_error_events = 50
[content]
# ask before choosing when the same file exists on multiple providers
ask_on_provider_conflict = true
# used automatically when conflict prompts are disabled
preferred_provider = "modrinth"
# retry unchanged files that were not found after this many hours
unmatched_retry_hours = 24
# avoid hashing enormous external packs during automatic provider matching;
# set to 0 to remove the limit
max_fingerprint_size_mib = 512
+1
View File
@@ -127,6 +127,7 @@ mod tests {
name: file_stem.to_string(), name: file_stem.to_string(),
source_slug: None, source_slug: None,
installed_path: None, installed_path: None,
provider_project: None,
title_suffix: None, title_suffix: None,
footer_label: None, footer_label: None,
description: String::new(), description: String::new(),
+2 -2
View File
@@ -58,7 +58,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
version.game_versions.first().unwrap_or(&"?".to_string()) version.game_versions.first().unwrap_or(&"?".to_string())
); );
let tmp_dir = manager.meta_dir.join("tmp"); let tmp_dir = crate::storage::MetadataPaths::new(&manager.meta_dir).temporary();
std::fs::create_dir_all(&tmp_dir)?; std::fs::create_dir_all(&tmp_dir)?;
modrinth::download_mrpack(&client, version, &tmp_dir) modrinth::download_mrpack(&client, version, &tmp_dir)
.await .await
@@ -79,7 +79,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
version.game_versions.first().unwrap_or(&"?".to_string()) version.game_versions.first().unwrap_or(&"?".to_string())
); );
let tmp_dir = manager.meta_dir.join("tmp"); let tmp_dir = crate::storage::MetadataPaths::new(&manager.meta_dir).temporary();
std::fs::create_dir_all(&tmp_dir)?; std::fs::create_dir_all(&tmp_dir)?;
modrinth::download_mrpack(&client, &version, &tmp_dir) modrinth::download_mrpack(&client, &version, &tmp_dir)
.await .await
+2 -2
View File
@@ -94,7 +94,7 @@ mod tests {
#[test] #[test]
fn resolves_latest_log_when_no_file_is_given() { fn resolves_latest_log_when_no_file_is_given() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/.minecraft/logs/launches"); let dir = tmp.path().join("demo/minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist"); std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log"); std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log"); std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
@@ -109,7 +109,7 @@ mod tests {
#[test] #[test]
fn resolves_named_log_file() { fn resolves_named_log_file() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/.minecraft/logs/launches"); let dir = tmp.path().join("demo/minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist"); std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("latest.log"), "hello").expect("write named log"); std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
+43
View File
@@ -24,6 +24,49 @@ pub async fn init() {
return; return;
} }
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
if crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
let config = crate::config::get_config_path().join("config.toml");
if let Err(error) =
crate::layout_migration::run(&instances_dir, &meta_dir, &config, |progress| {
eprintln!(
"{}: {} ({}/{})",
progress.phase, progress.item, progress.current, progress.total
);
})
{
eprintln!("error: layout migration failed safely: {error}");
std::process::exit(1);
}
} else if let Err(error) = crate::layout_migration::initialize_new_layout(&meta_dir) {
eprintln!("error: cannot initialize metadata layout: {error}");
std::process::exit(1);
}
if crate::layout_migration::cache_rebuild_pending(&meta_dir) {
let manager = crate::instance::InstanceManager::new(&instances_dir, &meta_dir);
let instances = manager.load_all();
for (index, instance) in instances.iter().enumerate() {
eprintln!(
"Rebuilding runtime cache: {} ({}/{})",
instance.name,
index + 1,
instances.len()
);
if let Err(error) = manager.repair_runtime_cache(instance).await {
eprintln!(
"error: runtime cache rebuild stopped safely for '{}': {error}",
instance.name
);
std::process::exit(1);
}
}
if let Err(error) = crate::layout_migration::finish_cache_rebuild(&meta_dir) {
eprintln!("error: cannot finish runtime cache migration: {error}");
std::process::exit(1);
}
}
let result = match matches.subcommand() { let result = match matches.subcommand() {
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await, Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
Some(("mod", sub_matches)) => content::handle_mod(sub_matches), Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
+1
View File
@@ -62,6 +62,7 @@ pub static SETTINGS: LazyLock<Config> = LazyLock::new(|| {
paths: settings::Paths::default(), paths: settings::Paths::default(),
defaults: settings::Defaults::default(), defaults: settings::Defaults::default(),
ui: settings::Ui::default(), ui: settings::Ui::default(),
content: settings::Content::default(),
} }
}) })
}); });
+41
View File
@@ -18,6 +18,45 @@ pub enum ImageProtocol {
#[derive(Debug, Deserialize, Default)] #[derive(Debug, Deserialize, Default)]
pub struct General {} pub struct General {}
#[derive(Debug, Deserialize)]
pub struct Content {
#[serde(default = "default_true")]
pub ask_on_provider_conflict: bool,
#[serde(default = "default_provider")]
pub preferred_provider: String,
#[serde(default = "default_unmatched_retry_hours")]
pub unmatched_retry_hours: u64,
#[serde(default = "default_max_fingerprint_size_mib")]
pub max_fingerprint_size_mib: u64,
}
fn default_true() -> bool {
true
}
fn default_provider() -> String {
"modrinth".to_owned()
}
fn default_unmatched_retry_hours() -> u64 {
24
}
fn default_max_fingerprint_size_mib() -> u64 {
512
}
impl Default for Content {
fn default() -> Self {
Self {
ask_on_provider_conflict: true,
preferred_provider: default_provider(),
unmatched_retry_hours: default_unmatched_retry_hours(),
max_fingerprint_size_mib: default_max_fingerprint_size_mib(),
}
}
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct Paths { pub struct Paths {
#[serde(default = "default_instances_dir")] #[serde(default = "default_instances_dir")]
@@ -159,6 +198,8 @@ pub struct Config {
pub defaults: Defaults, pub defaults: Defaults,
#[serde(default)] #[serde(default)]
pub ui: Ui, pub ui: Ui,
#[serde(default)]
pub content: Content,
} }
#[cfg(test)] #[cfg(test)]
+6 -5
View File
@@ -229,12 +229,13 @@ accent = "Red"
#[test] #[test]
fn resolve_builtin_theme() { fn resolve_builtin_theme() {
let config = ThemeConfig { let theme = resolve_theme("dracula");
theme: "dracula".to_owned(), let expected = if std::env::var_os("NO_COLOR").is_some() {
..ThemeConfig::default() "no-color"
} else {
"dracula"
}; };
let theme = resolve_app_theme(&config); assert_eq!(theme.id(), expected);
assert_eq!(theme.id(), "dracula");
} }
#[test] #[test]
+220
View File
@@ -0,0 +1,220 @@
use std::collections::HashMap;
use async_trait::async_trait;
use crate::instance::content::manifest::{ContentKind, FileFingerprint, ProviderProject};
use crate::instance::{InstanceConfig, ModLoader};
use crate::net::modrinth::{DiscoveryResults, VersionInfo};
#[derive(Debug, Clone)]
pub struct FingerprintQuery {
pub key: String,
pub kind: ContentKind,
pub fingerprint: FileFingerprint,
}
#[derive(Debug, Clone)]
pub struct ResolvedFile {
pub key: String,
pub project: ProviderProject,
}
#[async_trait]
pub trait ContentProvider: Send + Sync {
fn id(&self) -> &'static str;
async fn search(
&self,
kind: ContentKind,
query: &str,
instance: &InstanceConfig,
offset: usize,
limit: usize,
) -> Result<DiscoveryResults, crate::net::NetError>;
async fn resolve_files(
&self,
files: &[FingerprintQuery],
) -> Result<Vec<ResolvedFile>, crate::net::NetError>;
async fn project(
&self,
project_id: &str,
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError>;
async fn compatible_versions(
&self,
project_id: &str,
kind: ContentKind,
game_version: &str,
loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError>;
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError>;
async fn download_version(
&self,
version: &VersionInfo,
destination: &std::path::Path,
installed_path: Option<&std::path::Path>,
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError>;
}
#[derive(Clone)]
pub struct ModrinthProvider {
client: crate::net::HttpClient,
}
impl ModrinthProvider {
pub fn new(client: crate::net::HttpClient) -> Self {
Self { client }
}
}
#[async_trait]
impl ContentProvider for ModrinthProvider {
fn id(&self) -> &'static str {
"modrinth"
}
async fn search(
&self,
kind: ContentKind,
query: &str,
instance: &InstanceConfig,
offset: usize,
limit: usize,
) -> Result<DiscoveryResults, crate::net::NetError> {
crate::net::modrinth::search_discovery(
&self.client,
discovery_kind(kind),
query,
&instance.game_version,
instance.loader,
offset,
limit,
)
.await
}
async fn resolve_files(
&self,
files: &[FingerprintQuery],
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
let by_hash = files
.iter()
.filter_map(|file| {
file.fingerprint
.hash("sha512")
.map(|hash| (hash.to_owned(), file.key.clone()))
})
.collect::<HashMap<_, _>>();
let hashes = by_hash.keys().cloned().collect::<Vec<_>>();
let versions =
crate::net::modrinth::resolve_version_files(&self.client, &hashes, "sha512").await?;
Ok(versions
.into_iter()
.filter_map(|(hash, version)| {
let key = by_hash.get(&hash)?.clone();
(!version.project_id.is_empty()).then_some(ResolvedFile {
key,
project: ProviderProject {
provider: self.id().to_owned(),
project_id: version.project_id,
version_id: version.id,
},
})
})
.collect())
}
async fn project(
&self,
project_id: &str,
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError> {
crate::net::modrinth::fetch_project(&self.client, project_id).await
}
async fn compatible_versions(
&self,
project_id: &str,
kind: ContentKind,
game_version: &str,
loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
crate::net::modrinth::fetch_content_versions(
&self.client,
project_id,
discovery_kind(kind),
game_version,
loader,
)
.await
}
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError> {
self.client.get_bytes(url).await
}
async fn download_version(
&self,
version: &VersionInfo,
destination: &std::path::Path,
installed_path: Option<&std::path::Path>,
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError> {
if let Some(installed_path) = installed_path {
crate::net::modrinth::download_version_file_for_update(
&self.client,
version,
destination,
installed_path,
)
.await
} else {
crate::net::modrinth::download_version_file(&self.client, version, destination).await
}
}
}
fn discovery_kind(kind: ContentKind) -> crate::net::modrinth::DiscoveryKind {
match kind {
ContentKind::Mod => crate::net::modrinth::DiscoveryKind::Mod,
ContentKind::ResourcePack => crate::net::modrinth::DiscoveryKind::ResourcePack,
ContentKind::Shader => crate::net::modrinth::DiscoveryKind::Shader,
}
}
pub struct ProviderRegistry {
providers: Vec<Box<dyn ContentProvider>>,
}
impl ProviderRegistry {
pub fn modrinth(client: crate::net::HttpClient) -> Self {
Self {
providers: vec![Box::new(ModrinthProvider::new(client))],
}
}
pub fn providers(&self) -> &[Box<dyn ContentProvider>] {
&self.providers
}
pub fn preferred(&self, id: &str) -> Option<&dyn ContentProvider> {
self.providers
.iter()
.find(|provider| provider.id() == id)
.map(Box::as_ref)
.or_else(|| self.providers.first().map(Box::as_ref))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_falls_back_to_first_capable_provider() {
let registry = ProviderRegistry::modrinth(crate::net::HttpClient::new());
assert_eq!(registry.preferred("unknown").unwrap().id(), "modrinth");
}
}
+41 -66
View File
@@ -203,18 +203,15 @@ fn profile_dir(meta_dir: &Path, profile: &str) -> PathBuf {
} }
fn profiles_dir(meta_dir: &Path) -> PathBuf { fn profiles_dir(meta_dir: &Path) -> PathBuf {
meta_dir.join("config-sync").join("profiles") crate::storage::MetadataPaths::new(meta_dir).profiles()
} }
fn minecraft_dir(instance_dir: &Path) -> PathBuf { fn minecraft_dir(instance_dir: &Path) -> PathBuf {
instance_dir.join(".minecraft") instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)
} }
fn local_backup_dir(instance_dir: &Path) -> PathBuf { fn local_backup_dir(instance_dir: &Path) -> PathBuf {
instance_dir crate::storage::InstancePaths::new(instance_dir).local_config()
.join(".rmcl")
.join("config-sync")
.join("local-config")
} }
fn acquire_lock(profile_dir: &Path) -> Result<ConfigSyncLock, ConfigSyncError> { fn acquire_lock(profile_dir: &Path) -> Result<ConfigSyncLock, ConfigSyncError> {
@@ -339,7 +336,7 @@ mod tests {
fn first_prepare_seeds_shared_config() { fn first_prepare_seeds_shared_config() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft"); let minecraft = tmp.path().join("instance/minecraft");
create_profile(&meta, "main").unwrap(); create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config/nested")).unwrap(); std::fs::create_dir_all(minecraft.join("config/nested")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap(); std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
@@ -350,21 +347,19 @@ mod tests {
assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(), std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
"local-options" "local-options"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/optionsshaders.txt")) std::fs::read_to_string(meta.join("state/profiles/main/optionsshaders.txt")).unwrap(),
.unwrap(),
"shader-options" "shader-options"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/options.txt")) std::fs::read_to_string(meta.join("state/profiles/main/config/options.txt")).unwrap(),
.unwrap(),
"local-config" "local-config"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/nested/mod.toml")) std::fs::read_to_string(meta.join("state/profiles/main/config/nested/mod.toml"))
.unwrap(), .unwrap(),
"nested" "nested"
); );
@@ -374,16 +369,16 @@ mod tests {
fn prepare_mirrors_shared_config_into_instance() { fn prepare_mirrors_shared_config_into_instance() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft"); let minecraft = tmp.path().join("instance/minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap(); std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap(); std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write( std::fs::write(
meta.join("config-sync/profiles/main/options.txt"), meta.join("state/profiles/main/options.txt"),
"shared-options", "shared-options",
) )
.unwrap(); .unwrap();
std::fs::write( std::fs::write(
meta.join("config-sync/profiles/main/config/shared.toml"), meta.join("state/profiles/main/config/shared.toml"),
"shared", "shared",
) )
.unwrap(); .unwrap();
@@ -407,13 +402,9 @@ mod tests {
fn finish_mirrors_instance_config_back_to_shared() { fn finish_mirrors_instance_config_back_to_shared() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft"); let minecraft = tmp.path().join("instance/minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap(); std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
std::fs::write( std::fs::write(meta.join("state/profiles/main/config/old.toml"), "old").unwrap();
meta.join("config-sync/profiles/main/config/old.toml"),
"old",
)
.unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap(); std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "new-options").unwrap(); std::fs::write(minecraft.join("options.txt"), "new-options").unwrap();
std::fs::write(minecraft.join("config/new.toml"), "new").unwrap(); std::fs::write(minecraft.join("config/new.toml"), "new").unwrap();
@@ -421,31 +412,26 @@ mod tests {
finish(Some("main"), &meta, &minecraft).unwrap(); finish(Some("main"), &meta, &minecraft).unwrap();
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(), std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
"new-options" "new-options"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/new.toml")) std::fs::read_to_string(meta.join("state/profiles/main/config/new.toml")).unwrap(),
.unwrap(),
"new" "new"
); );
assert!( assert!(!meta.join("state/profiles/main/config/old.toml").exists());
!meta
.join("config-sync/profiles/main/config/old.toml")
.exists()
);
} }
#[test] #[test]
fn prepare_releases_lock_for_another_instance() { fn prepare_releases_lock_for_another_instance() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft"); let minecraft = tmp.path().join("instance/minecraft");
create_profile(&meta, "main").unwrap(); create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap(); std::fs::create_dir_all(minecraft.join("config")).unwrap();
assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
let second = tmp.path().join("second/.minecraft"); let second = tmp.path().join("second/minecraft");
std::fs::create_dir_all(second.join("config")).unwrap(); std::fs::create_dir_all(second.join("config")).unwrap();
assert!(prepare(Some("main"), &meta, &second).unwrap()); assert!(prepare(Some("main"), &meta, &second).unwrap());
@@ -477,13 +463,13 @@ mod tests {
fn prepare_ignores_deleted_profile() { fn prepare_ignores_deleted_profile() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft"); let minecraft = tmp.path().join("instance/minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap(); std::fs::create_dir_all(minecraft.join("config")).unwrap();
let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap(); let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap();
assert!(!lock); assert!(!lock);
assert!(!meta.join("config-sync/profiles/deleted").exists()); assert!(!meta.join("state/profiles/deleted").exists());
} }
#[test] #[test]
@@ -512,7 +498,7 @@ mod tests {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance"); let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft"); let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(minecraft.join("config")).unwrap(); std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap(); std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("config/local.txt"), "local").unwrap(); std::fs::write(minecraft.join("config/local.txt"), "local").unwrap();
@@ -520,15 +506,11 @@ mod tests {
let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap(); let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("main")); assert_eq!(selected.as_deref(), Some("main"));
assert_eq!( assert_eq!(
std::fs::read_to_string(instance.join(".rmcl/config-sync/local-config/options.txt")) std::fs::read_to_string(instance.join("rmcl/content/config/options.txt")).unwrap(),
.unwrap(),
"local-options" "local-options"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string( std::fs::read_to_string(instance.join("rmcl/content/config/config/local.txt")).unwrap(),
instance.join(".rmcl/config-sync/local-config/config/local.txt")
)
.unwrap(),
"local" "local"
); );
@@ -538,12 +520,11 @@ mod tests {
assert_eq!(selected, None); assert_eq!(selected, None);
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(), std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
"shared-options" "shared-options"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/shared.txt")) std::fs::read_to_string(meta.join("state/profiles/main/config/shared.txt")).unwrap(),
.unwrap(),
"shared" "shared"
); );
assert_eq!( assert_eq!(
@@ -562,17 +543,17 @@ mod tests {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance"); let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft"); let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(minecraft.join("config")).unwrap(); std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::create_dir_all(instance.join(".rmcl/config-sync/local-config/config")).unwrap(); std::fs::create_dir_all(instance.join("rmcl/content/config/config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap(); std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap();
std::fs::write( std::fs::write(
instance.join(".rmcl/config-sync/local-config/options.txt"), instance.join("rmcl/content/config/options.txt"),
"local-options", "local-options",
) )
.unwrap(); .unwrap();
std::fs::write( std::fs::write(
instance.join(".rmcl/config-sync/local-config/config/local.txt"), instance.join("rmcl/content/config/config/local.txt"),
"local", "local",
) )
.unwrap(); .unwrap();
@@ -588,7 +569,7 @@ mod tests {
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(), std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local" "local"
); );
assert!(!meta.join("config-sync/profiles/deleted").exists()); assert!(!meta.join("state/profiles/deleted").exists());
} }
#[test] #[test]
@@ -596,32 +577,28 @@ mod tests {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance"); let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft"); let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(minecraft.join("config")).unwrap(); std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap(); std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap();
std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap(); std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap();
create_profile(&meta, "a").unwrap(); create_profile(&meta, "a").unwrap();
std::fs::create_dir_all(meta.join("config-sync/profiles/b/config")).unwrap(); std::fs::create_dir_all(meta.join("state/profiles/b/config")).unwrap();
std::fs::write( std::fs::write(
meta.join("config-sync/profiles/b/options.txt"), meta.join("state/profiles/b/options.txt"),
"profile-b-options", "profile-b-options",
) )
.unwrap(); .unwrap();
std::fs::write( std::fs::write(meta.join("state/profiles/b/config/b.txt"), "profile-b").unwrap();
meta.join("config-sync/profiles/b/config/b.txt"),
"profile-b",
)
.unwrap();
let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap(); let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("b")); assert_eq!(selected.as_deref(), Some("b"));
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/options.txt")).unwrap(), std::fs::read_to_string(meta.join("state/profiles/a/options.txt")).unwrap(),
"changed-a-options" "changed-a-options"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/config/a.txt")).unwrap(), std::fs::read_to_string(meta.join("state/profiles/a/config/a.txt")).unwrap(),
"changed-a" "changed-a"
); );
assert_eq!( assert_eq!(
@@ -639,9 +616,9 @@ mod tests {
fn second_instance_uses_profile_options_saved_by_first_instance() { fn second_instance_uses_profile_options_saved_by_first_instance() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
let first = tmp.path().join("first/.minecraft"); let first = tmp.path().join("first/minecraft");
let second_instance = tmp.path().join("second"); let second_instance = tmp.path().join("second");
let second = second_instance.join(".minecraft"); let second = second_instance.join(crate::storage::MINECRAFT_DIR_NAME);
std::fs::create_dir_all(first.join("config")).unwrap(); std::fs::create_dir_all(first.join("config")).unwrap();
std::fs::create_dir_all(second.join("config")).unwrap(); std::fs::create_dir_all(second.join("config")).unwrap();
std::fs::write(first.join("options.txt"), "first-default").unwrap(); std::fs::write(first.join("options.txt"), "first-default").unwrap();
@@ -659,9 +636,7 @@ mod tests {
"changed-in-main" "changed-in-main"
); );
assert_eq!( assert_eq!(
std::fs::read_to_string( std::fs::read_to_string(second_instance.join("rmcl/content/config/options.txt"))
second_instance.join(".rmcl/config-sync/local-config/options.txt")
)
.unwrap(), .unwrap(),
"second-local" "second-local"
); );
+279
View File
@@ -0,0 +1,279 @@
use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use sha1::Digest as _;
const MANIFEST_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContentKind {
Mod,
ResourcePack,
Shader,
}
impl ContentKind {
pub fn directory(self) -> &'static str {
match self {
Self::Mod => "mods",
Self::ResourcePack => "resourcepacks",
Self::Shader => "shaderpacks",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProviderProject {
pub provider: String,
pub project_id: String,
pub version_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum Resolution {
Pending,
Resolved {
project: ProviderProject,
},
Unmatched {
checked_at: i64,
providers: Vec<String>,
},
Ambiguous {
candidates: Vec<ProviderProject>,
},
}
impl Default for Resolution {
fn default() -> Self {
Self::Pending
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileFingerprint {
pub size: u64,
pub modified_ns: u128,
pub hashes: BTreeMap<String, String>,
}
impl FileFingerprint {
pub fn hash(&self, algorithm: &str) -> Option<&str> {
self.hashes.get(algorithm).map(String::as_str)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContentFileRecord {
pub relative_path: PathBuf,
pub kind: ContentKind,
pub enabled: bool,
pub fingerprint: FileFingerprint,
#[serde(default)]
pub resolution: Resolution,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentManifest {
pub version: u32,
#[serde(default)]
pub files: Vec<ContentFileRecord>,
}
impl Default for ContentManifest {
fn default() -> Self {
Self {
version: MANIFEST_VERSION,
files: Vec::new(),
}
}
}
impl ContentManifest {
pub fn load(path: &Path) -> Result<Self, ManifestError> {
if !path.exists() {
return Ok(Self::default());
}
let bytes = std::fs::read(path)?;
let manifest: Self = serde_json::from_slice(&bytes)?;
if manifest.version != MANIFEST_VERSION {
return Err(ManifestError::UnsupportedVersion(manifest.version));
}
Ok(manifest)
}
pub fn save(&self, path: &Path) -> Result<(), ManifestError> {
let parent = path.parent().ok_or_else(|| {
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
})?;
std::fs::create_dir_all(parent)?;
let temporary = parent.join(format!(
".{}.tmp",
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("manifest")
));
let bytes = serde_json::to_vec_pretty(self)?;
std::fs::write(&temporary, bytes)?;
std::fs::rename(temporary, path)?;
Ok(())
}
pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> {
self.files
.iter()
.find(|record| record.relative_path == relative_path)
}
pub fn upsert(&mut self, record: ContentFileRecord) {
if let Some(existing) = self
.files
.iter_mut()
.find(|existing| existing.relative_path == record.relative_path)
{
*existing = record;
} else {
self.files.push(record);
self.files
.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
}
}
pub fn remove(&mut self, relative_path: &Path) {
self.files
.retain(|record| record.relative_path != relative_path);
}
pub fn resolved_project_path(
&self,
provider: &str,
project_id: &str,
minecraft_dir: &Path,
) -> Option<PathBuf> {
self.files.iter().find_map(|record| {
let Resolution::Resolved { project } = &record.resolution else {
return None;
};
(project.provider == provider && project.project_id == project_id)
.then(|| minecraft_dir.join(&record.relative_path))
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum ManifestError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("Unsupported content manifest version {0}")]
UnsupportedVersion(u32),
#[error("Invalid manifest path: {0}")]
InvalidPath(String),
}
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
let metadata = std::fs::metadata(path)?;
let modified_ns = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let mut file = std::fs::File::open(path)?;
let mut sha1 = sha1::Sha1::new();
let mut sha512 = sha2::Sha512::new();
let mut buffer = [0u8; 64 * 1024];
loop {
let read = file.read(&mut buffer)?;
if read == 0 {
break;
}
sha1.update(&buffer[..read]);
sha512.update(&buffer[..read]);
}
let hashes = BTreeMap::from([
("sha1".to_owned(), format!("{:x}", sha1.finalize())),
("sha512".to_owned(), format!("{:x}", sha512.finalize())),
]);
Ok(FileFingerprint {
size: metadata.len(),
modified_ns,
hashes,
})
}
pub fn fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::io::Error> {
let metadata = std::fs::metadata(path)?;
let modified_ns = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
Ok(FileFingerprint {
size: metadata.len(),
modified_ns,
hashes: BTreeMap::new(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manifest_round_trip_and_lookup_are_exact() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("rmcl/content/manifest.json");
let record = ContentFileRecord {
relative_path: PathBuf::from("mods/fabric-api.jar"),
kind: ContentKind::Mod,
enabled: true,
fingerprint: FileFingerprint {
size: 3,
modified_ns: 4,
hashes: BTreeMap::from([("sha1".to_owned(), "abc".to_owned())]),
},
resolution: Resolution::Resolved {
project: ProviderProject {
provider: "modrinth".to_owned(),
project_id: "P7dR8mSH".to_owned(),
version_id: "version".to_owned(),
},
},
};
let mut manifest = ContentManifest::default();
manifest.upsert(record);
manifest.save(&path).unwrap();
let loaded = ContentManifest::load(&path).unwrap();
assert_eq!(
loaded.resolved_project_path("modrinth", "P7dR8mSH", Path::new("/instance/minecraft")),
Some(PathBuf::from("/instance/minecraft/mods/fabric-api.jar"))
);
assert!(
loaded
.resolved_project_path("modrinth", "fabric-api", Path::new("/minecraft"))
.is_none()
);
}
#[test]
fn fingerprint_contains_both_modrinth_hashes() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("example.jar");
std::fs::write(&path, b"abc").unwrap();
let fingerprint = fingerprint(&path).unwrap();
assert_eq!(
fingerprint.hash("sha1"),
Some("a9993e364706816aba3e25717850c26c9cd0d89d")
);
assert_eq!(fingerprint.hash("sha512").unwrap().len(), 128);
}
}
+2
View File
@@ -1,7 +1,9 @@
// scanning and toggling instance content (mods, resource packs, shaders, worlds). // scanning and toggling instance content (mods, resource packs, shaders, worlds).
// minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily. // minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily.
pub mod manifest;
pub mod mods; pub mod mods;
pub mod reconcile;
pub mod resource_packs; pub mod resource_packs;
pub mod shaders; pub mod shaders;
pub mod worlds; pub mod worlds;
+9 -2
View File
@@ -28,6 +28,7 @@ pub struct ContentEntry {
pub name: String, pub name: String,
pub source_slug: Option<String>, pub source_slug: Option<String>,
pub installed_path: Option<PathBuf>, pub installed_path: Option<PathBuf>,
pub provider_project: Option<super::manifest::ProviderProject>,
pub title_suffix: Option<String>, pub title_suffix: Option<String>,
pub footer_label: Option<String>, pub footer_label: Option<String>,
pub description: String, pub description: String,
@@ -114,6 +115,7 @@ pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry
name: display_name, name: display_name,
source_slug: None, source_slug: None,
installed_path: None, installed_path: None,
provider_project: None,
title_suffix: None, title_suffix: None,
footer_label: None, footer_label: None,
description, description,
@@ -127,7 +129,7 @@ pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> { pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let mods_dir = instances_dir let mods_dir = instances_dir
.join(instance_name) .join(instance_name)
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("mods"); .join("mods");
let read_dir = match std::fs::read_dir(&mods_dir) { let read_dir = match std::fs::read_dir(&mods_dir) {
@@ -633,7 +635,10 @@ mod tests {
} }
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf { fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("mods"); let dir = tmp
.join(instance)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("mods");
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
dir dir
} }
@@ -711,6 +716,7 @@ mod tests {
name: "mymod".to_string(), name: "mymod".to_string(),
source_slug: None, source_slug: None,
installed_path: None, installed_path: None,
provider_project: None,
title_suffix: None, title_suffix: None,
footer_label: None, footer_label: None,
description: String::new(), description: String::new(),
@@ -986,6 +992,7 @@ description = "A neoforge mod"
name: "mymod".to_string(), name: "mymod".to_string(),
source_slug: None, source_slug: None,
installed_path: None, installed_path: None,
provider_project: None,
title_suffix: None, title_suffix: None,
footer_label: None, footer_label: None,
description: String::new(), description: String::new(),
+690
View File
@@ -0,0 +1,690 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::content_provider::{FingerprintQuery, ProviderRegistry};
use crate::instance::InstanceConfig;
use crate::instance::content::manifest::{
ContentFileRecord, ContentKind, ContentManifest, ProviderProject, Resolution, fingerprint,
fingerprint_metadata,
};
use crate::storage::{InstancePaths, MetadataPaths};
use crate::tui::progress::{ProgressTask, ProgressTaskHandle};
#[derive(Debug)]
pub struct ReconcileResult {
pub instance_name: String,
pub manifest: ContentManifest,
pub icons: HashMap<(String, String), Vec<u8>>,
pub error: Option<String>,
}
pub static PENDING_RECONCILIATIONS: LazyLock<Arc<Mutex<Vec<ReconcileResult>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
#[derive(Clone)]
struct ReconcileJob {
instance: InstanceConfig,
instances_dir: PathBuf,
meta_dir: PathBuf,
client: crate::net::HttpClient,
}
#[derive(Default)]
struct ReconcileCoordinator {
queue: VecDeque<ReconcileJob>,
scheduled: HashSet<String>,
rerun: HashSet<String>,
worker_running: bool,
}
impl ReconcileCoordinator {
fn enqueue(&mut self, job: ReconcileJob, rerun_if_scheduled: bool) -> bool {
let instance_name = job.instance.name.clone();
if !self.scheduled.insert(instance_name.clone()) {
if rerun_if_scheduled {
self.rerun.insert(instance_name);
}
return false;
}
self.queue.push_back(job);
if self.worker_running {
false
} else {
self.worker_running = true;
true
}
}
}
static RECONCILE_COORDINATOR: LazyLock<Mutex<ReconcileCoordinator>> =
LazyLock::new(|| Mutex::new(ReconcileCoordinator::default()));
pub fn spawn(
instance: InstanceConfig,
instances_dir: PathBuf,
meta_dir: PathBuf,
client: crate::net::HttpClient,
) {
schedule(instance, instances_dir, meta_dir, client, false);
}
pub fn spawn_after_change(
instance: InstanceConfig,
instances_dir: PathBuf,
meta_dir: PathBuf,
client: crate::net::HttpClient,
) {
schedule(instance, instances_dir, meta_dir, client, true);
}
fn schedule(
instance: InstanceConfig,
instances_dir: PathBuf,
meta_dir: PathBuf,
client: crate::net::HttpClient,
rerun_if_scheduled: bool,
) {
let start_worker = {
let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() else {
return;
};
coordinator.enqueue(
ReconcileJob {
instance,
instances_dir,
meta_dir,
client,
},
rerun_if_scheduled,
)
};
if start_worker {
tokio::spawn(reconcile_worker());
}
}
async fn reconcile_worker() {
let task = ProgressTask::start("Preparing content index");
loop {
let job = {
let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() else {
task.finish();
return;
};
match coordinator.queue.pop_front() {
Some(job) => job,
None => {
coordinator.worker_running = false;
task.finish();
return;
}
}
};
let instance_name = job.instance.name.clone();
let rerun_job = job.clone();
let result = reconcile(job, &task).await;
if let Ok(mut results) = PENDING_RECONCILIATIONS.lock() {
results.retain(|pending| pending.instance_name != instance_name);
results.push(result);
}
if let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() {
if coordinator.rerun.remove(&instance_name) {
coordinator.queue.push_back(rerun_job);
} else {
coordinator.scheduled.remove(&instance_name);
}
}
crate::tui::request_redraw();
}
}
async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
let ReconcileJob {
instance,
instances_dir,
meta_dir,
client,
} = job;
let instance_name = instance.name;
task.set_action(format!("Checking content for {instance_name}"));
task.set_sub_action("Reading saved content index");
task.set_progress(0, 1);
let paths = InstancePaths::new(instances_dir.join(&instance_name));
let manifest_path = paths.content_manifest();
let minecraft_dir = paths.minecraft();
let retry_hours = crate::config::SETTINGS.content.unmatched_retry_hours;
let max_fingerprint_size_mib = crate::config::SETTINGS.content.max_fingerprint_size_mib;
let inventory_progress = task.handle();
let inventory = tokio::task::spawn_blocking(move || {
reconcile_inventory(
&manifest_path,
&minecraft_dir,
retry_hours,
max_fingerprint_size_mib,
&inventory_progress,
)
.map(|result| (result, manifest_path))
})
.await;
let result = match inventory {
Ok(Ok((mut inventory, manifest_path))) => {
let registry = ProviderRegistry::modrinth(client);
task.set_action(format!("Identifying content for {instance_name}"));
task.set_sub_action(format!("{} file(s) need matching", inventory.queries.len()));
if !inventory.queries.is_empty() {
task.set_progress(0, inventory.queries.len() as u64);
}
let resolution_result =
resolve_queries(&registry, &inventory.queries, &mut inventory.manifest).await;
if !inventory.queries.is_empty() {
task.set_progress(
inventory.queries.len() as u64,
inventory.queries.len() as u64,
);
}
match resolution_result {
Ok(()) => {
task.set_action(format!("Loading content icons for {instance_name}"));
let icon_result = load_project_icons(
&registry,
&inventory.manifest,
&MetadataPaths::new(&meta_dir),
&task,
)
.await;
match inventory.manifest.save(&manifest_path) {
Ok(()) => ReconcileResult {
instance_name,
manifest: inventory.manifest,
icons: icon_result.unwrap_or_default(),
error: None,
},
Err(error) => ReconcileResult {
instance_name,
manifest: inventory.manifest,
icons: HashMap::new(),
error: Some(error.to_string()),
},
}
}
Err(error) => ReconcileResult {
instance_name,
manifest: inventory.manifest,
icons: HashMap::new(),
error: Some(error.to_string()),
},
}
}
Ok(Err(error)) => ReconcileResult {
instance_name,
manifest: ContentManifest::default(),
icons: HashMap::new(),
error: Some(error.to_string()),
},
Err(error) => ReconcileResult {
instance_name,
manifest: ContentManifest::default(),
icons: HashMap::new(),
error: Some(error.to_string()),
},
};
result
}
struct Inventory {
manifest: ContentManifest,
queries: Vec<FingerprintQuery>,
}
trait InventoryProgress {
fn set_sub_action(&self, text: &str);
fn set_progress(&self, current: u64, total: u64);
}
impl InventoryProgress for ProgressTaskHandle {
fn set_sub_action(&self, text: &str) {
ProgressTaskHandle::set_sub_action(self, text);
}
fn set_progress(&self, current: u64, total: u64) {
ProgressTaskHandle::set_progress(self, current, total);
}
}
fn reconcile_inventory(
manifest_path: &Path,
minecraft_dir: &Path,
unmatched_retry_hours: u64,
max_fingerprint_size_mib: u64,
task: &impl InventoryProgress,
) -> Result<Inventory, Box<dyn std::error::Error + Send + Sync>> {
let previous = ContentManifest::load(manifest_path)?;
let files = content_files(minecraft_dir)?;
let file_count = files.len() as u64;
if file_count == 0 {
task.set_sub_action("No local content files");
task.set_progress(1, 1);
} else {
task.set_progress(0, file_count);
}
let now = chrono::Utc::now().timestamp();
let retry_seconds = unmatched_retry_hours.saturating_mul(60 * 60) as i64;
let mut manifest = ContentManifest::default();
let mut queries = Vec::new();
for (index, (kind, path)) in files.into_iter().enumerate() {
task.set_sub_action(
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("content"),
);
let relative_path = path.strip_prefix(minecraft_dir)?.to_path_buf();
let enabled = !path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.ends_with(".disabled"));
let metadata = std::fs::metadata(&path)?;
let modified_ns = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let existing = previous.record(&relative_path);
let unchanged = existing.is_some_and(|record| {
record.fingerprint.size == metadata.len()
&& record.fingerprint.modified_ns == modified_ns
});
let oversized = max_fingerprint_size_mib > 0
&& metadata.len() > max_fingerprint_size_mib.saturating_mul(1024 * 1024);
let mut record = if unchanged {
existing.cloned().unwrap()
} else if oversized {
tracing::debug!(
"Skipping automatic provider matching for {} ({} bytes exceeds {} MiB limit)",
path.display(),
metadata.len(),
max_fingerprint_size_mib
);
ContentFileRecord {
relative_path: relative_path.clone(),
kind,
enabled,
fingerprint: fingerprint_metadata(&path)?,
resolution: Resolution::Unmatched {
checked_at: now,
providers: Vec::new(),
},
}
} else {
ContentFileRecord {
relative_path: relative_path.clone(),
kind,
enabled,
fingerprint: fingerprint(&path)?,
resolution: Resolution::Pending,
}
};
record.kind = kind;
record.enabled = enabled;
if oversized && matches!(record.resolution, Resolution::Pending) {
record.resolution = Resolution::Unmatched {
checked_at: now,
providers: Vec::new(),
};
}
let should_query = !oversized
&& match &record.resolution {
Resolution::Pending => true,
Resolution::Unmatched { checked_at, .. } => {
now.saturating_sub(*checked_at) >= retry_seconds
}
Resolution::Resolved { .. } | Resolution::Ambiguous { .. } => false,
};
if should_query {
record.resolution = Resolution::Pending;
queries.push(FingerprintQuery {
key: relative_path.to_string_lossy().into_owned(),
kind,
fingerprint: record.fingerprint.clone(),
});
}
manifest.upsert(record);
task.set_progress(index as u64 + 1, file_count);
}
Ok(Inventory { manifest, queries })
}
async fn resolve_queries(
registry: &ProviderRegistry,
queries: &[FingerprintQuery],
manifest: &mut ContentManifest,
) -> Result<(), crate::net::NetError> {
if queries.is_empty() {
return Ok(());
}
let mut matches: HashMap<String, Vec<ProviderProject>> = HashMap::new();
let mut checked = Vec::new();
for provider in registry.providers() {
let provider_id = provider.id();
match tokio::time::timeout(
std::time::Duration::from_secs(10),
provider.resolve_files(queries),
)
.await
{
Ok(Ok(resolved_files)) => {
checked.push(provider_id.to_owned());
for resolved in resolved_files {
matches
.entry(resolved.key)
.or_default()
.push(resolved.project);
}
}
Ok(Err(error)) => {
tracing::warn!(
"Skipping {provider_id} content matching after provider error: {error}"
);
}
Err(_) => {
tracing::warn!(
"Skipping {provider_id} content matching after the 10 second timeout"
);
}
}
}
let query_keys = queries
.iter()
.map(|query| query.key.as_str())
.collect::<HashSet<_>>();
let checked_at = chrono::Utc::now().timestamp();
for record in &mut manifest.files {
let key = record.relative_path.to_string_lossy();
if !query_keys.contains(key.as_ref()) {
continue;
}
let candidates = matches.remove(key.as_ref()).unwrap_or_default();
record.resolution = match candidates.as_slice() {
[] => Resolution::Unmatched {
checked_at,
providers: checked.clone(),
},
[project] => Resolution::Resolved {
project: project.clone(),
},
_ if !crate::config::SETTINGS.content.ask_on_provider_conflict => {
let preferred = &crate::config::SETTINGS.content.preferred_provider;
if let Some(project) = candidates
.iter()
.find(|project| &project.provider == preferred)
{
Resolution::Resolved {
project: project.clone(),
}
} else {
Resolution::Ambiguous { candidates }
}
}
_ => Resolution::Ambiguous { candidates },
};
}
Ok(())
}
async fn load_project_icons(
registry: &ProviderRegistry,
manifest: &ContentManifest,
metadata: &MetadataPaths,
task: &ProgressTask,
) -> Result<HashMap<(String, String), Vec<u8>>, crate::net::NetError> {
let mut projects = manifest
.files
.iter()
.filter_map(|record| match &record.resolution {
Resolution::Resolved { project } => {
Some((project.provider.clone(), project.project_id.clone()))
}
_ => None,
})
.collect::<Vec<_>>();
projects.sort();
projects.dedup();
let project_count = projects.len() as u64;
task.set_sub_action(format!("{} icon(s)", projects.len()));
if project_count > 0 {
task.set_progress(0, project_count);
}
let mut icons = HashMap::new();
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
for (index, (provider_id, project_id)) in projects.into_iter().enumerate() {
let Some(provider) = registry.preferred(&provider_id) else {
task.set_progress(index as u64 + 1, project_count);
continue;
};
let icon_path = metadata
.provider_icons(&provider_id)
.join(format!("{project_id}.img"));
if let Ok(bytes) = tokio::fs::read(&icon_path).await {
icons.insert((provider_id, project_id), bytes);
task.set_progress(index as u64 + 1, project_count);
continue;
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
tracing::debug!(
"Content icon loading reached its 10 second startup budget; remaining icons will use fallbacks"
);
task.set_progress(project_count, project_count);
break;
}
task.set_sub_action(&project_id);
match tokio::time::timeout(
remaining.min(std::time::Duration::from_secs(3)),
provider.project(&project_id),
)
.await
{
Ok(Ok(project)) => {
if let Err(error) = cache_project(metadata, &provider_id, &project) {
tracing::warn!("Failed to cache {provider_id} project {project_id}: {error}");
}
if let Some(url) = project.icon_url.as_deref() {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
match tokio::time::timeout(
remaining.min(std::time::Duration::from_secs(3)),
provider.icon(url),
)
.await
{
Ok(Ok(bytes)) => {
let cache_result = async {
if let Some(parent) = icon_path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
tokio::fs::write(&icon_path, &bytes).await
}
.await;
if let Err(error) = cache_result {
tracing::warn!(
"Failed to cache icon for {provider_id} project \
{project_id}: {error}"
);
}
icons.insert((provider_id, project_id), bytes);
}
Ok(Err(error)) => tracing::warn!(
"Failed to download icon for {provider_id} project \
{project_id}: {error}"
),
Err(_) => tracing::debug!(
"Timed out loading icon for {provider_id} project {project_id}; using fallback"
),
}
}
}
Ok(Err(error)) => {
tracing::warn!("Failed to load {provider_id} project {project_id}: {error}")
}
Err(_) => tracing::debug!(
"Timed out loading {provider_id} project {project_id}; using fallback"
),
}
task.set_progress(index as u64 + 1, project_count);
}
Ok(icons)
}
fn cache_project(
metadata: &MetadataPaths,
provider: &str,
project: &crate::net::modrinth::ProjectInfo,
) -> Result<(), crate::net::NetError> {
let path = metadata
.provider_projects(provider)
.join(format!("{}.json", project.id));
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(
path,
serde_json::to_vec_pretty(project)
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?,
)?;
Ok(())
}
fn content_files(minecraft_dir: &Path) -> std::io::Result<Vec<(ContentKind, PathBuf)>> {
let mut files = Vec::new();
for kind in [
ContentKind::Mod,
ContentKind::ResourcePack,
ContentKind::Shader,
] {
let directory = minecraft_dir.join(kind.directory());
let Ok(entries) = std::fs::read_dir(directory) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && supported_file(kind, &path) {
files.push((kind, path));
}
}
}
files.sort_by(|left, right| left.1.cmp(&right.1));
Ok(files)
}
fn supported_file(kind: ContentKind, path: &Path) -> bool {
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
return false;
};
match kind {
ContentKind::Mod => name.ends_with(".jar") || name.ends_with(".jar.disabled"),
ContentKind::ResourcePack | ContentKind::Shader => {
name.ends_with(".zip") || name.ends_with(".zip.disabled")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct NoopProgress;
impl InventoryProgress for NoopProgress {
fn set_sub_action(&self, _text: &str) {}
fn set_progress(&self, _current: u64, _total: u64) {}
}
fn job(name: &str) -> ReconcileJob {
ReconcileJob {
instance: InstanceConfig {
name: name.to_owned(),
game_version: "1.21.1".to_owned(),
loader: crate::instance::ModLoader::Fabric,
loader_version: None,
created: chrono::Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
},
instances_dir: PathBuf::new(),
meta_dir: PathBuf::new(),
client: crate::net::HttpClient::new(),
}
}
#[test]
fn coordinator_queues_instances_once_and_preserves_order() {
let mut coordinator = ReconcileCoordinator::default();
assert!(coordinator.enqueue(job("one"), false));
assert!(!coordinator.enqueue(job("two"), false));
assert!(!coordinator.enqueue(job("one"), false));
assert!(!coordinator.rerun.contains("one"));
assert!(!coordinator.enqueue(job("one"), true));
assert_eq!(coordinator.queue.len(), 2);
assert!(coordinator.rerun.contains("one"));
assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "one");
assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "two");
}
#[test]
fn oversized_content_is_kept_without_hashing_or_provider_query() {
let temp = tempfile::tempdir().unwrap();
let minecraft = temp.path().join("minecraft");
let resource_packs = minecraft.join("resourcepacks");
std::fs::create_dir_all(&resource_packs).unwrap();
let pack = resource_packs.join("large.zip");
let file = std::fs::File::create(&pack).unwrap();
file.set_len(2 * 1024 * 1024).unwrap();
let manifest_path = temp.path().join("manifest.json");
let inventory =
reconcile_inventory(&manifest_path, &minecraft, 24, 1, &NoopProgress).unwrap();
assert!(inventory.queries.is_empty());
assert_eq!(inventory.manifest.files.len(), 1);
assert!(inventory.manifest.files[0].fingerprint.hashes.is_empty());
assert!(matches!(
inventory.manifest.files[0].resolution,
Resolution::Unmatched { .. }
));
}
#[test]
fn unchanged_saved_index_reuses_fingerprint_and_skips_provider_query() {
let temp = tempfile::tempdir().unwrap();
let minecraft = temp.path().join("minecraft");
let mods = minecraft.join("mods");
std::fs::create_dir_all(&mods).unwrap();
std::fs::write(mods.join("example.jar"), b"example").unwrap();
let manifest_path = temp.path().join("manifest.json");
let mut first =
reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
assert_eq!(first.queries.len(), 1);
let fingerprint = first.manifest.files[0].fingerprint.clone();
first.manifest.files[0].resolution = Resolution::Unmatched {
checked_at: chrono::Utc::now().timestamp(),
providers: vec!["modrinth".to_owned()],
};
first.manifest.save(&manifest_path).unwrap();
let second =
reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
assert!(second.queries.is_empty());
assert_eq!(second.manifest.files[0].fingerprint, fingerprint);
}
}
+2 -1
View File
@@ -67,6 +67,7 @@ pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> Co
name: display_name, name: display_name,
source_slug: None, source_slug: None,
installed_path: None, installed_path: None,
provider_project: None,
title_suffix: None, title_suffix: None,
footer_label: None, footer_label: None,
description, description,
@@ -80,7 +81,7 @@ pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> Co
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> { pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let packs_dir = instances_dir let packs_dir = instances_dir
.join(instance_name) .join(instance_name)
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("resourcepacks"); .join("resourcepacks");
let read_dir = match std::fs::read_dir(&packs_dir) { let read_dir = match std::fs::read_dir(&packs_dir) {
+4 -2
View File
@@ -16,13 +16,15 @@ pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEn
let icon_lines = icon_bytes let icon_lines = icon_bytes
.as_ref() .as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3)); .and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(super::mods::fallback_icon()));
ContentEntry { ContentEntry {
file_stem: file_stem.to_owned(), file_stem: file_stem.to_owned(),
name: file_stem.to_owned(), name: file_stem.to_owned(),
source_slug: None, source_slug: None,
installed_path: None, installed_path: None,
provider_project: None,
title_suffix: None, title_suffix: None,
footer_label: None, footer_label: None,
description, description,
@@ -36,7 +38,7 @@ pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEn
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> { pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let shaders_dir = instances_dir let shaders_dir = instances_dir
.join(instance_name) .join(instance_name)
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("shaderpacks"); .join("shaderpacks");
let read_dir = match std::fs::read_dir(&shaders_dir) { let read_dir = match std::fs::read_dir(&shaders_dir) {
+2 -1
View File
@@ -20,6 +20,7 @@ pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEnt
file_stem: file_stem.to_owned(), file_stem: file_stem.to_owned(),
source_slug: None, source_slug: None,
installed_path: None, installed_path: None,
provider_project: None,
title_suffix: None, title_suffix: None,
footer_label: None, footer_label: None,
description, description,
@@ -33,7 +34,7 @@ pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEnt
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> { pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let saves_dir = instances_dir let saves_dir = instances_dir
.join(instance_name) .join(instance_name)
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("saves"); .join("saves");
let read_dir = match std::fs::read_dir(&saves_dir) { let read_dir = match std::fs::read_dir(&saves_dir) {
+4 -1
View File
@@ -114,7 +114,10 @@ pub async fn execute_import(
.await .await
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?; .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft"); let minecraft_dir = manager
.instances_dir
.join(&name)
.join(crate::storage::MINECRAFT_DIR_NAME);
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?; extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
progress::clear(); progress::clear();
+4 -1
View File
@@ -87,7 +87,10 @@ pub async fn execute_import(
.await .await
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?; .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft"); let minecraft_dir = manager
.instances_dir
.join(&name)
.join(crate::storage::MINECRAFT_DIR_NAME);
let index = crate::net::modrinth::parse_mrpack(&summary.archive_path) let index = crate::net::modrinth::parse_mrpack(&summary.archive_path)
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?; .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
+12 -11
View File
@@ -249,7 +249,7 @@ async fn migrate_legacy_loader_profile_if_needed(
}; };
let installer_json_path = instance_dir let installer_json_path = instance_dir
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("versions") .join("versions")
.join(&version_dir) .join(&version_dir)
.join(format!("{version_dir}.json")); .join(format!("{version_dir}.json"));
@@ -318,10 +318,11 @@ pub async fn build_launch_invocation(
auth: &LaunchAuth<'_>, auth: &LaunchAuth<'_>,
) -> Result<LaunchInvocation, LaunchError> { ) -> Result<LaunchInvocation, LaunchError> {
let instance_dir = instances_dir.join(&config.name); let instance_dir = instances_dir.join(&config.name);
let minecraft_dir = instance_dir.join(".minecraft"); let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
let meta_path = meta_dir let metadata_paths = crate::storage::MetadataPaths::new(meta_dir);
.join("versions") let meta_path = metadata_paths
.versions()
.join(&config.game_version) .join(&config.game_version)
.join("meta.json"); .join("meta.json");
if !meta_path.exists() { if !meta_path.exists() {
@@ -348,7 +349,7 @@ pub async fn build_launch_invocation(
.map(|ai| ai.id.clone()) .map(|ai| ai.id.clone())
.unwrap_or_default(); .unwrap_or_default();
let lib_dir = meta_dir.join("libraries"); let lib_dir = metadata_paths.libraries();
let lv = config.loader_version.as_deref().unwrap_or("unknown"); let lv = config.loader_version.as_deref().unwrap_or("unknown");
let profile_filename = match config.loader { let profile_filename = match config.loader {
@@ -364,7 +365,7 @@ pub async fn build_launch_invocation(
// the vanilla meta migration above ensured is fresh on disk). when no // the vanilla meta migration above ensured is fresh on disk). when no
// loader is configured we use the already-loaded vanilla meta directly. // loader is configured we use the already-loaded vanilla meta directly.
let merged_profile: LaunchProfile = if let Some(filename) = &profile_filename { let merged_profile: LaunchProfile = if let Some(filename) = &profile_filename {
let profile_path = meta_dir.join("loader-profiles").join(filename); let profile_path = metadata_paths.loader_profiles().join(filename);
if !profile_path.exists() { if !profile_path.exists() {
return Err(LaunchError::MetaNotFound( return Err(LaunchError::MetaNotFound(
profile_path.display().to_string(), profile_path.display().to_string(),
@@ -453,8 +454,8 @@ pub async fn build_launch_invocation(
} }
classpath.push( classpath.push(
meta_dir metadata_paths
.join("versions") .versions()
.join(&config.game_version) .join(&config.game_version)
.join(format!("{}.jar", config.game_version)), .join(format!("{}.jar", config.game_version)),
); );
@@ -497,9 +498,9 @@ pub async fn build_launch_invocation(
) )
.await?; .await?;
let assets_root = meta_dir.join("assets"); let assets_root = metadata_paths.assets();
let natives_dir = meta_dir let natives_dir = metadata_paths
.join("versions") .versions()
.join(&config.game_version) .join(&config.game_version)
.join("natives"); .join("natives");
let version_type = merged_profile.type_.as_deref().unwrap_or("release"); let version_type = merged_profile.type_.as_deref().unwrap_or("release");
+3 -1
View File
@@ -45,7 +45,9 @@ impl ModLoaderInstaller for ForgeInstaller {
instance_dir: &Path, instance_dir: &Path,
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), InstallError> { ) -> Result<(), InstallError> {
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar"); let installer_jar = instance_dir
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("forge-installer.jar");
tracing::info!( tracing::info!(
"Installing Forge {} for Minecraft {}", "Installing Forge {} for Minecraft {}",
loader_version, loader_version,
+5 -5
View File
@@ -74,7 +74,7 @@ pub(crate) fn save_profile_bytes(
filename: &str, filename: &str,
bytes: &[u8], bytes: &[u8],
) -> std::io::Result<()> { ) -> std::io::Result<()> {
let profiles_dir = meta_dir.join("loader-profiles"); let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles();
std::fs::create_dir_all(&profiles_dir)?; std::fs::create_dir_all(&profiles_dir)?;
std::fs::write(profiles_dir.join(filename), bytes) std::fs::write(profiles_dir.join(filename), bytes)
} }
@@ -92,7 +92,7 @@ pub(crate) fn save_installer_profile(
profile_filename: &str, profile_filename: &str,
) -> Result<(), InstallerError> { ) -> Result<(), InstallerError> {
let ver_json_path = instance_dir let ver_json_path = instance_dir
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("versions") .join("versions")
.join(version_dir_name) .join(version_dir_name)
.join(format!("{version_dir_name}.json")); .join(format!("{version_dir_name}.json"));
@@ -115,7 +115,7 @@ pub(crate) fn save_installer_profile(
); );
let raw = std::fs::read(&ver_json_path)?; let raw = std::fs::read(&ver_json_path)?;
let profiles_dir = meta_dir.join("loader-profiles"); let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles();
std::fs::create_dir_all(&profiles_dir)?; std::fs::create_dir_all(&profiles_dir)?;
let profile_path = profiles_dir.join(profile_filename); let profile_path = profiles_dir.join(profile_filename);
std::fs::write(&profile_path, &raw)?; std::fs::write(&profile_path, &raw)?;
@@ -186,7 +186,7 @@ mod tests {
}"#; }"#;
let ver_dir = instance_dir let ver_dir = instance_dir
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("versions") .join("versions")
.join("1.20.1-forge-47.2.0"); .join("1.20.1-forge-47.2.0");
std::fs::create_dir_all(&ver_dir).unwrap(); std::fs::create_dir_all(&ver_dir).unwrap();
@@ -203,7 +203,7 @@ mod tests {
let saved = std::fs::read( let saved = std::fs::read(
meta_dir meta_dir
.join("loader-profiles") .join("cache/loaders/profiles")
.join("forge-1.20.1-47.2.0.json"), .join("forge-1.20.1-47.2.0.json"),
) )
.unwrap(); .unwrap();
+1 -1
View File
@@ -45,7 +45,7 @@ impl ModLoaderInstaller for NeoForgeInstaller {
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), InstallError> { ) -> Result<(), InstallError> {
let installer_jar = instance_dir let installer_jar = instance_dir
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("neoforge-installer.jar"); .join("neoforge-installer.jar");
tracing::info!("Installing NeoForge {}", loader_version); tracing::info!("Installing NeoForge {}", loader_version);
tracing::debug!("NeoForge installer path: {}", installer_jar.display()); tracing::debug!("NeoForge installer path: {}", installer_jar.display());
+3 -3
View File
@@ -1,4 +1,4 @@
// per-launch log files stored under .minecraft/logs/launches/ // per-launch log files stored under minecraft/logs/launches/
// each launch gets its own timestamped file so you can go back and see what // each launch gets its own timestamped file so you can go back and see what
// crashed last tuesday at 3am // crashed last tuesday at 3am
@@ -13,7 +13,7 @@ pub struct LogFileEntry {
pub fn log_dir(instances_dir: &Path, instance_name: &str) -> PathBuf { pub fn log_dir(instances_dir: &Path, instance_name: &str) -> PathBuf {
instances_dir instances_dir
.join(instance_name) .join(instance_name)
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("logs") .join("logs")
.join("launches") .join("launches")
} }
@@ -66,7 +66,7 @@ mod tests {
let p = log_dir(Path::new("/instances"), "my-world"); let p = log_dir(Path::new("/instances"), "my-world");
assert_eq!( assert_eq!(
p, p,
PathBuf::from("/instances/my-world/.minecraft/logs/launches") PathBuf::from("/instances/my-world/minecraft/logs/launches")
); );
} }
} }
+92 -8
View File
@@ -126,7 +126,7 @@ impl InstanceManager {
loader_version: Option<&str>, loader_version: Option<&str>,
instance_dir: &std::path::Path, instance_dir: &std::path::Path,
) -> Result<InstanceConfig, InstanceError> { ) -> Result<InstanceConfig, InstanceError> {
let minecraft_dir = instance_dir.join(".minecraft"); let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
tracing::debug!( tracing::debug!(
"Preparing Minecraft directory for '{}': {}", "Preparing Minecraft directory for '{}': {}",
name, name,
@@ -149,11 +149,12 @@ impl InstanceManager {
); );
} }
let metadata_paths = crate::storage::MetadataPaths::new(&self.meta_dir);
for meta_subdir in &[ for meta_subdir in &[
self.meta_dir.join("versions"), metadata_paths.versions(),
self.meta_dir.join("libraries"), metadata_paths.libraries(),
self.meta_dir.join("assets").join("objects"), metadata_paths.assets().join("objects"),
self.meta_dir.join("assets").join("indexes"), metadata_paths.assets().join("indexes"),
] { ] {
std::fs::create_dir_all(meta_subdir)?; std::fs::create_dir_all(meta_subdir)?;
tracing::trace!("Ensured metadata directory {}", meta_subdir.display()); tracing::trace!("Ensured metadata directory {}", meta_subdir.display());
@@ -198,9 +199,8 @@ impl InstanceManager {
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir) crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await?; .await?;
let meta_json_path = self let meta_json_path = metadata_paths
.meta_dir .versions()
.join("versions")
.join(game_version) .join(game_version)
.join("meta.json"); .join("meta.json");
if let Some(parent) = meta_json_path.parent() if let Some(parent) = meta_json_path.parent()
@@ -281,6 +281,90 @@ impl InstanceManager {
Ok(config) Ok(config)
} }
pub async fn repair_runtime_cache(&self, config: &InstanceConfig) -> Result<(), InstanceError> {
let task = crate::tui::progress::ProgressTask::start(format!(
"Rebuilding runtime for '{}'",
config.name
));
task.set_sub_action(format!("Minecraft {}", config.game_version));
let metadata_paths = crate::storage::MetadataPaths::new(&self.meta_dir);
for directory in [
metadata_paths.versions(),
metadata_paths.libraries(),
metadata_paths.assets().join("objects"),
metadata_paths.assets().join("indexes"),
metadata_paths.loader_profiles(),
] {
std::fs::create_dir_all(directory)?;
}
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
let version_entry = manifest
.versions
.iter()
.find(|version| version.id == config.game_version)
.ok_or_else(|| {
InstanceError::InvalidName(format!(
"Minecraft version '{}' is no longer present in Mojang's manifest",
config.game_version
))
})?;
let (version_meta, raw_meta) =
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?;
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await?;
let meta_path = metadata_paths
.versions()
.join(&config.game_version)
.join("meta.json");
if let Some(parent) = meta_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(meta_path, raw_meta)?;
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
if config.loader != ModLoader::Vanilla {
let loader_version = config.loader_version.as_deref().ok_or_else(|| {
InstanceError::InvalidName(format!(
"Instance '{}' has no {} loader version",
config.name, config.loader
))
})?;
let profile_name = match config.loader {
ModLoader::Fabric => {
format!("fabric-{}-{loader_version}.json", config.game_version)
}
ModLoader::Quilt => {
format!("quilt-{}-{loader_version}.json", config.game_version)
}
ModLoader::Forge => {
format!("forge-{}-{loader_version}.json", config.game_version)
}
ModLoader::NeoForge => format!("neoforge-{loader_version}.json"),
ModLoader::Vanilla => unreachable!(),
};
if !metadata_paths.loader_profiles().join(profile_name).exists() {
task.set_sub_action(format!("{} {}", config.loader, loader_version));
crate::instance::loader::get_installer(config.loader)
.install(
&self.client,
&config.game_version,
loader_version,
&self.instances_dir.join(&config.name),
&self.meta_dir,
)
.await
.map_err(|error| match error {
InstallError::Download(error) => InstanceError::Download(error),
InstallError::Installer(error) => InstanceError::InstallerError(error),
})?;
}
}
task.finish();
Ok(())
}
pub fn delete(&self, name: &str) -> Result<(), InstanceError> { pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
let instance_dir = self.instances_dir.join(name); let instance_dir = self.instances_dir.join(name);
if !instance_dir.exists() { if !instance_dir.exists() {
+3
View File
@@ -12,6 +12,9 @@ pub mod manager;
pub mod models; pub mod models;
pub mod screenshots; pub mod screenshots;
pub use content::manifest::{
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
};
pub use content::{ pub use content::{
ContentEntry, scan_mods, scan_one_mod, scan_one_resource_pack, scan_one_shader, scan_one_world, ContentEntry, scan_mods, scan_one_mod, scan_one_resource_pack, scan_one_shader, scan_one_world,
scan_resource_packs, scan_shaders, scan_worlds, toggle_entry, scan_resource_packs, scan_shaders, scan_worlds, toggle_entry,
+1 -1
View File
@@ -14,7 +14,7 @@ pub struct ScreenshotEntry {
pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<ScreenshotEntry> { pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<ScreenshotEntry> {
let dir = instances_dir let dir = instances_dir
.join(instance_name) .join(instance_name)
.join(".minecraft") .join(crate::storage::MINECRAFT_DIR_NAME)
.join("screenshots"); .join("screenshots");
let read_dir = match std::fs::read_dir(&dir) { let read_dir = match std::fs::read_dir(&dir) {
+5 -1
View File
@@ -265,7 +265,11 @@ mod tests {
use tempfile::TempDir; use tempfile::TempDir;
let tmp = TempDir::new().unwrap(); let tmp = TempDir::new().unwrap();
let vanilla_path = tmp.path().join("versions").join("1.20.1").join("meta.json"); let vanilla_path = tmp
.path()
.join("cache/minecraft/versions")
.join("1.20.1")
.join("meta.json");
std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap(); std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap();
let vanilla_json = br#"{ let vanilla_json = br#"{
"id": "1.20.1", "id": "1.20.1",
+10 -3
View File
@@ -128,7 +128,10 @@ pub async fn resolve(
return Err(ResolveError::CircularInheritance(parent_id)); return Err(ResolveError::CircularInheritance(parent_id));
} }
let parent_path = meta_dir.join("versions").join(&parent_id).join("meta.json"); let parent_path = crate::storage::MetadataPaths::new(meta_dir)
.versions()
.join(&parent_id)
.join("meta.json");
if !parent_path.exists() { if !parent_path.exists() {
return Err(ResolveError::ParentNotFound( return Err(ResolveError::ParentNotFound(
parent_path.display().to_string(), parent_path.display().to_string(),
@@ -411,7 +414,7 @@ mod tests {
fn write_profile(meta_dir: &Path, profile: &LaunchProfile) { fn write_profile(meta_dir: &Path, profile: &LaunchProfile) {
let path = meta_dir let path = meta_dir
.join("versions") .join("cache/minecraft/versions")
.join(&profile.id) .join(&profile.id)
.join("meta.json"); .join("meta.json");
std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::create_dir_all(path.parent().unwrap()).unwrap();
@@ -470,7 +473,11 @@ mod tests {
async fn resolve_errors_when_parent_is_invalid_json() { async fn resolve_errors_when_parent_is_invalid_json() {
let tmp = TempDir::new().unwrap(); let tmp = TempDir::new().unwrap();
let parent_path = tmp.path().join("versions").join("1.20.1").join("meta.json"); let parent_path = tmp
.path()
.join("cache/minecraft/versions")
.join("1.20.1")
.join("meta.json");
std::fs::create_dir_all(parent_path.parent().unwrap()).unwrap(); std::fs::create_dir_all(parent_path.parent().unwrap()).unwrap();
std::fs::write(&parent_path, "{ not valid json").unwrap(); std::fs::write(&parent_path, "{ not valid json").unwrap();
+568
View File
@@ -0,0 +1,568 @@
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::storage::{InstancePaths, LAYOUT_VERSION, MetadataPaths};
const LEGACY_MINECRAFT: &str = ".minecraft";
const LEGACY_STATE: &str = ".rmcl";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationProgress {
pub phase: String,
pub item: String,
pub current: u64,
pub total: u64,
pub item_current: Option<u64>,
pub item_total: Option<u64>,
pub backup_dir: Option<PathBuf>,
}
impl MigrationProgress {
fn new(phase: impl Into<String>, item: impl Into<String>, current: u64, total: u64) -> Self {
Self {
phase: phase.into(),
item: item.into(),
current,
total,
item_current: None,
item_total: None,
backup_dir: None,
}
}
fn with_item_progress(mut self, current: u64, total: u64) -> Self {
self.item_current = Some(current);
self.item_total = Some(total);
self
}
fn with_backup(mut self, backup_dir: &Path) -> Self {
self.backup_dir = Some(backup_dir.to_owned());
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MigrationJournal {
version: u32,
backup_dir: PathBuf,
completed: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct LayoutMarker {
version: u32,
}
#[derive(Debug, thiserror::Error)]
pub enum MigrationError {
#[error("I/O error: {0}")]
Io(#[from] io::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("Cannot migrate {instance}: both {old} and {new} exist")]
PathConflict {
instance: String,
old: String,
new: String,
},
}
pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool {
let metadata = MetadataPaths::new(meta_dir);
if metadata.cache_rebuild_pending().exists() {
return true;
}
if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) {
return false;
}
has_legacy_instances(instances_dir)
|| [
"versions",
"libraries",
"assets",
"loader-profiles",
"config-sync",
]
.iter()
.any(|path| meta_dir.join(path).exists())
}
pub fn initialize_new_layout(meta_dir: &Path) -> Result<(), MigrationError> {
let metadata = MetadataPaths::new(meta_dir);
for directory in [
metadata.profiles(),
metadata.backups(),
metadata.versions(),
metadata.libraries(),
metadata.assets(),
metadata.loader_profiles(),
metadata.provider_projects("modrinth"),
metadata.provider_versions("modrinth"),
metadata.provider_icons("modrinth"),
metadata.temporary(),
] {
fs::create_dir_all(directory)?;
}
write_json_atomic(
&metadata.layout_marker(),
&LayoutMarker {
version: LAYOUT_VERSION,
},
)
}
pub fn run(
instances_dir: &Path,
meta_dir: &Path,
config_file: &Path,
mut report: impl FnMut(MigrationProgress),
) -> Result<PathBuf, MigrationError> {
fs::create_dir_all(instances_dir)?;
fs::create_dir_all(meta_dir)?;
let metadata = MetadataPaths::new(meta_dir);
if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION)
&& metadata.cache_rebuild_pending().exists()
{
return Ok(latest_layout_backup(&metadata).unwrap_or_else(|| metadata.backups()));
}
if !is_needed(instances_dir, meta_dir) {
initialize_new_layout(meta_dir)?;
return Ok(metadata.backups());
}
fs::create_dir_all(metadata.state())?;
fs::write(metadata.cache_rebuild_pending(), LAYOUT_VERSION.to_string())?;
let mut journal = load_or_create_journal(instances_dir, &metadata)?;
let instances = instance_directories(instances_dir)?;
let total = instances.len() as u64 + 7;
let mut current = journal.completed.len() as u64;
if !is_complete(&journal, "backup") {
let backup_dir = journal.backup_dir.clone();
backup_user_data(
instances_dir,
config_file,
meta_dir,
&backup_dir,
|copied, bytes, path| {
report(
MigrationProgress::new(
"Backing up user data",
path.display().to_string(),
current,
total,
)
.with_item_progress(copied, bytes)
.with_backup(&backup_dir),
);
},
)?;
complete(&mut journal, &metadata, "backup")?;
current += 1;
}
for instance in &instances {
let name = instance
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("instance")
.to_owned();
let key = format!("instance:{name}");
if is_complete(&journal, &key) {
continue;
}
report(
MigrationProgress::new("Migrating instances", name.clone(), current, total)
.with_backup(&journal.backup_dir),
);
migrate_instance(instance, &name)?;
complete(&mut journal, &metadata, &key)?;
current += 1;
}
let moves = [
(
"profiles",
meta_dir.join("config-sync").join("profiles"),
metadata.profiles(),
),
("versions", meta_dir.join("versions"), metadata.versions()),
(
"libraries",
meta_dir.join("libraries"),
metadata.libraries(),
),
("assets", meta_dir.join("assets"), metadata.assets()),
(
"loader-profiles",
meta_dir.join("loader-profiles"),
metadata.loader_profiles(),
),
];
for (key, source, destination) in moves {
let journal_key = format!("shared:{key}");
if is_complete(&journal, &journal_key) {
continue;
}
report(
MigrationProgress::new("Migrating shared data", key, current, total)
.with_backup(&journal.backup_dir),
);
move_or_merge(&source, &destination)?;
complete(&mut journal, &metadata, &journal_key)?;
current += 1;
}
let legacy_config_sync = meta_dir.join("config-sync");
if legacy_config_sync.exists() && fs::read_dir(&legacy_config_sync)?.next().is_none() {
fs::remove_dir(legacy_config_sync)?;
}
report(
MigrationProgress::new(
"Finalizing migration",
"Writing layout marker",
total.saturating_sub(1),
total,
)
.with_backup(&journal.backup_dir),
);
initialize_new_layout(meta_dir)?;
if metadata.migration_journal().exists() {
fs::remove_file(metadata.migration_journal())?;
}
report(
MigrationProgress::new("Migration complete", "Layout updated", total, total)
.with_backup(&journal.backup_dir),
);
Ok(journal.backup_dir)
}
pub fn cache_rebuild_pending(meta_dir: &Path) -> bool {
MetadataPaths::new(meta_dir)
.cache_rebuild_pending()
.exists()
}
pub fn finish_cache_rebuild(meta_dir: &Path) -> Result<(), MigrationError> {
let marker = MetadataPaths::new(meta_dir).cache_rebuild_pending();
if marker.exists() {
fs::remove_file(marker)?;
}
Ok(())
}
fn migrate_instance(instance: &Path, name: &str) -> Result<(), MigrationError> {
let paths = InstancePaths::new(instance);
rename_visible_directory(instance, LEGACY_MINECRAFT, paths.minecraft(), name)?;
rename_visible_directory(instance, LEGACY_STATE, paths.state(), name)?;
let old_config = paths.state().join("config-sync").join("local-config");
move_or_merge(&old_config, &paths.local_config())?;
let old_config_root = paths.state().join("config-sync");
if old_config_root.exists() && fs::read_dir(&old_config_root)?.next().is_none() {
fs::remove_dir(old_config_root)?;
}
fs::create_dir_all(paths.content())?;
Ok(())
}
fn rename_visible_directory(
instance: &Path,
legacy_name: &str,
destination: PathBuf,
instance_name: &str,
) -> Result<(), MigrationError> {
let source = instance.join(legacy_name);
if source.exists() && destination.exists() {
return Err(MigrationError::PathConflict {
instance: instance_name.to_owned(),
old: source.display().to_string(),
new: destination.display().to_string(),
});
}
if source.exists() {
fs::rename(source, destination)?;
}
Ok(())
}
fn backup_user_data(
instances_dir: &Path,
config_file: &Path,
meta_dir: &Path,
backup_dir: &Path,
mut report: impl FnMut(u64, u64, &Path),
) -> Result<(), MigrationError> {
let profiles = meta_dir.join("config-sync").join("profiles");
let total = tree_size(instances_dir)?
.saturating_add(file_size(config_file)?)
.saturating_add(tree_size(&profiles)?);
let mut copied = 0;
report(copied, total, instances_dir);
fs::create_dir_all(backup_dir)?;
copy_dir_recursive_with_progress(
instances_dir,
&backup_dir.join("instances"),
&mut |bytes, path| {
copied = copied.saturating_add(bytes);
report(copied, total, path);
},
)?;
if config_file.exists() {
let destination = backup_dir.join("config").join("config.toml");
fs::create_dir_all(destination.parent().unwrap())?;
let bytes = fs::copy(config_file, destination)?;
copied = copied.saturating_add(bytes);
report(copied, total, config_file);
}
if profiles.exists() {
copy_dir_recursive_with_progress(
&profiles,
&backup_dir.join("profiles"),
&mut |bytes, path| {
copied = copied.saturating_add(bytes);
report(copied, total, path);
},
)?;
}
Ok(())
}
fn tree_size(path: &Path) -> io::Result<u64> {
if !path.exists() {
return Ok(0);
}
let mut total = 0_u64;
for entry in fs::read_dir(path)? {
let entry = entry?;
let file_type = entry.file_type()?;
if file_type.is_dir() {
total = total.saturating_add(tree_size(&entry.path())?);
} else if file_type.is_file() {
total = total.saturating_add(entry.metadata()?.len());
}
}
Ok(total)
}
fn file_size(path: &Path) -> io::Result<u64> {
if path.exists() {
Ok(fs::metadata(path)?.len())
} else {
Ok(0)
}
}
fn move_or_merge(source: &Path, destination: &Path) -> Result<(), MigrationError> {
if !source.exists() {
return Ok(());
}
if !destination.exists() {
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(source, destination)?;
return Ok(());
}
copy_dir_recursive(source, destination)?;
fs::remove_dir_all(source)?;
Ok(())
}
fn copy_dir_recursive(source: &Path, destination: &Path) -> io::Result<()> {
copy_dir_recursive_with_progress(source, destination, &mut |_, _| {})
}
fn copy_dir_recursive_with_progress(
source: &Path,
destination: &Path,
report: &mut impl FnMut(u64, &Path),
) -> io::Result<()> {
fs::create_dir_all(destination)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
let file_type = entry.file_type()?;
let target = destination.join(entry.file_name());
if file_type.is_symlink() {
copy_symlink(&entry.path(), &target)?;
} else if file_type.is_dir() {
copy_dir_recursive_with_progress(&entry.path(), &target, report)?;
} else {
let path = entry.path();
let copied = fs::copy(&path, target)?;
report(copied, &path);
}
}
Ok(())
}
#[cfg(unix)]
fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
std::os::unix::fs::symlink(fs::read_link(source)?, destination)
}
#[cfg(windows)]
fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
let target = fs::read_link(source)?;
if source.is_dir() {
std::os::windows::fs::symlink_dir(target, destination)
} else {
std::os::windows::fs::symlink_file(target, destination)
}
}
fn load_or_create_journal(
_instances_dir: &Path,
metadata: &MetadataPaths,
) -> Result<MigrationJournal, MigrationError> {
if metadata.migration_journal().exists() {
return Ok(serde_json::from_slice(&fs::read(
metadata.migration_journal(),
)?)?);
}
let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();
let journal = MigrationJournal {
version: LAYOUT_VERSION,
backup_dir: metadata.backups().join(format!("layout-v2-{timestamp}")),
completed: Vec::new(),
};
write_json_atomic(&metadata.migration_journal(), &journal)?;
Ok(journal)
}
fn latest_layout_backup(metadata: &MetadataPaths) -> Option<PathBuf> {
let mut backups = fs::read_dir(metadata.backups())
.ok()?
.flatten()
.filter_map(|entry| {
let file_type = entry.file_type().ok()?;
let name = entry.file_name();
(file_type.is_dir() && name.to_string_lossy().starts_with("layout-v2-"))
.then(|| entry.path())
})
.collect::<Vec<_>>();
backups.sort();
backups.pop()
}
fn complete(
journal: &mut MigrationJournal,
metadata: &MetadataPaths,
key: &str,
) -> Result<(), MigrationError> {
journal.completed.push(key.to_owned());
write_json_atomic(&metadata.migration_journal(), journal)
}
fn is_complete(journal: &MigrationJournal, key: &str) -> bool {
journal.completed.iter().any(|completed| completed == key)
}
fn instance_directories(instances_dir: &Path) -> io::Result<Vec<PathBuf>> {
let mut instances = fs::read_dir(instances_dir)?
.flatten()
.filter_map(|entry| entry.file_type().ok()?.is_dir().then(|| entry.path()))
.collect::<Vec<_>>();
instances.sort();
Ok(instances)
}
fn has_legacy_instances(instances_dir: &Path) -> bool {
instance_directories(instances_dir).is_ok_and(|instances| {
instances.iter().any(|instance| {
instance.join(LEGACY_MINECRAFT).exists() || instance.join(LEGACY_STATE).exists()
})
})
}
fn marker_version(path: &Path) -> Option<u32> {
serde_json::from_slice::<LayoutMarker>(&fs::read(path).ok()?)
.ok()
.map(|marker| marker.version)
}
fn write_json_atomic(path: &Path, value: &impl Serialize) -> Result<(), MigrationError> {
let parent = path
.parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
fs::create_dir_all(parent)?;
let temporary = parent.join(format!(
".{}.tmp",
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("state")
));
fs::write(&temporary, serde_json::to_vec_pretty(value)?)?;
fs::rename(temporary, path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn migration_backs_up_and_renames_instance_directories() {
let temp = tempfile::tempdir().unwrap();
let instances = temp.path().join("instances");
let meta = temp.path().join("meta");
let config = temp.path().join("config.toml");
let instance = instances.join("Example");
fs::create_dir_all(instance.join(".minecraft/saves/world")).unwrap();
fs::create_dir_all(instance.join(".rmcl/config-sync/local-config/config")).unwrap();
fs::write(instance.join(".minecraft/saves/world/level.dat"), b"world").unwrap();
fs::write(
instance.join(".rmcl/config-sync/local-config/options.txt"),
b"options",
)
.unwrap();
fs::write(&config, b"[paths]").unwrap();
fs::create_dir_all(meta.join("config-sync/profiles/main")).unwrap();
fs::write(
meta.join("config-sync/profiles/main/options.txt"),
b"profile",
)
.unwrap();
let mut progress = Vec::new();
let backup = run(&instances, &meta, &config, |update| progress.push(update)).unwrap();
assert_eq!(
fs::read(instance.join("minecraft/saves/world/level.dat")).unwrap(),
b"world"
);
assert_eq!(
fs::read(instance.join("rmcl/content/config/options.txt")).unwrap(),
b"options"
);
assert!(backup.join("instances/Example/.minecraft").exists());
assert!(backup.join("profiles/main/options.txt").exists());
assert!(!meta.join("config-sync").exists());
assert!(progress.iter().any(|update| {
update.item_total.is_some_and(|total| total > 0)
&& update.item_current.is_some_and(|current| current > 0)
}));
assert_eq!(
marker_version(&MetadataPaths::new(&meta).layout_marker()),
Some(LAYOUT_VERSION)
);
assert!(cache_rebuild_pending(&meta));
assert_eq!(run(&instances, &meta, &config, |_| {}).unwrap(), backup);
finish_cache_rebuild(&meta).unwrap();
assert!(!cache_rebuild_pending(&meta));
}
#[test]
fn conflicting_visible_and_hidden_directories_are_not_merged() {
let temp = tempfile::tempdir().unwrap();
let instance = temp.path().join("Example");
fs::create_dir_all(instance.join(".minecraft")).unwrap();
fs::create_dir_all(instance.join("minecraft")).unwrap();
let error = migrate_instance(&instance, "Example").unwrap_err();
assert!(matches!(error, MigrationError::PathConflict { .. }));
}
}
+3
View File
@@ -7,12 +7,15 @@
pub mod auth; pub mod auth;
mod cli; mod cli;
pub mod config; pub mod config;
pub mod content_provider;
pub mod instance; pub mod instance;
pub mod instance_logs; pub mod instance_logs;
pub mod launch_profile; pub mod launch_profile;
pub mod layout_migration;
mod migrate; mod migrate;
pub mod net; pub mod net;
pub mod running; pub mod running;
pub mod storage;
pub mod tui; pub mod tui;
pub use cli::init as cli_init; pub use cli::init as cli_init;
+4 -2
View File
@@ -97,7 +97,7 @@ fn cleanup_instance_leftovers(instances_dir: &Path) {
return; return;
}; };
for entry in entries.flatten() { for entry in entries.flatten() {
let mc = entry.path().join(".minecraft"); let mc = entry.path().join(crate::storage::MINECRAFT_DIR_NAME);
for leftover in [".mcl-shim.jar", ".mcl-log4j2.xml"] { for leftover in [".mcl-shim.jar", ".mcl-log4j2.xml"] {
let p = mc.join(leftover); let p = mc.join(leftover);
if p.exists() { if p.exists() {
@@ -239,7 +239,9 @@ mod tests {
fn cleanup_instance_leftovers_removes_shim_and_log4j() { fn cleanup_instance_leftovers_removes_shim_and_log4j() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let instances = tmp.path().join("instances"); let instances = tmp.path().join("instances");
let mc = instances.join("Test").join(".minecraft"); let mc = instances
.join("Test")
.join(crate::storage::MINECRAFT_DIR_NAME);
fs::create_dir_all(&mc).unwrap(); fs::create_dir_all(&mc).unwrap();
fs::write(mc.join(".mcl-shim.jar"), b"jar").unwrap(); fs::write(mc.join(".mcl-shim.jar"), b"jar").unwrap();
fs::write(mc.join(".mcl-log4j2.xml"), b"xml").unwrap(); fs::write(mc.join(".mcl-log4j2.xml"), b"xml").unwrap();
+1 -1
View File
@@ -155,7 +155,7 @@ pub async fn download_fabric_libraries(
profile: &FabricProfile, profile: &FabricProfile,
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), NetError> { ) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries"); let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries();
tracing::debug!( tracing::debug!(
"Resolving {} Fabric libraries into {}", "Resolving {} Fabric libraries into {}",
profile.libraries.len(), profile.libraries.len(),
+5 -3
View File
@@ -150,7 +150,7 @@ pub async fn run_forge_installer(
.arg("-jar") .arg("-jar")
.arg(installer_path) .arg(installer_path)
.arg("--installClient") .arg("--installClient")
.current_dir(instance_dir.join(".minecraft")) .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
.output() .output()
.await .await
{ {
@@ -289,7 +289,9 @@ pub(crate) async fn install_forge_from_profile(
})?; })?;
set_sub_action("Extracting universal JAR..."); set_sub_action("Extracting universal JAR...");
let universal_dest = meta_dir.join("libraries").join(&universal_maven_path); let universal_dest = crate::storage::MetadataPaths::new(meta_dir)
.libraries()
.join(&universal_maven_path);
if let Some(parent) = universal_dest.parent() { if let Some(parent) = universal_dest.parent() {
std::fs::create_dir_all(parent) std::fs::create_dir_all(parent)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
@@ -318,7 +320,7 @@ pub(crate) async fn install_forge_from_profile(
// are forge-hosted, libs without one are typically from mojang's library // are forge-hosted, libs without one are typically from mojang's library
// server. old forge versions reference libs like launchwrapper that aren't // server. old forge versions reference libs like launchwrapper that aren't
// in mojang's modern version metadata, so we fetch those too. // in mojang's modern version metadata, so we fetch those too.
let libraries_dir = meta_dir.join("libraries"); let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries();
for lib in libraries { for lib in libraries {
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default(); let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
+30
View File
@@ -9,6 +9,7 @@ pub mod neoforge;
pub mod quilt; pub mod quilt;
use reqwest::Client; use reqwest::Client;
use serde::Serialize;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use std::path::Path; use std::path::Path;
use thiserror::Error; use thiserror::Error;
@@ -97,6 +98,35 @@ impl HttpClient {
.await .await
} }
pub async fn post_json<B, T>(&self, url: &str, body: &B) -> Result<T, NetError>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
for attempt in 0..=MAX_RETRIES {
tracing::trace!("HTTP POST {}", url);
let result = async {
let response = self.inner.post(url).json(body).send().await?;
if !response.status().is_success() {
return Err(NetError::StatusError {
status: response.status().as_u16(),
url: url.to_owned(),
});
}
Ok(response.json().await?)
}
.await;
match result {
Ok(value) => return Ok(value),
Err(error) if is_retryable(&error) && attempt < MAX_RETRIES => {
sleep_before_retry("request", url, attempt, &error).await;
}
Err(error) => return Err(error),
}
}
unreachable!("retry loop returns on success or final error")
}
// fetch JSON and also keep the raw bytes. used by install paths that // fetch JSON and also keep the raw bytes. used by install paths that
// want both the parsed shape (for downloading libraries from it) and // want both the parsed shape (for downloading libraries from it) and
// the original bytes (to write byte-for-byte to the loader-profiles // the original bytes (to write byte-for-byte to the loader-profiles
+74 -5
View File
@@ -4,16 +4,22 @@
use serde::Deserialize; use serde::Deserialize;
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize, serde::Serialize)]
pub struct ProjectInfo { pub struct ProjectInfo {
pub id: String, pub id: String,
pub slug: String, pub slug: String,
pub title: String, pub title: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub icon_url: Option<String>,
} }
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct VersionInfo { pub struct VersionInfo {
pub id: String, pub id: String,
#[serde(default)]
pub project_id: String,
pub name: String, pub name: String,
pub version_number: String, pub version_number: String,
pub game_versions: Vec<String>, pub game_versions: Vec<String>,
@@ -27,6 +33,8 @@ pub struct VersionFile {
pub filename: String, pub filename: String,
pub size: u64, pub size: u64,
pub primary: bool, pub primary: bool,
#[serde(default)]
pub hashes: HashMap<String, String>,
} }
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
@@ -129,6 +137,11 @@ pub async fn search_discovery(
offset: usize, offset: usize,
limit: usize, limit: usize,
) -> Result<DiscoveryResults, crate::net::NetError> { ) -> Result<DiscoveryResults, crate::net::NetError> {
let progress = crate::tui::progress::ProgressTask::start(if query.trim().is_empty() {
"Loading Modrinth discovery".to_owned()
} else {
format!("Searching Modrinth for '{}'", query.trim())
});
let facets = discovery_facets(kind, game_version, loader); let facets = discovery_facets(kind, game_version, loader);
let query = query.trim(); let query = query.trim();
let index = if query.is_empty() { let index = if query.is_empty() {
@@ -141,7 +154,14 @@ pub async fn search_discovery(
url_encode(query), url_encode(query),
url_encode(&facets), url_encode(&facets),
); );
let results: DiscoverySearchResponse = client.get_json(&url).await?; let results: DiscoverySearchResponse = match client.get_json(&url).await {
Ok(results) => results,
Err(error) => {
progress.fail(&error);
return Err(error);
}
};
progress.finish();
Ok(DiscoveryResults { Ok(DiscoveryResults {
total_hits: results.total_hits.max(0) as usize, total_hits: results.total_hits.max(0) as usize,
@@ -267,6 +287,7 @@ pub async fn fetch_content_versions(
game_version: &str, game_version: &str,
loader: ModLoader, loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError> { ) -> Result<Vec<VersionInfo>, crate::net::NetError> {
let progress = crate::tui::progress::ProgressTask::start("Loading compatible project versions");
let url = content_versions_url(API_BASE, project_id, kind, game_version, loader); let url = content_versions_url(API_BASE, project_id, kind, game_version, loader);
tracing::debug!( tracing::debug!(
"Fetching compatible Modrinth versions for '{}' ({}, {})", "Fetching compatible Modrinth versions for '{}' ({}, {})",
@@ -274,7 +295,16 @@ pub async fn fetch_content_versions(
game_version, game_version,
loader loader
); );
client.get_json(&url).await match client.get_json(&url).await {
Ok(versions) => {
progress.finish();
Ok(versions)
}
Err(error) => {
progress.fail(&error);
Err(error)
}
}
} }
fn content_versions_url( fn content_versions_url(
@@ -331,7 +361,13 @@ pub async fn download_version_file(
if path.exists() { if path.exists() {
return Ok(DownloadOutcome::SkippedExisting(path)); return Ok(DownloadOutcome::SkippedExisting(path));
} }
crate::net::download_file(client, &file.url, &path, |_, _| {}).await?; let progress =
crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename));
crate::net::download_file(client, &file.url, &path, |current, total| {
progress.set_progress(current, total);
})
.await?;
progress.finish();
Ok(DownloadOutcome::Downloaded(path)) Ok(DownloadOutcome::Downloaded(path))
} }
@@ -356,7 +392,13 @@ pub async fn download_version_file_for_update(
))); )));
} }
crate::net::download_file(client, &file.url, &temporary, |_, _| {}).await?; let progress =
crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename));
crate::net::download_file(client, &file.url, &temporary, |current, total| {
progress.set_progress(current, total);
})
.await?;
progress.finish();
replace_installed_file(&temporary, &target, installed_path, &backup).await?; replace_installed_file(&temporary, &target, installed_path, &backup).await?;
Ok(DownloadOutcome::Downloaded(target)) Ok(DownloadOutcome::Downloaded(target))
} }
@@ -395,6 +437,28 @@ pub async fn fetch_version(
Ok(version) Ok(version)
} }
#[derive(Debug, serde::Serialize)]
struct VersionFilesRequest<'a> {
hashes: &'a [String],
algorithm: &'a str,
}
pub async fn resolve_version_files(
client: &crate::net::HttpClient,
hashes: &[String],
algorithm: &str,
) -> Result<HashMap<String, VersionInfo>, crate::net::NetError> {
if hashes.is_empty() {
return Ok(HashMap::new());
}
client
.post_json(
&format!("{API_BASE}/version_files"),
&VersionFilesRequest { hashes, algorithm },
)
.await
}
// grabs the primary file from a version, falling back to the first file // grabs the primary file from a version, falling back to the first file
// if none is marked primary (some projects are sloppy about that) // if none is marked primary (some projects are sloppy about that)
pub async fn download_mrpack( pub async fn download_mrpack(
@@ -442,6 +506,7 @@ mod tests {
fn version_with_files(files: Vec<VersionFile>) -> VersionInfo { fn version_with_files(files: Vec<VersionFile>) -> VersionInfo {
VersionInfo { VersionInfo {
id: "version-id".to_owned(), id: "version-id".to_owned(),
project_id: "project-id".to_owned(),
name: "Version 1".to_owned(), name: "Version 1".to_owned(),
version_number: "1.0.0".to_owned(), version_number: "1.0.0".to_owned(),
game_versions: vec!["1.21.1".to_owned()], game_versions: vec!["1.21.1".to_owned()],
@@ -510,12 +575,14 @@ mod tests {
filename: "first.jar".to_owned(), filename: "first.jar".to_owned(),
size: 1, size: 1,
primary: false, primary: false,
hashes: HashMap::new(),
}, },
VersionFile { VersionFile {
url: "https://example.test/primary.jar".to_owned(), url: "https://example.test/primary.jar".to_owned(),
filename: "primary.jar".to_owned(), filename: "primary.jar".to_owned(),
size: 1, size: 1,
primary: true, primary: true,
hashes: HashMap::new(),
}, },
]); ]);
assert_eq!( assert_eq!(
@@ -528,6 +595,7 @@ mod tests {
filename: "first.jar".to_owned(), filename: "first.jar".to_owned(),
size: 1, size: 1,
primary: false, primary: false,
hashes: HashMap::new(),
}]); }]);
assert_eq!( assert_eq!(
select_primary_file(&fallback).unwrap().filename, select_primary_file(&fallback).unwrap().filename,
@@ -545,6 +613,7 @@ mod tests {
filename: "example.jar".to_owned(), filename: "example.jar".to_owned(),
size: 1, size: 1,
primary: true, primary: true,
hashes: HashMap::new(),
}]); }]);
let outcome = let outcome =
+9 -7
View File
@@ -152,8 +152,8 @@ pub async fn download_client_jar(
meta: &VersionMeta, meta: &VersionMeta,
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), NetError> { ) -> Result<(), NetError> {
let jar_path = meta_dir let jar_path = crate::storage::MetadataPaths::new(meta_dir)
.join("versions") .versions()
.join(&meta.id) .join(&meta.id)
.join(format!("{}.jar", meta.id)); .join(format!("{}.jar", meta.id));
@@ -225,7 +225,9 @@ pub async fn download_libraries(
} }
}; };
let destination = meta_dir.join("libraries").join(&artifact.path); let destination = crate::storage::MetadataPaths::new(meta_dir)
.libraries()
.join(&artifact.path);
if destination.exists() { if destination.exists() {
tracing::trace!("Library already cached: {}", artifact.path); tracing::trace!("Library already cached: {}", artifact.path);
@@ -278,8 +280,8 @@ pub async fn download_assets_from(
} }
}; };
let index_path = meta_dir let index_path = crate::storage::MetadataPaths::new(meta_dir)
.join("assets") .assets()
.join("indexes") .join("indexes")
.join(format!("{}.json", meta.asset_index.id)); .join(format!("{}.json", meta.asset_index.id));
if !index_path.exists() { if !index_path.exists() {
@@ -326,8 +328,8 @@ pub async fn download_assets_from(
let prefix = &object.hash[..2]; let prefix = &object.hash[..2];
let url = format!("{}/{}/{}", assets_base, prefix, object.hash); let url = format!("{}/{}/{}", assets_base, prefix, object.hash);
let destination = meta_dir let destination = crate::storage::MetadataPaths::new(meta_dir)
.join("assets") .assets()
.join("objects") .join("objects")
.join(prefix) .join(prefix)
.join(&object.hash); .join(&object.hash);
+1 -1
View File
@@ -182,7 +182,7 @@ pub async fn run_neoforge_installer(
.arg("-jar") .arg("-jar")
.arg(installer_path) .arg(installer_path)
.arg("--installClient") .arg("--installClient")
.current_dir(instance_dir.join(".minecraft")) .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
.output() .output()
.await .await
{ {
+1 -1
View File
@@ -149,7 +149,7 @@ pub async fn download_quilt_libraries(
profile: &QuiltProfile, profile: &QuiltProfile,
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), NetError> { ) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries"); let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries();
tracing::debug!( tracing::debug!(
"Resolving {} Quilt libraries into {}", "Resolving {} Quilt libraries into {}",
profile.libraries.len(), profile.libraries.len(),
+159
View File
@@ -0,0 +1,159 @@
use std::path::{Path, PathBuf};
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
pub const INSTANCE_STATE_DIR_NAME: &str = "rmcl";
pub const LAYOUT_VERSION: u32 = 2;
#[derive(Debug, Clone)]
pub struct InstancePaths {
root: PathBuf,
}
impl InstancePaths {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn minecraft(&self) -> PathBuf {
self.root.join(MINECRAFT_DIR_NAME)
}
pub fn state(&self) -> PathBuf {
self.root.join(INSTANCE_STATE_DIR_NAME)
}
pub fn content(&self) -> PathBuf {
self.state().join("content")
}
pub fn content_manifest(&self) -> PathBuf {
self.content().join("manifest.json")
}
pub fn local_config(&self) -> PathBuf {
self.content().join("config")
}
}
#[derive(Debug, Clone)]
pub struct MetadataPaths {
root: PathBuf,
}
impl MetadataPaths {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn state(&self) -> PathBuf {
self.root.join("state")
}
pub fn profiles(&self) -> PathBuf {
self.state().join("profiles")
}
pub fn backups(&self) -> PathBuf {
self.state().join("backups")
}
pub fn cache(&self) -> PathBuf {
self.root.join("cache")
}
pub fn minecraft_cache(&self) -> PathBuf {
self.cache().join("minecraft")
}
pub fn versions(&self) -> PathBuf {
self.minecraft_cache().join("versions")
}
pub fn libraries(&self) -> PathBuf {
self.minecraft_cache().join("libraries")
}
pub fn assets(&self) -> PathBuf {
self.minecraft_cache().join("assets")
}
pub fn loader_profiles(&self) -> PathBuf {
self.cache().join("loaders").join("profiles")
}
pub fn provider_cache(&self, provider: &str) -> PathBuf {
self.cache().join("providers").join(provider)
}
pub fn provider_projects(&self, provider: &str) -> PathBuf {
self.provider_cache(provider).join("projects")
}
pub fn provider_versions(&self, provider: &str) -> PathBuf {
self.provider_cache(provider).join("versions")
}
pub fn provider_icons(&self, provider: &str) -> PathBuf {
self.provider_cache(provider).join("icons")
}
pub fn temporary(&self) -> PathBuf {
self.root.join("tmp")
}
pub fn layout_marker(&self) -> PathBuf {
self.state().join("layout.json")
}
pub fn migration_journal(&self) -> PathBuf {
self.state().join("migration-v2.json")
}
pub fn cache_rebuild_pending(&self) -> PathBuf {
self.state().join("cache-rebuild.pending")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn instance_paths_use_visible_directories() {
let paths = InstancePaths::new("/instances/example");
assert_eq!(
paths.minecraft(),
PathBuf::from("/instances/example/minecraft")
);
assert_eq!(
paths.content_manifest(),
PathBuf::from("/instances/example/rmcl/content/manifest.json")
);
assert_eq!(
paths.local_config(),
PathBuf::from("/instances/example/rmcl/content/config")
);
}
#[test]
fn metadata_paths_separate_state_and_cache() {
let paths = MetadataPaths::new("/meta");
assert_eq!(paths.profiles(), PathBuf::from("/meta/state/profiles"));
assert_eq!(
paths.provider_icons("modrinth"),
PathBuf::from("/meta/cache/providers/modrinth/icons")
);
assert_eq!(
paths.versions(),
PathBuf::from("/meta/cache/minecraft/versions")
);
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
// integration tests for the public content-scanner APIs: shaders, worlds, // integration tests for the public content-scanner APIs: shaders, worlds,
// and resource packs. each scanner walks an instance's .minecraft subdir // and resource packs. each scanner walks an instance's minecraft subdir
// and returns ContentEntry rows; shape varies slightly per content type // and returns ContentEntry rows; shape varies slightly per content type
// (worlds are directories only, packs and shaders accept .zip or dir, etc.). // (worlds are directories only, packs and shaders accept .zip or dir, etc.).
@@ -10,7 +10,7 @@ use rmcl::instance::content::shaders::scan_shaders;
use rmcl::instance::content::worlds::scan_worlds; use rmcl::instance::content::worlds::scan_worlds;
fn setup_subdir(tmp: &Path, instance: &str, sub: &str) -> PathBuf { fn setup_subdir(tmp: &Path, instance: &str, sub: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join(sub); let dir = tmp.join(instance).join("minecraft").join(sub);
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
dir dir
} }
+25 -19
View File
@@ -73,9 +73,9 @@ fn fake_java(tmp: &TempDir, major: u32) -> String {
} }
// builds the on-disk layout that build_launch_invocation expects: // builds the on-disk layout that build_launch_invocation expects:
// <tmp>/instances/<name>/.minecraft/ (instance dir, created empty) // <tmp>/instances/<name>/minecraft/ (instance dir, created empty)
// <tmp>/meta/versions/<game_version>/meta.json // <tmp>/meta/versions/<game_version>/meta.json
// <tmp>/meta/loader-profiles/ (created empty) // <tmp>/meta/cache/loaders/profiles/ (created empty)
// <tmp>/meta/libraries/ (created empty) // <tmp>/meta/libraries/ (created empty)
struct Fixture { struct Fixture {
_tmp: TempDir, _tmp: TempDir,
@@ -89,12 +89,12 @@ impl Fixture {
let instances_dir = tmp.path().join("instances"); let instances_dir = tmp.path().join("instances");
let meta_dir = tmp.path().join("meta"); let meta_dir = tmp.path().join("meta");
let instance_minecraft = instances_dir.join(instance_name).join(".minecraft"); let instance_minecraft = instances_dir.join(instance_name).join("minecraft");
std::fs::create_dir_all(&instance_minecraft).unwrap(); std::fs::create_dir_all(&instance_minecraft).unwrap();
std::fs::create_dir_all(meta_dir.join("libraries")).unwrap(); std::fs::create_dir_all(meta_dir.join("cache/minecraft/libraries")).unwrap();
std::fs::create_dir_all(meta_dir.join("loader-profiles")).unwrap(); std::fs::create_dir_all(meta_dir.join("cache/loaders/profiles")).unwrap();
let version_dir = meta_dir.join("versions").join(game_version); let version_dir = meta_dir.join("cache/minecraft/versions").join(game_version);
std::fs::create_dir_all(&version_dir).unwrap(); std::fs::create_dir_all(&version_dir).unwrap();
std::fs::write( std::fs::write(
version_dir.join("meta.json"), version_dir.join("meta.json"),
@@ -111,7 +111,7 @@ impl Fixture {
fn write_loader_profile(&self, filename: &str, content: serde_json::Value) { fn write_loader_profile(&self, filename: &str, content: serde_json::Value) {
std::fs::write( std::fs::write(
self.meta_dir.join("loader-profiles").join(filename), self.meta_dir.join("cache/loaders/profiles").join(filename),
serde_json::to_vec_pretty(&content).unwrap(), serde_json::to_vec_pretty(&content).unwrap(),
) )
.unwrap(); .unwrap();
@@ -120,7 +120,7 @@ impl Fixture {
fn instance_libraries_dir(&self, instance_name: &str) -> PathBuf { fn instance_libraries_dir(&self, instance_name: &str) -> PathBuf {
self.instances_dir self.instances_dir
.join(instance_name) .join(instance_name)
.join(".minecraft") .join("minecraft")
.join("libraries") .join("libraries")
} }
} }
@@ -209,7 +209,11 @@ async fn vanilla_modern_builds_complete_invocation() {
assert_eq!(inv.main_class, "net.minecraft.client.main.Main"); assert_eq!(inv.main_class, "net.minecraft.client.main.Main");
assert!(inv.extra_args.is_empty()); assert!(inv.extra_args.is_empty());
let expected_natives = fx.meta_dir.join("versions").join("1.20.1").join("natives"); let expected_natives = fx
.meta_dir
.join("cache/minecraft/versions")
.join("1.20.1")
.join("natives");
assert!( assert!(
inv.jvm_args inv.jvm_args
.iter() .iter()
@@ -225,16 +229,18 @@ async fn vanilla_modern_builds_complete_invocation() {
inv.jvm_args inv.jvm_args
); );
// working_dir is <instances_dir>/<name>/.minecraft // working_dir is <instances_dir>/<name>/minecraft
assert_eq!( assert_eq!(
inv.working_dir, inv.working_dir,
fx.instances_dir.join("v1").join(".minecraft") fx.instances_dir.join("v1").join("minecraft")
); );
// classpath = the one vanilla lib + the vanilla client jar // classpath = the one vanilla lib + the vanilla client jar
let slf4j = fx let slf4j = fx
.meta_dir .meta_dir
.join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); .join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar");
let client_jar = fx.meta_dir.join("versions/1.20.1/1.20.1.jar"); let client_jar = fx
.meta_dir
.join("cache/minecraft/versions/1.20.1/1.20.1.jar");
assert!(inv.classpath.contains(&slf4j)); assert!(inv.classpath.contains(&slf4j));
assert!(inv.classpath.contains(&client_jar)); assert!(inv.classpath.contains(&client_jar));
} }
@@ -422,12 +428,12 @@ async fn fabric_implicit_inheritsfrom_resolves() {
"net.fabricmc.loader.impl.launch.knot.KnotClient" "net.fabricmc.loader.impl.launch.knot.KnotClient"
); );
// both fabric-loader and vanilla slf4j must appear on the merged classpath // both fabric-loader and vanilla slf4j must appear on the merged classpath
let fabric_loader = fx let fabric_loader = fx.meta_dir.join(
.meta_dir "cache/minecraft/libraries/net/fabricmc/fabric-loader/0.15.0/fabric-loader-0.15.0.jar",
.join("libraries/net/fabricmc/fabric-loader/0.15.0/fabric-loader-0.15.0.jar"); );
let slf4j = fx let slf4j = fx
.meta_dir .meta_dir
.join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); .join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar");
assert!( assert!(
inv.classpath.contains(&fabric_loader), inv.classpath.contains(&fabric_loader),
"fabric-loader missing from classpath: {:?}", "fabric-loader missing from classpath: {:?}",
@@ -631,8 +637,8 @@ async fn meta_not_found_returns_error() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let instances_dir = tmp.path().join("instances"); let instances_dir = tmp.path().join("instances");
let meta_dir = tmp.path().join("meta"); let meta_dir = tmp.path().join("meta");
std::fs::create_dir_all(instances_dir.join("ghost").join(".minecraft")).unwrap(); std::fs::create_dir_all(instances_dir.join("ghost").join("minecraft")).unwrap();
std::fs::create_dir_all(meta_dir.join("versions")).unwrap(); std::fs::create_dir_all(meta_dir.join("cache/minecraft/versions")).unwrap();
let config = make_config("ghost", "1.20.1", ModLoader::Vanilla); let config = make_config("ghost", "1.20.1", ModLoader::Vanilla);
let err = build_launch_invocation(&config, &instances_dir, &meta_dir, &test_auth()) let err = build_launch_invocation(&config, &instances_dir, &meta_dir, &test_auth())
+5 -5
View File
@@ -170,7 +170,7 @@ async fn download_libraries_writes_artifact_to_meta_dir() {
let written = tmp let written = tmp
.path() .path()
.join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); .join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar");
assert!(written.exists(), "expected library file at {written:?}"); assert!(written.exists(), "expected library file at {written:?}");
let contents = std::fs::read(&written).unwrap(); let contents = std::fs::read(&written).unwrap();
assert_eq!(contents, b"jar-bytes"); assert_eq!(contents, b"jar-bytes");
@@ -193,7 +193,7 @@ async fn download_libraries_skips_when_destination_exists() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let existing = tmp let existing = tmp
.path() .path()
.join("libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); .join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar");
std::fs::create_dir_all(existing.parent().unwrap()).unwrap(); std::fs::create_dir_all(existing.parent().unwrap()).unwrap();
std::fs::write(&existing, b"already there").unwrap(); std::fs::write(&existing, b"already there").unwrap();
@@ -240,11 +240,11 @@ async fn download_assets_from_writes_index_and_assets() {
.await .await
.expect("download_assets_from"); .expect("download_assets_from");
let index_path = tmp.path().join("assets/indexes/5.json"); let index_path = tmp.path().join("cache/minecraft/assets/indexes/5.json");
assert!(index_path.exists(), "index file missing"); assert!(index_path.exists(), "index file missing");
let asset_path = tmp let asset_path = tmp
.path() .path()
.join("assets/objects/ab/ab1234567890abcdef1234567890abcdef123456"); .join("cache/minecraft/assets/objects/ab/ab1234567890abcdef1234567890abcdef123456");
assert!(asset_path.exists(), "asset file missing"); assert!(asset_path.exists(), "asset file missing");
assert_eq!(std::fs::read(&asset_path).unwrap(), b"asset-bytes"); assert_eq!(std::fs::read(&asset_path).unwrap(), b"asset-bytes");
} }
@@ -269,7 +269,7 @@ async fn download_assets_writes_index_when_objects_is_empty() {
.await .await
.expect("download_assets index-only"); .expect("download_assets index-only");
let index_path = tmp.path().join("assets/indexes/5.json"); let index_path = tmp.path().join("cache/minecraft/assets/indexes/5.json");
assert!( assert!(
index_path.exists(), index_path.exists(),
"expected asset index at {index_path:?}" "expected asset index at {index_path:?}"
+1 -1
View File
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
use rmcl::instance::screenshots::scan_screenshots; use rmcl::instance::screenshots::scan_screenshots;
fn setup_screenshots_dir(tmp: &Path, instance: &str) -> PathBuf { fn setup_screenshots_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("screenshots"); let dir = tmp.join(instance).join("minecraft").join("screenshots");
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
dir dir
} }