fix(migration): recover safe upgrade conflicts for 0.6.1

Deduplicate identical files, merge nonconflicting legacy directories, and archive differing disposable caches without overwriting current data. Resume stale journals and detect local settings conflicts before moving instances.

Render migration Retry/Quit in the shared popup footer and add regression coverage for recovery and data preservation.
This commit is contained in:
objz committed 2026-10-06 11:58:22 +02:00
1 parent e58da16cdc
commit f417808791
7 files changed
+827 -143

No files matched your search

Generated
+1 -1
View File
@@ -3856,7 +3856,7 @@ dependencies = [
[[package]]
name = "rmcl"
version = "0.6.0"
version = "0.6.1"
dependencies = [
"async-trait",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rmcl"
version = "0.6.0"
version = "0.6.1"
authors = ["objz"]
edition = "2024"
description = "A fully featured Minecraft TUI launcher"
+258 -84
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-only
use std::fs;
use std::io;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -72,8 +72,10 @@ pub enum MigrationError {
old: String,
new: String,
},
#[error("Cannot merge migration data because both paths contain {path}")]
MergeConflict { path: String },
#[error(
"Cannot safely merge migration data from {old} into {new}: conflicting contents or incompatible paths"
)]
MergeConflict { old: String, new: String },
#[error("Migration backup would be created inside the data being backed up: {0}")]
BackupOverlap(String),
#[error(
@@ -85,6 +87,8 @@ pub enum MigrationError {
pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool {
let metadata = MetadataPaths::new(meta_dir);
metadata.cache_rebuild_pending().exists()
|| metadata.migration_journal().exists()
|| metadata.state().join("migration-v2.json").exists()
|| has_legacy_instances(instances_dir)
|| has_legacy_shared_data(meta_dir)
}
@@ -137,6 +141,7 @@ pub fn run(
if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION)
&& metadata.cache_rebuild_pending().exists()
&& !metadata.migration_journal().exists()
&& !metadata.state().join("migration-v2.json").exists()
&& !has_legacy_instances(instances_dir)
&& !has_legacy_shared_data(meta_dir)
{
@@ -156,7 +161,7 @@ pub fn run(
let total = instances.len() as u64 + 8;
let mut current = journal.completed.len() as u64;
if !is_complete(&journal, "backup") {
if !is_complete(&journal, "backup") || !journal.backup_dir.exists() {
let backup_dir = journal.backup_dir.clone();
backup_user_data(
instances_dir,
@@ -177,7 +182,7 @@ pub fn run(
},
)?;
complete(&mut journal, &metadata, "backup")?;
current += 1;
current = journal.completed.len() as u64;
}
if !is_complete(&journal, "config") {
@@ -192,7 +197,7 @@ pub fn run(
);
crate::config::upgrade_config_file(config_file)?;
complete(&mut journal, &metadata, "config")?;
current += 1;
current = journal.completed.len() as u64;
}
validate_migration_conflicts(&instances, meta_dir)?;
@@ -204,7 +209,7 @@ pub fn run(
.unwrap_or("instance")
.to_owned();
let key = format!("instance:{name}");
if is_complete(&journal, &key) {
if is_complete(&journal, &key) && !has_legacy_instance_data(instance) {
continue;
}
report(
@@ -213,40 +218,23 @@ pub fn run(
);
migrate_instance(instance, &name)?;
complete(&mut journal, &metadata, &key)?;
current += 1;
current = journal.completed.len() as u64;
}
let moves = [
(
"profiles",
meta_dir.join("config-sync").join("profiles"),
metadata.profiles(),
),
("versions", meta_dir.join("versions"), metadata.versions()),
(
"libraries",
meta_dir.join("libraries"),
metadata.libraries(),
),
("assets", meta_dir.join("assets"), metadata.assets()),
(
"loader-profiles",
meta_dir.join("loader-profiles"),
metadata.loader_profiles(),
),
];
for (key, source, destination) in moves {
for (key, source, destination) in shared_moves(meta_dir) {
let journal_key = format!("shared:{key}");
if is_complete(&journal, &journal_key) {
if is_complete(&journal, &journal_key) && !source.exists() {
continue;
}
report(
MigrationProgress::new("Migrating shared data", key, current, total)
.with_backup(&journal.backup_dir),
);
move_or_merge(&source, &destination)?;
let conflicts =
(key != "profiles").then(|| journal.backup_dir.join("cache-conflicts").join(key));
move_or_merge(&source, &destination, conflicts.as_deref())?;
complete(&mut journal, &metadata, &journal_key)?;
current += 1;
current = journal.completed.len() as u64;
}
let legacy_config_sync = meta_dir.join("config-sync");
if legacy_config_sync.exists() && fs::read_dir(&legacy_config_sync)?.next().is_none() {
@@ -263,8 +251,13 @@ pub fn run(
.with_backup(&journal.backup_dir),
);
initialize_new_layout(meta_dir)?;
if metadata.migration_journal().exists() {
fs::remove_file(metadata.migration_journal())?;
for journal_path in [
metadata.migration_journal(),
metadata.state().join("migration-v2.json"),
] {
if journal_path.exists() {
fs::remove_file(journal_path)?;
}
}
report(
MigrationProgress::new("Migration complete", "Layout updated", total, total)
@@ -293,7 +286,7 @@ fn migrate_instance(instance: &Path, name: &str) -> Result<(), MigrationError> {
rename_visible_directory(instance, LEGACY_STATE, paths.state(), name)?;
let old_config = paths.state().join("config-sync").join("local-config");
move_or_merge(&old_config, &paths.local_config())?;
move_or_merge(&old_config, &paths.local_config(), None)?;
let old_config_root = paths.state().join("config-sync");
if old_config_root.exists() && fs::read_dir(&old_config_root)?.next().is_none() {
fs::remove_dir(old_config_root)?;
@@ -309,17 +302,18 @@ fn rename_visible_directory(
instance_name: &str,
) -> Result<(), MigrationError> {
let source = instance.join(legacy_name);
if source.exists() && destination.exists() {
if path_exists(&source)?
&& path_exists(&destination)?
&& (!fs::symlink_metadata(&source)?.is_dir()
|| !fs::symlink_metadata(&destination)?.is_dir())
{
return Err(MigrationError::PathConflict {
instance: instance_name.to_owned(),
old: source.display().to_string(),
new: destination.display().to_string(),
});
}
if source.exists() {
fs::rename(source, destination)?;
}
Ok(())
move_or_merge(&source, &destination, None)
}
fn backup_user_data(
@@ -399,51 +393,78 @@ fn validate_migration_conflicts(
(instance.join(LEGACY_MINECRAFT), paths.minecraft()),
(instance.join(LEGACY_STATE), paths.state()),
] {
if legacy.exists() && destination.exists() {
if path_exists(&legacy)?
&& path_exists(&destination)?
&& (!fs::symlink_metadata(&legacy)?.is_dir()
|| !fs::symlink_metadata(&destination)?.is_dir())
{
return Err(MigrationError::PathConflict {
instance: name.to_owned(),
old: legacy.display().to_string(),
new: destination.display().to_string(),
});
}
validate_merge(&legacy, &destination, false)?;
}
for state in [instance.join(LEGACY_STATE), paths.state()] {
for destination in [
instance.join(LEGACY_STATE).join("content/config"),
paths.local_config(),
] {
validate_merge(&state.join("config-sync/local-config"), &destination, false)?;
}
}
validate_merge(
&paths.state().join("config-sync").join("local-config"),
&paths.local_config(),
)?;
}
let metadata = MetadataPaths::new(meta_dir);
for (source, destination) in [
(
meta_dir.join("config-sync").join("profiles"),
metadata.profiles(),
),
(meta_dir.join("versions"), metadata.versions()),
(meta_dir.join("libraries"), metadata.libraries()),
(meta_dir.join("assets"), metadata.assets()),
(meta_dir.join("loader-profiles"), metadata.loader_profiles()),
] {
validate_merge(&source, &destination)?;
for (key, source, destination) in shared_moves(meta_dir) {
validate_merge(&source, &destination, key != "profiles")?;
}
Ok(())
}
fn validate_merge(source: &Path, destination: &Path) -> Result<(), MigrationError> {
if !source.exists() || !destination.exists() {
fn shared_moves(meta_dir: &Path) -> [(&'static str, PathBuf, PathBuf); 5] {
let metadata = MetadataPaths::new(meta_dir);
[
(
"profiles",
meta_dir.join("config-sync").join("profiles"),
metadata.profiles(),
),
("versions", meta_dir.join("versions"), metadata.versions()),
(
"libraries",
meta_dir.join("libraries"),
metadata.libraries(),
),
("assets", meta_dir.join("assets"), metadata.assets()),
(
"loader-profiles",
meta_dir.join("loader-profiles"),
metadata.loader_profiles(),
),
]
}
pub(crate) fn validate_merge(
source: &Path,
destination: &Path,
archive_cache_conflicts: bool,
) -> Result<(), MigrationError> {
if !path_exists(source)? || !path_exists(destination)? {
return Ok(());
}
validate_merge_roots(source, destination)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
let target = destination.join(entry.file_name());
if !target.exists() {
if !path_exists(&target)? {
continue;
}
if entry.file_type()?.is_dir() && target.is_dir() {
validate_merge(&entry.path(), &target)?;
} else {
return Err(MigrationError::MergeConflict {
path: target.display().to_string(),
});
if entry.file_type()?.is_dir() && fs::symlink_metadata(&target)?.is_dir() {
validate_merge(&entry.path(), &target, archive_cache_conflicts)?;
} else if !files_identical(&entry.path(), &target)?
&& !(archive_cache_conflicts && distinct_regular_files(&entry.path(), &target)?)
{
return Err(merge_conflict(&entry.path(), &target));
}
}
Ok(())
@@ -508,42 +529,180 @@ fn file_size(path: &Path) -> io::Result<u64> {
}
}
fn move_or_merge(source: &Path, destination: &Path) -> Result<(), MigrationError> {
if !source.exists() {
pub(crate) fn move_or_merge(
source: &Path,
destination: &Path,
cache_conflicts: Option<&Path>,
) -> Result<(), MigrationError> {
if !path_exists(source)? {
return Ok(());
}
if !destination.exists() {
if !path_exists(destination)? {
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(source, destination)?;
return Ok(());
match fs::rename(source, destination) {
Ok(()) => return Ok(()),
Err(error) if error.kind() == io::ErrorKind::CrossesDevices => {}
Err(error) => return Err(error.into()),
}
}
merge_dir_without_overwrite(source, destination)?;
fs::remove_dir_all(source)?;
merge_dir_without_overwrite(source, destination, cache_conflicts)?;
fs::remove_dir(source)?;
Ok(())
}
fn merge_dir_without_overwrite(source: &Path, destination: &Path) -> Result<(), MigrationError> {
fn merge_dir_without_overwrite(
source: &Path,
destination: &Path,
cache_conflicts: Option<&Path>,
) -> Result<(), MigrationError> {
let new_directory = !path_exists(destination)?;
fs::create_dir_all(destination)?;
validate_merge_roots(source, destination)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
let target = destination.join(entry.file_name());
let file_type = entry.file_type()?;
if !target.exists() {
fs::rename(entry.path(), target)?;
} else if file_type.is_dir() && target.is_dir() {
merge_dir_without_overwrite(&entry.path(), &target)?;
fs::remove_dir(entry.path())?;
let target_exists = path_exists(&target)?;
if file_type.is_dir() && (!target_exists || fs::symlink_metadata(&target)?.is_dir()) {
move_or_merge(
&entry.path(),
&target,
cache_conflicts
.map(|path| path.join(entry.file_name()))
.as_deref(),
)?;
} else if !target_exists {
move_file(&entry.path(), &target)?;
} else if files_identical(&entry.path(), &target)? {
fs::remove_file(entry.path())?;
} else if let Some(conflicts) = cache_conflicts
&& distinct_regular_files(&entry.path(), &target)?
{
fs::create_dir_all(conflicts)?;
let mut archived = conflicts.join(entry.file_name());
let mut suffix = 0;
while path_exists(&archived)? && !files_identical(&entry.path(), &archived)? {
suffix += 1;
let mut name = entry.file_name();
name.push(format!(".{suffix}"));
archived = conflicts.join(name);
}
if path_exists(&archived)? {
fs::remove_file(entry.path())?;
} else {
move_file(&entry.path(), &archived)?;
}
tracing::warn!(
"Kept current cache {}; archived conflicting legacy copy at {}",
target.display(),
archived.display()
);
} else {
return Err(MigrationError::MergeConflict {
path: target.display().to_string(),
});
return Err(merge_conflict(&entry.path(), &target));
}
}
if new_directory {
fs::set_permissions(destination, fs::metadata(source)?.permissions())?;
}
Ok(())
}
fn path_exists(path: &Path) -> io::Result<bool> {
match fs::symlink_metadata(path) {
Ok(_) => Ok(true),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
fn merge_conflict(source: &Path, destination: &Path) -> MigrationError {
MigrationError::MergeConflict {
old: source.display().to_string(),
new: destination.display().to_string(),
}
}
fn validate_merge_roots(source: &Path, destination: &Path) -> Result<(), MigrationError> {
if !fs::symlink_metadata(source)?.is_dir() || !fs::symlink_metadata(destination)?.is_dir() {
return Err(merge_conflict(source, destination));
}
let source_path = source.canonicalize()?;
let destination_path = destination.canonicalize()?;
if source_path.starts_with(&destination_path) || destination_path.starts_with(&source_path) {
return Err(merge_conflict(source, destination));
}
Ok(())
}
fn move_file(source: &Path, destination: &Path) -> io::Result<()> {
match fs::rename(source, destination) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::CrossesDevices => {
copy_file_then_remove(source, destination)
}
Err(error) => Err(error),
}
}
fn copy_file_then_remove(source: &Path, destination: &Path) -> io::Result<()> {
let metadata = fs::symlink_metadata(source)?;
if metadata.is_symlink() {
crate::storage::copy_symlink(source, destination)?;
} else if metadata.is_file() {
let mut input = fs::File::open(source)?;
let mut output = tempfile::NamedTempFile::new_in(
destination
.parent()
.ok_or_else(|| io::Error::other("migration destination has no parent"))?,
)?;
io::copy(&mut input, &mut output)?;
output.as_file().set_permissions(metadata.permissions())?;
output.as_file().sync_all()?;
output
.persist_noclobber(destination)
.map_err(|error| error.error)?;
} else {
return Err(io::Error::other(
"migration source is not a regular file or symlink",
));
}
fs::remove_file(source)
}
fn distinct_regular_files(source: &Path, destination: &Path) -> io::Result<bool> {
Ok(fs::symlink_metadata(source)?.is_file()
&& fs::symlink_metadata(destination)?.is_file()
&& source.canonicalize()? != destination.canonicalize()?)
}
fn files_identical(source: &Path, destination: &Path) -> io::Result<bool> {
let source_metadata = fs::symlink_metadata(source)?;
let destination_metadata = fs::symlink_metadata(destination)?;
if !source_metadata.is_file()
|| !destination_metadata.is_file()
|| source_metadata.len() != destination_metadata.len()
|| source.canonicalize()? == destination.canonicalize()?
{
return Ok(false);
}
let mut source = fs::File::open(source)?;
let mut destination = fs::File::open(destination)?;
let mut source_bytes = [0; 8192];
let mut destination_bytes = [0; 8192];
loop {
let count = source.read(&mut source_bytes)?;
destination.read_exact(&mut destination_bytes[..count])?;
if source_bytes[..count] != destination_bytes[..count] {
return Ok(false);
}
if count == 0 {
return Ok(destination.read(&mut destination_bytes)? == 0);
}
}
}
fn copy_dir_recursive_with_progress(
source: &Path,
destination: &Path,
@@ -611,6 +770,9 @@ fn complete(
metadata: &MetadataPaths,
key: &str,
) -> Result<(), MigrationError> {
if is_complete(journal, key) {
return Ok(());
}
journal.completed.push(key.to_owned());
write_json_atomic(&metadata.migration_journal(), journal)
}
@@ -630,12 +792,24 @@ fn instance_directories(instances_dir: &Path) -> io::Result<Vec<PathBuf>> {
fn has_legacy_instances(instances_dir: &Path) -> bool {
instance_directories(instances_dir).is_ok_and(|instances| {
instances.iter().any(|instance| {
instance.join(LEGACY_MINECRAFT).exists() || instance.join(LEGACY_STATE).exists()
})
instances
.iter()
.any(|instance| has_legacy_instance_data(instance))
})
}
fn has_legacy_instance_data(instance: &Path) -> bool {
[
instance.join(LEGACY_MINECRAFT),
instance.join(LEGACY_STATE),
InstancePaths::new(instance)
.state()
.join("config-sync/local-config"),
]
.iter()
.any(|path| path.exists())
}
fn marker_version(path: &Path) -> Option<u32> {
serde_json::from_slice::<LayoutMarker>(&fs::read(path).ok()?)
.ok()
+24 -14
View File
@@ -41,11 +41,16 @@ fn rename_top_level(old: &Path, new: &Path) {
return;
}
if new.exists() {
eprintln!(
"rmcl migration: both {} and {} exist; leaving as-is, please merge manually",
old.display(),
new.display()
);
match crate::layout_migration::validate_merge(old, new, false)
.and_then(|_| crate::layout_migration::move_or_merge(old, new, None))
{
Ok(()) => eprintln!(
"rmcl migration: merged {} -> {}",
old.display(),
new.display()
),
Err(error) => eprintln!("rmcl migration stopped safely: {error}"),
}
return;
}
match fs::rename(old, new) {
@@ -55,7 +60,7 @@ fn rename_top_level(old: &Path, new: &Path) {
new.display()
),
Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
if let Err(e2) = copy_dir_recursive(old, new) {
if let Err(e2) = copy_top_level_across_devices(old, new) {
eprintln!(
"rmcl migration: failed cross-device copy {} -> {}: {}",
old.display(),
@@ -64,14 +69,6 @@ fn rename_top_level(old: &Path, new: &Path) {
);
return;
}
if let Err(e3) = fs::remove_dir_all(old) {
eprintln!(
"rmcl migration: copied but failed to remove {}: {}",
old.display(),
e3
);
return;
}
eprintln!(
"rmcl migration: cross-device moved {} -> {}",
old.display(),
@@ -87,6 +84,18 @@ fn rename_top_level(old: &Path, new: &Path) {
}
}
fn copy_top_level_across_devices(old: &Path, new: &Path) -> io::Result<()> {
let parent = new
.parent()
.ok_or_else(|| io::Error::other("migration destination has no parent"))?;
let staging = tempfile::Builder::new()
.prefix(".rmcl-migration-")
.tempdir_in(parent)?;
copy_dir_recursive(old, staging.path())?;
fs::rename(staging.path(), new)?;
fs::remove_dir_all(old)
}
fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> {
fs::create_dir_all(dst)?;
for entry in fs::read_dir(src)? {
@@ -101,6 +110,7 @@ fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> {
fs::copy(entry.path(), &dst_path)?;
}
}
fs::set_permissions(dst, fs::metadata(src)?.permissions())?;
Ok(())
}
+424 -5
View File
@@ -50,7 +50,98 @@ fn migrated_layout_detects_newly_copied_shared_data() {
}
#[test]
fn incomplete_migration_is_not_skipped_after_legacy_directories_were_renamed() {
fn migration_merges_identical_files_and_preserves_unique_files() {
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::write(&config, b"[paths]").unwrap();
initialize_new_layout(&meta).unwrap();
let metadata = MetadataPaths::new(&meta);
let directories = [
(meta.join("versions/26.2"), metadata.versions().join("26.2")),
(meta.join("libraries"), metadata.libraries()),
(meta.join("assets"), metadata.assets()),
(meta.join("loader-profiles"), metadata.loader_profiles()),
(meta.join("config-sync/profiles"), metadata.profiles()),
];
let bytes = vec![42; 20_000];
for (source, destination) in &directories {
fs::create_dir_all(source).unwrap();
fs::create_dir_all(destination).unwrap();
fs::write(source.join("duplicate"), &bytes).unwrap();
fs::write(destination.join("duplicate"), &bytes).unwrap();
fs::write(source.join("legacy-only"), b"legacy").unwrap();
fs::write(destination.join("current-only"), b"current").unwrap();
}
run(&instances, &meta, &config, |_| {}).unwrap();
for (source, destination) in &directories {
assert!(!source.exists());
assert_eq!(fs::read(destination.join("duplicate")).unwrap(), bytes);
assert_eq!(
fs::read(destination.join("legacy-only")).unwrap(),
b"legacy"
);
assert_eq!(
fs::read(destination.join("current-only")).unwrap(),
b"current"
);
}
assert!(!metadata.migration_journal().exists());
finish_cache_rebuild(&meta).unwrap();
assert!(!is_needed(&instances, &meta));
}
#[test]
fn migration_archives_different_cache_files_without_overwriting_current_files() {
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 source = meta.join("versions/26.2");
let destination = MetadataPaths::new(&meta).versions().join("26.2");
fs::create_dir_all(&source).unwrap();
fs::create_dir_all(&destination).unwrap();
fs::write(source.join("26.2.jar"), b"same").unwrap();
fs::write(destination.join("26.2.jar"), b"same").unwrap();
fs::write(source.join("26.2.json"), b"legacy").unwrap();
fs::write(destination.join("26.2.json"), b"actual").unwrap();
for (key, legacy, current) in shared_moves(&meta) {
if matches!(key, "profiles" | "versions") {
continue;
}
fs::create_dir_all(&legacy).unwrap();
fs::create_dir_all(&current).unwrap();
fs::write(legacy.join("conflict"), b"legacy").unwrap();
fs::write(current.join("conflict"), b"actual").unwrap();
}
let backup = run(&instances, &meta, &config, |_| {}).unwrap();
assert!(!source.exists());
assert_eq!(fs::read(destination.join("26.2.jar")).unwrap(), b"same");
assert_eq!(
fs::read(backup.join("cache-conflicts/versions/26.2/26.2.json")).unwrap(),
b"legacy"
);
assert_eq!(fs::read(destination.join("26.2.json")).unwrap(), b"actual");
for (key, legacy, current) in shared_moves(&meta) {
if matches!(key, "profiles" | "versions") {
continue;
}
assert!(!legacy.exists());
assert_eq!(fs::read(current.join("conflict")).unwrap(), b"actual");
assert_eq!(
fs::read(backup.join("cache-conflicts").join(key).join("conflict")).unwrap(),
b"legacy"
);
}
}
#[test]
fn local_config_conflicts_are_detected_before_legacy_directories_are_renamed() {
let temp = tempfile::tempdir().unwrap();
let instances = temp.path().join("instances");
let meta = temp.path().join("meta");
@@ -63,11 +154,11 @@ fn incomplete_migration_is_not_skipped_after_legacy_directories_were_renamed() {
initialize_new_layout(&meta).unwrap();
assert!(run(&instances, &meta, &config, |_| {}).is_err());
assert!(!state.exists());
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(),
fs::read(state.join("content/config/options.txt")).unwrap(),
b"current"
);
}
@@ -278,8 +369,18 @@ fn conflicting_visible_and_hidden_directories_are_not_merged() {
let instance = temp.path().join("Example");
fs::create_dir_all(instance.join(".minecraft")).unwrap();
fs::create_dir_all(instance.join("minecraft")).unwrap();
fs::write(instance.join(".minecraft/level.dat"), b"old world").unwrap();
fs::write(instance.join("minecraft/level.dat"), b"new world").unwrap();
let error = migrate_instance(&instance, "Example").unwrap_err();
assert!(matches!(error, MigrationError::PathConflict { .. }));
assert!(matches!(error, MigrationError::MergeConflict { .. }));
assert_eq!(
fs::read(instance.join(".minecraft/level.dat")).unwrap(),
b"old world"
);
assert_eq!(
fs::read(instance.join("minecraft/level.dat")).unwrap(),
b"new world"
);
}
#[test]
@@ -292,7 +393,7 @@ fn merge_conflicts_do_not_overwrite_existing_profiles() {
fs::write(source.join("nested/options.txt"), b"legacy").unwrap();
fs::write(destination.join("nested/options.txt"), b"current").unwrap();
let error = move_or_merge(&source, &destination).unwrap_err();
let error = move_or_merge(&source, &destination, None).unwrap_err();
assert!(matches!(error, MigrationError::MergeConflict { .. }));
assert_eq!(
@@ -304,3 +405,321 @@ fn merge_conflicts_do_not_overwrite_existing_profiles() {
b"legacy"
);
}
#[test]
fn file_comparison_checks_lengths_empty_files_and_differences_after_the_first_chunk() {
let temp = tempfile::tempdir().unwrap();
let source = temp.path().join("source");
let destination = temp.path().join("destination");
let mut bytes = vec![42; 20_000];
fs::write(&source, &bytes).unwrap();
fs::write(&destination, &bytes).unwrap();
assert!(files_identical(&source, &destination).unwrap());
bytes[19_999] = 43;
fs::write(&destination, &bytes).unwrap();
assert!(!files_identical(&source, &destination).unwrap());
fs::write(&destination, &bytes[..19_999]).unwrap();
assert!(!files_identical(&source, &destination).unwrap());
fs::write(&source, []).unwrap();
fs::write(&destination, []).unwrap();
assert!(files_identical(&source, &destination).unwrap());
assert!(!files_identical(&source, &source).unwrap());
assert!(!files_identical(&source, temp.path()).unwrap());
}
#[cfg(unix)]
#[test]
fn identical_targets_do_not_allow_removing_symlinks_or_aliased_files() {
let temp = tempfile::tempdir().unwrap();
let source = temp.path().join("source");
let destination = temp.path().join("destination");
fs::create_dir_all(&source).unwrap();
fs::create_dir_all(&destination).unwrap();
fs::write(source.join("file"), b"same").unwrap();
std::os::unix::fs::symlink(source.join("file"), destination.join("file")).unwrap();
assert!(matches!(
validate_merge(&source, &destination, true),
Err(MigrationError::MergeConflict { .. })
));
assert!(matches!(
move_or_merge(&source, &destination, Some(&temp.path().join("archives"))),
Err(MigrationError::MergeConflict { .. })
));
assert!(!temp.path().join("archives").exists());
assert!(matches!(
validate_merge(&source, &destination, false),
Err(MigrationError::MergeConflict { .. })
));
assert!(matches!(
move_or_merge(&source, &destination, None),
Err(MigrationError::MergeConflict { .. })
));
assert_eq!(fs::read(source.join("file")).unwrap(), b"same");
assert!(
fs::symlink_metadata(destination.join("file"))
.unwrap()
.is_symlink()
);
let alias = temp.path().join("alias");
std::os::unix::fs::symlink(&source, &alias).unwrap();
assert!(matches!(
move_or_merge(&alias, &source, None),
Err(MigrationError::MergeConflict { .. })
));
assert_eq!(fs::read(source.join("file")).unwrap(), b"same");
}
#[test]
fn split_instance_directories_merge_without_losing_worlds_or_local_settings() {
let temp = tempfile::tempdir().unwrap();
let instances = temp.path().join("instances");
let meta = temp.path().join("meta");
let instance = instances.join("Example");
let legacy = instance.join(".minecraft/saves/old-world");
let current = instance.join("minecraft/saves/current-world");
fs::create_dir_all(&legacy).unwrap();
fs::create_dir_all(&current).unwrap();
fs::write(legacy.join("level.dat"), b"old world").unwrap();
fs::write(current.join("level.dat"), b"current world").unwrap();
fs::create_dir_all(instance.join(".rmcl/config-sync/local-config")).unwrap();
fs::create_dir_all(instance.join("rmcl/content/config")).unwrap();
fs::write(
instance.join(".rmcl/config-sync/local-config/options.txt"),
b"options",
)
.unwrap();
fs::write(instance.join("rmcl/content/config/options.txt"), b"options").unwrap();
let backup = run(&instances, &meta, &temp.path().join("config.toml"), |_| {}).unwrap();
assert!(!instance.join(".minecraft").exists());
assert!(!instance.join(".rmcl").exists());
assert_eq!(
fs::read(instance.join("minecraft/saves/old-world/level.dat")).unwrap(),
b"old world"
);
assert_eq!(
fs::read(current.join("level.dat")).unwrap(),
b"current world"
);
assert_eq!(
fs::read(instance.join("rmcl/content/config/options.txt")).unwrap(),
b"options"
);
assert!(
backup
.join("instances/Example/.minecraft/saves/old-world/level.dat")
.exists()
);
assert!(
backup
.join("instances/Example/minecraft/saves/current-world/level.dat")
.exists()
);
}
#[test]
fn conflicting_user_data_prevents_cache_archiving_or_instance_moves() {
let temp = tempfile::tempdir().unwrap();
let instances = temp.path().join("instances");
let meta = temp.path().join("meta");
let instance = instances.join("Example");
fs::create_dir_all(instance.join(".rmcl/config-sync/local-config")).unwrap();
fs::create_dir_all(instance.join("rmcl/content/config")).unwrap();
fs::write(
instance.join(".rmcl/config-sync/local-config/options.txt"),
b"old settings",
)
.unwrap();
fs::write(
instance.join("rmcl/content/config/options.txt"),
b"current settings",
)
.unwrap();
fs::create_dir_all(meta.join("versions")).unwrap();
let current = MetadataPaths::new(&meta).versions();
fs::create_dir_all(&current).unwrap();
fs::write(meta.join("versions/meta.json"), b"old cache").unwrap();
fs::write(current.join("meta.json"), b"new cache").unwrap();
assert!(matches!(
run(&instances, &meta, &temp.path().join("config.toml"), |_| {}),
Err(MigrationError::MergeConflict { .. })
));
assert_eq!(
fs::read(instance.join(".rmcl/config-sync/local-config/options.txt")).unwrap(),
b"old settings"
);
assert_eq!(
fs::read(instance.join("rmcl/content/config/options.txt")).unwrap(),
b"current settings"
);
assert_eq!(
fs::read(meta.join("versions/meta.json")).unwrap(),
b"old cache"
);
assert_eq!(fs::read(current.join("meta.json")).unwrap(), b"new cache");
}
#[test]
fn recorded_journals_resume_without_pending_markers_or_skipping_reintroduced_cache_data() {
for journal_name in ["migration.json", "migration-v2.json"] {
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::write(&config, b"[paths]").unwrap();
initialize_new_layout(&meta).unwrap();
let metadata = MetadataPaths::new(&meta);
let backup = metadata.backups().join("backup-resume");
fs::create_dir_all(&backup).unwrap();
write_json_atomic(
&metadata.state().join(journal_name),
&MigrationJournal {
version: LAYOUT_VERSION,
backup_dir: backup.clone(),
completed: vec![
"backup".to_owned(),
"config".to_owned(),
"shared:versions".to_owned(),
],
},
)
.unwrap();
if journal_name == "migration.json" {
fs::copy(
metadata.migration_journal(),
metadata.state().join("migration-v2.json"),
)
.unwrap();
}
assert!(is_needed(&instances, &meta));
fs::create_dir_all(meta.join("versions")).unwrap();
fs::write(meta.join("versions/meta.json"), b"old cache").unwrap();
fs::write(metadata.versions().join("meta.json"), b"new cache").unwrap();
let archived = backup.join("cache-conflicts/versions/meta.json");
fs::create_dir_all(archived.parent().unwrap()).unwrap();
fs::write(&archived, b"earlier conflict").unwrap();
assert_eq!(run(&instances, &meta, &config, |_| {}).unwrap(), backup);
assert!(!meta.join("versions").exists());
assert!(!metadata.migration_journal().exists());
assert!(!metadata.state().join("migration-v2.json").exists());
assert_eq!(
fs::read(backup.join("cache-conflicts/versions/meta.json.1")).unwrap(),
b"old cache"
);
assert_eq!(fs::read(&archived).unwrap(), b"earlier conflict");
assert_eq!(
fs::read(metadata.versions().join("meta.json")).unwrap(),
b"new cache"
);
finish_cache_rebuild(&meta).unwrap();
assert!(!is_needed(&instances, &meta));
}
}
#[test]
fn cross_device_file_copy_preserves_source_on_conflict_and_permissions_on_success() {
let temp = tempfile::tempdir().unwrap();
let source = temp.path().join("source");
let destination = temp.path().join("destination");
fs::write(&source, b"source data").unwrap();
fs::write(&destination, b"current data").unwrap();
assert!(copy_file_then_remove(&source, &destination).is_err());
assert_eq!(fs::read(&source).unwrap(), b"source data");
assert_eq!(fs::read(&destination).unwrap(), b"current data");
fs::remove_file(&destination).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&source, fs::Permissions::from_mode(0o600)).unwrap();
}
copy_file_then_remove(&source, &destination).unwrap();
assert!(!source.exists());
assert_eq!(fs::read(&destination).unwrap(), b"source data");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&destination).unwrap().permissions().mode() & 0o777,
0o600
);
}
}
#[test]
fn visible_instances_with_leftover_local_configs_are_migrated_even_after_a_completed_step() {
for recorded_step in [false, true] {
let temp = tempfile::tempdir().unwrap();
let instances = temp.path().join("instances");
let meta = temp.path().join("meta");
let config = temp.path().join("config.toml");
let instance = instances.join("Example");
let source = instance.join("rmcl/config-sync/local-config");
let destination = instance.join("rmcl/content/config");
fs::create_dir_all(&source).unwrap();
fs::create_dir_all(&destination).unwrap();
fs::write(source.join("options.txt"), b"options").unwrap();
fs::write(destination.join("options.txt"), b"options").unwrap();
fs::write(&config, b"[paths]").unwrap();
initialize_new_layout(&meta).unwrap();
if recorded_step {
let metadata = MetadataPaths::new(&meta);
let backup = metadata.backups().join("backup-resume");
fs::create_dir_all(&backup).unwrap();
write_json_atomic(
&metadata.migration_journal(),
&MigrationJournal {
version: LAYOUT_VERSION,
backup_dir: backup,
completed: vec!["backup".to_owned(), "instance:Example".to_owned()],
},
)
.unwrap();
}
assert!(is_needed(&instances, &meta));
run(&instances, &meta, &config, |_| {}).unwrap();
assert!(!source.exists());
assert_eq!(
fs::read(destination.join("options.txt")).unwrap(),
b"options"
);
finish_cache_rebuild(&meta).unwrap();
assert!(!is_needed(&instances, &meta));
}
}
#[test]
fn missing_recorded_backup_is_recreated_before_moving_user_data() {
let temp = tempfile::tempdir().unwrap();
let instances = temp.path().join("instances");
let meta = temp.path().join("meta");
let config = temp.path().join("config.toml");
let instance = instances.join("Example");
fs::create_dir_all(instance.join(".minecraft/saves/world")).unwrap();
fs::write(instance.join(".minecraft/saves/world/level.dat"), b"world").unwrap();
let metadata = MetadataPaths::new(&meta);
let backup = metadata.backups().join("backup-resume");
write_json_atomic(
&metadata.migration_journal(),
&MigrationJournal {
version: LAYOUT_VERSION,
backup_dir: backup.clone(),
completed: vec!["backup".to_owned()],
},
)
.unwrap();
assert_eq!(run(&instances, &meta, &config, |_| {}).unwrap(), backup);
assert_eq!(
fs::read(backup.join("instances/Example/.minecraft/saves/world/level.dat")).unwrap(),
b"world"
);
assert_eq!(
fs::read(instance.join("minecraft/saves/world/level.dat")).unwrap(),
b"world"
);
}
+63 -3
View File
@@ -33,7 +33,7 @@ fn rename_top_level_skips_when_only_new_exists() {
}
#[test]
fn rename_top_level_skips_when_both_exist() {
fn rename_top_level_merges_nonconflicting_existing_directories() {
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl");
@@ -44,12 +44,44 @@ fn rename_top_level_skips_when_both_exist() {
rename_top_level(&old, &new);
assert!(old.exists(), "old should remain when both exist");
assert!(!old.exists());
assert!(new.exists(), "new should remain when both exist");
assert_eq!(fs::read(old.join("a")).unwrap(), b"old");
assert_eq!(fs::read(new.join("a")).unwrap(), b"old");
assert_eq!(fs::read(new.join("b")).unwrap(), b"new");
}
#[test]
fn rename_top_level_deduplicates_identical_files_but_preserves_conflicting_user_data() {
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl");
fs::create_dir_all(&old).unwrap();
fs::create_dir_all(&new).unwrap();
fs::write(old.join("accounts.json"), b"old accounts").unwrap();
fs::write(new.join("accounts.json"), b"current accounts").unwrap();
fs::write(old.join("unique"), b"keep").unwrap();
rename_top_level(&old, &new);
assert_eq!(
fs::read(old.join("accounts.json")).unwrap(),
b"old accounts"
);
assert_eq!(
fs::read(new.join("accounts.json")).unwrap(),
b"current accounts"
);
assert!(old.join("unique").exists());
assert!(!new.join("unique").exists());
fs::write(old.join("accounts.json"), b"current accounts").unwrap();
rename_top_level(&old, &new);
assert!(!old.exists());
assert_eq!(
fs::read(new.join("accounts.json")).unwrap(),
b"current accounts"
);
assert_eq!(fs::read(new.join("unique")).unwrap(), b"keep");
}
#[test]
fn rename_top_level_noop_when_neither_exists() {
let tmp = tempfile::tempdir().unwrap();
@@ -124,6 +156,34 @@ fn copy_dir_recursive_copies_nested_tree() {
);
}
#[test]
fn cross_device_top_level_copy_does_not_remove_source_until_the_tree_is_published() {
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl");
fs::create_dir_all(old.join("instances/Example")).unwrap();
fs::write(old.join("instances/Example/instance.json"), b"instance").unwrap();
fs::create_dir_all(&new).unwrap();
fs::write(new.join("accounts.json"), b"current accounts").unwrap();
assert!(copy_top_level_across_devices(&old, &new).is_err());
assert_eq!(
fs::read(old.join("instances/Example/instance.json")).unwrap(),
b"instance"
);
assert_eq!(
fs::read(new.join("accounts.json")).unwrap(),
b"current accounts"
);
fs::remove_file(new.join("accounts.json")).unwrap();
fs::remove_dir(&new).unwrap();
copy_top_level_across_devices(&old, &new).unwrap();
assert!(!old.exists());
assert_eq!(
fs::read(new.join("instances/Example/instance.json")).unwrap(),
b"instance"
);
}
#[cfg(unix)]
#[test]
fn cross_device_copy_preserves_links_without_following_directory_cycles() {
+56 -35
View File
@@ -278,47 +278,13 @@ async fn migration_retry_requested(
app: &mut app::App,
error: &str,
) -> color_eyre::Result<bool> {
use crate::config::theme::{BORDER_STYLE, THEME};
use crossterm::event::{Event, KeyCode};
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::style::Style;
use ratatui::widgets::{Block, Paragraph, Wrap};
use std::time::Duration;
loop {
terminal.draw(|frame| {
app.render_migration_frame(frame);
let theme = THEME.as_ref();
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Fill(1),
Constraint::Length(9),
Constraint::Fill(1),
])
.split(frame.area());
let columns = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(12),
Constraint::Percentage(76),
Constraint::Percentage(12),
])
.split(rows[1]);
frame.render_widget(
Paragraph::new(format!(
"Migration stopped safely:\n\n{error}\n\n[r] retry [q] quit"
))
.block(
Block::bordered()
.title(" Migration needs attention ")
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(theme.error()))
.style(Style::default().fg(theme.text()).bg(theme.surface())),
)
.wrap(Wrap { trim: false }),
columns[1],
);
render_migration_error_popup(frame, error);
})?;
if crossterm::event::poll(Duration::from_millis(100))?
&& let Event::Key(key) = crossterm::event::read()?
@@ -332,6 +298,36 @@ async fn migration_retry_requested(
}
}
fn render_migration_error_popup(frame: &mut ratatui::Frame, error: &str) {
use crate::config::theme::THEME;
use ratatui::style::{Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::{Paragraph, Widget, Wrap};
use widgets::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
frame.render_widget(
PopupFrame {
title: Line::from(" Migration needs attention ").style(
Style::default()
.fg(theme.error())
.add_modifier(Modifier::BOLD),
),
border_color: theme.error(),
bg: Some(theme.surface()),
keybinds: Some(keybind_line(&[("r", " retry"), ("q", " quit")])),
search_line: None,
content: Box::new(move |area, buffer| {
Paragraph::new(format!("Migration stopped safely:\n\n{error}"))
.style(Style::default().fg(theme.text()))
.wrap(Wrap { trim: false })
.render(area, buffer);
}),
},
migration_popup_area(frame.area(), 12),
);
}
async fn migration_completion_confirmation(
terminal: &mut Tui,
app: &mut app::App,
@@ -441,3 +437,28 @@ fn migration_popup_area(area: ratatui::layout::Rect, height: u16) -> ratatui::la
Constraint::Length(area.height.saturating_sub(2).min(height)),
)
}
#[cfg(test)]
#[test]
fn migration_error_actions_are_rendered_in_the_popup_footer() {
let _guard = crate::tests::TEST_LOCK
.lock()
.unwrap_or_else(|error| error.into_inner());
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 24)).unwrap();
terminal
.draw(|frame| render_migration_error_popup(frame, "conflicting files"))
.unwrap();
let area = migration_popup_area(ratatui::layout::Rect::new(0, 0, 100, 24), 12);
let buffer = terminal.backend().buffer();
let footer = (area.x..area.right())
.map(|x| buffer[(x, area.bottom() - 1)].symbol())
.collect::<String>();
assert!(footer.contains("[r] retry"), "{footer}");
assert!(footer.contains("[q] quit"), "{footer}");
for y in area.y + 1..area.bottom() - 1 {
let line = (area.x..area.right())
.map(|x| buffer[(x, y)].symbol())
.collect::<String>();
assert!(!line.contains("[r]") && !line.contains("[q]"), "{line}");
}
}