feat(content): add managed content metadata layout
This commit is contained in:
1 parent
a05b030862
commit
fbf8142ea0
46 files changed
+2404
-166
No files matched your search
@@ -127,6 +127,7 @@ mod tests {
|
||||
name: file_stem.to_string(),
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
description: String::new(),
|
||||
|
||||
+2
-2
@@ -58,7 +58,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
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)?;
|
||||
modrinth::download_mrpack(&client, version, &tmp_dir)
|
||||
.await
|
||||
@@ -79,7 +79,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
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)?;
|
||||
modrinth::download_mrpack(&client, &version, &tmp_dir)
|
||||
.await
|
||||
|
||||
+2
-2
@@ -94,7 +94,7 @@ mod tests {
|
||||
#[test]
|
||||
fn resolves_latest_log_when_no_file_is_given() {
|
||||
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::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");
|
||||
@@ -109,7 +109,7 @@ mod tests {
|
||||
#[test]
|
||||
fn resolves_named_log_file() {
|
||||
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::write(dir.join("latest.log"), "hello").expect("write named log");
|
||||
|
||||
|
||||
@@ -24,6 +24,49 @@ pub async fn init() {
|
||||
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() {
|
||||
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
|
||||
Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
|
||||
|
||||
@@ -62,6 +62,7 @@ pub static SETTINGS: LazyLock<Config> = LazyLock::new(|| {
|
||||
paths: settings::Paths::default(),
|
||||
defaults: settings::Defaults::default(),
|
||||
ui: settings::Ui::default(),
|
||||
content: settings::Content::default(),
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
@@ -18,6 +18,45 @@ pub enum ImageProtocol {
|
||||
#[derive(Debug, Deserialize, Default)]
|
||||
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)]
|
||||
pub struct Paths {
|
||||
#[serde(default = "default_instances_dir")]
|
||||
@@ -159,6 +198,8 @@ pub struct Config {
|
||||
pub defaults: Defaults,
|
||||
#[serde(default)]
|
||||
pub ui: Ui,
|
||||
#[serde(default)]
|
||||
pub content: Content,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+6
-5
@@ -229,12 +229,13 @@ accent = "Red"
|
||||
|
||||
#[test]
|
||||
fn resolve_builtin_theme() {
|
||||
let config = ThemeConfig {
|
||||
theme: "dracula".to_owned(),
|
||||
..ThemeConfig::default()
|
||||
let theme = resolve_theme("dracula");
|
||||
let expected = if std::env::var_os("NO_COLOR").is_some() {
|
||||
"no-color"
|
||||
} else {
|
||||
"dracula"
|
||||
};
|
||||
let theme = resolve_app_theme(&config);
|
||||
assert_eq!(theme.id(), "dracula");
|
||||
assert_eq!(theme.id(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
+42
-67
@@ -203,18 +203,15 @@ fn profile_dir(meta_dir: &Path, profile: &str) -> 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 {
|
||||
instance_dir.join(".minecraft")
|
||||
instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
}
|
||||
|
||||
fn local_backup_dir(instance_dir: &Path) -> PathBuf {
|
||||
instance_dir
|
||||
.join(".rmcl")
|
||||
.join("config-sync")
|
||||
.join("local-config")
|
||||
crate::storage::InstancePaths::new(instance_dir).local_config()
|
||||
}
|
||||
|
||||
fn acquire_lock(profile_dir: &Path) -> Result<ConfigSyncLock, ConfigSyncError> {
|
||||
@@ -339,7 +336,7 @@ mod tests {
|
||||
fn first_prepare_seeds_shared_config() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
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();
|
||||
std::fs::create_dir_all(minecraft.join("config/nested")).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_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"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(meta.join("config-sync/profiles/main/optionsshaders.txt"))
|
||||
.unwrap(),
|
||||
std::fs::read_to_string(meta.join("state/profiles/main/optionsshaders.txt")).unwrap(),
|
||||
"shader-options"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/options.txt"))
|
||||
.unwrap(),
|
||||
std::fs::read_to_string(meta.join("state/profiles/main/config/options.txt")).unwrap(),
|
||||
"local-config"
|
||||
);
|
||||
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(),
|
||||
"nested"
|
||||
);
|
||||
@@ -374,16 +369,16 @@ mod tests {
|
||||
fn prepare_mirrors_shared_config_into_instance() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let meta = tmp.path().join("meta");
|
||||
let minecraft = tmp.path().join("instance/.minecraft");
|
||||
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
|
||||
let minecraft = tmp.path().join("instance/minecraft");
|
||||
std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
|
||||
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||
std::fs::write(
|
||||
meta.join("config-sync/profiles/main/options.txt"),
|
||||
meta.join("state/profiles/main/options.txt"),
|
||||
"shared-options",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
meta.join("config-sync/profiles/main/config/shared.toml"),
|
||||
meta.join("state/profiles/main/config/shared.toml"),
|
||||
"shared",
|
||||
)
|
||||
.unwrap();
|
||||
@@ -407,13 +402,9 @@ mod tests {
|
||||
fn finish_mirrors_instance_config_back_to_shared() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let meta = tmp.path().join("meta");
|
||||
let minecraft = tmp.path().join("instance/.minecraft");
|
||||
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
|
||||
std::fs::write(
|
||||
meta.join("config-sync/profiles/main/config/old.toml"),
|
||||
"old",
|
||||
)
|
||||
.unwrap();
|
||||
let minecraft = tmp.path().join("instance/minecraft");
|
||||
std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
|
||||
std::fs::write(meta.join("state/profiles/main/config/old.toml"), "old").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("config/new.toml"), "new").unwrap();
|
||||
@@ -421,31 +412,26 @@ mod tests {
|
||||
finish(Some("main"), &meta, &minecraft).unwrap();
|
||||
|
||||
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"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/new.toml"))
|
||||
.unwrap(),
|
||||
std::fs::read_to_string(meta.join("state/profiles/main/config/new.toml")).unwrap(),
|
||||
"new"
|
||||
);
|
||||
assert!(
|
||||
!meta
|
||||
.join("config-sync/profiles/main/config/old.toml")
|
||||
.exists()
|
||||
);
|
||||
assert!(!meta.join("state/profiles/main/config/old.toml").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_releases_lock_for_another_instance() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
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();
|
||||
std::fs::create_dir_all(minecraft.join("config")).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();
|
||||
|
||||
assert!(prepare(Some("main"), &meta, &second).unwrap());
|
||||
@@ -477,13 +463,13 @@ mod tests {
|
||||
fn prepare_ignores_deleted_profile() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
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();
|
||||
|
||||
let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap();
|
||||
|
||||
assert!(!lock);
|
||||
assert!(!meta.join("config-sync/profiles/deleted").exists());
|
||||
assert!(!meta.join("state/profiles/deleted").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -512,7 +498,7 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let meta = tmp.path().join("meta");
|
||||
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::write(minecraft.join("options.txt"), "local-options").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();
|
||||
assert_eq!(selected.as_deref(), Some("main"));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(instance.join(".rmcl/config-sync/local-config/options.txt"))
|
||||
.unwrap(),
|
||||
std::fs::read_to_string(instance.join("rmcl/content/config/options.txt")).unwrap(),
|
||||
"local-options"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(
|
||||
instance.join(".rmcl/config-sync/local-config/config/local.txt")
|
||||
)
|
||||
.unwrap(),
|
||||
std::fs::read_to_string(instance.join("rmcl/content/config/config/local.txt")).unwrap(),
|
||||
"local"
|
||||
);
|
||||
|
||||
@@ -538,12 +520,11 @@ mod tests {
|
||||
|
||||
assert_eq!(selected, None);
|
||||
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"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/shared.txt"))
|
||||
.unwrap(),
|
||||
std::fs::read_to_string(meta.join("state/profiles/main/config/shared.txt")).unwrap(),
|
||||
"shared"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -562,17 +543,17 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let meta = tmp.path().join("meta");
|
||||
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(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(
|
||||
instance.join(".rmcl/config-sync/local-config/options.txt"),
|
||||
instance.join("rmcl/content/config/options.txt"),
|
||||
"local-options",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
instance.join(".rmcl/config-sync/local-config/config/local.txt"),
|
||||
instance.join("rmcl/content/config/config/local.txt"),
|
||||
"local",
|
||||
)
|
||||
.unwrap();
|
||||
@@ -588,7 +569,7 @@ mod tests {
|
||||
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
|
||||
"local"
|
||||
);
|
||||
assert!(!meta.join("config-sync/profiles/deleted").exists());
|
||||
assert!(!meta.join("state/profiles/deleted").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -596,32 +577,28 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let meta = tmp.path().join("meta");
|
||||
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::write(minecraft.join("options.txt"), "changed-a-options").unwrap();
|
||||
std::fs::write(minecraft.join("config/a.txt"), "changed-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(
|
||||
meta.join("config-sync/profiles/b/options.txt"),
|
||||
meta.join("state/profiles/b/options.txt"),
|
||||
"profile-b-options",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
meta.join("config-sync/profiles/b/config/b.txt"),
|
||||
"profile-b",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(meta.join("state/profiles/b/config/b.txt"), "profile-b").unwrap();
|
||||
|
||||
let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
|
||||
|
||||
assert_eq!(selected.as_deref(), Some("b"));
|
||||
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"
|
||||
);
|
||||
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"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -639,9 +616,9 @@ mod tests {
|
||||
fn second_instance_uses_profile_options_saved_by_first_instance() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
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 = 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(second.join("config")).unwrap();
|
||||
std::fs::write(first.join("options.txt"), "first-default").unwrap();
|
||||
@@ -659,10 +636,8 @@ mod tests {
|
||||
"changed-in-main"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(
|
||||
second_instance.join(".rmcl/config-sync/local-config/options.txt")
|
||||
)
|
||||
.unwrap(),
|
||||
std::fs::read_to_string(second_instance.join("rmcl/content/config/options.txt"))
|
||||
.unwrap(),
|
||||
"second-local"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
// 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.
|
||||
|
||||
pub mod manifest;
|
||||
pub mod mods;
|
||||
pub mod reconcile;
|
||||
pub mod resource_packs;
|
||||
pub mod shaders;
|
||||
pub mod worlds;
|
||||
|
||||
@@ -28,6 +28,7 @@ pub struct ContentEntry {
|
||||
pub name: String,
|
||||
pub source_slug: Option<String>,
|
||||
pub installed_path: Option<PathBuf>,
|
||||
pub provider_project: Option<super::manifest::ProviderProject>,
|
||||
pub title_suffix: Option<String>,
|
||||
pub footer_label: Option<String>,
|
||||
pub description: String,
|
||||
@@ -114,6 +115,7 @@ pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry
|
||||
name: display_name,
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
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> {
|
||||
let mods_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("mods");
|
||||
|
||||
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 {
|
||||
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();
|
||||
dir
|
||||
}
|
||||
@@ -711,6 +716,7 @@ mod tests {
|
||||
name: "mymod".to_string(),
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
description: String::new(),
|
||||
@@ -986,6 +992,7 @@ description = "A neoforge mod"
|
||||
name: "mymod".to_string(),
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
description: String::new(),
|
||||
|
||||
@@ -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(®istry, &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(
|
||||
®istry,
|
||||
&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);
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,7 @@ pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> Co
|
||||
name: display_name,
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
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> {
|
||||
let packs_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("resourcepacks");
|
||||
|
||||
let read_dir = match std::fs::read_dir(&packs_dir) {
|
||||
|
||||
@@ -16,13 +16,15 @@ pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEn
|
||||
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||
.or_else(|| Some(super::mods::fallback_icon()));
|
||||
|
||||
ContentEntry {
|
||||
file_stem: file_stem.to_owned(),
|
||||
name: file_stem.to_owned(),
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
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> {
|
||||
let shaders_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("shaderpacks");
|
||||
|
||||
let read_dir = match std::fs::read_dir(&shaders_dir) {
|
||||
|
||||
@@ -20,6 +20,7 @@ pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEnt
|
||||
file_stem: file_stem.to_owned(),
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
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> {
|
||||
let saves_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("saves");
|
||||
|
||||
let read_dir = match std::fs::read_dir(&saves_dir) {
|
||||
|
||||
@@ -114,7 +114,10 @@ pub async fn execute_import(
|
||||
.await
|
||||
.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)?;
|
||||
|
||||
progress::clear();
|
||||
|
||||
@@ -87,7 +87,10 @@ pub async fn execute_import(
|
||||
.await
|
||||
.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)
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
|
||||
|
||||
+12
-11
@@ -249,7 +249,7 @@ async fn migrate_legacy_loader_profile_if_needed(
|
||||
};
|
||||
|
||||
let installer_json_path = instance_dir
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("versions")
|
||||
.join(&version_dir)
|
||||
.join(format!("{version_dir}.json"));
|
||||
@@ -318,10 +318,11 @@ pub async fn build_launch_invocation(
|
||||
auth: &LaunchAuth<'_>,
|
||||
) -> Result<LaunchInvocation, LaunchError> {
|
||||
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
|
||||
.join("versions")
|
||||
let metadata_paths = crate::storage::MetadataPaths::new(meta_dir);
|
||||
let meta_path = metadata_paths
|
||||
.versions()
|
||||
.join(&config.game_version)
|
||||
.join("meta.json");
|
||||
if !meta_path.exists() {
|
||||
@@ -348,7 +349,7 @@ pub async fn build_launch_invocation(
|
||||
.map(|ai| ai.id.clone())
|
||||
.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 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
|
||||
// loader is configured we use the already-loaded vanilla meta directly.
|
||||
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() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
profile_path.display().to_string(),
|
||||
@@ -453,8 +454,8 @@ pub async fn build_launch_invocation(
|
||||
}
|
||||
|
||||
classpath.push(
|
||||
meta_dir
|
||||
.join("versions")
|
||||
metadata_paths
|
||||
.versions()
|
||||
.join(&config.game_version)
|
||||
.join(format!("{}.jar", config.game_version)),
|
||||
);
|
||||
@@ -497,9 +498,9 @@ pub async fn build_launch_invocation(
|
||||
)
|
||||
.await?;
|
||||
|
||||
let assets_root = meta_dir.join("assets");
|
||||
let natives_dir = meta_dir
|
||||
.join("versions")
|
||||
let assets_root = metadata_paths.assets();
|
||||
let natives_dir = metadata_paths
|
||||
.versions()
|
||||
.join(&config.game_version)
|
||||
.join("natives");
|
||||
let version_type = merged_profile.type_.as_deref().unwrap_or("release");
|
||||
|
||||
@@ -45,7 +45,9 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> 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!(
|
||||
"Installing Forge {} for Minecraft {}",
|
||||
loader_version,
|
||||
|
||||
@@ -74,7 +74,7 @@ pub(crate) fn save_profile_bytes(
|
||||
filename: &str,
|
||||
bytes: &[u8],
|
||||
) -> 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::write(profiles_dir.join(filename), bytes)
|
||||
}
|
||||
@@ -92,7 +92,7 @@ pub(crate) fn save_installer_profile(
|
||||
profile_filename: &str,
|
||||
) -> Result<(), InstallerError> {
|
||||
let ver_json_path = instance_dir
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("versions")
|
||||
.join(version_dir_name)
|
||||
.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 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)?;
|
||||
let profile_path = profiles_dir.join(profile_filename);
|
||||
std::fs::write(&profile_path, &raw)?;
|
||||
@@ -186,7 +186,7 @@ mod tests {
|
||||
}"#;
|
||||
|
||||
let ver_dir = instance_dir
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("versions")
|
||||
.join("1.20.1-forge-47.2.0");
|
||||
std::fs::create_dir_all(&ver_dir).unwrap();
|
||||
@@ -203,7 +203,7 @@ mod tests {
|
||||
|
||||
let saved = std::fs::read(
|
||||
meta_dir
|
||||
.join("loader-profiles")
|
||||
.join("cache/loaders/profiles")
|
||||
.join("forge-1.20.1-47.2.0.json"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -45,7 +45,7 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("neoforge-installer.jar");
|
||||
tracing::info!("Installing NeoForge {}", loader_version);
|
||||
tracing::debug!("NeoForge installer path: {}", installer_jar.display());
|
||||
|
||||
@@ -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
|
||||
// crashed last tuesday at 3am
|
||||
|
||||
@@ -13,7 +13,7 @@ pub struct LogFileEntry {
|
||||
pub fn log_dir(instances_dir: &Path, instance_name: &str) -> PathBuf {
|
||||
instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("logs")
|
||||
.join("launches")
|
||||
}
|
||||
@@ -66,7 +66,7 @@ mod tests {
|
||||
let p = log_dir(Path::new("/instances"), "my-world");
|
||||
assert_eq!(
|
||||
p,
|
||||
PathBuf::from("/instances/my-world/.minecraft/logs/launches")
|
||||
PathBuf::from("/instances/my-world/minecraft/logs/launches")
|
||||
);
|
||||
}
|
||||
}
|
||||
+92
-8
@@ -126,7 +126,7 @@ impl InstanceManager {
|
||||
loader_version: Option<&str>,
|
||||
instance_dir: &std::path::Path,
|
||||
) -> Result<InstanceConfig, InstanceError> {
|
||||
let minecraft_dir = instance_dir.join(".minecraft");
|
||||
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
tracing::debug!(
|
||||
"Preparing Minecraft directory for '{}': {}",
|
||||
name,
|
||||
@@ -149,11 +149,12 @@ impl InstanceManager {
|
||||
);
|
||||
}
|
||||
|
||||
let metadata_paths = crate::storage::MetadataPaths::new(&self.meta_dir);
|
||||
for meta_subdir in &[
|
||||
self.meta_dir.join("versions"),
|
||||
self.meta_dir.join("libraries"),
|
||||
self.meta_dir.join("assets").join("objects"),
|
||||
self.meta_dir.join("assets").join("indexes"),
|
||||
metadata_paths.versions(),
|
||||
metadata_paths.libraries(),
|
||||
metadata_paths.assets().join("objects"),
|
||||
metadata_paths.assets().join("indexes"),
|
||||
] {
|
||||
std::fs::create_dir_all(meta_subdir)?;
|
||||
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)
|
||||
.await?;
|
||||
|
||||
let meta_json_path = self
|
||||
.meta_dir
|
||||
.join("versions")
|
||||
let meta_json_path = metadata_paths
|
||||
.versions()
|
||||
.join(game_version)
|
||||
.join("meta.json");
|
||||
if let Some(parent) = meta_json_path.parent()
|
||||
@@ -281,6 +281,90 @@ impl InstanceManager {
|
||||
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> {
|
||||
let instance_dir = self.instances_dir.join(name);
|
||||
if !instance_dir.exists() {
|
||||
|
||||
@@ -12,6 +12,9 @@ pub mod manager;
|
||||
pub mod models;
|
||||
pub mod screenshots;
|
||||
|
||||
pub use content::manifest::{
|
||||
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
|
||||
};
|
||||
pub use content::{
|
||||
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,
|
||||
|
||||
@@ -14,7 +14,7 @@ pub struct ScreenshotEntry {
|
||||
pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<ScreenshotEntry> {
|
||||
let dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("screenshots");
|
||||
|
||||
let read_dir = match std::fs::read_dir(&dir) {
|
||||
|
||||
@@ -265,7 +265,11 @@ mod tests {
|
||||
use tempfile::TempDir;
|
||||
|
||||
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();
|
||||
let vanilla_json = br#"{
|
||||
"id": "1.20.1",
|
||||
|
||||
@@ -128,7 +128,10 @@ pub async fn resolve(
|
||||
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() {
|
||||
return Err(ResolveError::ParentNotFound(
|
||||
parent_path.display().to_string(),
|
||||
@@ -411,7 +414,7 @@ mod tests {
|
||||
|
||||
fn write_profile(meta_dir: &Path, profile: &LaunchProfile) {
|
||||
let path = meta_dir
|
||||
.join("versions")
|
||||
.join("cache/minecraft/versions")
|
||||
.join(&profile.id)
|
||||
.join("meta.json");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
@@ -470,7 +473,11 @@ mod tests {
|
||||
async fn resolve_errors_when_parent_is_invalid_json() {
|
||||
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::write(&parent_path, "{ not valid json").unwrap();
|
||||
|
||||
|
||||
@@ -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 { .. }));
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,15 @@
|
||||
pub mod auth;
|
||||
mod cli;
|
||||
pub mod config;
|
||||
pub mod content_provider;
|
||||
pub mod instance;
|
||||
pub mod instance_logs;
|
||||
pub mod launch_profile;
|
||||
pub mod layout_migration;
|
||||
mod migrate;
|
||||
pub mod net;
|
||||
pub mod running;
|
||||
pub mod storage;
|
||||
pub mod tui;
|
||||
|
||||
pub use cli::init as cli_init;
|
||||
|
||||
+4
-2
@@ -97,7 +97,7 @@ fn cleanup_instance_leftovers(instances_dir: &Path) {
|
||||
return;
|
||||
};
|
||||
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"] {
|
||||
let p = mc.join(leftover);
|
||||
if p.exists() {
|
||||
@@ -239,7 +239,9 @@ mod tests {
|
||||
fn cleanup_instance_leftovers_removes_shim_and_log4j() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
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::write(mc.join(".mcl-shim.jar"), b"jar").unwrap();
|
||||
fs::write(mc.join(".mcl-log4j2.xml"), b"xml").unwrap();
|
||||
|
||||
+1
-1
@@ -155,7 +155,7 @@ pub async fn download_fabric_libraries(
|
||||
profile: &FabricProfile,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let libraries_dir = meta_dir.join("libraries");
|
||||
let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries();
|
||||
tracing::debug!(
|
||||
"Resolving {} Fabric libraries into {}",
|
||||
profile.libraries.len(),
|
||||
|
||||
+5
-3
@@ -150,7 +150,7 @@ pub async fn run_forge_installer(
|
||||
.arg("-jar")
|
||||
.arg(installer_path)
|
||||
.arg("--installClient")
|
||||
.current_dir(instance_dir.join(".minecraft"))
|
||||
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
|
||||
.output()
|
||||
.await
|
||||
{
|
||||
@@ -289,7 +289,9 @@ pub(crate) async fn install_forge_from_profile(
|
||||
})?;
|
||||
|
||||
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() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.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
|
||||
// server. old forge versions reference libs like launchwrapper that aren't
|
||||
// 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 {
|
||||
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod neoforge;
|
||||
pub mod quilt;
|
||||
|
||||
use reqwest::Client;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::path::Path;
|
||||
use thiserror::Error;
|
||||
@@ -97,6 +98,35 @@ impl HttpClient {
|
||||
.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
|
||||
// want both the parsed shape (for downloading libraries from it) and
|
||||
// the original bytes (to write byte-for-byte to the loader-profiles
|
||||
|
||||
+74
-5
@@ -4,16 +4,22 @@
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
|
||||
pub struct ProjectInfo {
|
||||
pub id: String,
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub icon_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct VersionInfo {
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub project_id: String,
|
||||
pub name: String,
|
||||
pub version_number: String,
|
||||
pub game_versions: Vec<String>,
|
||||
@@ -27,6 +33,8 @@ pub struct VersionFile {
|
||||
pub filename: String,
|
||||
pub size: u64,
|
||||
pub primary: bool,
|
||||
#[serde(default)]
|
||||
pub hashes: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -129,6 +137,11 @@ pub async fn search_discovery(
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> 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 query = query.trim();
|
||||
let index = if query.is_empty() {
|
||||
@@ -141,7 +154,14 @@ pub async fn search_discovery(
|
||||
url_encode(query),
|
||||
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 {
|
||||
total_hits: results.total_hits.max(0) as usize,
|
||||
@@ -267,6 +287,7 @@ pub async fn fetch_content_versions(
|
||||
game_version: &str,
|
||||
loader: ModLoader,
|
||||
) -> 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);
|
||||
tracing::debug!(
|
||||
"Fetching compatible Modrinth versions for '{}' ({}, {})",
|
||||
@@ -274,7 +295,16 @@ pub async fn fetch_content_versions(
|
||||
game_version,
|
||||
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(
|
||||
@@ -331,7 +361,13 @@ pub async fn download_version_file(
|
||||
if path.exists() {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -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?;
|
||||
Ok(DownloadOutcome::Downloaded(target))
|
||||
}
|
||||
@@ -395,6 +437,28 @@ pub async fn fetch_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
|
||||
// if none is marked primary (some projects are sloppy about that)
|
||||
pub async fn download_mrpack(
|
||||
@@ -442,6 +506,7 @@ mod tests {
|
||||
fn version_with_files(files: Vec<VersionFile>) -> VersionInfo {
|
||||
VersionInfo {
|
||||
id: "version-id".to_owned(),
|
||||
project_id: "project-id".to_owned(),
|
||||
name: "Version 1".to_owned(),
|
||||
version_number: "1.0.0".to_owned(),
|
||||
game_versions: vec!["1.21.1".to_owned()],
|
||||
@@ -510,12 +575,14 @@ mod tests {
|
||||
filename: "first.jar".to_owned(),
|
||||
size: 1,
|
||||
primary: false,
|
||||
hashes: HashMap::new(),
|
||||
},
|
||||
VersionFile {
|
||||
url: "https://example.test/primary.jar".to_owned(),
|
||||
filename: "primary.jar".to_owned(),
|
||||
size: 1,
|
||||
primary: true,
|
||||
hashes: HashMap::new(),
|
||||
},
|
||||
]);
|
||||
assert_eq!(
|
||||
@@ -528,6 +595,7 @@ mod tests {
|
||||
filename: "first.jar".to_owned(),
|
||||
size: 1,
|
||||
primary: false,
|
||||
hashes: HashMap::new(),
|
||||
}]);
|
||||
assert_eq!(
|
||||
select_primary_file(&fallback).unwrap().filename,
|
||||
@@ -545,6 +613,7 @@ mod tests {
|
||||
filename: "example.jar".to_owned(),
|
||||
size: 1,
|
||||
primary: true,
|
||||
hashes: HashMap::new(),
|
||||
}]);
|
||||
|
||||
let outcome =
|
||||
|
||||
+9
-7
@@ -152,8 +152,8 @@ pub async fn download_client_jar(
|
||||
meta: &VersionMeta,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let jar_path = meta_dir
|
||||
.join("versions")
|
||||
let jar_path = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.versions()
|
||||
.join(&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() {
|
||||
tracing::trace!("Library already cached: {}", artifact.path);
|
||||
@@ -278,8 +280,8 @@ pub async fn download_assets_from(
|
||||
}
|
||||
};
|
||||
|
||||
let index_path = meta_dir
|
||||
.join("assets")
|
||||
let index_path = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.assets()
|
||||
.join("indexes")
|
||||
.join(format!("{}.json", meta.asset_index.id));
|
||||
if !index_path.exists() {
|
||||
@@ -326,8 +328,8 @@ pub async fn download_assets_from(
|
||||
|
||||
let prefix = &object.hash[..2];
|
||||
let url = format!("{}/{}/{}", assets_base, prefix, object.hash);
|
||||
let destination = meta_dir
|
||||
.join("assets")
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.assets()
|
||||
.join("objects")
|
||||
.join(prefix)
|
||||
.join(&object.hash);
|
||||
|
||||
+1
-1
@@ -182,7 +182,7 @@ pub async fn run_neoforge_installer(
|
||||
.arg("-jar")
|
||||
.arg(installer_path)
|
||||
.arg("--installClient")
|
||||
.current_dir(instance_dir.join(".minecraft"))
|
||||
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
|
||||
.output()
|
||||
.await
|
||||
{
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@ pub async fn download_quilt_libraries(
|
||||
profile: &QuiltProfile,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let libraries_dir = meta_dir.join("libraries");
|
||||
let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries();
|
||||
tracing::debug!(
|
||||
"Resolving {} Quilt libraries into {}",
|
||||
profile.libraries.len(),
|
||||
|
||||
+159
@@ -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")
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user