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
+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) {
|
||||
|
||||
Reference in new issue
Block a user