refactor: share filesystem helpers and correct pack imports

This commit is contained in:
objz committed 2026-10-01 18:48:37 +02:00
1 parent 4de886fcd0
commit 2114cdc72a
19 files changed
+524 -378

No files matched your search

+3 -19
View File
@@ -436,7 +436,7 @@ fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
&& (file_type.is_file() || file_type.is_symlink())
{
if file_type.is_symlink() {
copy_link(&entry.path(), &staging.join(&name))?;
crate::storage::copy_symlink(&entry.path(), &staging.join(&name))?;
} else {
std::fs::copy(entry.path(), staging.join(&name))?;
}
@@ -446,7 +446,7 @@ fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
}
for entry in std::fs::read_dir(&staging)? {
let entry = entry?;
crate::storage::replace_file(&entry.path(), &dst.join(entry.file_name()))?;
std::fs::rename(entry.path(), dst.join(entry.file_name()))?;
}
remove_options(dst, &copied)?;
Ok(())
@@ -506,29 +506,13 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
} else if file_type.is_file() {
std::fs::copy(&source, &target)?;
} else if file_type.is_symlink() {
copy_link(&source, &target)?;
crate::storage::copy_symlink(&source, &target)?;
}
}
Ok(())
}
#[cfg(unix)]
fn copy_link(source: &Path, target: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(std::fs::read_link(source)?, target)
}
#[cfg(not(unix))]
fn copy_link(source: &Path, _target: &Path) -> std::io::Result<()> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!(
"Cannot copy config symlink '{}' on this platform",
source.display()
),
))
}
#[cfg(test)]
#[path = "tests/config_sync.rs"]
mod tests;
+92
View File
@@ -0,0 +1,92 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::io::Read;
use std::path::{Path, PathBuf};
const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
pub(super) fn read_pack_manifest(reader: impl Read) -> Result<Vec<u8>, String> {
let mut bytes = Vec::new();
reader
.take(MAX_PACK_MANIFEST_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|error| error.to_string())?;
if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES {
return Err("Pack manifest exceeds 8 MiB".to_owned());
}
Ok(bytes)
}
fn relative_path(
entry: &zip::read::ZipFile<'_, std::fs::File>,
root: &str,
) -> Result<Option<PathBuf>, String> {
let root = root.trim_matches('/');
if root.is_empty() || !entry.name().starts_with(&format!("{root}/")) {
return Ok(None);
}
let enclosed = entry
.enclosed_name()
.ok_or_else(|| format!("Unsafe override path: {}", entry.name()))?;
let relative = enclosed
.strip_prefix(root)
.map_err(|_| format!("Invalid override path: {}", entry.name()))?;
Ok(Some(relative.to_owned()))
}
pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result<Vec<PathBuf>, String> {
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
let mut files = Vec::new();
for index in 0..archive.len() {
let entry = archive.by_index(index).map_err(|error| error.to_string())?;
if entry.is_dir() {
continue;
}
for root in roots {
if let Some(relative) = relative_path(&entry, root)?
&& !relative.as_os_str().is_empty()
{
files.push(relative);
break;
}
}
}
Ok(files)
}
pub(super) fn extract_overrides(
path: &Path,
destination: &Path,
roots: &[&str],
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let file = std::fs::File::open(path)?;
let mut archive = zip::ZipArchive::new(file)?;
// Later roots override earlier ones, independently of ZIP entry order.
for root in roots {
for index in 0..archive.len() {
let mut entry = archive.by_index(index)?;
let Some(relative) = relative_path(&entry, root)? else {
continue;
};
let target = destination.join(relative);
if entry.is_dir() {
std::fs::create_dir_all(&target)?;
continue;
}
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
let mut file = std::fs::File::create(&target)?;
let size = std::io::copy(&mut entry, &mut file)?;
tracing::trace!(
"Extracted {} to {} ({} bytes)",
entry.name(),
target.display(),
size
);
}
}
Ok(())
}
+8 -48
View File
@@ -1,9 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
// curseforge modpack archives: manifest.json references provider file ids,
// while the overrides directory contains configs and other bundled files.
use std::path::Path;
use serde::Deserialize;
@@ -97,7 +94,7 @@ fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let manifest = parse(path)?;
let (loader, loader_version) = loader(&manifest);
let override_count = count_overrides(path, &manifest.overrides)?;
let override_count = super::override_files(path, &[&manifest.overrides])?.len();
Ok(ImportSummary {
name: manifest.name,
pack_version: manifest.version,
@@ -131,15 +128,18 @@ async fn download_files(
manifest: &Manifest,
minecraft_dir: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let api_key =
crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?;
let client = crate::net::HttpClient::new();
let ids = manifest
.files
.iter()
.filter(|file| file.required)
.map(|file| file.file_id)
.collect::<Vec<_>>();
if ids.is_empty() {
return Ok(());
}
let api_key =
crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?;
let client = crate::net::HttpClient::new();
let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?;
if versions.len() != ids.len() {
return Err(format!(
@@ -218,53 +218,13 @@ pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>,
Ok(files)
}
fn count_overrides(path: &Path, root: &str) -> Result<usize, String> {
let root = root.trim_matches('/');
if root.is_empty() {
return Ok(0);
}
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
let prefix = format!("{root}/");
Ok(archive
.file_names()
.filter(|name| name.starts_with(&prefix) && !name.ends_with('/'))
.count())
}
fn extract_overrides(
path: &Path,
minecraft_dir: &Path,
root: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
progress::set_action("Extracting overrides...");
let file = std::fs::File::open(path)?;
let mut archive = zip::ZipArchive::new(file)?;
let root = root.trim_matches('/');
if root.is_empty() {
return Ok(());
}
for index in 0..archive.len() {
let mut entry = archive.by_index(index)?;
let enclosed = entry.enclosed_name().ok_or("Unsafe override path")?;
let Ok(relative) = enclosed.strip_prefix(root) else {
continue;
};
if relative.as_os_str().is_empty() {
continue;
}
let destination = minecraft_dir.join(relative);
if entry.is_dir() {
std::fs::create_dir_all(destination)?;
continue;
}
if let Some(parent) = destination.parent() {
std::fs::create_dir_all(parent)?;
}
let mut destination = std::fs::File::create(destination)?;
std::io::copy(&mut entry, &mut destination)?;
}
Ok(())
super::archive::extract_overrides(path, minecraft_dir, &[root])
}
#[cfg(test)]
+3 -6
View File
@@ -233,12 +233,9 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
}
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
for name in archive.file_names() {
if name.ends_with("mmc-pack.json") {
return name.strip_suffix("mmc-pack.json").unwrap_or("").to_string();
}
}
String::new()
find_entry(archive, "mmc-pack.json")
.and_then(|name| name.strip_suffix("mmc-pack.json").map(str::to_owned))
.unwrap_or_default()
}
// looks for a file at root or one level deep (some archives nest everything
+5 -49
View File
@@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
mod archive;
pub mod curseforge;
pub mod mmc;
pub mod mrpack;
@@ -8,21 +9,7 @@ pub mod refresh;
use std::path::{Path, PathBuf};
const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
fn read_pack_manifest(reader: impl std::io::Read) -> Result<Vec<u8>, String> {
use std::io::Read;
let mut bytes = Vec::new();
reader
.take(MAX_PACK_MANIFEST_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|error| error.to_string())?;
if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES {
return Err("Pack manifest exceeds 8 MiB".to_owned());
}
Ok(bytes)
}
use archive::{override_files, read_pack_manifest};
use crate::instance::manager::InstanceManager;
use crate::instance::models::ModLoader;
@@ -152,7 +139,8 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
tracing::trace!("Import instance name '{}' is available", candidate);
return candidate;
}
for n in 2..100 {
let mut n = 2;
loop {
let candidate = format!("{base} ({n})");
if !instances_dir.join(&candidate).exists() {
tracing::debug!(
@@ -162,12 +150,8 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
);
return candidate;
}
n += 1;
}
tracing::warn!(
"Import instance name '{}' had many collisions; using fallback suffix",
base
);
format!("{base} (import)")
}
pub async fn execute_import(
@@ -286,34 +270,6 @@ async fn owned_files(summary: &ImportSummary) -> Result<Vec<PathBuf>, String> {
}
}
fn override_files(path: &Path, roots: &[&str]) -> Result<Vec<PathBuf>, String> {
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
let mut files = Vec::new();
for index in 0..archive.len() {
let entry = archive.by_index(index).map_err(|error| error.to_string())?;
if entry.is_dir() {
continue;
}
let Some(root) = roots
.iter()
.find(|root| entry.name().starts_with(&format!("{root}/")))
else {
continue;
};
let relative = entry
.enclosed_name()
.ok_or_else(|| format!("Unsafe override path: {}", entry.name()))?
.strip_prefix(root)
.map_err(|error| error.to_string())?
.to_owned();
if !relative.as_os_str().is_empty() {
files.push(relative);
}
}
Ok(files)
}
fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
let instance_dir = manager.instances_dir.join(name);
if let Err(error) = std::fs::remove_dir_all(&instance_dir)
+38 -141
View File
@@ -35,11 +35,23 @@ pub struct MrpackFile {
pub path: String,
#[serde(default)]
pub hashes: HashMap<String, String>,
#[serde(default)]
pub env: HashMap<String, String>,
pub downloads: Vec<String>,
#[serde(rename = "fileSize")]
pub file_size: u64,
}
impl MrpackIndex {
fn client_files(&self) -> impl Iterator<Item = &MrpackFile> {
self.files.iter().filter(|file| {
file.env
.get("client")
.is_none_or(|support| support != "unsupported")
})
}
}
pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
@@ -50,6 +62,12 @@ pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
let raw = super::read_pack_manifest(entry)?;
let index: MrpackIndex =
serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
if index.format_version != 1 || index.game != "minecraft" {
return Err(format!(
"Unsupported .mrpack format {} for game '{}'",
index.format_version, index.game
));
}
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
@@ -104,7 +122,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let (loader_opt, loader_version) = loader_from_dependencies(&index.dependencies);
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
let override_count = count_overrides(path).unwrap_or(0);
let override_count = super::override_files(path, &["overrides", "client-overrides"])?.len();
tracing::trace!(
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
game_version,
@@ -119,7 +137,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
game_version,
loader,
loader_version,
mod_count: index.files.len(),
mod_count: index.client_files().count(),
override_count,
format: PackFormat::Mrpack,
archive_path: path.to_path_buf(),
@@ -127,19 +145,6 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
})
}
fn count_overrides(mrpack_path: &Path) -> Result<usize, String> {
let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?;
let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
let count = archive
.file_names()
.filter(|name| {
(name.starts_with("overrides/") || name.starts_with("client-overrides/"))
&& !name.ends_with('/')
})
.count();
Ok(count)
}
pub async fn execute_import(
summary: &ImportSummary,
manager: &InstanceManager,
@@ -173,8 +178,6 @@ pub async fn execute_import(
Ok(())
}
// downloads all mod files listed in the mrpack index, capped at 10 concurrent
// downloads to avoid getting rate-limited into oblivion
async fn download_mod_files(
index: &MrpackIndex,
minecraft_dir: &Path,
@@ -183,7 +186,7 @@ async fn download_mod_files(
use std::sync::atomic::{AtomicUsize, Ordering};
let client = crate::net::HttpClient::new();
let total = index.files.len();
let total = index.client_files().count();
let completed = Arc::new(AtomicUsize::new(0));
tracing::debug!(
"Downloading {} file(s) from .mrpack '{}' into {}",
@@ -194,60 +197,14 @@ async fn download_mod_files(
progress::set_action(format!("Downloading mods... 0/{total}"));
// bounded concurrency via manual JoinSet draining: seed with max_concurrent
// tasks, then spawn a new one each time one finishes
let mut tasks = tokio::task::JoinSet::new();
let max_concurrent = 10;
let mut file_iter = index.files.iter();
for _ in 0..max_concurrent {
if let Some(file) = file_iter.next() {
let client = client.clone();
let relative = safe_mrpack_path(&file.path)?;
let dest = minecraft_dir.join(relative);
let url = file.downloads.first().cloned().ok_or_else(|| {
crate::net::NetError::Parse(format!(
".mrpack file '{}' has no download URL",
file.path
))
})?;
let filename = file
.path
.rsplit('/')
.next()
.unwrap_or(&file.path)
.to_string();
let hashes = file.hashes.clone();
let file_size = file.file_size;
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent()
&& let Err(error) = tokio::fs::create_dir_all(parent).await
{
return Err(crate::net::NetError::from(error));
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
if !verify_mrpack_file(&dest, file_size, &hashes)? {
let _ = tokio::fs::remove_file(&dest).await;
return Err(crate::net::NetError::Parse(format!(
"Downloaded .mrpack file '{}' failed its size or hash verification",
dest.display()
)));
}
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
Ok::<(), crate::net::NetError>(())
});
}
}
for file in file_iter {
if let Some(result) = tasks.join_next().await {
result
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
for file in index.client_files() {
// Keep at most ten downloads in flight to avoid provider rate limits.
if tasks.len() == 10
&& let Some(result) = tasks.join_next().await
{
result??;
}
let client = client.clone();
let relative = safe_mrpack_path(&file.path)?;
@@ -287,9 +244,7 @@ async fn download_mod_files(
}
while let Some(result) = tasks.join_next().await {
result
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
result??;
}
Ok(())
@@ -297,11 +252,7 @@ async fn download_mod_files(
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
let path = Path::new(path);
if path.as_os_str().is_empty()
|| path
.components()
.any(|component| !matches!(component, std::path::Component::Normal(_)))
{
if !crate::storage::safe_relative_path(path) {
return Err(crate::net::NetError::Parse(format!(
"Unsafe .mrpack file path '{}'",
path.display()
@@ -311,9 +262,9 @@ fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
}
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
let mut files: Vec<_> = parse_mrpack(path)?
.files
.into_iter()
let index = parse_mrpack(path)?;
let mut files: Vec<_> = index
.client_files()
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
.collect::<Result<_, _>>()?;
files.extend(super::override_files(
@@ -346,7 +297,7 @@ fn seed_content_manifest(
paths: &InstancePaths,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut manifest = ContentManifest::default();
for file in &index.files {
for file in index.client_files() {
let relative_path = Path::new(&file.path);
let Some(kind) = mrpack_content_kind(relative_path) else {
continue;
@@ -429,65 +380,11 @@ fn extract_overrides(
progress::set_action("Extracting overrides...".to_string());
progress::set_sub_action(String::new());
let file = std::fs::File::open(mrpack_path)?;
let mut archive = zip::ZipArchive::new(file)?;
let mut extracted = 0usize;
let mut dirs = 0usize;
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
let entry_name = entry.name().to_string();
let root = if entry_name.starts_with("overrides/") {
"overrides"
} else if entry_name.starts_with("client-overrides/") {
"client-overrides"
} else {
continue;
};
let enclosed = entry.enclosed_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Unsafe override path: {entry_name}"),
)
})?;
let relative = enclosed.strip_prefix(root).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid override path: {entry_name}"),
)
})?;
if relative.as_os_str().is_empty() || entry_name.ends_with('/') {
let dir = minecraft_dir.join(relative);
std::fs::create_dir_all(dir)?;
dirs += 1;
continue;
}
let dest = minecraft_dir.join(relative);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
let mut destination = std::fs::File::create(&dest)?;
let size = std::io::copy(&mut entry, &mut destination)?;
tracing::trace!(
"Extracting .mrpack override {} to {} ({} bytes)",
entry_name,
dest.display(),
size
);
extracted += 1;
}
tracing::debug!(
"Extracted {} override files and {} directories from {}",
extracted,
dirs,
mrpack_path.display()
);
Ok(())
super::archive::extract_overrides(
mrpack_path,
minecraft_dir,
&["overrides", "client-overrides"],
)
}
#[cfg(test)]
+100 -18
View File
@@ -75,7 +75,12 @@ pub async fn prepare(
.map_err(|error| error.to_string())?;
let live = manager.instances_dir.join(&instance.name);
let needed = directory_size(&live)
.saturating_add(target.files.iter().map(|file| file.size).sum::<u64>())
.saturating_add(
target
.files
.iter()
.fold(0u64, |size, file| size.saturating_add(file.size)),
)
.saturating_add(64 * 1024 * 1024);
let available = fs2::available_space(&manager.instances_dir).map_err(|e| e.to_string())?;
if available < needed {
@@ -156,6 +161,9 @@ pub fn apply(
plan: RefreshPlan,
replace_conflicts: &HashSet<PathBuf>,
) -> Result<InstanceConfig, String> {
if crate::instance::runtime::is_active(&plan.instance.name) {
return Err("Stop the instance before changing its modpack".to_owned());
}
let live = plan
.stage_root
.parent()
@@ -188,7 +196,13 @@ pub fn apply(
}
std::fs::rename(&live, &backup).map_err(|error| error.to_string())?;
if let Err(error) = std::fs::rename(&plan.staged_instance, &live) {
let _ = std::fs::rename(&backup, &live);
if let Err(rollback) = std::fs::rename(&backup, &live) {
return Err(format!(
"Could not activate the staged update: {error}; could not restore '{}' from '{}': {rollback}",
live.display(),
backup.display()
));
}
return Err(format!("Could not activate the staged update: {error}"));
}
if let Err(error) = std::fs::remove_dir_all(&backup) {
@@ -284,7 +298,7 @@ fn preserve_refresh_state(
let path = &record.relative_path;
if !old_owned.contains(path)
&& !(new_owned.contains(path) && replace_conflicts.contains(path))
&& old.minecraft().join(path).exists()
&& std::fs::symlink_metadata(old.minecraft().join(path)).is_ok()
{
new_manifest.upsert(record.clone());
}
@@ -292,7 +306,7 @@ fn preserve_refresh_state(
for path in new_owned {
if !replace_conflicts.contains(path)
&& !old_owned.contains(path)
&& old.minecraft().join(path).exists()
&& std::fs::symlink_metadata(old.minecraft().join(path)).is_ok()
&& old_manifest.record(path).is_none()
{
new_manifest.remove(path);
@@ -300,7 +314,15 @@ fn preserve_refresh_state(
}
new_manifest
.save(&new.content_manifest())
.map_err(|e| e.to_string())
.map_err(|e| e.to_string())?;
let mut state = PackState::load(&new)
.ok_or_else(|| "The staged pack did not record its owned files".to_owned())?;
state.files.retain(|path| {
old_owned.contains(path)
|| replace_conflicts.contains(path)
|| std::fs::symlink_metadata(old.minecraft().join(path)).is_err()
});
state.save(&new)
}
fn preserve_user_files(
@@ -332,17 +354,7 @@ fn preserve_user_files(
}
std::fs::remove_file(&target).map_err(|error| error.to_string())?;
}
#[cfg(unix)]
std::os::unix::fs::symlink(
std::fs::read_link(&path).map_err(|error| error.to_string())?,
&target,
)
.map_err(|error| error.to_string())?;
#[cfg(not(unix))]
return Err(format!(
"Cannot preserve symbolic link '{}' on this platform",
path.display()
));
crate::storage::copy_symlink(&path, &target).map_err(|error| error.to_string())?;
} else if metadata.is_dir() {
let target = destination.join(entry.file_name());
std::fs::create_dir_all(&target).map_err(|error| error.to_string())?;
@@ -387,9 +399,13 @@ fn collect_files(
}
fn directory_size(path: &Path) -> u64 {
let mut size = 0;
let mut size = 0u64;
let _ = collect_files(path, path, &mut |_, file| {
size += file.metadata().map(|metadata| metadata.len()).unwrap_or(0);
size = size.saturating_add(
std::fs::symlink_metadata(file)
.map(|metadata| metadata.len())
.unwrap_or(0),
);
Ok(())
});
size
@@ -409,6 +425,50 @@ mod tests {
use crate::instance::content::manifest::{ContentFileRecord, ContentKind, FileFingerprint};
#[test]
fn refresh_rechecks_whether_the_instance_started_after_preparation() {
let temp = tempfile::tempdir().unwrap();
let name = "refresh-became-active";
let stage_root = temp.path().join(".rmcl-refresh-test");
let live = temp.path().join(name);
let staged_instance = stage_root.join(name);
std::fs::create_dir_all(live.join("minecraft")).unwrap();
std::fs::create_dir_all(staged_instance.join("minecraft")).unwrap();
let instance = serde_json::from_value(serde_json::json!({
"name": name, "game_version": "1.21", "loader": "vanilla",
"loader_version": null, "created": "2026-01-01T00:00:00Z"
}))
.unwrap();
let plan = RefreshPlan {
instance,
summary: ImportSummary {
name: name.to_owned(),
pack_version: "2".to_owned(),
game_version: "1.21".to_owned(),
loader: crate::instance::ModLoader::Vanilla,
loader_version: None,
mod_count: 0,
override_count: 0,
format: super::super::PackFormat::Mrpack,
archive_path: stage_root.join("pack.mrpack"),
source: None,
},
current_version: "1".to_owned(),
target_version: "2".to_owned(),
conflicts: Vec::new(),
stage_root,
staged_instance,
old_owned: HashSet::new(),
new_owned: HashSet::new(),
};
crate::instance::runtime::set_state(name, crate::instance::runtime::RunState::Running);
let result = apply(plan, &HashSet::new());
crate::instance::runtime::remove(name);
assert!(result.unwrap_err().contains("Stop the instance"));
assert!(live.join("minecraft").is_dir());
}
fn record(path: &str) -> ContentFileRecord {
ContentFileRecord {
relative_path: path.into(),
@@ -446,6 +506,20 @@ mod tests {
let mut staged = ContentManifest::default();
staged.upsert(record("mods/pack.jar"));
staged.save(&new.content_manifest()).unwrap();
PackState {
source: ProviderProject {
provider: "modrinth".to_owned(),
project_id: "pack".to_owned(),
version_id: "2".to_owned(),
},
files: vec![
"mods/pack.jar".into(),
"mods/user.jar".into(),
"mods/replace.jar".into(),
],
}
.save(&new)
.unwrap();
preserve_refresh_state(
old.root(),
@@ -453,6 +527,7 @@ mod tests {
&HashSet::new(),
&HashSet::from([
PathBuf::from("mods/pack.jar"),
PathBuf::from("mods/user.jar"),
PathBuf::from("mods/replace.jar"),
]),
&HashSet::from([PathBuf::from("mods/replace.jar")]),
@@ -467,6 +542,13 @@ mod tests {
assert!(manifest.record(Path::new("mods/user.jar")).is_some());
assert!(manifest.record(Path::new("mods/pack.jar")).is_some());
assert!(manifest.record(Path::new("mods/replace.jar")).is_none());
assert_eq!(
PackState::load(&new).unwrap().files,
vec![
PathBuf::from("mods/pack.jar"),
PathBuf::from("mods/replace.jar")
]
);
}
#[cfg(unix)]
+3
View File
@@ -87,4 +87,7 @@ async fn override_only_pack_tracks_files_under_its_configured_root() {
owned_files(&path).await.unwrap(),
vec![std::path::PathBuf::from("config/pack.toml")]
);
download_files(&parse(&path).unwrap(), &temp.path().join("minecraft"))
.await
.unwrap();
}
+11 -6
View File
@@ -36,8 +36,6 @@ fn detect_format_recognises_mrpack() {
#[test]
fn detect_format_recognises_mmc_flat() {
// mmc-pack.json at the zip root - the flat layout that some mmc
// archives use.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
@@ -45,8 +43,6 @@ fn detect_format_recognises_mmc_flat() {
#[test]
fn detect_format_recognises_mmc_nested() {
// mmc-pack.json one directory deep - the more common layout where
// the archive wraps everything in a named directory.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
@@ -54,8 +50,6 @@ fn detect_format_recognises_mmc_nested() {
#[test]
fn detect_format_prefers_mrpack_when_both_markers_present() {
// a zip with both markers should resolve to Mrpack since the
// detector checks modrinth.index.json first.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(
tmp.path(),
@@ -121,6 +115,17 @@ fn unique_name_multiple_collisions() {
assert_eq!(name, "TestPack (4)");
}
#[test]
fn unique_name_keeps_searching_after_ninety_nine_collisions() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("Pack")).unwrap();
for suffix in 2..=100 {
std::fs::create_dir(tmp.path().join(format!("Pack ({suffix})"))).unwrap();
}
std::fs::create_dir(tmp.path().join("Pack (import)")).unwrap();
assert_eq!(unique_instance_name("Pack", tmp.path()), "Pack (101)");
}
#[test]
fn parse_project_url() {
assert_eq!(
+26
View File
@@ -3,6 +3,32 @@
use super::*;
#[test]
fn minecraft_prefix_comes_from_the_manifest_used_for_import() {
use std::io::Write;
let tmp = tempfile::tempdir().unwrap();
let archive_path = tmp.path().join("pack.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap());
let options = zip::write::SimpleFileOptions::default();
zip.start_file("Decoy/mmc-pack.json", options).unwrap();
zip.write_all(b"{}").unwrap();
zip.start_file("mmc-pack.json", options).unwrap();
zip.write_all(br#"{"components":[{"uid":"net.minecraft","version":"1.21"}]}"#)
.unwrap();
zip.start_file(".minecraft/options.txt", options).unwrap();
zip.write_all(b"correct").unwrap();
zip.finish().unwrap();
let destination = tmp.path().join("minecraft");
assert_eq!(build_summary(&archive_path).unwrap().override_count, 1);
extract_mmc_archive(&archive_path, &destination).unwrap();
assert_eq!(
std::fs::read(destination.join("options.txt")).unwrap(),
b"correct"
);
}
#[test]
fn parse_mmc_pack_json() {
let json = r#"{
+85 -3
View File
@@ -108,6 +108,7 @@ fn extraction_merges_both_override_roots() {
&[
("overrides/config/test.toml", b"config"),
("client-overrides/options.txt", b"options"),
("overrides/options.txt", b"generic"),
],
);
let minecraft = tmp.path().join("minecraft");
@@ -124,6 +125,63 @@ fn extraction_merges_both_override_roots() {
);
}
#[test]
fn server_only_files_are_excluded_from_client_imports() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("server-only.mrpack");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
zip.start_file(
"modrinth.index.json",
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(br#"{
"formatVersion": 1, "game": "minecraft", "versionId": "1", "name": "Pack",
"dependencies": {"minecraft": "1.21"},
"files": [
{"path": "mods/server.jar", "env": {"client": "unsupported"}, "downloads": [], "fileSize": 0},
{"path": "mods/client.jar", "downloads": [], "fileSize": 0}
]
}"#).unwrap();
zip.finish().unwrap();
assert_eq!(build_summary(&path).unwrap().mod_count, 1);
assert_eq!(
owned_files(&path).unwrap(),
vec![PathBuf::from("mods/client.jar")]
);
}
#[test]
fn unsupported_pack_format_or_game_is_rejected() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("unsupported.mrpack");
for (from, to) in [
("\"formatVersion\": 1", "\"formatVersion\": 2"),
("\"game\": \"minecraft\"", "\"game\": \"other\""),
] {
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
zip.start_file(
"modrinth.index.json",
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(
std::str::from_utf8(INDEX)
.unwrap()
.replace(from, to)
.as_bytes(),
)
.unwrap();
zip.finish().unwrap();
assert!(
parse_mrpack(&path)
.unwrap_err()
.contains("Unsupported .mrpack")
);
}
}
#[test]
fn extraction_rejects_path_traversal() {
let tmp = tempfile::tempdir().unwrap();
@@ -150,7 +208,7 @@ fn mod_files_download_to_their_manifest_paths() {
Mock::given(method("GET"))
.and(path("/first.jar"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"first".to_vec()))
.expect(1)
.expect(11)
.mount(&server)
.await;
Mock::given(method("GET"))
@@ -159,7 +217,7 @@ fn mod_files_download_to_their_manifest_paths() {
.expect(1)
.mount(&server)
.await;
let index = MrpackIndex {
let mut index = MrpackIndex {
format_version: 1,
game: "minecraft".to_owned(),
version_id: "1".to_owned(),
@@ -168,18 +226,27 @@ fn mod_files_download_to_their_manifest_paths() {
files: vec![
MrpackFile {
path: "mods/first.jar".to_owned(),
env: Default::default(),
hashes: Default::default(),
downloads: vec![format!("{}/first.jar", server.uri())],
file_size: 5,
},
MrpackFile {
path: "resourcepacks/second.jar".to_owned(),
env: Default::default(),
hashes: Default::default(),
downloads: vec![format!("{}/second.jar", server.uri())],
file_size: 6,
},
],
};
index.files.extend((2..12).map(|number| MrpackFile {
path: format!("mods/extra-{number}.jar"),
env: Default::default(),
hashes: Default::default(),
downloads: vec![format!("{}/first.jar", server.uri())],
file_size: 5,
}));
let tmp = tempfile::tempdir().unwrap();
download_mod_files(&index, tmp.path()).await.unwrap();
@@ -192,6 +259,12 @@ fn mod_files_download_to_their_manifest_paths() {
std::fs::read(tmp.path().join("resourcepacks/second.jar")).unwrap(),
b"second"
);
for number in 2..12 {
assert_eq!(
std::fs::read(tmp.path().join(format!("mods/extra-{number}.jar"))).unwrap(),
b"first"
);
}
crate::feedback::progress::clear();
});
}
@@ -206,7 +279,7 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() {
.build()
.unwrap();
runtime.block_on(async {
let index = MrpackIndex {
let mut index = MrpackIndex {
format_version: 1,
game: "minecraft".to_owned(),
version_id: "1".to_owned(),
@@ -214,6 +287,7 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() {
dependencies: Default::default(),
files: vec![MrpackFile {
path: "mods/missing.jar".to_owned(),
env: Default::default(),
hashes: Default::default(),
downloads: Vec::new(),
file_size: 0,
@@ -223,6 +297,11 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() {
assert!(download_mod_files(&index, tmp.path()).await.is_err());
assert!(!tmp.path().join("mods/missing.jar").exists());
index.files[0]
.env
.insert("client".to_owned(), "unsupported".to_owned());
download_mod_files(&index, tmp.path()).await.unwrap();
assert!(!tmp.path().join("mods/missing.jar").exists());
crate::feedback::progress::clear();
});
}
@@ -247,6 +326,7 @@ fn mod_file_rejects_paths_outside_the_instance() {
dependencies: Default::default(),
files: vec![MrpackFile {
path: "../escape.jar".to_owned(),
env: Default::default(),
hashes: Default::default(),
downloads: vec!["https://example.invalid/escape.jar".to_owned()],
file_size: 1,
@@ -286,6 +366,7 @@ fn mod_file_removes_downloads_with_invalid_metadata() {
dependencies: Default::default(),
files: vec![MrpackFile {
path: "mods/corrupt.jar".to_owned(),
env: Default::default(),
hashes: Default::default(),
downloads: vec![format!("{}/corrupt.jar", server.uri())],
file_size: 1,
@@ -320,6 +401,7 @@ fn import_seeds_exact_modrinth_content_identity() {
dependencies: Default::default(),
files: vec![MrpackFile {
path: relative_path.to_string_lossy().into_owned(),
env: Default::default(),
hashes: HashMap::from([("sha512".to_owned(), sha512)]),
downloads: vec![
"https://cdn.modrinth.com/data/project/versions/version/example.zip".to_owned(),