refactor: share filesystem helpers and correct pack imports
This commit is contained in:
1 parent
4de886fcd0
commit
2114cdc72a
19 files changed
+524
-378
No files matched your search
@@ -436,7 +436,7 @@ fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
|||||||
&& (file_type.is_file() || file_type.is_symlink())
|
&& (file_type.is_file() || file_type.is_symlink())
|
||||||
{
|
{
|
||||||
if 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 {
|
} else {
|
||||||
std::fs::copy(entry.path(), staging.join(&name))?;
|
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)? {
|
for entry in std::fs::read_dir(&staging)? {
|
||||||
let entry = entry?;
|
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)?;
|
remove_options(dst, &copied)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -506,29 +506,13 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
|||||||
} else if file_type.is_file() {
|
} else if file_type.is_file() {
|
||||||
std::fs::copy(&source, &target)?;
|
std::fs::copy(&source, &target)?;
|
||||||
} else if file_type.is_symlink() {
|
} else if file_type.is_symlink() {
|
||||||
copy_link(&source, &target)?;
|
crate::storage::copy_symlink(&source, &target)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
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)]
|
#[cfg(test)]
|
||||||
#[path = "tests/config_sync.rs"]
|
#[path = "tests/config_sync.rs"]
|
||||||
mod tests;
|
mod tests;
|
||||||
@@ -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(())
|
||||||
|
}
|
||||||
@@ -1,9 +1,6 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// SPDX-License-Identifier: GPL-3.0-only
|
// 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 std::path::Path;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -97,7 +94,7 @@ fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
|
|||||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
let manifest = parse(path)?;
|
let manifest = parse(path)?;
|
||||||
let (loader, loader_version) = loader(&manifest);
|
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 {
|
Ok(ImportSummary {
|
||||||
name: manifest.name,
|
name: manifest.name,
|
||||||
pack_version: manifest.version,
|
pack_version: manifest.version,
|
||||||
@@ -131,15 +128,18 @@ async fn download_files(
|
|||||||
manifest: &Manifest,
|
manifest: &Manifest,
|
||||||
minecraft_dir: &Path,
|
minecraft_dir: &Path,
|
||||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
) -> 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
|
let ids = manifest
|
||||||
.files
|
.files
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|file| file.required)
|
.filter(|file| file.required)
|
||||||
.map(|file| file.file_id)
|
.map(|file| file.file_id)
|
||||||
.collect::<Vec<_>>();
|
.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?;
|
let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?;
|
||||||
if versions.len() != ids.len() {
|
if versions.len() != ids.len() {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
@@ -218,53 +218,13 @@ pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>,
|
|||||||
Ok(files)
|
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(
|
fn extract_overrides(
|
||||||
path: &Path,
|
path: &Path,
|
||||||
minecraft_dir: &Path,
|
minecraft_dir: &Path,
|
||||||
root: &str,
|
root: &str,
|
||||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
progress::set_action("Extracting overrides...");
|
progress::set_action("Extracting overrides...");
|
||||||
let file = std::fs::File::open(path)?;
|
super::archive::extract_overrides(path, minecraft_dir, &[root])
|
||||||
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(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -233,12 +233,9 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
||||||
for name in archive.file_names() {
|
find_entry(archive, "mmc-pack.json")
|
||||||
if name.ends_with("mmc-pack.json") {
|
.and_then(|name| name.strip_suffix("mmc-pack.json").map(str::to_owned))
|
||||||
return name.strip_suffix("mmc-pack.json").unwrap_or("").to_string();
|
.unwrap_or_default()
|
||||||
}
|
|
||||||
}
|
|
||||||
String::new()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// looks for a file at root or one level deep (some archives nest everything
|
// looks for a file at root or one level deep (some archives nest everything
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// SPDX-License-Identifier: GPL-3.0-only
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
mod archive;
|
||||||
pub mod curseforge;
|
pub mod curseforge;
|
||||||
pub mod mmc;
|
pub mod mmc;
|
||||||
pub mod mrpack;
|
pub mod mrpack;
|
||||||
@@ -8,21 +9,7 @@ pub mod refresh;
|
|||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
|
use archive::{override_files, read_pack_manifest};
|
||||||
|
|
||||||
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 crate::instance::manager::InstanceManager;
|
use crate::instance::manager::InstanceManager;
|
||||||
use crate::instance::models::ModLoader;
|
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);
|
tracing::trace!("Import instance name '{}' is available", candidate);
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
for n in 2..100 {
|
let mut n = 2;
|
||||||
|
loop {
|
||||||
let candidate = format!("{base} ({n})");
|
let candidate = format!("{base} ({n})");
|
||||||
if !instances_dir.join(&candidate).exists() {
|
if !instances_dir.join(&candidate).exists() {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
@@ -162,12 +150,8 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
|||||||
);
|
);
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
|
n += 1;
|
||||||
}
|
}
|
||||||
tracing::warn!(
|
|
||||||
"Import instance name '{}' had many collisions; using fallback suffix",
|
|
||||||
base
|
|
||||||
);
|
|
||||||
format!("{base} (import)")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn execute_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) {
|
fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
|
||||||
let instance_dir = manager.instances_dir.join(name);
|
let instance_dir = manager.instances_dir.join(name);
|
||||||
if let Err(error) = std::fs::remove_dir_all(&instance_dir)
|
if let Err(error) = std::fs::remove_dir_all(&instance_dir)
|
||||||
|
|||||||
+38
-141
@@ -35,11 +35,23 @@ pub struct MrpackFile {
|
|||||||
pub path: String,
|
pub path: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub hashes: HashMap<String, String>,
|
pub hashes: HashMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub env: HashMap<String, String>,
|
||||||
pub downloads: Vec<String>,
|
pub downloads: Vec<String>,
|
||||||
#[serde(rename = "fileSize")]
|
#[serde(rename = "fileSize")]
|
||||||
pub file_size: u64,
|
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> {
|
pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
|
||||||
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
|
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
|
||||||
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
|
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 raw = super::read_pack_manifest(entry)?;
|
||||||
let index: MrpackIndex =
|
let index: MrpackIndex =
|
||||||
serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
|
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!(
|
tracing::debug!(
|
||||||
"Parsed .mrpack '{}' version_id={} files={} deps={}",
|
"Parsed .mrpack '{}' version_id={} files={} deps={}",
|
||||||
index.name,
|
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_opt, loader_version) = loader_from_dependencies(&index.dependencies);
|
||||||
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
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!(
|
tracing::trace!(
|
||||||
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
|
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
|
||||||
game_version,
|
game_version,
|
||||||
@@ -119,7 +137,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
|||||||
game_version,
|
game_version,
|
||||||
loader,
|
loader,
|
||||||
loader_version,
|
loader_version,
|
||||||
mod_count: index.files.len(),
|
mod_count: index.client_files().count(),
|
||||||
override_count,
|
override_count,
|
||||||
format: PackFormat::Mrpack,
|
format: PackFormat::Mrpack,
|
||||||
archive_path: path.to_path_buf(),
|
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(
|
pub async fn execute_import(
|
||||||
summary: &ImportSummary,
|
summary: &ImportSummary,
|
||||||
manager: &InstanceManager,
|
manager: &InstanceManager,
|
||||||
@@ -173,8 +178,6 @@ pub async fn execute_import(
|
|||||||
Ok(())
|
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(
|
async fn download_mod_files(
|
||||||
index: &MrpackIndex,
|
index: &MrpackIndex,
|
||||||
minecraft_dir: &Path,
|
minecraft_dir: &Path,
|
||||||
@@ -183,7 +186,7 @@ async fn download_mod_files(
|
|||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
let client = crate::net::HttpClient::new();
|
let client = crate::net::HttpClient::new();
|
||||||
let total = index.files.len();
|
let total = index.client_files().count();
|
||||||
let completed = Arc::new(AtomicUsize::new(0));
|
let completed = Arc::new(AtomicUsize::new(0));
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
"Downloading {} file(s) from .mrpack '{}' into {}",
|
"Downloading {} file(s) from .mrpack '{}' into {}",
|
||||||
@@ -194,60 +197,14 @@ async fn download_mod_files(
|
|||||||
|
|
||||||
progress::set_action(format!("Downloading mods... 0/{total}"));
|
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 mut tasks = tokio::task::JoinSet::new();
|
||||||
let max_concurrent = 10;
|
|
||||||
let mut file_iter = index.files.iter();
|
|
||||||
|
|
||||||
for _ in 0..max_concurrent {
|
for file in index.client_files() {
|
||||||
if let Some(file) = file_iter.next() {
|
// Keep at most ten downloads in flight to avoid provider rate limits.
|
||||||
let client = client.clone();
|
if tasks.len() == 10
|
||||||
let relative = safe_mrpack_path(&file.path)?;
|
&& let Some(result) = tasks.join_next().await
|
||||||
let dest = minecraft_dir.join(relative);
|
{
|
||||||
let url = file.downloads.first().cloned().ok_or_else(|| {
|
result??;
|
||||||
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) })?;
|
|
||||||
}
|
}
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
let relative = safe_mrpack_path(&file.path)?;
|
let relative = safe_mrpack_path(&file.path)?;
|
||||||
@@ -287,9 +244,7 @@ async fn download_mod_files(
|
|||||||
}
|
}
|
||||||
|
|
||||||
while let Some(result) = tasks.join_next().await {
|
while let Some(result) = tasks.join_next().await {
|
||||||
result
|
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) })?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -297,11 +252,7 @@ async fn download_mod_files(
|
|||||||
|
|
||||||
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
|
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
|
||||||
let path = Path::new(path);
|
let path = Path::new(path);
|
||||||
if path.as_os_str().is_empty()
|
if !crate::storage::safe_relative_path(path) {
|
||||||
|| path
|
|
||||||
.components()
|
|
||||||
.any(|component| !matches!(component, std::path::Component::Normal(_)))
|
|
||||||
{
|
|
||||||
return Err(crate::net::NetError::Parse(format!(
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
"Unsafe .mrpack file path '{}'",
|
"Unsafe .mrpack file path '{}'",
|
||||||
path.display()
|
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> {
|
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
|
||||||
let mut files: Vec<_> = parse_mrpack(path)?
|
let index = parse_mrpack(path)?;
|
||||||
.files
|
let mut files: Vec<_> = index
|
||||||
.into_iter()
|
.client_files()
|
||||||
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
|
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
|
||||||
.collect::<Result<_, _>>()?;
|
.collect::<Result<_, _>>()?;
|
||||||
files.extend(super::override_files(
|
files.extend(super::override_files(
|
||||||
@@ -346,7 +297,7 @@ fn seed_content_manifest(
|
|||||||
paths: &InstancePaths,
|
paths: &InstancePaths,
|
||||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let mut manifest = ContentManifest::default();
|
let mut manifest = ContentManifest::default();
|
||||||
for file in &index.files {
|
for file in index.client_files() {
|
||||||
let relative_path = Path::new(&file.path);
|
let relative_path = Path::new(&file.path);
|
||||||
let Some(kind) = mrpack_content_kind(relative_path) else {
|
let Some(kind) = mrpack_content_kind(relative_path) else {
|
||||||
continue;
|
continue;
|
||||||
@@ -429,65 +380,11 @@ fn extract_overrides(
|
|||||||
progress::set_action("Extracting overrides...".to_string());
|
progress::set_action("Extracting overrides...".to_string());
|
||||||
progress::set_sub_action(String::new());
|
progress::set_sub_action(String::new());
|
||||||
|
|
||||||
let file = std::fs::File::open(mrpack_path)?;
|
super::archive::extract_overrides(
|
||||||
let mut archive = zip::ZipArchive::new(file)?;
|
mrpack_path,
|
||||||
let mut extracted = 0usize;
|
minecraft_dir,
|
||||||
let mut dirs = 0usize;
|
&["overrides", "client-overrides"],
|
||||||
|
)
|
||||||
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(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
+100
-18
@@ -75,7 +75,12 @@ pub async fn prepare(
|
|||||||
.map_err(|error| error.to_string())?;
|
.map_err(|error| error.to_string())?;
|
||||||
let live = manager.instances_dir.join(&instance.name);
|
let live = manager.instances_dir.join(&instance.name);
|
||||||
let needed = directory_size(&live)
|
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);
|
.saturating_add(64 * 1024 * 1024);
|
||||||
let available = fs2::available_space(&manager.instances_dir).map_err(|e| e.to_string())?;
|
let available = fs2::available_space(&manager.instances_dir).map_err(|e| e.to_string())?;
|
||||||
if available < needed {
|
if available < needed {
|
||||||
@@ -156,6 +161,9 @@ pub fn apply(
|
|||||||
plan: RefreshPlan,
|
plan: RefreshPlan,
|
||||||
replace_conflicts: &HashSet<PathBuf>,
|
replace_conflicts: &HashSet<PathBuf>,
|
||||||
) -> Result<InstanceConfig, String> {
|
) -> 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
|
let live = plan
|
||||||
.stage_root
|
.stage_root
|
||||||
.parent()
|
.parent()
|
||||||
@@ -188,7 +196,13 @@ pub fn apply(
|
|||||||
}
|
}
|
||||||
std::fs::rename(&live, &backup).map_err(|error| error.to_string())?;
|
std::fs::rename(&live, &backup).map_err(|error| error.to_string())?;
|
||||||
if let Err(error) = std::fs::rename(&plan.staged_instance, &live) {
|
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}"));
|
return Err(format!("Could not activate the staged update: {error}"));
|
||||||
}
|
}
|
||||||
if let Err(error) = std::fs::remove_dir_all(&backup) {
|
if let Err(error) = std::fs::remove_dir_all(&backup) {
|
||||||
@@ -284,7 +298,7 @@ fn preserve_refresh_state(
|
|||||||
let path = &record.relative_path;
|
let path = &record.relative_path;
|
||||||
if !old_owned.contains(path)
|
if !old_owned.contains(path)
|
||||||
&& !(new_owned.contains(path) && replace_conflicts.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());
|
new_manifest.upsert(record.clone());
|
||||||
}
|
}
|
||||||
@@ -292,7 +306,7 @@ fn preserve_refresh_state(
|
|||||||
for path in new_owned {
|
for path in new_owned {
|
||||||
if !replace_conflicts.contains(path)
|
if !replace_conflicts.contains(path)
|
||||||
&& !old_owned.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()
|
&& old_manifest.record(path).is_none()
|
||||||
{
|
{
|
||||||
new_manifest.remove(path);
|
new_manifest.remove(path);
|
||||||
@@ -300,7 +314,15 @@ fn preserve_refresh_state(
|
|||||||
}
|
}
|
||||||
new_manifest
|
new_manifest
|
||||||
.save(&new.content_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(
|
fn preserve_user_files(
|
||||||
@@ -332,17 +354,7 @@ fn preserve_user_files(
|
|||||||
}
|
}
|
||||||
std::fs::remove_file(&target).map_err(|error| error.to_string())?;
|
std::fs::remove_file(&target).map_err(|error| error.to_string())?;
|
||||||
}
|
}
|
||||||
#[cfg(unix)]
|
crate::storage::copy_symlink(&path, &target).map_err(|error| error.to_string())?;
|
||||||
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()
|
|
||||||
));
|
|
||||||
} else if metadata.is_dir() {
|
} else if metadata.is_dir() {
|
||||||
let target = destination.join(entry.file_name());
|
let target = destination.join(entry.file_name());
|
||||||
std::fs::create_dir_all(&target).map_err(|error| error.to_string())?;
|
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 {
|
fn directory_size(path: &Path) -> u64 {
|
||||||
let mut size = 0;
|
let mut size = 0u64;
|
||||||
let _ = collect_files(path, path, &mut |_, file| {
|
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(())
|
Ok(())
|
||||||
});
|
});
|
||||||
size
|
size
|
||||||
@@ -409,6 +425,50 @@ mod tests {
|
|||||||
|
|
||||||
use crate::instance::content::manifest::{ContentFileRecord, ContentKind, FileFingerprint};
|
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 {
|
fn record(path: &str) -> ContentFileRecord {
|
||||||
ContentFileRecord {
|
ContentFileRecord {
|
||||||
relative_path: path.into(),
|
relative_path: path.into(),
|
||||||
@@ -446,6 +506,20 @@ mod tests {
|
|||||||
let mut staged = ContentManifest::default();
|
let mut staged = ContentManifest::default();
|
||||||
staged.upsert(record("mods/pack.jar"));
|
staged.upsert(record("mods/pack.jar"));
|
||||||
staged.save(&new.content_manifest()).unwrap();
|
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(
|
preserve_refresh_state(
|
||||||
old.root(),
|
old.root(),
|
||||||
@@ -453,6 +527,7 @@ mod tests {
|
|||||||
&HashSet::new(),
|
&HashSet::new(),
|
||||||
&HashSet::from([
|
&HashSet::from([
|
||||||
PathBuf::from("mods/pack.jar"),
|
PathBuf::from("mods/pack.jar"),
|
||||||
|
PathBuf::from("mods/user.jar"),
|
||||||
PathBuf::from("mods/replace.jar"),
|
PathBuf::from("mods/replace.jar"),
|
||||||
]),
|
]),
|
||||||
&HashSet::from([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/user.jar")).is_some());
|
||||||
assert!(manifest.record(Path::new("mods/pack.jar")).is_some());
|
assert!(manifest.record(Path::new("mods/pack.jar")).is_some());
|
||||||
assert!(manifest.record(Path::new("mods/replace.jar")).is_none());
|
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)]
|
#[cfg(unix)]
|
||||||
|
|||||||
@@ -87,4 +87,7 @@ async fn override_only_pack_tracks_files_under_its_configured_root() {
|
|||||||
owned_files(&path).await.unwrap(),
|
owned_files(&path).await.unwrap(),
|
||||||
vec![std::path::PathBuf::from("config/pack.toml")]
|
vec![std::path::PathBuf::from("config/pack.toml")]
|
||||||
);
|
);
|
||||||
|
download_files(&parse(&path).unwrap(), &temp.path().join("minecraft"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
@@ -36,8 +36,6 @@ fn detect_format_recognises_mrpack() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn detect_format_recognises_mmc_flat() {
|
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 tmp = tempfile::tempdir().unwrap();
|
||||||
let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]);
|
let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]);
|
||||||
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
|
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
|
||||||
@@ -45,8 +43,6 @@ fn detect_format_recognises_mmc_flat() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn detect_format_recognises_mmc_nested() {
|
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 tmp = tempfile::tempdir().unwrap();
|
||||||
let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]);
|
let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]);
|
||||||
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
|
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
|
||||||
@@ -54,8 +50,6 @@ fn detect_format_recognises_mmc_nested() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn detect_format_prefers_mrpack_when_both_markers_present() {
|
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 tmp = tempfile::tempdir().unwrap();
|
||||||
let path = make_pack_zip(
|
let path = make_pack_zip(
|
||||||
tmp.path(),
|
tmp.path(),
|
||||||
@@ -121,6 +115,17 @@ fn unique_name_multiple_collisions() {
|
|||||||
assert_eq!(name, "TestPack (4)");
|
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]
|
#[test]
|
||||||
fn parse_project_url() {
|
fn parse_project_url() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
@@ -3,6 +3,32 @@
|
|||||||
|
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn parse_mmc_pack_json() {
|
fn parse_mmc_pack_json() {
|
||||||
let json = r#"{
|
let json = r#"{
|
||||||
|
|||||||
@@ -108,6 +108,7 @@ fn extraction_merges_both_override_roots() {
|
|||||||
&[
|
&[
|
||||||
("overrides/config/test.toml", b"config"),
|
("overrides/config/test.toml", b"config"),
|
||||||
("client-overrides/options.txt", b"options"),
|
("client-overrides/options.txt", b"options"),
|
||||||
|
("overrides/options.txt", b"generic"),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let minecraft = tmp.path().join("minecraft");
|
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]
|
#[test]
|
||||||
fn extraction_rejects_path_traversal() {
|
fn extraction_rejects_path_traversal() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
@@ -150,7 +208,7 @@ fn mod_files_download_to_their_manifest_paths() {
|
|||||||
Mock::given(method("GET"))
|
Mock::given(method("GET"))
|
||||||
.and(path("/first.jar"))
|
.and(path("/first.jar"))
|
||||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"first".to_vec()))
|
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"first".to_vec()))
|
||||||
.expect(1)
|
.expect(11)
|
||||||
.mount(&server)
|
.mount(&server)
|
||||||
.await;
|
.await;
|
||||||
Mock::given(method("GET"))
|
Mock::given(method("GET"))
|
||||||
@@ -159,7 +217,7 @@ fn mod_files_download_to_their_manifest_paths() {
|
|||||||
.expect(1)
|
.expect(1)
|
||||||
.mount(&server)
|
.mount(&server)
|
||||||
.await;
|
.await;
|
||||||
let index = MrpackIndex {
|
let mut index = MrpackIndex {
|
||||||
format_version: 1,
|
format_version: 1,
|
||||||
game: "minecraft".to_owned(),
|
game: "minecraft".to_owned(),
|
||||||
version_id: "1".to_owned(),
|
version_id: "1".to_owned(),
|
||||||
@@ -168,18 +226,27 @@ fn mod_files_download_to_their_manifest_paths() {
|
|||||||
files: vec![
|
files: vec![
|
||||||
MrpackFile {
|
MrpackFile {
|
||||||
path: "mods/first.jar".to_owned(),
|
path: "mods/first.jar".to_owned(),
|
||||||
|
env: Default::default(),
|
||||||
hashes: Default::default(),
|
hashes: Default::default(),
|
||||||
downloads: vec![format!("{}/first.jar", server.uri())],
|
downloads: vec![format!("{}/first.jar", server.uri())],
|
||||||
file_size: 5,
|
file_size: 5,
|
||||||
},
|
},
|
||||||
MrpackFile {
|
MrpackFile {
|
||||||
path: "resourcepacks/second.jar".to_owned(),
|
path: "resourcepacks/second.jar".to_owned(),
|
||||||
|
env: Default::default(),
|
||||||
hashes: Default::default(),
|
hashes: Default::default(),
|
||||||
downloads: vec![format!("{}/second.jar", server.uri())],
|
downloads: vec![format!("{}/second.jar", server.uri())],
|
||||||
file_size: 6,
|
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();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
download_mod_files(&index, tmp.path()).await.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(),
|
std::fs::read(tmp.path().join("resourcepacks/second.jar")).unwrap(),
|
||||||
b"second"
|
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();
|
crate::feedback::progress::clear();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -206,7 +279,7 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() {
|
|||||||
.build()
|
.build()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
runtime.block_on(async {
|
runtime.block_on(async {
|
||||||
let index = MrpackIndex {
|
let mut index = MrpackIndex {
|
||||||
format_version: 1,
|
format_version: 1,
|
||||||
game: "minecraft".to_owned(),
|
game: "minecraft".to_owned(),
|
||||||
version_id: "1".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(),
|
dependencies: Default::default(),
|
||||||
files: vec![MrpackFile {
|
files: vec![MrpackFile {
|
||||||
path: "mods/missing.jar".to_owned(),
|
path: "mods/missing.jar".to_owned(),
|
||||||
|
env: Default::default(),
|
||||||
hashes: Default::default(),
|
hashes: Default::default(),
|
||||||
downloads: Vec::new(),
|
downloads: Vec::new(),
|
||||||
file_size: 0,
|
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!(download_mod_files(&index, tmp.path()).await.is_err());
|
||||||
assert!(!tmp.path().join("mods/missing.jar").exists());
|
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();
|
crate::feedback::progress::clear();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -247,6 +326,7 @@ fn mod_file_rejects_paths_outside_the_instance() {
|
|||||||
dependencies: Default::default(),
|
dependencies: Default::default(),
|
||||||
files: vec![MrpackFile {
|
files: vec![MrpackFile {
|
||||||
path: "../escape.jar".to_owned(),
|
path: "../escape.jar".to_owned(),
|
||||||
|
env: Default::default(),
|
||||||
hashes: Default::default(),
|
hashes: Default::default(),
|
||||||
downloads: vec!["https://example.invalid/escape.jar".to_owned()],
|
downloads: vec!["https://example.invalid/escape.jar".to_owned()],
|
||||||
file_size: 1,
|
file_size: 1,
|
||||||
@@ -286,6 +366,7 @@ fn mod_file_removes_downloads_with_invalid_metadata() {
|
|||||||
dependencies: Default::default(),
|
dependencies: Default::default(),
|
||||||
files: vec![MrpackFile {
|
files: vec![MrpackFile {
|
||||||
path: "mods/corrupt.jar".to_owned(),
|
path: "mods/corrupt.jar".to_owned(),
|
||||||
|
env: Default::default(),
|
||||||
hashes: Default::default(),
|
hashes: Default::default(),
|
||||||
downloads: vec![format!("{}/corrupt.jar", server.uri())],
|
downloads: vec![format!("{}/corrupt.jar", server.uri())],
|
||||||
file_size: 1,
|
file_size: 1,
|
||||||
@@ -320,6 +401,7 @@ fn import_seeds_exact_modrinth_content_identity() {
|
|||||||
dependencies: Default::default(),
|
dependencies: Default::default(),
|
||||||
files: vec![MrpackFile {
|
files: vec![MrpackFile {
|
||||||
path: relative_path.to_string_lossy().into_owned(),
|
path: relative_path.to_string_lossy().into_owned(),
|
||||||
|
env: Default::default(),
|
||||||
hashes: HashMap::from([("sha512".to_owned(), sha512)]),
|
hashes: HashMap::from([("sha512".to_owned(), sha512)]),
|
||||||
downloads: vec![
|
downloads: vec![
|
||||||
"https://cdn.modrinth.com/data/project/versions/version/example.zip".to_owned(),
|
"https://cdn.modrinth.com/data/project/versions/version/example.zip".to_owned(),
|
||||||
|
|||||||
+5
-22
@@ -136,6 +136,7 @@ pub fn run(
|
|||||||
let metadata = MetadataPaths::new(meta_dir);
|
let metadata = MetadataPaths::new(meta_dir);
|
||||||
if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION)
|
if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION)
|
||||||
&& metadata.cache_rebuild_pending().exists()
|
&& metadata.cache_rebuild_pending().exists()
|
||||||
|
&& !metadata.migration_journal().exists()
|
||||||
&& !has_legacy_instances(instances_dir)
|
&& !has_legacy_instances(instances_dir)
|
||||||
&& !has_legacy_shared_data(meta_dir)
|
&& !has_legacy_shared_data(meta_dir)
|
||||||
{
|
{
|
||||||
@@ -150,7 +151,7 @@ pub fn run(
|
|||||||
fs::create_dir_all(metadata.state())?;
|
fs::create_dir_all(metadata.state())?;
|
||||||
fs::write(metadata.cache_rebuild_pending(), LAYOUT_VERSION.to_string())?;
|
fs::write(metadata.cache_rebuild_pending(), LAYOUT_VERSION.to_string())?;
|
||||||
|
|
||||||
let mut journal = load_or_create_journal(instances_dir, &metadata)?;
|
let mut journal = load_or_create_journal(&metadata)?;
|
||||||
let instances = instance_directories(instances_dir)?;
|
let instances = instance_directories(instances_dir)?;
|
||||||
let total = instances.len() as u64 + 8;
|
let total = instances.len() as u64 + 8;
|
||||||
let mut current = journal.completed.len() as u64;
|
let mut current = journal.completed.len() as u64;
|
||||||
@@ -554,7 +555,7 @@ fn copy_dir_recursive_with_progress(
|
|||||||
let file_type = entry.file_type()?;
|
let file_type = entry.file_type()?;
|
||||||
let target = destination.join(entry.file_name());
|
let target = destination.join(entry.file_name());
|
||||||
if file_type.is_symlink() {
|
if file_type.is_symlink() {
|
||||||
copy_symlink(&entry.path(), &target)?;
|
crate::storage::copy_symlink(&entry.path(), &target)?;
|
||||||
} else if file_type.is_dir() {
|
} else if file_type.is_dir() {
|
||||||
copy_dir_recursive_with_progress(&entry.path(), &target, report)?;
|
copy_dir_recursive_with_progress(&entry.path(), &target, report)?;
|
||||||
} else {
|
} else {
|
||||||
@@ -566,25 +567,7 @@ fn copy_dir_recursive_with_progress(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
fn load_or_create_journal(metadata: &MetadataPaths) -> Result<MigrationJournal, MigrationError> {
|
||||||
fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
|
||||||
std::os::unix::fs::symlink(fs::read_link(source)?, destination)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
|
||||||
fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
|
||||||
let target = fs::read_link(source)?;
|
|
||||||
if source.is_dir() {
|
|
||||||
std::os::windows::fs::symlink_dir(target, destination)
|
|
||||||
} else {
|
|
||||||
std::os::windows::fs::symlink_file(target, destination)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load_or_create_journal(
|
|
||||||
_instances_dir: &Path,
|
|
||||||
metadata: &MetadataPaths,
|
|
||||||
) -> Result<MigrationJournal, MigrationError> {
|
|
||||||
let legacy_journal = metadata.state().join("migration-v2.json");
|
let legacy_journal = metadata.state().join("migration-v2.json");
|
||||||
if metadata.migration_journal().exists() {
|
if metadata.migration_journal().exists() {
|
||||||
return Ok(serde_json::from_slice(&fs::read(
|
return Ok(serde_json::from_slice(&fs::read(
|
||||||
@@ -597,7 +580,7 @@ fn load_or_create_journal(
|
|||||||
fs::remove_file(legacy_journal)?;
|
fs::remove_file(legacy_journal)?;
|
||||||
return Ok(journal);
|
return Ok(journal);
|
||||||
}
|
}
|
||||||
let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();
|
let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S-%f").to_string();
|
||||||
let journal = MigrationJournal {
|
let journal = MigrationJournal {
|
||||||
version: LAYOUT_VERSION,
|
version: LAYOUT_VERSION,
|
||||||
backup_dir: metadata.backups().join(format!("backup-{timestamp}")),
|
backup_dir: metadata.backups().join(format!("backup-{timestamp}")),
|
||||||
|
|||||||
+3
-1
@@ -93,7 +93,9 @@ fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> {
|
|||||||
let entry = entry?;
|
let entry = entry?;
|
||||||
let ty = entry.file_type()?;
|
let ty = entry.file_type()?;
|
||||||
let dst_path = dst.join(entry.file_name());
|
let dst_path = dst.join(entry.file_name());
|
||||||
if ty.is_dir() {
|
if ty.is_symlink() {
|
||||||
|
crate::storage::copy_symlink(&entry.path(), &dst_path)?;
|
||||||
|
} else if ty.is_dir() {
|
||||||
copy_dir_recursive(&entry.path(), &dst_path)?;
|
copy_dir_recursive(&entry.path(), &dst_path)?;
|
||||||
} else {
|
} else {
|
||||||
fs::copy(entry.path(), &dst_path)?;
|
fs::copy(entry.path(), &dst_path)?;
|
||||||
|
|||||||
+1
-1
@@ -333,7 +333,7 @@ async fn download_file_once(
|
|||||||
}
|
}
|
||||||
file.flush().await?;
|
file.flush().await?;
|
||||||
drop(file);
|
drop(file);
|
||||||
crate::storage::replace_file(&temporary, dest)?;
|
tokio::fs::rename(&temporary, dest).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
+3
-64
@@ -3,9 +3,10 @@
|
|||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
|
|
||||||
static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1);
|
mod filesystem;
|
||||||
|
pub(crate) use filesystem::copy_symlink;
|
||||||
|
pub use filesystem::{write_atomic, write_atomic_private};
|
||||||
|
|
||||||
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
|
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
|
||||||
pub const INSTANCE_STATE_DIR_NAME: &str = "rmcl";
|
pub const INSTANCE_STATE_DIR_NAME: &str = "rmcl";
|
||||||
@@ -161,68 +162,6 @@ pub fn safe_relative_path(path: &Path) -> bool {
|
|||||||
&& components.all(|part| matches!(part, std::path::Component::Normal(_)))
|
&& components.all(|part| matches!(part, std::path::Component::Normal(_)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
|
||||||
write_atomic_with_mode(path, bytes, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
|
||||||
write_atomic_with_mode(path, bytes, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> {
|
|
||||||
let parent = path
|
|
||||||
.parent()
|
|
||||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
|
|
||||||
std::fs::create_dir_all(parent)?;
|
|
||||||
let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
|
|
||||||
let name = path
|
|
||||||
.file_name()
|
|
||||||
.and_then(|name| name.to_str())
|
|
||||||
.unwrap_or("data");
|
|
||||||
let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id));
|
|
||||||
let result = (|| {
|
|
||||||
use std::io::Write;
|
|
||||||
|
|
||||||
let mut options = std::fs::OpenOptions::new();
|
|
||||||
options.create_new(true).write(true);
|
|
||||||
#[cfg(unix)]
|
|
||||||
if private {
|
|
||||||
use std::os::unix::fs::OpenOptionsExt;
|
|
||||||
options.mode(0o600);
|
|
||||||
}
|
|
||||||
#[cfg(not(unix))]
|
|
||||||
let _ = private;
|
|
||||||
let mut file = options.open(&temporary)?;
|
|
||||||
file.write_all(bytes)?;
|
|
||||||
file.sync_all()?;
|
|
||||||
replace_file(&temporary, path)
|
|
||||||
})();
|
|
||||||
if result.is_err() {
|
|
||||||
let _ = std::fs::remove_file(&temporary);
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
|
|
||||||
std::fs::rename(source, destination)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
|
||||||
pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
|
|
||||||
if !destination.exists() {
|
|
||||||
return std::fs::rename(source, destination);
|
|
||||||
}
|
|
||||||
let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
|
|
||||||
let backup = destination.with_extension(format!("rmcl-replaced-{id}"));
|
|
||||||
std::fs::rename(destination, &backup)?;
|
|
||||||
if let Err(error) = std::fs::rename(source, destination) {
|
|
||||||
let _ = std::fs::rename(&backup, destination);
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
std::fs::remove_file(backup)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[path = "tests/storage.rs"]
|
#[path = "tests/storage.rs"]
|
||||||
mod tests;
|
mod tests;
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
|
||||||
|
static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1);
|
||||||
|
|
||||||
|
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||||
|
write_atomic_with_mode(path, bytes, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||||
|
write_atomic_with_mode(path, bytes, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> {
|
||||||
|
let parent = path
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let name = path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or("data");
|
||||||
|
let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id));
|
||||||
|
let result = (|| {
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
let mut options = std::fs::OpenOptions::new();
|
||||||
|
options.create_new(true).write(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
if private {
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
options.mode(0o600);
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let _ = private;
|
||||||
|
let mut file = options.open(&temporary)?;
|
||||||
|
file.write_all(bytes)?;
|
||||||
|
file.sync_all()?;
|
||||||
|
drop(file);
|
||||||
|
std::fs::rename(&temporary, path)
|
||||||
|
})();
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = std::fs::remove_file(&temporary);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
||||||
|
std::os::unix::fs::symlink(std::fs::read_link(source)?, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
||||||
|
let target = std::fs::read_link(source)?;
|
||||||
|
if source.is_dir() {
|
||||||
|
std::os::windows::fs::symlink_dir(target, destination)
|
||||||
|
} else {
|
||||||
|
std::os::windows::fs::symlink_file(target, destination)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,6 +49,44 @@ fn migrated_layout_detects_newly_copied_shared_data() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incomplete_migration_is_not_skipped_after_legacy_directories_were_renamed() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let instances = temp.path().join("instances");
|
||||||
|
let meta = temp.path().join("meta");
|
||||||
|
let config = temp.path().join("config.toml");
|
||||||
|
let state = instances.join("Copied/.rmcl");
|
||||||
|
fs::create_dir_all(state.join("config-sync/local-config")).unwrap();
|
||||||
|
fs::create_dir_all(state.join("content/config")).unwrap();
|
||||||
|
fs::write(state.join("config-sync/local-config/options.txt"), b"old").unwrap();
|
||||||
|
fs::write(state.join("content/config/options.txt"), b"current").unwrap();
|
||||||
|
initialize_new_layout(&meta).unwrap();
|
||||||
|
|
||||||
|
assert!(run(&instances, &meta, &config, |_| {}).is_err());
|
||||||
|
assert!(!state.exists());
|
||||||
|
assert!(MetadataPaths::new(&meta).migration_journal().exists());
|
||||||
|
assert!(run(&instances, &meta, &config, |_| {}).is_err());
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(instances.join("Copied/rmcl/content/config/options.txt")).unwrap(),
|
||||||
|
b"current"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeated_migrations_create_separate_backups() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let instances = temp.path().join("instances");
|
||||||
|
let meta = temp.path().join("meta");
|
||||||
|
let config = temp.path().join("config.toml");
|
||||||
|
fs::create_dir_all(instances.join("First/.minecraft")).unwrap();
|
||||||
|
let first = run(&instances, &meta, &config, |_| {}).unwrap();
|
||||||
|
fs::create_dir_all(instances.join("Second/.minecraft")).unwrap();
|
||||||
|
let second = run(&instances, &meta, &config, |_| {}).unwrap();
|
||||||
|
|
||||||
|
assert_ne!(first, second);
|
||||||
|
assert!(second.join("instances/Second/.minecraft").is_dir());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn migration_backs_up_and_renames_instance_directories() {
|
fn migration_backs_up_and_renames_instance_directories() {
|
||||||
let temp = tempfile::tempdir().unwrap();
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -123,3 +123,25 @@ fn copy_dir_recursive_copies_nested_tree() {
|
|||||||
b"inner"
|
b"inner"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn cross_device_copy_preserves_links_without_following_directory_cycles() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let source = tmp.path().join("old");
|
||||||
|
let destination = tmp.path().join("new");
|
||||||
|
fs::create_dir(&source).unwrap();
|
||||||
|
fs::write(source.join("data.txt"), b"data").unwrap();
|
||||||
|
std::os::unix::fs::symlink("data.txt", source.join("linked.txt")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(".", source.join("cycle")).unwrap();
|
||||||
|
|
||||||
|
copy_dir_recursive(&source, &destination).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_link(destination.join("linked.txt")).unwrap(),
|
||||||
|
Path::new("data.txt")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_link(destination.join("cycle")).unwrap(),
|
||||||
|
Path::new(".")
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -68,3 +68,15 @@ fn atomic_write_replaces_existing_file() {
|
|||||||
write_atomic(&path, b"new").unwrap();
|
write_atomic(&path, b"new").unwrap();
|
||||||
assert_eq!(std::fs::read(path).unwrap(), b"new");
|
assert_eq!(std::fs::read(path).unwrap(), b"new");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn failed_atomic_replacement_keeps_the_destination_and_removes_staging() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("state.json");
|
||||||
|
std::fs::create_dir(&path).unwrap();
|
||||||
|
std::fs::write(path.join("keep"), b"old").unwrap();
|
||||||
|
|
||||||
|
assert!(write_atomic(&path, b"new").is_err());
|
||||||
|
assert_eq!(std::fs::read(path.join("keep")).unwrap(), b"old");
|
||||||
|
assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user