6 Commits
Author SHA1 Message Date
objz ebbadeb53b chore: release 0.6.2 2026-10-10 18:18:36 +02:00
Consti Bauer 697f3f3e85 Merge pull request #52 from objz/feat/40-directional-navigation
Add Ctrl-arrow panel navigation
2026-10-10 12:23:53 +02:00
objz 2d77d5b57d feat(tui): add Ctrl-arrow panel navigation 2026-10-10 11:52:09 +02:00
Consti Bauer 8de8654d64 Merge pull request #51 from GitanElyon/fix/nix-graphics-libs
fix(flake.nix): graphics libs
2026-10-08 10:00:58 +02:00
GitanElyon 59becfd7c9 fix(flake.nix): added extra minecraft dependencies
expanded runtimeLibs in flake.nix with libXi, libXinerama, libGL (libglvnd), vulkan-loader, libxkbcommon, udev, alsa-lib, libpulseaudio, and appended /run/opengl-driver/lib for the Mesa drivers
2026-10-06 14:42:15 -04:00
objz a2d337397c 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.
2026-10-06 11:58:22 +02:00
12 changed files with 1000 additions and 150 deletions

No files matched your search

Generated
+1 -1
View File
@@ -3856,7 +3856,7 @@ dependencies = [
[[package]] [[package]]
name = "rmcl" name = "rmcl"
version = "0.6.0" version = "0.6.2"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64", "base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "rmcl" name = "rmcl"
version = "0.6.0" version = "0.6.2"
authors = ["objz"] authors = ["objz"]
edition = "2024" edition = "2024"
description = "A fully featured Minecraft TUI launcher" description = "A fully featured Minecraft TUI launcher"
+6
View File
@@ -47,6 +47,12 @@ Browse Modrinth and CurseForge modpacks or import Modrinth, CurseForge, and Mult
--- ---
## navigation
Use `Ctrl` + arrow keys to move between the Instances, Content, Accounts,
Settings, and Overview panels. In Content, use plain `Left` / `Right` or `h` / `l`
to switch tabs, and `Tab` to switch between installed content and discovery.
## authentication ## authentication
rmcl uses its own Microsoft client ID for Minecraft account authentication. rmcl uses its own Microsoft client ID for Minecraft account authentication.
+27 -7
View File
@@ -13,19 +13,29 @@
}: }:
flake-utils.lib.eachDefaultSystem (system: let flake-utils.lib.eachDefaultSystem (system: let
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
# release binaries have the curseforge key compiled in; source builds
# don't, so forward the caller's key when building impurely.
curseforgeApiKey = builtins.getEnv "CURSEFORGE_API_KEY"; curseforgeApiKey = builtins.getEnv "CURSEFORGE_API_KEY";
# minecraft's bundled lwjgl natives dlopen the host's x11 stack, which # minecraft's lwjgl/sdl natives dlopen the host's x11, opengl, vulkan,
# isn't on the default loader path on nixos. java is spawned as a child # input and audio stack, which isn't on the default loader path on nixos.
# of rmcl, so a wrapper LD_LIBRARY_PATH propagates all the way down. # java is spawned as a child of rmcl, so a wrapper LD_LIBRARY_PATH
runtimeLibs = pkgs.lib.makeLibraryPath (with pkgs; [ # propagates all the way down. /run/opengl-driver/lib holds the mesa
# drivers that libglvnd dispatches to.
runtimeLibs =
pkgs.lib.makeLibraryPath (with pkgs; [
libX11 libX11
libXext libXext
libXcursor libXcursor
libXrandr libXrandr
libXxf86vm libXxf86vm
]); libXi
libXinerama
libGL
vulkan-loader
libxkbcommon
udev
alsa-lib
libpulseaudio
])
+ ":/run/opengl-driver/lib";
in { in {
packages.default = pkgs.rustPlatform.buildRustPackage { packages.default = pkgs.rustPlatform.buildRustPackage {
pname = "rmcl"; pname = "rmcl";
@@ -50,5 +60,15 @@
mainProgram = "rmcl"; mainProgram = "rmcl";
}; };
}; };
# `nix develop` + `cargo run --release` spawns java directly, bypassing
# the wrapper above, so expose the same runtime libs in the dev shell.
devShells.default = pkgs.mkShell {
packages = with pkgs; [cargo rustc rustfmt clippy jdk pkg-config];
buildInputs = [pkgs.libxcb];
shellHook = ''
export LD_LIBRARY_PATH="${runtimeLibs}:$LD_LIBRARY_PATH"
'';
};
}); });
} }
+259 -85
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
use std::fs; use std::fs;
use std::io; use std::io::{self, Read};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -72,8 +72,10 @@ pub enum MigrationError {
old: String, old: String,
new: String, new: String,
}, },
#[error("Cannot merge migration data because both paths contain {path}")] #[error(
MergeConflict { path: String }, "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}")] #[error("Migration backup would be created inside the data being backed up: {0}")]
BackupOverlap(String), BackupOverlap(String),
#[error( #[error(
@@ -85,6 +87,8 @@ pub enum MigrationError {
pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool { pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool {
let metadata = MetadataPaths::new(meta_dir); let metadata = MetadataPaths::new(meta_dir);
metadata.cache_rebuild_pending().exists() metadata.cache_rebuild_pending().exists()
|| metadata.migration_journal().exists()
|| metadata.state().join("migration-v2.json").exists()
|| has_legacy_instances(instances_dir) || has_legacy_instances(instances_dir)
|| has_legacy_shared_data(meta_dir) || has_legacy_shared_data(meta_dir)
} }
@@ -137,6 +141,7 @@ pub fn run(
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() && !metadata.migration_journal().exists()
&& !metadata.state().join("migration-v2.json").exists()
&& !has_legacy_instances(instances_dir) && !has_legacy_instances(instances_dir)
&& !has_legacy_shared_data(meta_dir) && !has_legacy_shared_data(meta_dir)
{ {
@@ -156,7 +161,7 @@ pub fn run(
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;
if !is_complete(&journal, "backup") { if !is_complete(&journal, "backup") || !journal.backup_dir.exists() {
let backup_dir = journal.backup_dir.clone(); let backup_dir = journal.backup_dir.clone();
backup_user_data( backup_user_data(
instances_dir, instances_dir,
@@ -177,7 +182,7 @@ pub fn run(
}, },
)?; )?;
complete(&mut journal, &metadata, "backup")?; complete(&mut journal, &metadata, "backup")?;
current += 1; current = journal.completed.len() as u64;
} }
if !is_complete(&journal, "config") { if !is_complete(&journal, "config") {
@@ -192,7 +197,7 @@ pub fn run(
); );
crate::config::upgrade_config_file(config_file)?; crate::config::upgrade_config_file(config_file)?;
complete(&mut journal, &metadata, "config")?; complete(&mut journal, &metadata, "config")?;
current += 1; current = journal.completed.len() as u64;
} }
validate_migration_conflicts(&instances, meta_dir)?; validate_migration_conflicts(&instances, meta_dir)?;
@@ -204,7 +209,7 @@ pub fn run(
.unwrap_or("instance") .unwrap_or("instance")
.to_owned(); .to_owned();
let key = format!("instance:{name}"); let key = format!("instance:{name}");
if is_complete(&journal, &key) { if is_complete(&journal, &key) && !has_legacy_instance_data(instance) {
continue; continue;
} }
report( report(
@@ -213,40 +218,23 @@ pub fn run(
); );
migrate_instance(instance, &name)?; migrate_instance(instance, &name)?;
complete(&mut journal, &metadata, &key)?; complete(&mut journal, &metadata, &key)?;
current += 1; current = journal.completed.len() as u64;
} }
let moves = [ for (key, source, destination) in shared_moves(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(),
),
];
for (key, source, destination) in moves {
let journal_key = format!("shared:{key}"); let journal_key = format!("shared:{key}");
if is_complete(&journal, &journal_key) { if is_complete(&journal, &journal_key) && !source.exists() {
continue; continue;
} }
report( report(
MigrationProgress::new("Migrating shared data", key, current, total) MigrationProgress::new("Migrating shared data", key, current, total)
.with_backup(&journal.backup_dir), .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)?; complete(&mut journal, &metadata, &journal_key)?;
current += 1; current = journal.completed.len() as u64;
} }
let legacy_config_sync = meta_dir.join("config-sync"); let legacy_config_sync = meta_dir.join("config-sync");
if legacy_config_sync.exists() && fs::read_dir(&legacy_config_sync)?.next().is_none() { 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), .with_backup(&journal.backup_dir),
); );
initialize_new_layout(meta_dir)?; initialize_new_layout(meta_dir)?;
if metadata.migration_journal().exists() { for journal_path in [
fs::remove_file(metadata.migration_journal())?; metadata.migration_journal(),
metadata.state().join("migration-v2.json"),
] {
if journal_path.exists() {
fs::remove_file(journal_path)?;
}
} }
report( report(
MigrationProgress::new("Migration complete", "Layout updated", total, total) 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)?; rename_visible_directory(instance, LEGACY_STATE, paths.state(), name)?;
let old_config = paths.state().join("config-sync").join("local-config"); 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"); let old_config_root = paths.state().join("config-sync");
if old_config_root.exists() && fs::read_dir(&old_config_root)?.next().is_none() { if old_config_root.exists() && fs::read_dir(&old_config_root)?.next().is_none() {
fs::remove_dir(old_config_root)?; fs::remove_dir(old_config_root)?;
@@ -309,17 +302,18 @@ fn rename_visible_directory(
instance_name: &str, instance_name: &str,
) -> Result<(), MigrationError> { ) -> Result<(), MigrationError> {
let source = instance.join(legacy_name); 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 { return Err(MigrationError::PathConflict {
instance: instance_name.to_owned(), instance: instance_name.to_owned(),
old: source.display().to_string(), old: source.display().to_string(),
new: destination.display().to_string(), new: destination.display().to_string(),
}); });
} }
if source.exists() { move_or_merge(&source, &destination, None)
fs::rename(source, destination)?;
}
Ok(())
} }
fn backup_user_data( fn backup_user_data(
@@ -399,51 +393,78 @@ fn validate_migration_conflicts(
(instance.join(LEGACY_MINECRAFT), paths.minecraft()), (instance.join(LEGACY_MINECRAFT), paths.minecraft()),
(instance.join(LEGACY_STATE), paths.state()), (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 { return Err(MigrationError::PathConflict {
instance: name.to_owned(), instance: name.to_owned(),
old: legacy.display().to_string(), old: legacy.display().to_string(),
new: destination.display().to_string(), new: destination.display().to_string(),
}); });
} }
validate_merge(&legacy, &destination, false)?;
} }
validate_merge( for state in [instance.join(LEGACY_STATE), paths.state()] {
&paths.state().join("config-sync").join("local-config"), for destination in [
&paths.local_config(), instance.join(LEGACY_STATE).join("content/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)?; validate_merge(&state.join("config-sync/local-config"), &destination, false)?;
}
}
}
for (key, source, destination) in shared_moves(meta_dir) {
validate_merge(&source, &destination, key != "profiles")?;
} }
Ok(()) Ok(())
} }
fn validate_merge(source: &Path, destination: &Path) -> Result<(), MigrationError> { fn shared_moves(meta_dir: &Path) -> [(&'static str, PathBuf, PathBuf); 5] {
if !source.exists() || !destination.exists() { 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(()); return Ok(());
} }
validate_merge_roots(source, destination)?;
for entry in fs::read_dir(source)? { for entry in fs::read_dir(source)? {
let entry = entry?; let entry = entry?;
let target = destination.join(entry.file_name()); let target = destination.join(entry.file_name());
if !target.exists() { if !path_exists(&target)? {
continue; continue;
} }
if entry.file_type()?.is_dir() && target.is_dir() { if entry.file_type()?.is_dir() && fs::symlink_metadata(&target)?.is_dir() {
validate_merge(&entry.path(), &target)?; validate_merge(&entry.path(), &target, archive_cache_conflicts)?;
} else { } else if !files_identical(&entry.path(), &target)?
return Err(MigrationError::MergeConflict { && !(archive_cache_conflicts && distinct_regular_files(&entry.path(), &target)?)
path: target.display().to_string(), {
}); return Err(merge_conflict(&entry.path(), &target));
} }
} }
Ok(()) Ok(())
@@ -508,42 +529,180 @@ fn file_size(path: &Path) -> io::Result<u64> {
} }
} }
fn move_or_merge(source: &Path, destination: &Path) -> Result<(), MigrationError> { pub(crate) fn move_or_merge(
if !source.exists() { source: &Path,
destination: &Path,
cache_conflicts: Option<&Path>,
) -> Result<(), MigrationError> {
if !path_exists(source)? {
return Ok(()); return Ok(());
} }
if !destination.exists() { if !path_exists(destination)? {
if let Some(parent) = destination.parent() { if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
} }
fs::rename(source, destination)?; match fs::rename(source, destination) {
return Ok(()); 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(()) 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)?; fs::create_dir_all(destination)?;
validate_merge_roots(source, destination)?;
for entry in fs::read_dir(source)? { for entry in fs::read_dir(source)? {
let entry = entry?; let entry = entry?;
let target = destination.join(entry.file_name()); let target = destination.join(entry.file_name());
let file_type = entry.file_type()?; let file_type = entry.file_type()?;
if !target.exists() { let target_exists = path_exists(&target)?;
fs::rename(entry.path(), target)?; if file_type.is_dir() && (!target_exists || fs::symlink_metadata(&target)?.is_dir()) {
} else if file_type.is_dir() && target.is_dir() { move_or_merge(
merge_dir_without_overwrite(&entry.path(), &target)?; &entry.path(),
fs::remove_dir(entry.path())?; &target,
} else { cache_conflicts
return Err(MigrationError::MergeConflict { .map(|path| path.join(entry.file_name()))
path: target.display().to_string(), .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(merge_conflict(&entry.path(), &target));
}
}
if new_directory {
fs::set_permissions(destination, fs::metadata(source)?.permissions())?;
} }
Ok(()) 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( fn copy_dir_recursive_with_progress(
source: &Path, source: &Path,
destination: &Path, destination: &Path,
@@ -611,6 +770,9 @@ fn complete(
metadata: &MetadataPaths, metadata: &MetadataPaths,
key: &str, key: &str,
) -> Result<(), MigrationError> { ) -> Result<(), MigrationError> {
if is_complete(journal, key) {
return Ok(());
}
journal.completed.push(key.to_owned()); journal.completed.push(key.to_owned());
write_json_atomic(&metadata.migration_journal(), journal) 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 { fn has_legacy_instances(instances_dir: &Path) -> bool {
instance_directories(instances_dir).is_ok_and(|instances| { instance_directories(instances_dir).is_ok_and(|instances| {
instances.iter().any(|instance| { instances
instance.join(LEGACY_MINECRAFT).exists() || instance.join(LEGACY_STATE).exists() .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> { fn marker_version(path: &Path) -> Option<u32> {
serde_json::from_slice::<LayoutMarker>(&fs::read(path).ok()?) serde_json::from_slice::<LayoutMarker>(&fs::read(path).ok()?)
.ok() .ok()
+22 -12
View File
@@ -41,11 +41,16 @@ fn rename_top_level(old: &Path, new: &Path) {
return; return;
} }
if new.exists() { if new.exists() {
eprintln!( match crate::layout_migration::validate_merge(old, new, false)
"rmcl migration: both {} and {} exist; leaving as-is, please merge manually", .and_then(|_| crate::layout_migration::move_or_merge(old, new, None))
{
Ok(()) => eprintln!(
"rmcl migration: merged {} -> {}",
old.display(), old.display(),
new.display() new.display()
); ),
Err(error) => eprintln!("rmcl migration stopped safely: {error}"),
}
return; return;
} }
match fs::rename(old, new) { match fs::rename(old, new) {
@@ -55,7 +60,7 @@ fn rename_top_level(old: &Path, new: &Path) {
new.display() new.display()
), ),
Err(e) if e.kind() == io::ErrorKind::CrossesDevices => { 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!( eprintln!(
"rmcl migration: failed cross-device copy {} -> {}: {}", "rmcl migration: failed cross-device copy {} -> {}: {}",
old.display(), old.display(),
@@ -64,14 +69,6 @@ fn rename_top_level(old: &Path, new: &Path) {
); );
return; return;
} }
if let Err(e3) = fs::remove_dir_all(old) {
eprintln!(
"rmcl migration: copied but failed to remove {}: {}",
old.display(),
e3
);
return;
}
eprintln!( eprintln!(
"rmcl migration: cross-device moved {} -> {}", "rmcl migration: cross-device moved {} -> {}",
old.display(), 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<()> { fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> {
fs::create_dir_all(dst)?; fs::create_dir_all(dst)?;
for entry in fs::read_dir(src)? { 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::copy(entry.path(), &dst_path)?;
} }
} }
fs::set_permissions(dst, fs::metadata(src)?.permissions())?;
Ok(()) Ok(())
} }
+424 -5
View File
@@ -50,7 +50,98 @@ fn migrated_layout_detects_newly_copied_shared_data() {
} }
#[test] #[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 temp = tempfile::tempdir().unwrap();
let instances = temp.path().join("instances"); let instances = temp.path().join("instances");
let meta = temp.path().join("meta"); 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(); initialize_new_layout(&meta).unwrap();
assert!(run(&instances, &meta, &config, |_| {}).is_err()); assert!(run(&instances, &meta, &config, |_| {}).is_err());
assert!(!state.exists()); assert!(state.exists());
assert!(MetadataPaths::new(&meta).migration_journal().exists()); assert!(MetadataPaths::new(&meta).migration_journal().exists());
assert!(run(&instances, &meta, &config, |_| {}).is_err()); assert!(run(&instances, &meta, &config, |_| {}).is_err());
assert_eq!( assert_eq!(
fs::read(instances.join("Copied/rmcl/content/config/options.txt")).unwrap(), fs::read(state.join("content/config/options.txt")).unwrap(),
b"current" b"current"
); );
} }
@@ -278,8 +369,18 @@ fn conflicting_visible_and_hidden_directories_are_not_merged() {
let instance = temp.path().join("Example"); let instance = temp.path().join("Example");
fs::create_dir_all(instance.join(".minecraft")).unwrap(); fs::create_dir_all(instance.join(".minecraft")).unwrap();
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(); 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] #[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(source.join("nested/options.txt"), b"legacy").unwrap();
fs::write(destination.join("nested/options.txt"), b"current").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!(matches!(error, MigrationError::MergeConflict { .. }));
assert_eq!( assert_eq!(
@@ -304,3 +405,321 @@ fn merge_conflicts_do_not_overwrite_existing_profiles() {
b"legacy" 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] #[test]
fn rename_top_level_skips_when_both_exist() { fn rename_top_level_merges_nonconflicting_existing_directories() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("mcl"); let old = tmp.path().join("mcl");
let new = tmp.path().join("rmcl"); let new = tmp.path().join("rmcl");
@@ -44,12 +44,44 @@ fn rename_top_level_skips_when_both_exist() {
rename_top_level(&old, &new); 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!(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"); 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] #[test]
fn rename_top_level_noop_when_neither_exists() { fn rename_top_level_noop_when_neither_exists() {
let tmp = tempfile::tempdir().unwrap(); 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)] #[cfg(unix)]
#[test] #[test]
fn cross_device_copy_preserves_links_without_following_directory_cycles() { fn cross_device_copy_preserves_links_without_following_directory_cycles() {
+13
View File
@@ -763,6 +763,19 @@ impl App {
if text_input_active { if text_input_active {
return repeatable_text_key(key); return repeatable_text_key(key);
} }
if key.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key.code, KeyCode::Left | KeyCode::Right)
&& matches!(
self.focused,
FocusedArea::Instances
| FocusedArea::Content
| FocusedArea::Account
| FocusedArea::Settings
| FocusedArea::Overview
)
{
return true;
}
if vertical_navigation { if vertical_navigation {
return true; return true;
} }
+42
View File
@@ -522,6 +522,48 @@ impl App {
} }
} }
if key_event.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(
key_event.code,
KeyCode::Up | KeyCode::Down | KeyCode::Left | KeyCode::Right
)
&& match self.focused {
FocusedArea::Instances => self.instances_state.renaming.is_none(),
FocusedArea::Content => !self.active_discovery_state().is_some_and(|state| {
state.version_popup.is_some() || state.project_page_open()
}),
FocusedArea::Account => {
matches!(self.account_state.add_mode, widgets::account::AddMode::None)
}
FocusedArea::Settings => {
matches!(
self.settings_state.add_mode,
widgets::settings::AddMode::None
)
}
FocusedArea::Overview => true,
_ => false,
}
{
self.focused =
match (self.focused, key_event.code) {
(FocusedArea::Instances, KeyCode::Right) => FocusedArea::Content,
(FocusedArea::Content, KeyCode::Left)
| (FocusedArea::Account, KeyCode::Left) => FocusedArea::Instances,
(FocusedArea::Content, KeyCode::Down)
| (FocusedArea::Settings, KeyCode::Left) => FocusedArea::Account,
(FocusedArea::Account, KeyCode::Right)
| (FocusedArea::Overview, KeyCode::Left) => FocusedArea::Settings,
(FocusedArea::Settings, KeyCode::Right) => FocusedArea::Overview,
(
FocusedArea::Account | FocusedArea::Settings | FocusedArea::Overview,
KeyCode::Up,
) => FocusedArea::Content,
(focused, _) => focused,
};
return Ok(());
}
if self.focused == FocusedArea::Content if self.focused == FocusedArea::Content
&& self.content_mode == widgets::content::ContentMode::Installed && self.content_mode == widgets::content::ContentMode::Installed
&& let Some(state) = self.active_discovery_state_mut() && let Some(state) = self.active_discovery_state_mut()
+56 -35
View File
@@ -278,47 +278,13 @@ async fn migration_retry_requested(
app: &mut app::App, app: &mut app::App,
error: &str, error: &str,
) -> color_eyre::Result<bool> { ) -> color_eyre::Result<bool> {
use crate::config::theme::{BORDER_STYLE, THEME};
use crossterm::event::{Event, KeyCode}; 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; use std::time::Duration;
loop { loop {
terminal.draw(|frame| { terminal.draw(|frame| {
app.render_migration_frame(frame); app.render_migration_frame(frame);
let theme = THEME.as_ref(); render_migration_error_popup(frame, error);
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],
);
})?; })?;
if crossterm::event::poll(Duration::from_millis(100))? if crossterm::event::poll(Duration::from_millis(100))?
&& let Event::Key(key) = crossterm::event::read()? && 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( async fn migration_completion_confirmation(
terminal: &mut Tui, terminal: &mut Tui,
app: &mut app::App, 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)), 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}");
}
}
+86 -1
View File
@@ -1,7 +1,9 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
use crossterm::event::{KeyCode, MouseButton, MouseEvent, MouseEventKind}; use crossterm::event::{
KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use super::harness::UiHarness; use super::harness::UiHarness;
@@ -34,6 +36,85 @@ fn remote_project_links_use_http_urls_and_encode_shell_metacharacters() {
} }
} }
#[test]
fn ctrl_arrows_navigate_adjacent_panels_without_changing_content_tabs() {
let mut ui = UiHarness::new();
let panels = [
FocusedArea::Instances,
FocusedArea::Content,
FocusedArea::Account,
FocusedArea::Settings,
FocusedArea::Overview,
];
let directions = [KeyCode::Up, KeyCode::Down, KeyCode::Left, KeyCode::Right];
let destinations = [
[panels[0], panels[0], panels[0], panels[1]],
[panels[1], panels[2], panels[0], panels[1]],
[panels[1], panels[2], panels[0], panels[3]],
[panels[1], panels[3], panels[2], panels[4]],
[panels[1], panels[4], panels[3], panels[4]],
];
for (panel, expected) in panels.into_iter().zip(destinations) {
for (direction, destination) in directions.into_iter().zip(expected) {
for kind in [KeyEventKind::Press, KeyEventKind::Repeat] {
ui.app.focused = panel;
assert!(ui.key_event(KeyEvent::new_with_kind(
direction,
KeyModifiers::CONTROL,
kind,
)));
assert_eq!(ui.app.focused, destination, "{panel:?} {direction:?}");
assert_eq!(ui.app.content_tab, ContentTab::Mods);
}
}
}
ui.app.focused = FocusedArea::Content;
for mode in [ContentMode::Installed, ContentMode::Discover] {
ui.app.content_mode = mode;
ui.key(KeyCode::Right);
assert_eq!(ui.app.content_tab, ContentTab::ResourcePacks);
ui.key(KeyCode::Left);
assert_eq!(ui.app.content_tab, ContentTab::Mods);
assert_eq!(ui.app.focused, FocusedArea::Content);
}
}
#[test]
fn ctrl_arrows_do_not_escape_modal_input() {
let mut ui = UiHarness::new();
for panel in [FocusedArea::ConfirmDelete, FocusedArea::OverviewExpanded] {
ui.app.focused = panel;
ui.key_with(KeyCode::Down, KeyModifiers::CONTROL);
assert_eq!(ui.app.focused, panel);
}
ui.app.focused = FocusedArea::Instances;
ui.key(KeyCode::Char('a'));
ui.key_with(KeyCode::Down, KeyModifiers::CONTROL);
assert_eq!(ui.app.focused, FocusedArea::Popup);
ui.key(KeyCode::Esc);
ui.key(KeyCode::Char('m'));
ui.key_with(KeyCode::Down, KeyModifiers::CONTROL);
assert_eq!(ui.app.focused, FocusedArea::ImportPopup);
ui.key(KeyCode::Esc);
ui.app.focused = FocusedArea::Account;
ui.key(KeyCode::Char('a'));
ui.key_with(KeyCode::Right, KeyModifiers::CONTROL);
assert_eq!(ui.app.focused, FocusedArea::Account);
ui.app.focused = FocusedArea::Settings;
ui.key(KeyCode::Char('a'));
ui.key_with(KeyCode::Right, KeyModifiers::CONTROL);
assert_eq!(ui.app.focused, FocusedArea::Settings);
ui.app.focused = FocusedArea::Instances;
ui.app.instances_state.renaming = Some("Renaming".to_owned());
ui.key_with(KeyCode::Right, KeyModifiers::CONTROL);
assert_eq!(ui.app.focused, FocusedArea::Instances);
}
#[test] #[test]
fn global_navigation_returns_from_log_overlay() { fn global_navigation_returns_from_log_overlay() {
let mut ui = UiHarness::new(); let mut ui = UiHarness::new();
@@ -170,6 +251,10 @@ fn installed_popup_navigation_preserves_local_filters() {
assert!(ui.app.mods_discovery_state.local_mode); assert!(ui.app.mods_discovery_state.local_mode);
let filters_before = ui.app.mods_discovery_state.filters.clone(); let filters_before = ui.app.mods_discovery_state.filters.clone();
ui.key_with(KeyCode::Left, KeyModifiers::CONTROL);
assert_eq!(ui.app.focused, FocusedArea::Content);
assert!(ui.app.mods_discovery_state.version_popup.is_some());
// Navigating the popup versions must not flip the state into discovery // Navigating the popup versions must not flip the state into discovery
// mode (which used to swap the filters and refresh the background list). // mode (which used to swap the filters and refresh the background list).
ui.key(KeyCode::Char('j')); ui.key(KeyCode::Char('j'));