fix: preserve authoritative settings through profile switches and refreshes

This commit is contained in:
objz committed 2026-10-01 23:23:26 +02:00
1 parent dc351df546
commit 00ba2faffe
23 files changed
+3768 -527

No files matched your search

+6 -14
View File
@@ -22,7 +22,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
Some(("rename", sub_matches)) => rename_instance(sub_matches), Some(("rename", sub_matches)) => rename_instance(sub_matches),
Some(("launch", sub_matches)) => launch_instance(sub_matches).await, Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
Some(("config", sub_matches)) => config_instance(sub_matches), Some(("config", sub_matches)) => config_instance(sub_matches),
Some(("profile", sub_matches)) => profile_instance(sub_matches), Some(("profile", sub_matches)) => profile_instance(sub_matches, &manager()),
Some(("desktop", sub_matches)) => desktop_instance(sub_matches), Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
_ => Ok(()), _ => Ok(()),
} }
@@ -206,7 +206,7 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
if config.jvm_args.is_empty() { if config.jvm_args.is_empty() {
"-".to_string() "-".to_string()
} else { } else {
config.jvm_args.join(" ") crate::config::settings::format_tag_values(&config.jvm_args)
}, },
], ],
vec![ vec![
@@ -226,19 +226,10 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
Ok(()) Ok(())
} }
fn profile_instance(matches: &ArgMatches) -> CliResult { fn profile_instance(matches: &ArgMatches, manager: &InstanceManager) -> CliResult {
let name = required_arg(matches, "name")?; let name = required_arg(matches, "name")?;
let manager = manager();
let mut config = manager.load_one(name)?; let mut config = manager.load_one(name)?;
let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?; let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?;
if config
.config_sync_profile
.as_ref()
.is_some_and(|profile| !profiles.iter().any(|candidate| candidate == profile))
{
config.config_sync_profile = None;
manager.save(&config)?;
}
let Some(profile) = matches.get_one::<String>("profile") else { let Some(profile) = matches.get_one::<String>("profile") else {
let rows = vec![ let rows = vec![
@@ -264,7 +255,7 @@ fn profile_instance(matches: &ArgMatches) -> CliResult {
} else { } else {
Some(profile.as_str()) Some(profile.as_str())
}; };
crate::instance::config_sync::switch_profile_and_save(&manager, &mut config, target)?; crate::instance::config_sync::switch_profile_and_save(manager, &mut config, target)?;
println!( println!(
"Updated '{}' config profile to {}.", "Updated '{}' config profile to {}.",
@@ -308,7 +299,8 @@ fn apply_config_update(
} }
} }
"jvm-args" => { "jvm-args" => {
config.jvm_args = value.split_whitespace().map(String::from).collect(); config.jvm_args =
crate::config::settings::parse_tag_values(value).map_err(io::Error::other)?;
} }
"resolution" => { "resolution" => {
config.resolution = if value.is_empty() { config.resolution = if value.is_empty() {
+125
View File
@@ -29,3 +29,128 @@ fn invalid_memory_update_keeps_existing_setting() {
assert!(super::apply_config_update(&mut config, "memory-max", "garbage").is_err()); assert!(super::apply_config_update(&mut config, "memory-max", "garbage").is_err());
assert_eq!(config.memory_max.as_deref(), Some("8G")); assert_eq!(config.memory_max.as_deref(), Some("8G"));
} }
#[test]
fn jvm_argument_updates_preserve_quoted_paths_and_repeated_options() {
let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({
"name": "test", "game_version": "1.21.1", "loader": "vanilla",
"loader_version": null, "created": "2026-01-01T00:00:00Z"
}))
.unwrap();
super::apply_config_update(&mut config, "jvm-args", r#""-Dpath=C:\Program Files\Java" --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED"#).unwrap();
assert_eq!(
config.jvm_args,
[
r"-Dpath=C:\Program Files\Java",
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
"--add-opens",
"java.base/java.util=ALL-UNNAMED"
]
);
let previous = config.jvm_args.clone();
assert!(super::apply_config_update(&mut config, "jvm-args", "\"unterminated").is_err());
assert_eq!(config.jvm_args, previous);
super::apply_config_update(&mut config, "jvm-args", "").unwrap();
assert!(config.jvm_args.is_empty());
}
#[test]
fn config_sync_profile_display_is_read_only_and_deleted_profiles_restore_local_defaults() {
for target in ["default", "other"] {
let tmp = tempfile::tempdir().unwrap();
let manager = crate::instance::InstanceManager::new(
tmp.path().join("instances"),
tmp.path().join("meta"),
);
let instance = manager.instances_dir.join("inst");
let minecraft = crate::storage::InstancePaths::new(&instance).minecraft();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), b"local-default").unwrap();
std::fs::write(minecraft.join("config/value"), b"local-default").unwrap();
let mut config = serde_json::from_value(serde_json::json!({
"name": "inst", "game_version": "1.21.1", "loader": "vanilla", "loader_version": null,
"created": "2026-01-01T00:00:00Z"
}))
.unwrap();
manager.save(&config).unwrap();
crate::instance::config_sync::switch_profile_and_save(&manager, &mut config, Some("main"))
.unwrap();
std::fs::write(minecraft.join("options.txt"), b"profile-options").unwrap();
crate::instance::config_sync::delete_profile(&manager.meta_dir, "main").unwrap();
crate::instance::config_sync::create_profile(&manager.meta_dir, "other").unwrap();
std::fs::write(
crate::storage::MetadataPaths::new(&manager.meta_dir)
.profiles()
.join("other/options.txt"),
b"other-options",
)
.unwrap();
let original_config = std::fs::read(instance.join("instance.json")).unwrap();
let matches = crate::cli::build_command()
.try_get_matches_from(["rmcl", "instance", "profile", "inst"])
.unwrap();
let profile_matches = matches
.subcommand_matches("instance")
.unwrap()
.subcommand_matches("profile")
.unwrap();
super::profile_instance(profile_matches, &manager).unwrap();
assert_eq!(
std::fs::read(instance.join("instance.json")).unwrap(),
original_config
);
assert_eq!(
std::fs::read(minecraft.join("options.txt")).unwrap(),
b"profile-options"
);
let matches = crate::cli::build_command()
.try_get_matches_from(["rmcl", "instance", "profile", "inst", target])
.unwrap();
let profile_matches = matches
.subcommand_matches("instance")
.unwrap()
.subcommand_matches("profile")
.unwrap();
super::profile_instance(profile_matches, &manager).unwrap();
if target == "other" {
assert_eq!(
manager
.load_one("inst")
.unwrap()
.config_sync_profile
.as_deref(),
Some("other")
);
assert_eq!(
std::fs::read(minecraft.join("options.txt")).unwrap(),
b"other-options"
);
let matches = crate::cli::build_command()
.try_get_matches_from(["rmcl", "instance", "profile", "inst", "default"])
.unwrap();
let profile_matches = matches
.subcommand_matches("instance")
.unwrap()
.subcommand_matches("profile")
.unwrap();
super::profile_instance(profile_matches, &manager).unwrap();
}
assert_eq!(manager.load_one("inst").unwrap().config_sync_profile, None);
assert_eq!(
std::fs::read(minecraft.join("options.txt")).unwrap(),
b"local-default"
);
assert_eq!(
std::fs::read(minecraft.join("config/value")).unwrap(),
b"local-default"
);
assert!(
!crate::storage::MetadataPaths::new(&manager.meta_dir)
.profiles()
.join("main")
.exists()
);
}
}
+7
View File
@@ -251,6 +251,13 @@ pub static SETTINGS: LazyLock<ConfigStore> = LazyLock::new(|| {
fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> { fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> {
write_merged_toml_document(path, config, |document| { write_merged_toml_document(path, config, |document| {
if let Some(environment) = document
.get_mut("defaults")
.and_then(|defaults| defaults.get_mut("environment"))
.and_then(toml_edit::Item::as_table_mut)
{
environment.retain(|key, _| config.defaults.environment.contains_key(key));
}
if config.paths.java_path.is_none() if config.paths.java_path.is_none()
&& let Some(paths) = document && let Some(paths) = document
.get_mut("paths") .get_mut("paths")
+69 -3
View File
@@ -248,7 +248,7 @@ impl Default for Paths {
} }
pub fn resolve_path(raw: &str) -> PathBuf { pub fn resolve_path(raw: &str) -> PathBuf {
if let Some(stripped) = raw.strip_prefix("~/") { if let Some(stripped) = raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\")) {
if let Some(home) = dirs::home_dir() { if let Some(home) = dirs::home_dir() {
return home.join(stripped); return home.join(stripped);
} }
@@ -315,9 +315,75 @@ impl Default for Defaults {
} }
} }
pub(crate) fn parse_tag_values(input: &str) -> Result<Vec<String>, String> {
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quote {
None,
Single,
Double,
}
let mut values = Vec::new();
let mut current = String::new();
let mut quote = Quote::None;
let mut started = false;
let mut characters = input.chars().peekable();
while let Some(character) = characters.next() {
match (quote, character) {
(Quote::None, character) if character.is_whitespace() => {
if started {
values.push(std::mem::take(&mut current));
started = false;
}
}
(Quote::None, '\'') => {
quote = Quote::Single;
started = true;
}
(Quote::None, '"') => {
quote = Quote::Double;
started = true;
}
(Quote::Single, '\'') => quote = Quote::None,
(Quote::Double, '"') => quote = Quote::None,
(Quote::Double, '\\') if matches!(characters.peek(), Some('"' | '\\')) => {
current.push(characters.next().unwrap_or_default());
started = true;
}
(_, character) => {
current.push(character);
started = true;
}
}
}
if quote != Quote::None {
return Err("Quoted value is missing its closing quote.".to_owned());
}
if started {
values.push(current);
}
Ok(values)
}
pub(crate) fn format_tag_values(values: &[String]) -> String {
values
.iter()
.map(|value| {
if !value.is_empty()
&& !value
.chars()
.any(|character| character.is_whitespace() || matches!(character, '\'' | '"'))
{
value.clone()
} else {
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
}
})
.collect::<Vec<_>>()
.join(" ")
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui { pub struct Ui {
#[serde(default)] #[serde(default)]
pub image_protocol: ImageProtocol, pub image_protocol: ImageProtocol,
+22
View File
@@ -3,6 +3,28 @@
use super::*; use super::*;
#[test]
fn saving_settings_removes_deleted_environment_keys_and_keeps_retained_comments() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("config.toml");
std::fs::write(
&path,
"[defaults.environment]\nKEEP = 'old' # retained\nREMOVE = 'gone'\n[unknown]\nvalue = 1\n",
)
.unwrap();
let mut config = Config::default();
config
.defaults
.environment
.insert("KEEP".to_owned(), "new".to_owned());
write_config_document(&path, &config).unwrap();
let source = std::fs::read_to_string(&path).unwrap();
assert!(!source.contains("REMOVE"));
assert!(source.contains("# retained"));
assert!(source.contains("[unknown]"));
assert_eq!(load_config(&path).unwrap().defaults.environment.len(), 1);
}
#[test] #[test]
fn load_config_from_valid_toml() { fn load_config_from_valid_toml() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
+8 -5
View File
@@ -80,15 +80,18 @@ fn resolve_path_absolute() {
#[test] #[test]
fn resolve_path_tilde_prefix() { fn resolve_path_tilde_prefix() {
let resolved = resolve_path("~/games/rmcl"); let home = dirs::home_dir().expect("test environment has a home directory");
assert!(!resolved.to_string_lossy().starts_with('~')); for path in ["~/games/rmcl", r"~\games/rmcl"] {
assert!(resolved.to_string_lossy().ends_with("games/rmcl")); assert_eq!(resolve_path(path), home.join("games/rmcl"));
}
} }
#[test] #[test]
fn resolve_path_bare_tilde() { fn resolve_path_bare_tilde() {
let resolved = resolve_path("~"); assert_eq!(
assert!(!resolved.to_string_lossy().starts_with('~')); resolve_path("~"),
dirs::home_dir().expect("test environment has a home directory")
);
} }
#[test] #[test]
+32 -5
View File
@@ -3,8 +3,6 @@
use super::*; use super::*;
// cover every BorderStyle variant. a mutation that swaps two arms of the
// match (e.g. Rounded -> Plain) would slip past testing just one variant.
#[rstest::rstest] #[rstest::rstest]
#[case::plain(BorderStyle::Plain, BorderType::Plain)] #[case::plain(BorderStyle::Plain, BorderType::Plain)]
#[case::rounded(BorderStyle::Rounded, BorderType::Rounded)] #[case::rounded(BorderStyle::Rounded, BorderType::Rounded)]
@@ -51,13 +49,43 @@ fn resolve_with_overrides_keeps_base() {
}), }),
..ThemeConfig::default() ..ThemeConfig::default()
}; };
let theme = resolve_app_theme(&config); let theme = resolve_app_theme(&config).unwrap();
assert_eq!(theme.accent(), Color::Red); assert_eq!(
theme.accent(),
if ratatui_themekit::no_color_active() {
resolve_theme("dracula").accent()
} else {
Color::Red
}
);
let base = resolve_theme("dracula"); let base = resolve_theme("dracula");
assert_eq!(theme.text(), base.text()); assert_eq!(theme.text(), base.text());
assert_eq!(theme.error(), base.error()); assert_eq!(theme.error(), base.error());
} }
#[test]
fn missing_and_invalid_custom_themes_are_errors() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("theme.toml");
let config = ThemeConfig {
theme: path.to_string_lossy().into_owned(),
..Default::default()
};
assert!(resolve_app_theme(&config).is_err());
std::fs::write(&path, "bad theme").unwrap();
assert!(resolve_app_theme(&config).is_err());
std::fs::write(&path, include_str!("../../../assets/example-theme.toml")).unwrap();
let theme = resolve_app_theme(&config).unwrap();
assert_eq!(
theme.id(),
if ratatui_themekit::no_color_active() {
"no-color"
} else {
"my-theme"
}
);
}
#[test] #[test]
fn resolve_builtin_theme() { fn resolve_builtin_theme() {
let theme = resolve_theme("dracula"); let theme = resolve_theme("dracula");
@@ -83,7 +111,6 @@ fn custom_theme_file_parses() {
toml::from_str::<CustomTheme>("name = \"X\"\nid = \"x\"\naccent = \"#f97316\"\n").unwrap(); toml::from_str::<CustomTheme>("name = \"X\"\nid = \"x\"\naccent = \"#f97316\"\n").unwrap();
assert_eq!(minimal.accent, Color::Rgb(249, 115, 22)); assert_eq!(minimal.accent, Color::Rgb(249, 115, 22));
// the two failure modes users hit: nesting under [theme], or omitting name/id
assert!( assert!(
toml::from_str::<CustomTheme>("[theme]\nname = \"X\"\nid = \"x\"\naccent = \"Red\"\n") toml::from_str::<CustomTheme>("[theme]\nname = \"X\"\nid = \"x\"\naccent = \"Red\"\n")
.is_err() .is_err()
+38 -53
View File
@@ -97,14 +97,17 @@ fn ensure_theme_exists(path: &Path) {
let _ = std::fs::write(path, include_str!("../../assets/theme.toml")); let _ = std::fs::write(path, include_str!("../../assets/theme.toml"));
} }
fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> { fn resolve_app_theme(config: &ThemeConfig) -> std::io::Result<Box<dyn Theme>> {
let base = load_base_theme(&config.theme); let base = load_base_theme(&config.theme)?;
if ratatui_themekit::no_color_active() {
return Ok(resolve_theme("catppuccin"));
}
let Some(overrides) = &config.custom else { let Some(overrides) = &config.custom else {
return base; return Ok(base);
}; };
Box::new(CustomTheme { Ok(Box::new(CustomTheme {
name: format!("{} (customized)", base.name()), name: format!("{} (customized)", base.name()),
id: base.id().to_owned(), id: base.id().to_owned(),
accent: overrides.accent.unwrap_or_else(|| base.accent()), accent: overrides.accent.unwrap_or_else(|| base.accent()),
@@ -126,10 +129,10 @@ fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
border: overrides.border.unwrap_or_else(|| base.border()), border: overrides.border.unwrap_or_else(|| base.border()),
surface: overrides.surface.unwrap_or_else(|| base.surface()), surface: overrides.surface.unwrap_or_else(|| base.surface()),
background: overrides.background.unwrap_or_else(|| base.background()), background: overrides.background.unwrap_or_else(|| base.background()),
}) }))
} }
fn load_base_theme(name: &str) -> Box<dyn Theme> { fn load_base_theme(name: &str) -> std::io::Result<Box<dyn Theme>> {
let path = if Path::new(name).is_absolute() { let path = if Path::new(name).is_absolute() {
Some(std::path::PathBuf::from(name)) Some(std::path::PathBuf::from(name))
} else { } else {
@@ -147,20 +150,27 @@ fn load_base_theme(name: &str) -> Box<dyn Theme> {
} }
}; };
if let Some(path) = path if path.is_none() && ratatui_themekit::available_theme_ids().contains(&name) {
&& let Ok(content) = std::fs::read_to_string(&path) return Ok(resolve_theme(name));
{
match toml::from_str::<CustomTheme>(&content) {
Ok(custom) => return Box::new(custom),
Err(e) => tracing::warn!(
"Failed to parse theme file {}: {e}. Theme files need top-level \
name, id and accent keys (not nested under [theme]).",
path.display()
),
}
} }
let path = path.unwrap_or_else(|| {
resolve_theme(name) super::get_config_path()
.join("theme")
.join(format!("{name}.toml"))
});
let content = std::fs::read_to_string(&path).map_err(|error| {
std::io::Error::new(
error.kind(),
format!("failed to load theme {}: {error}", path.display()),
)
})?;
let custom = toml::from_str::<CustomTheme>(&content).map_err(|error| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("invalid theme {}: {error}", path.display()),
)
})?;
Ok(Box::new(custom))
} }
pub struct ThemeStore(RwLock<Arc<dyn Theme>>); pub struct ThemeStore(RwLock<Arc<dyn Theme>>);
@@ -215,7 +225,11 @@ pub static THEME: LazyLock<ThemeStore> = LazyLock::new(|| {
let config = THEME_CONFIG let config = THEME_CONFIG
.read() .read()
.unwrap_or_else(std::sync::PoisonError::into_inner); .unwrap_or_else(std::sync::PoisonError::into_inner);
ThemeStore(RwLock::new(Arc::from(resolve_app_theme(&config)))) let theme = resolve_app_theme(&config).unwrap_or_else(|error| {
tracing::error!("Could not load theme: {error}");
resolve_theme("catppuccin")
});
ThemeStore(RwLock::new(Arc::from(theme)))
}); });
pub static BORDER_STYLE: LazyLock<BorderStyleStore> = LazyLock::new(|| { pub static BORDER_STYLE: LazyLock<BorderStyleStore> = LazyLock::new(|| {
@@ -233,10 +247,10 @@ pub fn current_theme_config() -> ThemeConfig {
} }
pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> { pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> {
validate_theme_name(&theme)?;
let mut config = current_theme_config(); let mut config = current_theme_config();
config.theme = theme; config.theme = theme;
config.border_style = border_style.clone(); config.border_style = border_style.clone();
let resolved = resolve_app_theme(&config)?;
super::write_merged_toml_document( super::write_merged_toml_document(
&super::get_config_path().join("theme.toml"), &super::get_config_path().join("theme.toml"),
&config, &config,
@@ -246,7 +260,7 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<
} }
}, },
)?; )?;
THEME.set(resolve_app_theme(&config)); THEME.set(resolved);
BORDER_STYLE.set(border_style); BORDER_STYLE.set(border_style);
*THEME_CONFIG *THEME_CONFIG
.write() .write()
@@ -255,42 +269,13 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<
Ok(()) Ok(())
} }
fn validate_theme_name(name: &str) -> std::io::Result<()> {
if ratatui_themekit::available_theme_ids().contains(&name) {
return Ok(());
}
let path = if Path::new(name).is_absolute() {
std::path::PathBuf::from(name)
} else {
let directory = super::get_config_path().join("theme");
let direct = directory.join(name);
if direct.exists() {
direct
} else {
directory.join(format!("{name}.toml"))
}
};
let content = std::fs::read_to_string(&path).map_err(|error| {
std::io::Error::new(
error.kind(),
format!("failed to load theme {}: {error}", path.display()),
)
})?;
toml::from_str::<CustomTheme>(&content).map_err(|error| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("invalid theme {}: {error}", path.display()),
)
})?;
Ok(())
}
pub fn reload_theme() -> std::io::Result<()> { pub fn reload_theme() -> std::io::Result<()> {
let path = super::get_config_path().join("theme.toml"); let path = super::get_config_path().join("theme.toml");
let content = std::fs::read_to_string(path)?; let content = std::fs::read_to_string(path)?;
let config: ThemeConfig = toml::from_str(&content) let config: ThemeConfig = toml::from_str(&content)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?; .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
THEME.set(resolve_app_theme(&config)); let resolved = resolve_app_theme(&config)?;
THEME.set(resolved);
BORDER_STYLE.set(config.border_style.clone()); BORDER_STYLE.set(config.border_style.clone());
*THEME_CONFIG *THEME_CONFIG
.write() .write()
File diff suppressed because it is too large. Load diff
+177 -40
View File
@@ -76,32 +76,95 @@ fn legacy_path(name: &str) -> Option<PathBuf> {
} }
fn owns_legacy_shortcut(path: &Path, name: &str) -> bool { fn owns_legacy_shortcut(path: &Path, name: &str) -> bool {
let content = build_content(name, None); let Ok(existing) = read_shortcut(path) else {
let command = content.lines().find(|line| { return false;
line.starts_with("Exec=") };
|| line.starts_with("shell.Run ") let marker = shortcut_marker(name);
|| line.starts_with("rmcl instance launch ") if existing.lines().any(|line| line == marker) {
}); return true;
command.is_some_and(|command| { }
std::fs::read_to_string(path) #[cfg(target_os = "linux")]
.is_ok_and(|existing| existing.lines().any(|line| line == command)) let commands = {
}) let quoted = quote_desktop_exec_arg(name);
[
format!("Exec=rmcl instance launch {quoted}"),
format!(
"Exec=rmcl instance launch {}",
quoted.replace("\\\\", "\\").replace("%%", "%")
),
]
};
#[cfg(target_os = "windows")]
let commands = {
let command =
format!("rmcl instance launch {}", quote_windows_arg(name)).replace('"', "\"\"");
[format!("shell.Run \"{command}\", 0, False")]
};
#[cfg(target_os = "macos")]
let commands = [format!("rmcl instance launch {}", quote_shell_arg(name))];
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
let commands: [String; 0] = [];
existing
.lines()
.any(|line| commands.iter().any(|command| line == command))
} }
fn read_shortcut(path: &Path) -> std::io::Result<String> {
let bytes = std::fs::read(path)?;
if let Some(bytes) = bytes.strip_prefix(&[0xff, 0xfe]) {
if bytes.len() % 2 != 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Invalid UTF-16 shortcut",
));
}
let units = bytes
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
.collect::<Vec<_>>();
String::from_utf16(&units)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
} else {
String::from_utf8(bytes)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
}
}
#[cfg(any(windows, test))]
fn windows_script_bytes(content: &str) -> Vec<u8> {
// Windows Script Host reads Unicode scripts as BOM-prefixed UTF-16, not UTF-8.
[0xfeff]
.into_iter()
.chain(content.encode_utf16())
.flat_map(u16::to_le_bytes)
.collect()
}
fn shortcut_marker(name: &str) -> String {
let prefix = if cfg!(windows) { "'" } else { "#" };
format!("{prefix} rmcl-instance: {}", shortcut_name(name))
}
pub fn exists(name: &str) -> bool { pub fn exists(name: &str) -> bool {
desktop_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name)) desktop_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name))
|| legacy_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name)) || legacy_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name))
} }
pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> { pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
crate::instance::manager::validate_name(&config.name).map_err(std::io::Error::other)?;
let path = desktop_path(&config.name) let path = desktop_path(&config.name)
.ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?; .ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?;
if path.exists() && !owns_legacy_shortcut(&path, &config.name) { match std::fs::symlink_metadata(&path) {
return Err(std::io::Error::new( Ok(_) if !owns_legacy_shortcut(&path, &config.name) => {
std::io::ErrorKind::AlreadyExists, return Err(std::io::Error::new(
format!("Another shortcut already exists at '{}'", path.display()), std::io::ErrorKind::AlreadyExists,
)); format!("Another shortcut already exists at '{}'", path.display()),
));
}
Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error),
_ => {}
} }
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
@@ -109,9 +172,22 @@ pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
} }
let icon = ensure_icon(); let icon = ensure_icon();
let content = build_content(&config.name, icon.as_deref()); let executable = std::env::current_exe()?;
if std::fs::read_to_string(&path).ok().as_deref() != Some(content.as_str()) { let executable = executable.to_str().ok_or_else(|| {
crate::storage::write_atomic(&path, content.as_bytes())?; std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Launcher executable path is not UTF-8",
)
})?;
let content = build_content(&config.name, icon.as_deref(), executable);
if read_shortcut(&path).ok().as_deref() != Some(content.as_str()) {
#[cfg(windows)]
let encoded = windows_script_bytes(&content);
#[cfg(windows)]
let bytes = encoded.as_slice();
#[cfg(not(windows))]
let bytes = content.as_bytes();
crate::storage::write_atomic(&path, bytes)?;
} }
#[cfg(unix)] #[cfg(unix)]
@@ -164,6 +240,19 @@ pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()
return Ok(()); return Ok(());
} }
let same_path = desktop_path(old_name) == desktop_path(&new_config.name); let same_path = desktop_path(old_name) == desktop_path(&new_config.name);
if !same_path && let Some(new_path) = desktop_path(&new_config.name) {
for old_path in [desktop_path(old_name), legacy_path(old_name)]
.into_iter()
.flatten()
{
if rename_shortcut_alias(&old_path, &new_path, old_name, || {
create(new_config).map(|_| ())
})? {
remove(old_name)?;
return Ok(());
}
}
}
create(new_config)?; create(new_config)?;
if !same_path { if !same_path {
remove(old_name)?; remove(old_name)?;
@@ -171,41 +260,77 @@ pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()
Ok(()) Ok(())
} }
fn build_content(name: &str, icon: Option<&Path>) -> String { fn rename_shortcut_alias(
old_path: &Path,
new_path: &Path,
old_name: &str,
create: impl FnOnce() -> std::io::Result<()>,
) -> std::io::Result<bool> {
if old_path == new_path
|| !owns_legacy_shortcut(old_path, old_name)
|| !crate::instance::manager::paths_alias(old_path, new_path)?
{
return Ok(false);
}
let temporary = tempfile::Builder::new()
.prefix(".rmcl-shortcut-")
.tempdir_in(
old_path
.parent()
.ok_or_else(|| std::io::Error::other("Shortcut has no parent"))?,
)?;
let original = temporary.path().join("original");
std::fs::rename(old_path, &original)?;
if let Err(error) = create() {
if let Err(rollback) = std::fs::rename(&original, old_path) {
let retained = temporary.keep();
return Err(std::io::Error::other(format!(
"Could not update shortcut: {error}; rollback failed: {rollback}; original retained at '{}'",
retained.join("original").display(),
)));
}
return Err(error);
}
Ok(true)
}
fn build_content(name: &str, icon: Option<&Path>, executable: &str) -> String {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
{ {
build_linux_desktop(name, icon) build_linux_desktop(name, icon, executable)
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
let _ = icon; let _ = icon;
build_windows_shortcut(name) build_windows_shortcut(name, executable)
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
let _ = icon; let _ = icon;
build_macos_command(name) build_macos_command(name, executable)
} }
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
{ {
let _ = (name, icon); let _ = (name, icon, executable);
String::new() String::new()
} }
} }
#[cfg(target_os = "linux")] #[cfg(any(target_os = "linux", test))]
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String { fn build_linux_desktop(name: &str, icon: Option<&Path>, executable: &str) -> String {
let mut out = String::new(); let mut out = String::new();
out.push_str("[Desktop Entry]\n"); out.push_str("[Desktop Entry]\n");
out.push_str("Version=0.3.1\n"); out.push_str("Version=1.0\n");
out.push_str("Type=Application\n"); out.push_str("Type=Application\n");
out.push_str(&format!("Name=Minecraft - {name}\n")); out.push_str(&format!("Name=Minecraft - {name}\n"));
out.push_str(&format!("Comment=Launch {name} Minecraft instance\n")); out.push_str(&format!("Comment=Launch {name} Minecraft instance\n"));
out.push_str(&format!("# rmcl-instance: {}\n", shortcut_name(name)));
out.push_str(&format!( out.push_str(&format!(
"Exec=rmcl instance launch {}\n", "Exec={} instance launch {}\n",
quote_desktop_exec_arg(executable),
quote_desktop_exec_arg(name) quote_desktop_exec_arg(name)
)); ));
if let Some(icon) = icon { if let Some(icon) = icon {
@@ -216,26 +341,38 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
out out
} }
#[cfg(target_os = "windows")] #[cfg(any(target_os = "windows", test))]
fn build_windows_shortcut(name: &str) -> String { fn build_windows_shortcut(name: &str, executable: &str) -> String {
let command = format!("rmcl instance launch {}", quote_windows_arg(name)); let arguments = format!("instance launch {}", quote_windows_arg(name));
let escaped_command = command.replace('"', "\"\""); let mut out = format!("' rmcl-instance: {}\r\n", shortcut_name(name));
out.push_str(&windows_shell_execute(executable, &arguments));
let mut out = String::new();
out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n");
out.push_str(&format!("shell.Run \"{escaped_command}\", 0, False\r\n"));
out out
} }
#[cfg(target_os = "macos")] #[cfg(any(target_os = "windows", test))]
fn build_macos_command(name: &str) -> String { fn windows_shell_execute(executable: &str, arguments: &str) -> String {
// ShellExecute passes parameters literally; WScript.Shell.Run expands %VAR% in them.
format!(
"Set shell = CreateObject(\"Shell.Application\")\r\nshell.ShellExecute \"{}\", \"{}\", \"\", \"open\", 0\r\n",
executable.replace('"', "\"\""),
arguments.replace('"', "\"\"")
)
}
#[cfg(any(target_os = "macos", test))]
fn build_macos_command(name: &str, executable: &str) -> String {
let mut out = String::new(); let mut out = String::new();
out.push_str("#!/bin/bash\n"); out.push_str("#!/bin/bash\n");
out.push_str(&format!("# Launch Minecraft instance: {name}\n")); out.push_str(&format!("# rmcl-instance: {}\n", shortcut_name(name)));
out.push_str(&format!("rmcl instance launch {}\n", quote_shell_arg(name))); out.push_str(&format!(
"{} instance launch {}\n",
quote_shell_arg(executable),
quote_shell_arg(name)
));
out out
} }
#[cfg(any(target_os = "linux", test))]
fn quote_desktop_exec_arg(value: &str) -> String { fn quote_desktop_exec_arg(value: &str) -> String {
let mut escaped = String::with_capacity(value.len() + 2); let mut escaped = String::with_capacity(value.len() + 2);
escaped.push('"'); escaped.push('"');
@@ -246,7 +383,7 @@ fn quote_desktop_exec_arg(value: &str) -> String {
escaped.push(character); escaped.push(character);
} }
escaped.push('"'); escaped.push('"');
escaped escaped.replace('\\', "\\\\").replace('%', "%%")
} }
#[cfg(any(target_os = "macos", test))] #[cfg(any(target_os = "macos", test))]
+7 -1
View File
@@ -32,7 +32,13 @@ fn relative_path(
let relative = enclosed let relative = enclosed
.strip_prefix(root) .strip_prefix(root)
.map_err(|_| format!("Invalid override path: {}", entry.name()))?; .map_err(|_| format!("Invalid override path: {}", entry.name()))?;
Ok(Some(relative.to_owned())) if relative.as_os_str().is_empty() {
return Ok(Some(relative.to_owned()));
}
let relative = relative
.to_str()
.ok_or_else(|| "Override path is not UTF-8".to_owned())?;
Ok(Some(PathBuf::from(super::portable_pack_path(relative)?)))
} }
pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result<Vec<PathBuf>, String> { pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result<Vec<PathBuf>, String> {
+3 -1
View File
@@ -114,6 +114,7 @@ pub async fn execute_import(
manager: &InstanceManager, manager: &InstanceManager,
config: &InstanceConfig, config: &InstanceConfig,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
crate::instance::manager::validate_name(&config.name)?;
let minecraft_dir = manager let minecraft_dir = manager
.instances_dir .instances_dir
.join(&config.name) .join(&config.name)
@@ -210,8 +211,9 @@ pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>,
.iter() .iter()
.find(|file| file.primary) .find(|file| file.primary)
.or_else(|| version.files.first()) .or_else(|| version.files.first())
.map(|file| std::path::PathBuf::from("mods").join(&file.filename))
.ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id)) .ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id))
.and_then(|file| super::portable_pack_path(&format!("mods/{}", file.filename)))
.map(std::path::PathBuf::from)
}) })
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
files.extend(overrides); files.extend(overrides);
+10 -2
View File
@@ -95,6 +95,7 @@ pub async fn execute_import(
manager: &InstanceManager, manager: &InstanceManager,
config: &crate::instance::InstanceConfig, config: &crate::instance::InstanceConfig,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
crate::instance::manager::validate_name(&config.name)?;
tracing::info!( tracing::info!(
"Importing MultiMC/Prism pack '{}' as instance '{}'", "Importing MultiMC/Prism pack '{}' as instance '{}'",
summary.name, summary.name,
@@ -159,13 +160,20 @@ fn extract_mmc_archive(
) )
})?; })?;
let relative = if relative.as_os_str().is_empty() {
std::path::PathBuf::new()
} else {
std::path::PathBuf::from(super::portable_pack_path(
relative.to_str().ok_or("Archive path is not UTF-8")?,
)?)
};
if relative.as_os_str().is_empty() || entry_name.ends_with('/') { if relative.as_os_str().is_empty() || entry_name.ends_with('/') {
std::fs::create_dir_all(minecraft_dir.join(relative))?; std::fs::create_dir_all(minecraft_dir.join(&relative))?;
dirs += 1; dirs += 1;
continue; continue;
} }
let dest = minecraft_dir.join(relative); let dest = minecraft_dir.join(&relative);
if let Some(parent) = dest.parent() { if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?; std::fs::create_dir_all(parent)?;
} }
+42 -13
View File
@@ -31,15 +31,6 @@ pub enum ImportInput {
pub fn parse_import_input(input: &str) -> ImportInput { pub fn parse_import_input(input: &str) -> ImportInput {
let input = input.trim(); let input = input.trim();
if input.ends_with(".mrpack")
|| input.ends_with(".zip")
|| input.starts_with('/')
|| input.starts_with("~/")
{
tracing::debug!("Import input resolved as local file: {}", input);
return ImportInput::LocalFile(input.to_string());
}
if let Some(rest) = input if let Some(rest) = input
.strip_prefix("https://modrinth.com/modpack/") .strip_prefix("https://modrinth.com/modpack/")
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/")) .or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
@@ -57,6 +48,22 @@ pub fn parse_import_input(input: &str) -> ImportInput {
return parsed; return parsed;
} }
if input.rsplit_once('.').is_some_and(|(_, extension)| {
extension.eq_ignore_ascii_case("mrpack") || extension.eq_ignore_ascii_case("zip")
}) || input.starts_with('/')
|| input.starts_with("~/")
|| input.starts_with("./")
|| input.starts_with("../")
|| input.contains('\\')
|| input
.as_bytes()
.get(..2)
.is_some_and(|prefix| prefix[0].is_ascii_alphabetic() && prefix[1] == b':')
{
tracing::debug!("Import input resolved as local file: {}", input);
return ImportInput::LocalFile(input.to_string());
}
tracing::debug!("Import input resolved as Modrinth project slug: {}", input); tracing::debug!("Import input resolved as Modrinth project slug: {}", input);
ImportInput::ProjectSlug(input.to_string()) ImportInput::ProjectSlug(input.to_string())
} }
@@ -133,22 +140,27 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
Ok(summary) Ok(summary)
} }
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { pub fn unique_instance_name(
base: &str,
instances_dir: &Path,
) -> Result<String, crate::instance::manager::InstanceError> {
crate::instance::manager::validate_name(base)?;
let candidate = base.to_string(); let candidate = base.to_string();
if !instances_dir.join(&candidate).exists() { if !instances_dir.join(&candidate).exists() {
tracing::trace!("Import instance name '{}' is available", candidate); tracing::trace!("Import instance name '{}' is available", candidate);
return candidate; return Ok(candidate);
} }
let mut n = 2; let mut n = 2;
loop { loop {
let candidate = format!("{base} ({n})"); let candidate = format!("{base} ({n})");
crate::instance::manager::validate_name(&candidate)?;
if !instances_dir.join(&candidate).exists() { if !instances_dir.join(&candidate).exists() {
tracing::debug!( tracing::debug!(
"Import instance name '{}' collided; using '{}'", "Import instance name '{}' collided; using '{}'",
base, base,
candidate candidate
); );
return candidate; return Ok(candidate);
} }
n += 1; n += 1;
} }
@@ -164,7 +176,8 @@ pub async fn execute_import(
summary.name, summary.name,
summary.archive_path.display() summary.archive_path.display()
); );
let name = unique_instance_name(&summary.name, &manager.instances_dir); let name = unique_instance_name(&summary.name, &manager.instances_dir)
.inspect_err(|_| crate::feedback::progress::clear())?;
crate::feedback::progress::set_action(format!("Importing '{name}'...")); crate::feedback::progress::set_action(format!("Importing '{name}'..."));
crate::feedback::progress::set_sub_action(format!( crate::feedback::progress::set_sub_action(format!(
"{} {}", "{} {}",
@@ -271,6 +284,10 @@ async fn owned_files(summary: &ImportSummary) -> Result<Vec<PathBuf>, String> {
} }
fn cleanup_failed_import(manager: &InstanceManager, name: &str) { fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
if let Err(error) = crate::instance::manager::validate_name(name) {
tracing::warn!("Refusing to clean up an invalid imported instance: {error}");
return;
}
let instance_dir = manager.instances_dir.join(name); let instance_dir = manager.instances_dir.join(name);
if let Err(error) = std::fs::remove_dir_all(&instance_dir) if let Err(error) = std::fs::remove_dir_all(&instance_dir)
&& error.kind() != std::io::ErrorKind::NotFound && error.kind() != std::io::ErrorKind::NotFound
@@ -283,6 +300,18 @@ fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
} }
} }
pub(super) fn portable_pack_path(path: &str) -> Result<String, String> {
let normalized = path.replace('\\', "/");
if !crate::storage::safe_relative_path(Path::new(&normalized))
|| !normalized
.split('/')
.all(crate::instance::manager::portable_component)
{
return Err(format!("Unsafe pack-owned path: {path:?}"));
}
Ok(normalized)
}
#[cfg(test)] #[cfg(test)]
#[path = "../tests/import/format_detection.rs"] #[path = "../tests/import/format_detection.rs"]
mod tests; mod tests;
+10 -12
View File
@@ -150,6 +150,7 @@ pub async fn execute_import(
manager: &InstanceManager, manager: &InstanceManager,
config: &crate::instance::InstanceConfig, config: &crate::instance::InstanceConfig,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
crate::instance::manager::validate_name(&config.name)?;
tracing::info!( tracing::info!(
"Importing Modrinth pack '{}' as instance '{}'", "Importing Modrinth pack '{}' as instance '{}'",
summary.name, summary.name,
@@ -251,14 +252,11 @@ async fn download_mod_files(
} }
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> { fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
let path = Path::new(path); super::portable_pack_path(path)
if !crate::storage::safe_relative_path(path) { .map(PathBuf::from)
return Err(crate::net::NetError::Parse(format!( .map_err(|error| {
"Unsafe .mrpack file path '{}'", crate::net::NetError::Parse(format!("Unsafe .mrpack file path '{path}': {error}"))
path.display() })
)));
}
Ok(path.to_owned())
} }
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> { pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
@@ -298,8 +296,8 @@ fn seed_content_manifest(
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut manifest = ContentManifest::default(); let mut manifest = ContentManifest::default();
for file in index.client_files() { for file in index.client_files() {
let relative_path = Path::new(&file.path); let relative_path = safe_mrpack_path(&file.path)?;
let Some(kind) = mrpack_content_kind(relative_path) else { let Some(kind) = mrpack_content_kind(&relative_path) else {
continue; continue;
}; };
let Some((project_id, version_id)) = file.downloads.iter().find_map(|url| { let Some((project_id, version_id)) = file.downloads.iter().find_map(|url| {
@@ -314,7 +312,7 @@ fn seed_content_manifest(
let Some(expected_sha512) = file.hashes.get("sha512") else { let Some(expected_sha512) = file.hashes.get("sha512") else {
continue; continue;
}; };
let file_fingerprint = fingerprint(&paths.minecraft().join(relative_path))?; let file_fingerprint = fingerprint(&paths.minecraft().join(&relative_path))?;
if file_fingerprint if file_fingerprint
.hash("sha512") .hash("sha512")
.is_none_or(|actual| !actual.eq_ignore_ascii_case(expected_sha512)) .is_none_or(|actual| !actual.eq_ignore_ascii_case(expected_sha512))
@@ -326,7 +324,7 @@ fn seed_content_manifest(
continue; continue;
} }
manifest.upsert(ContentFileRecord { manifest.upsert(ContentFileRecord {
relative_path: relative_path.to_owned(), relative_path,
kind, kind,
enabled: true, enabled: true,
fingerprint: file_fingerprint, fingerprint: file_fingerprint,
File diff suppressed because it is too large. Load diff
+143 -14
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
use std::path::PathBuf; use std::path::{Path, PathBuf};
use chrono::Utc; use chrono::Utc;
use thiserror::Error; use thiserror::Error;
@@ -465,6 +465,8 @@ impl InstanceManager {
if crate::instance::runtime::is_active(name) { if crate::instance::runtime::is_active(name) {
return Err(InstanceError::InstanceRunning(name.to_owned())); return Err(InstanceError::InstanceRunning(name.to_owned()));
} }
let _lock = crate::instance::runtime::lock_instance(&self.instances_dir, name)?;
let _config_lock = self.config_lock(name)?;
let instance_dir = self.instances_dir.join(name); let instance_dir = self.instances_dir.join(name);
if !instance_dir.exists() { if !instance_dir.exists() {
tracing::warn!( tracing::warn!(
@@ -505,10 +507,8 @@ impl InstanceManager {
tracing::debug!("Ignoring no-op instance rename '{}'", old_name); tracing::debug!("Ignoring no-op instance rename '{}'", old_name);
return Ok(()); return Ok(());
} }
// same path-traversal guards as create: without this, "../x" or ".x"
// would move the instance directory out of (or hide it inside) the
// instances root.
validate_name(new_name)?; validate_name(new_name)?;
let _old_lock = crate::instance::runtime::lock_instance(&self.instances_dir, old_name)?;
let old_dir = self.instances_dir.join(old_name); let old_dir = self.instances_dir.join(old_name);
let new_dir = self.instances_dir.join(new_name); let new_dir = self.instances_dir.join(new_name);
if !old_dir.exists() { if !old_dir.exists() {
@@ -519,7 +519,16 @@ impl InstanceManager {
); );
return Err(InstanceError::NotFound(old_name.to_string())); return Err(InstanceError::NotFound(old_name.to_string()));
} }
if new_dir.exists() { let aliases_source = paths_alias(&old_dir, &new_dir)?;
let _new_lock = if aliases_source {
None
} else {
Some(crate::instance::runtime::lock_instance(
&self.instances_dir,
new_name,
)?)
};
if std::fs::symlink_metadata(&new_dir).is_ok() && !aliases_source {
tracing::warn!( tracing::warn!(
"Cannot rename instance '{}' to '{}': destination exists at {}", "Cannot rename instance '{}' to '{}': destination exists at {}",
old_name, old_name,
@@ -528,11 +537,17 @@ impl InstanceManager {
); );
return Err(InstanceError::AlreadyExists(new_name.to_string())); return Err(InstanceError::AlreadyExists(new_name.to_string()));
} }
let _old_config_lock = self.config_lock(old_name)?;
let _new_config_lock = if aliases_source {
None
} else {
Some(self.config_lock(new_name)?)
};
let mut config = self.load_one(old_name)?; let mut config = self.load_one(old_name)?;
config.name = new_name.to_owned(); config.name = new_name.to_owned();
let json = serde_json::to_vec_pretty(&config)?; let json = serde_json::to_vec_pretty(&config)?;
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name); tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
if let Err(e) = std::fs::rename(&old_dir, &new_dir) { if let Err(e) = rename_path(&old_dir, &new_dir, aliases_source) {
tracing::error!( tracing::error!(
"Failed to rename instance directory {} to {}: {}", "Failed to rename instance directory {} to {}: {}",
old_dir.display(), old_dir.display(),
@@ -544,7 +559,7 @@ impl InstanceManager {
let config_path = new_dir.join("instance.json"); let config_path = new_dir.join("instance.json");
if let Err(error) = crate::storage::write_atomic(&config_path, &json) { if let Err(error) = crate::storage::write_atomic(&config_path, &json) {
if let Err(rollback_error) = std::fs::rename(&new_dir, &old_dir) { if let Err(rollback_error) = rename_path(&new_dir, &old_dir, aliases_source) {
tracing::error!( tracing::error!(
"Failed to roll back instance rename from {} to {}: {}", "Failed to roll back instance rename from {} to {}: {}",
new_dir.display(), new_dir.display(),
@@ -583,6 +598,12 @@ impl InstanceManager {
continue; continue;
} }
}; };
let Some(directory_name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if validate_name(&directory_name).is_err() {
continue;
}
let config_path = entry.path().join("instance.json"); let config_path = entry.path().join("instance.json");
if !config_path.exists() { if !config_path.exists() {
tracing::trace!("Skipping non-instance directory {}", entry.path().display()); tracing::trace!("Skipping non-instance directory {}", entry.path().display());
@@ -597,12 +618,6 @@ impl InstanceManager {
}; };
match serde_json::from_str::<InstanceConfig>(&contents) { match serde_json::from_str::<InstanceConfig>(&contents) {
Ok(mut config) => { Ok(mut config) => {
let Some(directory_name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if validate_name(&directory_name).is_err() {
continue;
}
config.name = directory_name; config.name = directory_name;
instances.push(config); instances.push(config);
} }
@@ -659,6 +674,47 @@ impl InstanceManager {
} }
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> { pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
let _lock = self.config_lock(&instance.name)?;
let mut instance = instance.clone();
match self.load_one(&instance.name) {
Ok(current) => {
instance.last_played = instance.last_played.max(current.last_played);
// Selection changes must commit with their corresponding filesystem payload.
instance.config_sync_profile = current.config_sync_profile;
}
Err(InstanceError::NotFound(_)) => {}
Err(error) => return Err(error),
}
self.save_unlocked(&instance)
}
pub(crate) fn save_config_sync_profile(
&self,
name: &str,
profile: Option<String>,
) -> Result<InstanceConfig, InstanceError> {
let _lock = self.config_lock(name)?;
let mut config = self.load_one(name)?;
config.config_sync_profile = profile;
self.save_unlocked(&config)?;
Ok(config)
}
pub(crate) fn config_lock(&self, name: &str) -> Result<std::fs::File, InstanceError> {
validate_name(name)?;
// the lock must survive replacing or renaming the instance directory.
std::fs::create_dir_all(&self.instances_dir)?;
let path = self.instances_dir.join(format!(".rmcl-config-{name}.lock"));
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(path)?;
file.lock()?;
Ok(file)
}
fn save_unlocked(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
validate_name(&instance.name)?; validate_name(&instance.name)?;
let instance_dir = self.instances_dir.join(&instance.name); let instance_dir = self.instances_dir.join(&instance.name);
if !instance_dir.is_dir() { if !instance_dir.is_dir() {
@@ -676,10 +732,11 @@ impl InstanceManager {
} }
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> { pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
let _lock = self.config_lock(name)?;
let mut config = self.load_one(name)?; let mut config = self.load_one(name)?;
config.last_played = Some(chrono::Utc::now()); config.last_played = Some(chrono::Utc::now());
tracing::debug!("Updating last_played for '{}'", name); tracing::debug!("Updating last_played for '{}'", name);
self.save(&config) self.save_unlocked(&config)
} }
} }
@@ -727,6 +784,78 @@ pub(crate) fn portable_component(name: &str) -> bool {
}) })
} }
pub(crate) fn paths_alias(left: &Path, right: &Path) -> std::io::Result<bool> {
if left.parent() != right.parent() {
return Ok(false);
}
let right_metadata = match std::fs::symlink_metadata(right) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error),
};
let left_metadata = std::fs::symlink_metadata(left)?;
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if left_metadata.dev() != right_metadata.dev()
|| left_metadata.ino() != right_metadata.ino()
{
return Ok(false);
}
// Distinct hard links are not aliases of the same directory entry.
if left.file_name() != right.file_name() {
let mut left_entry = false;
let mut right_entry = false;
for entry in std::fs::read_dir(
left.parent()
.ok_or_else(|| std::io::Error::other("Path has no parent"))?,
)? {
let name = entry?.file_name();
left_entry |= Some(name.as_os_str()) == left.file_name();
right_entry |= Some(name.as_os_str()) == right.file_name();
}
if left_entry && right_entry {
return Ok(false);
}
}
Ok(true)
}
#[cfg(not(unix))]
{
if left_metadata.file_type().is_symlink() || right_metadata.file_type().is_symlink() {
return Ok(false);
}
Ok(std::fs::canonicalize(left)? == std::fs::canonicalize(right)?)
}
}
pub(crate) fn rename_path(from: &Path, to: &Path, aliases_source: bool) -> std::io::Result<()> {
if !aliases_source {
return std::fs::rename(from, to);
}
let temporary = tempfile::Builder::new()
.prefix(".rmcl-rename-")
.tempdir_in(
from.parent()
.ok_or_else(|| std::io::Error::other("Path has no parent"))?,
)?;
let staged = temporary.path().join("original");
std::fs::rename(from, &staged)?;
if let Err(error) = std::fs::rename(&staged, to) {
if let Err(rollback) = std::fs::rename(&staged, from) {
let retained = temporary.keep();
return Err(std::io::Error::other(format!(
"Could not rename '{}' to '{}': {error}; rollback failed: {rollback}; original retained at '{}'",
from.display(),
to.display(),
retained.join("original").display(),
)));
}
return Err(error);
}
Ok(())
}
#[cfg(test)] #[cfg(test)]
#[path = "tests/manager.rs"] #[path = "tests/manager.rs"]
mod tests; mod tests;
+881
View File
@@ -449,6 +449,14 @@ fn failed_profile_save_restores_previous_files() {
"local" "local"
); );
assert!(!minecraft.join("config/shared.txt").exists()); assert!(!minecraft.join("config/shared.txt").exists());
assert_eq!(
std::fs::read(meta.join("state/profiles/main/options.txt")).unwrap(),
b"shared-options"
);
assert_eq!(
std::fs::read(meta.join("state/profiles/main/config/shared.txt")).unwrap(),
b"shared"
);
} }
#[test] #[test]
@@ -479,3 +487,876 @@ fn second_instance_uses_profile_options_saved_by_first_instance() {
"second-local" "second-local"
); );
} }
#[test]
fn options_commit_failure_restores_the_entire_payload() {
for sync in [sync_to_profile as fn(&Path, &Path) -> _, sync_from_profile] {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("source");
let dst = tmp.path().join("target");
std::fs::create_dir_all(src.join("config")).unwrap();
std::fs::create_dir_all(dst.join("config")).unwrap();
std::fs::create_dir_all(dst.join("optionsz.txt")).unwrap();
std::fs::write(src.join("config/new"), b"new").unwrap();
std::fs::write(src.join("options.txt"), b"new-options").unwrap();
std::fs::write(src.join("optionsz.txt"), b"collision").unwrap();
std::fs::write(dst.join("config/old"), b"old").unwrap();
std::fs::write(dst.join("options.txt"), b"old-options").unwrap();
std::fs::write(dst.join("optionslegacy.txt"), b"legacy").unwrap();
std::fs::write(dst.join("optionsz.txt/keep"), b"keep").unwrap();
assert!(sync(&src, &dst).is_err());
assert_eq!(std::fs::read(dst.join("config/old")).unwrap(), b"old");
assert!(!dst.join("config/new").exists());
assert_eq!(
std::fs::read(dst.join("options.txt")).unwrap(),
b"old-options"
);
assert_eq!(
std::fs::read(dst.join("optionslegacy.txt")).unwrap(),
b"legacy"
);
assert_eq!(
std::fs::read(dst.join("optionsz.txt/keep")).unwrap(),
b"keep"
);
assert!(!tmp.path().join(".target.sync-backup").exists());
}
}
#[test]
fn failed_rollback_retains_original_payload_backup() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("source");
let dst = tmp.path().join("target");
std::fs::create_dir_all(src.join("config")).unwrap();
std::fs::create_dir_all(dst.join("config")).unwrap();
std::fs::write(src.join("config/value"), b"new").unwrap();
std::fs::write(dst.join("config/value"), b"original").unwrap();
std::fs::write(dst.join("options.txt"), b"original-options").unwrap();
let error = mirror_payload(&src, &dst, true, || {
std::fs::rename(&dst, tmp.path().join("displaced"))?;
std::fs::write(&dst, b"blocks restoration")?;
Err::<(), _>(ConfigSyncError::Save("injected failure".to_owned()))
})
.unwrap_err();
assert!(matches!(error, ConfigSyncError::SaveRollback { .. }));
let backup = tmp.path().join(".target.sync-backup");
assert_eq!(
std::fs::read(backup.join("config/value")).unwrap(),
b"original"
);
assert_eq!(
std::fs::read(backup.join("options.txt")).unwrap(),
b"original-options"
);
}
#[test]
fn failed_switch_io_does_not_save_selection_or_change_local_files() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let local = minecraft_dir(&instance);
let profile = profile_dir(&meta, "main");
std::fs::create_dir_all(local.join("config")).unwrap();
std::fs::create_dir_all(local.join("optionsz.txt")).unwrap();
std::fs::create_dir_all(profile.join("config")).unwrap();
std::fs::write(local.join("config/value"), b"local").unwrap();
std::fs::write(local.join("options.txt"), b"local-options").unwrap();
std::fs::write(profile.join("config/value"), b"profile").unwrap();
std::fs::write(profile.join("optionsz.txt"), b"collision").unwrap();
let mut saved = false;
assert!(
switch_profile_and_persist("inst", None, Some("main"), &meta, &instance, |_| {
saved = true;
Ok::<(), std::io::Error>(())
})
.is_err()
);
assert!(!saved);
assert_eq!(std::fs::read(local.join("config/value")).unwrap(), b"local");
assert_eq!(
std::fs::read(local.join("options.txt")).unwrap(),
b"local-options"
);
}
#[test]
fn failed_publication_recovers_local_changes_before_the_next_import() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let local = tmp.path().join("instance/minecraft");
std::fs::create_dir_all(local.join("config")).unwrap();
std::fs::write(local.join("config/value"), b"original").unwrap();
create_profile(&meta, "main").unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &local)
.unwrap()
.unwrap();
let profile = profile_dir(&meta, "main");
std::fs::write(local.join("config/value"), b"changed").unwrap();
std::fs::write(local.join("optionsz.txt"), b"changed-options").unwrap();
std::fs::create_dir(profile.join("optionsz.txt")).unwrap();
assert!(finish_launch(lock, &local).is_err());
assert!(unsynced_marker(&profile).exists());
assert!(prepare_for_launch(Some("main"), &meta, &local).is_err());
assert_eq!(
std::fs::read(local.join("config/value")).unwrap(),
b"changed"
);
std::fs::remove_dir(profile.join("optionsz.txt")).unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &local)
.unwrap()
.unwrap();
assert_eq!(
std::fs::read(local.join("config/value")).unwrap(),
b"changed"
);
assert_eq!(
std::fs::read(profile.join("config/value")).unwrap(),
b"changed"
);
assert_eq!(
std::fs::read(profile.join("optionsz.txt")).unwrap(),
b"changed-options"
);
finish_launch(lock, &local).unwrap();
assert!(!unsynced_marker(&profile).exists());
}
#[test]
fn invalid_recovery_source_keeps_profile_and_local_payloads() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let local = tmp.path().join("instance/minecraft");
let profile = profile_dir(&meta, "main");
std::fs::create_dir_all(local.join("config")).unwrap();
std::fs::create_dir_all(profile.join("config")).unwrap();
std::fs::write(local.join("config/value"), b"local").unwrap();
std::fs::write(profile.join("config/value"), b"shared").unwrap();
std::fs::write(
unsynced_marker(&profile),
serde_json::to_vec(&tmp.path().join("missing")).unwrap(),
)
.unwrap();
assert!(prepare_for_launch(Some("main"), &meta, &local).is_err());
assert!(unsynced_marker(&profile).exists());
assert_eq!(std::fs::read(local.join("config/value")).unwrap(), b"local");
assert_eq!(
std::fs::read(profile.join("config/value")).unwrap(),
b"shared"
);
}
#[cfg(unix)]
#[test]
fn relative_symlinks_keep_internal_and_external_referents_at_different_depths() {
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
let target = tmp.path().join("deep/target");
std::fs::create_dir_all(source.join("config/nested")).unwrap();
std::fs::write(tmp.path().join("shared"), b"external").unwrap();
std::fs::write(source.join("options.txt"), b"options").unwrap();
std::fs::write(source.join("config/nested/value"), b"nested").unwrap();
std::os::unix::fs::symlink("value", source.join("config/nested/sibling")).unwrap();
std::os::unix::fs::symlink("../options.txt", source.join("config/to-options")).unwrap();
std::os::unix::fs::symlink("config/nested/value", source.join("optionslinked.txt")).unwrap();
std::os::unix::fs::symlink("missing", source.join("config/dangling")).unwrap();
std::os::unix::fs::symlink("../../shared", source.join("config/external")).unwrap();
std::os::unix::fs::symlink("../shared", source.join("optionsexternal.txt")).unwrap();
sync_to_profile(&source, &target).unwrap();
std::fs::remove_dir_all(&source).unwrap();
for (path, bytes) in [
("config/nested/sibling", b"nested".as_slice()),
("config/to-options", b"options".as_slice()),
("optionslinked.txt", b"nested".as_slice()),
("config/external", b"external".as_slice()),
("optionsexternal.txt", b"external".as_slice()),
] {
assert_eq!(std::fs::read(target.join(path)).unwrap(), bytes, "{path}");
}
assert_eq!(
std::fs::read_link(target.join("config/dangling")).unwrap(),
Path::new("missing")
);
}
fn write_payload(dir: &Path, value: &str) {
std::fs::create_dir_all(dir.join("config")).unwrap();
std::fs::write(dir.join("config/value"), value).unwrap();
std::fs::write(dir.join("options.txt"), value).unwrap();
}
fn saved_instance(
manager: &crate::instance::InstanceManager,
name: &str,
) -> crate::instance::InstanceConfig {
let config = serde_json::from_value(serde_json::json!({
"name": name, "game_version": "1.21.1", "loader": "vanilla", "loader_version": null,
"created": "2026-01-01T00:00:00Z"
}))
.unwrap();
write_payload(
&minecraft_dir(&manager.instances_dir.join(name)),
"local-default",
);
manager.save(&config).unwrap();
config
}
#[test]
fn missing_launch_source_preserves_profile_and_recovery_marker() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let local = tmp.path().join("instance/minecraft");
write_payload(&local, "keep");
create_profile(&meta, "main").unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &local)
.unwrap()
.unwrap();
std::fs::remove_dir_all(&local).unwrap();
assert!(finish_launch(lock, &local).is_err());
let profile = profile_dir(&meta, "main");
assert_eq!(
std::fs::read(profile.join("config/value")).unwrap(),
b"keep"
);
assert_eq!(std::fs::read(profile.join("options.txt")).unwrap(), b"keep");
assert!(unsynced_marker(&profile).exists());
}
#[test]
fn missing_seed_source_does_not_initialize_the_profile() {
let tmp = tempfile::tempdir().unwrap();
create_profile(tmp.path(), "main").unwrap();
let local = tmp.path().join("missing/minecraft");
assert!(prepare_for_launch(Some("main"), tmp.path(), &local).is_err());
let profile = profile_dir(tmp.path(), "main");
assert!(std::fs::read_dir(&profile).unwrap().next().is_none());
assert!(!local.exists());
}
#[test]
fn missing_switch_source_does_not_publish_or_save_selection() {
let tmp = tempfile::tempdir().unwrap();
let manager = crate::instance::InstanceManager::new(
tmp.path().join("instances"),
tmp.path().join("meta"),
);
saved_instance(&manager, "inst");
let mut config = manager
.save_config_sync_profile("inst", Some("main".to_owned()))
.unwrap();
let profile = profile_dir(&manager.meta_dir, "main");
write_payload(&profile, "shared");
std::fs::remove_dir_all(minecraft_dir(&manager.instances_dir.join("inst"))).unwrap();
assert!(switch_profile_and_save(&manager, &mut config, None).is_err());
assert_eq!(
manager
.load_one("inst")
.unwrap()
.config_sync_profile
.as_deref(),
Some("main")
);
assert_eq!(
std::fs::read(profile.join("config/value")).unwrap(),
b"shared"
);
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"shared"
);
}
#[test]
fn stale_public_config_reloads_current_profile_and_preserves_newer_fields_and_payload() {
let tmp = tempfile::tempdir().unwrap();
let manager = crate::instance::InstanceManager::new(
tmp.path().join("instances"),
tmp.path().join("meta"),
);
let mut stale = saved_instance(&manager, "inst");
let mut current = stale.clone();
write_payload(&profile_dir(&manager.meta_dir, "a"), "profile-a");
write_payload(&profile_dir(&manager.meta_dir, "b"), "profile-b");
switch_profile_and_save(&manager, &mut current, Some("a")).unwrap();
current.memory_max = Some("8G".to_owned());
current
.environment
.insert("UPDATED".to_owned(), "yes".to_owned());
manager.save(&current).unwrap();
let other = minecraft_dir(&manager.instances_dir.join("other"));
write_payload(&other, "other-default");
let lock = prepare_for_launch(Some("a"), &manager.meta_dir, &other)
.unwrap()
.unwrap();
write_payload(&other, "newer-a");
finish_launch(lock, &other).unwrap();
switch_profile_and_save(&manager, &mut stale, Some("b")).unwrap();
assert_eq!(stale, manager.load_one("inst").unwrap());
assert_eq!(stale.memory_max.as_deref(), Some("8G"));
assert_eq!(stale.environment["UPDATED"], "yes");
assert_eq!(
std::fs::read(profile_dir(&manager.meta_dir, "a").join("options.txt")).unwrap(),
b"newer-a"
);
assert_eq!(
std::fs::read(local_backup_dir(&manager.instances_dir.join("inst")).join("options.txt"))
.unwrap(),
b"local-default"
);
switch_profile_and_save(&manager, &mut stale, None).unwrap();
assert_eq!(
std::fs::read(minecraft_dir(&manager.instances_dir.join("inst")).join("options.txt"))
.unwrap(),
b"local-default"
);
}
#[test]
fn public_switch_preserves_settings_updated_while_selection_save_is_blocked() {
let tmp = tempfile::tempdir().unwrap();
let manager = crate::instance::InstanceManager::new(
tmp.path().join("instances"),
tmp.path().join("meta"),
);
let config = saved_instance(&manager, "inst");
let instance = manager.instances_dir.join("inst");
write_payload(&profile_dir(&manager.meta_dir, "main"), "shared");
let config_lock = manager.config_lock("inst").unwrap();
let instances_dir = manager.instances_dir.clone();
let meta_dir = manager.meta_dir.clone();
let worker = std::thread::spawn(move || {
let manager = crate::instance::InstanceManager::new(instances_dir, meta_dir);
let mut config = config;
switch_profile_and_save(&manager, &mut config, Some("main")).unwrap();
config
});
let start = std::time::Instant::now();
while !std::fs::read(minecraft_dir(&instance).join("options.txt"))
.is_ok_and(|bytes| bytes == b"shared")
{
assert!(
start.elapsed() < std::time::Duration::from_secs(5),
"profile payload was not installed before persistence"
);
std::thread::yield_now();
}
let mut concurrent = manager.load_one("inst").unwrap();
assert_eq!(concurrent.config_sync_profile, None);
concurrent.java_path = Some("changed-during-switch".to_owned());
// This writer owns the config lock while the switch waits to persist its selection.
crate::storage::write_atomic(
&instance.join("instance.json"),
&serde_json::to_vec_pretty(&concurrent).unwrap(),
)
.unwrap();
drop(config_lock);
let saved = worker.join().unwrap();
assert_eq!(saved.java_path.as_deref(), Some("changed-during-switch"));
assert_eq!(saved.config_sync_profile.as_deref(), Some("main"));
assert_eq!(saved, manager.load_one("inst").unwrap());
}
#[test]
fn second_instance_switch_recovers_failed_publication_without_overwriting_it() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let profile = profile_dir(&meta, "main");
let first = tmp.path().join("first/minecraft");
let second_instance = tmp.path().join("second");
let second = minecraft_dir(&second_instance);
write_payload(&profile, "original");
write_payload(&first, "first-default");
write_payload(&second, "second-default");
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &first)
.unwrap()
.unwrap();
write_payload(&first, "changed");
std::fs::write(first.join("optionsz.txt"), b"changed-options").unwrap();
std::fs::create_dir(profile.join("optionsz.txt")).unwrap();
assert!(finish_launch(lock, &first).is_err());
assert!(switch_profile("second", Some("main"), None, &meta, &second_instance).is_err());
assert!(unsynced_marker(&profile).exists());
assert_eq!(
std::fs::read(second.join("options.txt")).unwrap(),
b"original"
);
write_payload(&first, "changed-after-failure");
std::fs::remove_dir(profile.join("optionsz.txt")).unwrap();
switch_profile("second", Some("main"), None, &meta, &second_instance).unwrap();
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"changed-after-failure"
);
assert_eq!(
std::fs::read(first.join("options.txt")).unwrap(),
b"changed-after-failure"
);
assert_eq!(
std::fs::read(second.join("options.txt")).unwrap(),
b"second-default"
);
assert!(!unsynced_marker(&profile).exists());
let third = tmp.path().join("third/minecraft");
write_payload(&third, "third-default");
let lock = prepare_for_launch(Some("main"), &meta, &third)
.unwrap()
.unwrap();
assert_eq!(
std::fs::read(third.join("options.txt")).unwrap(),
b"changed-after-failure"
);
finish_launch(lock, &third).unwrap();
}
#[test]
fn successful_publication_keeps_stale_copies_from_overwriting_newer_settings() {
for edited in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let profile = profile_dir(&meta, "main");
let first = tmp.path().join("first/minecraft");
let second_instance = tmp.path().join("second");
let second = minecraft_dir(&second_instance);
write_payload(&profile, "original");
write_payload(&first, "first-default");
write_payload(&second, "second-default");
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &first)
.unwrap()
.unwrap();
write_payload(&first, "new-shared");
finish_launch(lock, &first).unwrap();
if edited {
write_payload(&second, "local-edits");
}
let baseline = std::fs::read(baseline_path(&second).unwrap()).unwrap();
let mut saved = false;
let result = switch_profile_and_persist(
"second",
Some("main"),
None,
&meta,
&second_instance,
|_| {
saved = true;
Ok::<(), std::io::Error>(())
},
);
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"new-shared"
);
if edited {
assert!(matches!(result, Err(ConfigSyncError::Conflict { .. })));
assert!(!saved);
assert_eq!(
std::fs::read(second.join("options.txt")).unwrap(),
b"local-edits"
);
assert_eq!(
std::fs::read(baseline_path(&second).unwrap()).unwrap(),
baseline
);
assert!(matches!(
prepare_for_launch(Some("main"), &meta, &second),
Err(ConfigSyncError::Conflict { .. })
));
assert_eq!(
std::fs::read(second.join("options.txt")).unwrap(),
b"local-edits"
);
} else {
result.unwrap();
assert!(saved);
assert_eq!(
std::fs::read(second.join("options.txt")).unwrap(),
b"second-default"
);
}
}
}
#[test]
fn local_edits_publish_when_the_imported_profile_has_not_changed() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let local = minecraft_dir(&instance);
write_payload(&local, "default");
write_payload(&profile_dir(&meta, "a"), "profile-a");
write_payload(&profile_dir(&meta, "b"), "profile-b");
switch_profile("inst", None, Some("a"), &meta, &instance).unwrap();
write_payload(&local, "local-edits");
switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
assert_eq!(
std::fs::read(profile_dir(&meta, "a").join("options.txt")).unwrap(),
b"local-edits"
);
assert_eq!(
std::fs::read(local.join("options.txt")).unwrap(),
b"profile-b"
);
}
#[test]
fn untracked_selected_payload_cannot_overwrite_a_different_existing_profile() {
let tmp = tempfile::tempdir().unwrap();
let instance = tmp.path().join("instance");
let meta = tmp.path().join("meta");
write_payload(&minecraft_dir(&instance), "untracked-local");
let profile = profile_dir(&meta, "main");
write_payload(&profile, "shared");
assert!(matches!(
switch_profile("inst", Some("main"), None, &meta, &instance),
Err(ConfigSyncError::Conflict { .. })
));
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"shared"
);
assert_eq!(
std::fs::read(minecraft_dir(&instance).join("options.txt")).unwrap(),
b"untracked-local"
);
}
#[test]
fn next_launch_refreshes_an_unchanged_stale_import() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let profile = profile_dir(&meta, "main");
let first = tmp.path().join("first/minecraft");
let second_instance = tmp.path().join("second");
let second = minecraft_dir(&second_instance);
write_payload(&profile, "original");
write_payload(&first, "first-default");
write_payload(&second, "second-default");
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &first)
.unwrap()
.unwrap();
write_payload(&first, "new-shared");
finish_launch(lock, &first).unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &second)
.unwrap()
.unwrap();
assert_eq!(
std::fs::read(second.join("options.txt")).unwrap(),
b"new-shared"
);
finish_launch(lock, &second).unwrap();
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"new-shared"
);
}
#[test]
fn finishing_an_untracked_second_source_cannot_overwrite_a_recovered_origin() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let profile = profile_dir(&meta, "main");
let first = tmp.path().join("first/minecraft");
let second = tmp.path().join("second/minecraft");
write_payload(&profile, "original");
write_payload(&first, "first-default");
write_payload(&second, "original");
let lock = prepare_for_launch(Some("main"), &meta, &first)
.unwrap()
.unwrap();
write_payload(&first, "new-shared");
std::fs::write(first.join("optionsz.txt"), b"new-options").unwrap();
std::fs::create_dir(profile.join("optionsz.txt")).unwrap();
assert!(finish_launch(lock, &first).is_err());
std::fs::remove_dir(profile.join("optionsz.txt")).unwrap();
assert!(matches!(
finish(Some("main"), &meta, &second),
Err(ConfigSyncError::Conflict { .. })
));
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"new-shared"
);
assert_eq!(
std::fs::read(first.join("options.txt")).unwrap(),
b"new-shared"
);
assert_eq!(
std::fs::read(second.join("options.txt")).unwrap(),
b"original"
);
}
#[test]
fn baseline_io_failure_rolls_back_import_without_saving_selection() {
let tmp = tempfile::tempdir().unwrap();
let manager = crate::instance::InstanceManager::new(
tmp.path().join("instances"),
tmp.path().join("meta"),
);
let mut config = saved_instance(&manager, "inst");
let local = minecraft_dir(&manager.instances_dir.join("inst"));
write_payload(&profile_dir(&manager.meta_dir, "main"), "shared");
let baseline = baseline_path(&local).unwrap();
std::fs::create_dir_all(&baseline).unwrap();
std::fs::write(baseline.join("keep"), b"keep").unwrap();
assert!(switch_profile_and_save(&manager, &mut config, Some("main")).is_err());
assert_eq!(manager.load_one("inst").unwrap().config_sync_profile, None);
assert_eq!(
std::fs::read(local.join("options.txt")).unwrap(),
b"local-default"
);
assert_eq!(
std::fs::read(local.join("config/value")).unwrap(),
b"local-default"
);
assert_eq!(std::fs::read(baseline.join("keep")).unwrap(), b"keep");
}
#[cfg(unix)]
#[test]
fn failed_baseline_write_rolls_back_publication_and_remains_recoverable() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let local = tmp.path().join("instance/minecraft");
write_payload(&local, "original");
create_profile(&meta, "main").unwrap();
let lock = prepare_for_launch(Some("main"), &meta, &local)
.unwrap()
.unwrap();
let profile = profile_dir(&meta, "main");
let baseline = baseline_path(&local).unwrap();
let original_baseline = std::fs::read(&baseline).unwrap();
let state = baseline.parent().unwrap();
let permissions = std::fs::metadata(state).unwrap().permissions();
std::fs::set_permissions(state, std::fs::Permissions::from_mode(0o500)).unwrap();
let probe = state.join("write-probe");
if std::fs::File::create(&probe).is_ok() {
// Privileged runners can bypass the write denial needed for this check.
std::fs::set_permissions(state, permissions).unwrap();
std::fs::remove_file(probe).unwrap();
return;
}
write_payload(&local, "changed");
std::fs::write(
local.parent().unwrap().join("shared-options"),
b"new-link-data",
)
.unwrap();
std::fs::remove_file(local.join("options.txt")).unwrap();
std::os::unix::fs::symlink("../shared-options", local.join("options.txt")).unwrap();
let result = finish_launch(lock, &local);
std::fs::set_permissions(state, permissions).unwrap();
assert!(matches!(result, Err(ConfigSyncError::Io(_))));
assert_eq!(
std::fs::read(profile.join("config/value")).unwrap(),
b"original"
);
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"original"
);
assert!(
std::fs::symlink_metadata(profile.join("options.txt"))
.unwrap()
.is_file()
);
assert_eq!(std::fs::read(&baseline).unwrap(), original_baseline);
assert!(unsynced_marker(&profile).exists());
assert_eq!(
std::fs::read_link(local.join("options.txt")).unwrap(),
Path::new("../shared-options")
);
let lock = prepare_for_launch(Some("main"), &meta, &local)
.unwrap()
.unwrap();
assert_eq!(
std::fs::read(profile.join("config/value")).unwrap(),
b"changed"
);
assert_eq!(
std::fs::read(profile.join("options.txt")).unwrap(),
b"new-link-data"
);
assert_eq!(
std::fs::read(local.join("options.txt")).unwrap(),
b"new-link-data"
);
finish_launch(lock, &local).unwrap();
assert!(!unsynced_marker(&profile).exists());
}
#[test]
fn prepare_rechecks_a_profile_deleted_before_the_locked_payload_phase() {
let tmp = tempfile::tempdir().unwrap();
create_profile(tmp.path(), "main").unwrap();
let profile = profile_dir(tmp.path(), "main");
let lock = acquire_lock(&profile).unwrap();
std::fs::remove_dir(&profile).unwrap();
let local = tmp.path().join("instance/minecraft");
write_payload(&local, "keep");
assert!(prepare_locked(lock, &local).unwrap().is_none());
assert!(!profile.exists());
assert_eq!(std::fs::read(local.join("options.txt")).unwrap(), b"keep");
}
#[test]
fn profile_names_are_portable_components() {
for name in [
"main.", "main ", "NUL", "Con.cfg", "COM1", "COM¹", "LPT9", "C:victim", "a/b", "a\\b",
] {
assert!(
matches!(
validate_profile(name),
Err(ConfigSyncError::InvalidProfile(_))
),
"{name}"
);
}
let tmp = tempfile::tempdir().unwrap();
for name in ["main.", "NUL", "C:victim"] {
assert!(create_profile(tmp.path(), name).is_err());
}
assert!(list_profiles(tmp.path()).unwrap().is_empty());
}
#[cfg(unix)]
#[test]
fn dangling_payload_links_remain_internal_but_non_payload_referents_stay_anchored() {
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
let profile = tmp.path().join("profile");
let replay = tmp.path().join("deep/instance/minecraft");
std::fs::create_dir(&source).unwrap();
std::os::unix::fs::symlink("optionsbase.txt", source.join("options.txt")).unwrap();
std::os::unix::fs::symlink("config/value", source.join("optionsconfig.txt")).unwrap();
std::os::unix::fs::symlink("custom.txt", source.join("optionsexternal.txt")).unwrap();
std::fs::create_dir(source.join("optionsdir.txt")).unwrap();
std::fs::write(source.join("optionsdir.txt/value"), b"external-dir").unwrap();
std::os::unix::fs::symlink("optionsdir.txt/value", source.join("optionsdirectory.txt"))
.unwrap();
sync_to_profile(&source, &profile).unwrap();
sync_from_profile(&profile, &replay).unwrap();
assert_eq!(
std::fs::read_link(replay.join("options.txt")).unwrap(),
Path::new("optionsbase.txt")
);
assert_eq!(
std::fs::read_link(replay.join("optionsconfig.txt")).unwrap(),
Path::new("config/value")
);
assert_eq!(
std::fs::read_link(replay.join("optionsexternal.txt")).unwrap(),
source.join("custom.txt")
);
assert_eq!(
std::fs::read(replay.join("optionsdirectory.txt")).unwrap(),
b"external-dir"
);
std::fs::remove_dir_all(&source).unwrap();
std::fs::write(replay.join("optionsbase.txt"), b"new-options").unwrap();
std::fs::write(replay.join("config/value"), b"new-config").unwrap();
assert_eq!(
std::fs::read(replay.join("options.txt")).unwrap(),
b"new-options"
);
assert_eq!(
std::fs::read(replay.join("optionsconfig.txt")).unwrap(),
b"new-config"
);
}
#[cfg(unix)]
#[test]
fn failed_selection_save_restores_the_original_option_symlink_and_baseline() {
use std::os::unix::fs::MetadataExt;
let tmp = tempfile::tempdir().unwrap();
let instance = tmp.path().join("instance");
let meta = tmp.path().join("meta");
let local = minecraft_dir(&instance);
write_payload(&local, "default");
write_payload(&profile_dir(&meta, "a"), "profile-a");
write_payload(&profile_dir(&meta, "b"), "profile-b");
switch_profile("inst", None, Some("a"), &meta, &instance).unwrap();
std::fs::write(instance.join("shared-options"), b"original-link-data").unwrap();
std::fs::remove_file(local.join("options.txt")).unwrap();
std::os::unix::fs::symlink("../shared-options", local.join("options.txt")).unwrap();
let inode = std::fs::symlink_metadata(local.join("options.txt"))
.unwrap()
.ino();
let error = switch_profile_and_persist("inst", Some("a"), Some("b"), &meta, &instance, |_| {
assert_eq!(
std::fs::read(local.join("options.txt")).unwrap(),
b"profile-b"
);
Err(std::io::Error::other("selection save failed"))
})
.unwrap_err();
assert!(matches!(error, ConfigSyncError::Save(_)));
assert_eq!(
std::fs::read_link(local.join("options.txt")).unwrap(),
Path::new("../shared-options")
);
assert_eq!(
std::fs::symlink_metadata(local.join("options.txt"))
.unwrap()
.ino(),
inode
);
assert_eq!(
std::fs::read(instance.join("shared-options")).unwrap(),
b"original-link-data"
);
let baseline = read_baseline(&local).unwrap().unwrap();
assert_eq!(
baseline.profile,
std::fs::canonicalize(profile_dir(&meta, "a")).unwrap()
);
assert_eq!(baseline.local, payload_hash(&local).unwrap());
// The failed switch must not turn the restored A payload into an untracked export.
switch_profile("inst", Some("a"), None, &meta, &instance).unwrap();
assert_eq!(
std::fs::read(local.join("options.txt")).unwrap(),
b"default"
);
}
#[cfg(unix)]
#[test]
fn profile_root_symlink_aliases_are_not_listed_or_used() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let local = minecraft_dir(&instance);
write_payload(&local, "local");
create_profile(&meta, "real").unwrap();
let real = profile_dir(&meta, "real");
write_payload(&real, "shared");
let alias = profile_dir(&meta, "alias");
std::os::unix::fs::symlink(&real, &alias).unwrap();
assert_eq!(list_profiles(&meta).unwrap(), vec!["real"]);
assert!(prepare_for_launch(Some("alias"), &meta, &local).is_err());
assert!(switch_profile("inst", None, Some("alias"), &meta, &instance).is_err());
assert!(switch_profile("inst", Some("alias"), Some("alias"), &meta, &instance).is_err());
assert!(create_profile(&meta, "alias").is_err());
assert!(delete_profile(&meta, "alias").is_err());
assert!(
std::fs::symlink_metadata(&alias)
.unwrap()
.file_type()
.is_symlink()
);
assert_eq!(std::fs::read(real.join("options.txt")).unwrap(), b"shared");
assert_eq!(std::fs::read(local.join("options.txt")).unwrap(), b"local");
}
+194 -5
View File
@@ -26,7 +26,7 @@ fn shortcut_paths_do_not_collide_after_escaping() {
fn legacy_shortcut_is_attributed_to_the_right_instance() { fn legacy_shortcut_is_attributed_to_the_right_instance() {
let temp = tempfile::tempdir().unwrap(); let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("rmcl-a_b.desktop"); let path = temp.path().join("rmcl-a_b.desktop");
std::fs::write(&path, build_content("a b", None)).unwrap(); std::fs::write(&path, build_content("a b", None, "/path with spaces/rmcl")).unwrap();
assert!(owns_legacy_shortcut(&path, "a b")); assert!(owns_legacy_shortcut(&path, "a b"));
assert!(!owns_legacy_shortcut(&path, "a_b")); assert!(!owns_legacy_shortcut(&path, "a_b"));
} }
@@ -34,9 +34,9 @@ fn legacy_shortcut_is_attributed_to_the_right_instance() {
#[test] #[test]
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn build_content_linux() { fn build_content_linux() {
let content = build_content("TestPack", None); let content = build_content("TestPack", None, "/path with spaces/rmcl");
assert!(content.contains("Name=Minecraft - TestPack")); assert!(content.contains("Name=Minecraft - TestPack"));
assert!(content.contains("Exec=rmcl instance launch \"TestPack\"")); assert!(content.contains("Exec=\"/path with spaces/rmcl\" instance launch \"TestPack\""));
assert!(content.contains("Terminal=false")); assert!(content.contains("Terminal=false"));
assert!(content.contains("Categories=Game;")); assert!(content.contains("Categories=Game;"));
} }
@@ -45,7 +45,7 @@ fn build_content_linux() {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn build_content_linux_with_icon() { fn build_content_linux_with_icon() {
let icon = PathBuf::from("/tmp/icon.png"); let icon = PathBuf::from("/tmp/icon.png");
let content = build_content("TestPack", Some(&icon)); let content = build_content("TestPack", Some(&icon), "/bin/rmcl");
assert!(content.contains("Icon=/tmp/icon.png")); assert!(content.contains("Icon=/tmp/icon.png"));
} }
@@ -53,11 +53,200 @@ fn build_content_linux_with_icon() {
fn shortcut_arguments_escape_platform_metacharacters() { fn shortcut_arguments_escape_platform_metacharacters() {
assert_eq!( assert_eq!(
quote_desktop_exec_arg("Pack \"$HOME`\\"), quote_desktop_exec_arg("Pack \"$HOME`\\"),
"\"Pack \\\"\\$HOME\\`\\\\\"" r#""Pack \\"\\$HOME\\`\\\\""#
); );
assert_eq!(quote_desktop_exec_arg("Pack%f %Z"), r#""Pack%%f %%Z""#);
assert_eq!(quote_shell_arg("Pack 'quoted'"), "'Pack '\\''quoted'\\'''"); assert_eq!(quote_shell_arg("Pack 'quoted'"), "'Pack '\\''quoted'\\'''");
assert_eq!( assert_eq!(
quote_windows_arg("Pack \\\"quoted"), quote_windows_arg("Pack \\\"quoted"),
"\"Pack \\\\\\\"quoted\"" "\"Pack \\\\\\\"quoted\""
); );
} }
#[test]
fn shortcuts_use_the_current_executable_and_literal_instance_arguments() {
let executable = "/path with spaces/rmcl";
let linux = build_linux_desktop("%USERNAME%", None, executable);
assert!(linux.contains("Exec=\"/path with spaces/rmcl\" instance launch \"%%USERNAME%%\""));
let macos = build_macos_command("%USERNAME%", executable);
assert!(macos.contains("'/path with spaces/rmcl' instance launch '%USERNAME%'"));
let windows = build_windows_shortcut("%USERNAME%", r"C:\path with spaces\rmcl.exe");
assert!(windows.contains("shell.ShellExecute \"C:\\path with spaces\\rmcl.exe\", \"instance launch \"\"%USERNAME%\"\"\""));
assert!(!windows.contains("shell.Run"));
}
#[test]
fn old_bare_executable_shortcuts_remain_owned() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("shortcut");
#[cfg(target_os = "linux")]
let content = "Exec=rmcl instance launch \"a b\"\n";
#[cfg(target_os = "macos")]
let content = "#!/bin/bash\nrmcl instance launch 'a b'\n";
#[cfg(target_os = "windows")]
let content = "shell.Run \"rmcl instance launch \"\"a b\"\"\", 0, False\r\n";
std::fs::write(&path, content).unwrap();
assert!(owns_legacy_shortcut(&path, "a b"));
assert!(!owns_legacy_shortcut(&path, "a_b"));
}
#[test]
fn unicode_windows_scripts_round_trip_and_keep_ownership() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("unicode.vbs");
let content = format!(
"{}\r\n{}",
shortcut_marker("世界"),
build_windows_shortcut("世界", r"C:\用户\rmcl.exe")
);
std::fs::write(&path, windows_script_bytes(&content)).unwrap();
assert_eq!(read_shortcut(&path).unwrap(), content);
assert!(owns_legacy_shortcut(&path, "世界"));
assert!(!owns_legacy_shortcut(&path, "other"));
}
#[cfg(windows)]
#[test]
fn windows_shortcut_execution_preserves_percent_expressions() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("literal.txt");
let powershell = PathBuf::from(std::env::var_os("SystemRoot").unwrap())
.join("System32/WindowsPowerShell/v1.0/powershell.exe");
let script = format!(
"[IO.File]::WriteAllText('{}', '%USERNAME% 世界')",
output.display().to_string().replace('\'', "''")
);
let arguments = format!(
"-NoProfile -NonInteractive -Command {}",
quote_windows_arg(&script)
);
let shortcut = temp.path().join("literal.vbs");
std::fs::write(
&shortcut,
windows_script_bytes(&windows_shell_execute(
powershell.to_str().unwrap(),
&arguments,
)),
)
.unwrap();
assert!(
std::process::Command::new("cscript.exe")
.arg("//Nologo")
.arg(&shortcut)
.status()
.unwrap()
.success()
);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !output.exists() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert_eq!(std::fs::read_to_string(output).unwrap(), "%USERNAME% 世界");
}
#[test]
fn case_only_shortcut_rename_preserves_current_and_legacy_ownership_on_aliasing_volumes() {
let temp = tempfile::tempdir().unwrap();
let old_path = temp.path().join("CasePack.shortcut");
let new_path = temp.path().join("casepack.shortcut");
let current = build_content(
"CasePack",
None,
std::env::current_exe().unwrap().to_str().unwrap(),
);
#[cfg(target_os = "linux")]
let legacy = "Exec=rmcl instance launch \"CasePack\"\n";
#[cfg(target_os = "macos")]
let legacy = "#!/bin/bash\nrmcl instance launch 'CasePack'\n";
#[cfg(target_os = "windows")]
let legacy = "shell.Run \"rmcl instance launch \"\"CasePack\"\"\", 0, False\r\n";
for content in [current.as_str(), legacy] {
#[cfg(windows)]
let original = windows_script_bytes(content);
#[cfg(not(windows))]
let original = content.as_bytes().to_vec();
std::fs::write(&old_path, &original).unwrap();
if !new_path.exists() {
assert!(
!rename_shortcut_alias(&old_path, &new_path, "CasePack", || panic!(
"Distinct paths are not aliases"
))
.unwrap()
);
eprintln!("case-insensitive shortcut branch skipped: test volume is case-sensitive");
return;
}
let failure = rename_shortcut_alias(&old_path, &new_path, "CasePack", || {
Err(std::io::Error::other("test write failure"))
});
assert!(failure.is_err());
assert_eq!(std::fs::read(&old_path).unwrap(), original);
assert!(owns_legacy_shortcut(&old_path, "CasePack"));
let updated = build_content(
"casepack",
None,
std::env::current_exe().unwrap().to_str().unwrap(),
);
#[cfg(windows)]
let bytes = windows_script_bytes(&updated);
#[cfg(not(windows))]
let bytes = updated.as_bytes().to_vec();
assert!(
rename_shortcut_alias(&old_path, &new_path, "CasePack", || {
crate::storage::write_atomic(&new_path, &bytes)
})
.unwrap()
);
assert!(owns_legacy_shortcut(&new_path, "casepack"));
assert!(!owns_legacy_shortcut(&old_path, "CasePack"));
assert!(
std::fs::read_dir(temp.path())
.unwrap()
.any(|entry| entry.unwrap().file_name() == "casepack.shortcut")
);
#[cfg(windows)]
assert!(std::fs::read(&new_path).unwrap().starts_with(&[0xff, 0xfe]));
std::fs::remove_file(&new_path).unwrap();
}
}
#[test]
fn disabled_or_foreign_shortcuts_are_not_enabled_by_alias_handling() {
let temp = tempfile::tempdir().unwrap();
let old = temp.path().join("CasePack.shortcut");
let new = temp.path().join("casepack.shortcut");
assert!(
!rename_shortcut_alias(&old, &new, "CasePack", || panic!(
"Disabled shortcut must stay disabled"
))
.unwrap()
);
assert!(!old.exists() && !new.exists());
std::fs::write(&old, build_content("other", None, "/launcher")).unwrap();
assert!(
!rename_shortcut_alias(&old, &new, "CasePack", || panic!(
"Foreign shortcut must stay untouched"
))
.unwrap()
);
assert!(owns_legacy_shortcut(&old, "other"));
}
#[test]
fn distinct_hard_link_shortcuts_are_not_case_aliases() {
let temp = tempfile::tempdir().unwrap();
let old = temp.path().join("source.shortcut");
let new = temp.path().join("destination.shortcut");
std::fs::write(&old, build_content("Pack", None, "/launcher")).unwrap();
if std::fs::hard_link(&old, &new).is_err() {
eprintln!("hard-link collision check skipped: test volume does not support hard links");
return;
}
assert!(
!rename_shortcut_alias(&old, &new, "Pack", || panic!(
"Distinct hard links are not aliases"
))
.unwrap()
);
assert!(owns_legacy_shortcut(&old, "Pack") && owns_legacy_shortcut(&new, "Pack"));
}
+115 -5
View File
@@ -80,7 +80,7 @@ fn detect_format_errors_on_missing_file() {
#[test] #[test]
fn unique_name_no_collision() { fn unique_name_no_collision() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let name = unique_instance_name("TestPack", tmp.path()); let name = unique_instance_name("TestPack", tmp.path()).unwrap();
assert_eq!(name, "TestPack"); assert_eq!(name, "TestPack");
} }
@@ -90,7 +90,7 @@ fn unique_name_with_collision() {
let dir = tmp.path().join("TestPack"); let dir = tmp.path().join("TestPack");
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("instance.json"), "{}").unwrap(); std::fs::write(dir.join("instance.json"), "{}").unwrap();
let name = unique_instance_name("TestPack", tmp.path()); let name = unique_instance_name("TestPack", tmp.path()).unwrap();
assert_eq!(name, "TestPack (2)"); assert_eq!(name, "TestPack (2)");
} }
@@ -99,7 +99,10 @@ fn unique_name_preserves_directory_without_config() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("TestPack")).unwrap(); std::fs::create_dir(tmp.path().join("TestPack")).unwrap();
assert_eq!(unique_instance_name("TestPack", tmp.path()), "TestPack (2)"); assert_eq!(
unique_instance_name("TestPack", tmp.path()).unwrap(),
"TestPack (2)"
);
assert!(tmp.path().join("TestPack").exists()); assert!(tmp.path().join("TestPack").exists());
} }
@@ -111,7 +114,7 @@ fn unique_name_multiple_collisions() {
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("instance.json"), "{}").unwrap(); std::fs::write(dir.join("instance.json"), "{}").unwrap();
} }
let name = unique_instance_name("TestPack", tmp.path()); let name = unique_instance_name("TestPack", tmp.path()).unwrap();
assert_eq!(name, "TestPack (4)"); assert_eq!(name, "TestPack (4)");
} }
@@ -123,7 +126,10 @@ fn unique_name_keeps_searching_after_ninety_nine_collisions() {
std::fs::create_dir(tmp.path().join(format!("Pack ({suffix})"))).unwrap(); std::fs::create_dir(tmp.path().join(format!("Pack ({suffix})"))).unwrap();
} }
std::fs::create_dir(tmp.path().join("Pack (import)")).unwrap(); std::fs::create_dir(tmp.path().join("Pack (import)")).unwrap();
assert_eq!(unique_instance_name("Pack", tmp.path()), "Pack (101)"); assert_eq!(
unique_instance_name("Pack", tmp.path()).unwrap(),
"Pack (101)"
);
} }
#[test] #[test]
@@ -185,6 +191,110 @@ fn parse_input_trims_whitespace() {
); );
} }
#[test]
fn windows_and_mixed_case_archive_inputs_stay_local() {
for input in [
r"C:\Downloads\Pack.ZIP",
r"c:extensionless",
r"C:/Downloads/Pack.MrPaCk",
r"\\server\share\Pack.ZIP",
r"\\server\share\extensionless",
r"\Downloads\extensionless",
r"\\?\C:\Downloads\Pack",
r".\extensionless",
"./extensionless",
"../extensionless",
"Pack.ZIP",
"Pack.MRPACK",
"~/Downloads/Pack.ZIP",
] {
assert_eq!(
parse_import_input(input),
ImportInput::LocalFile(input.to_owned()),
"{input}"
);
}
assert_eq!(
parse_import_input("https://modrinth.com/modpack/pack.zip"),
ImportInput::ProjectSlug("pack.zip".to_owned())
);
}
#[test]
fn imported_names_and_pack_paths_are_validated_before_joining() {
let temp = tempfile::tempdir().unwrap();
for name in ["C:victim", "CON.txt", "trailing.", "../escape"] {
assert!(unique_instance_name(name, temp.path()).is_err(), "{name}");
cleanup_failed_import(
&InstanceManager::new(temp.path(), temp.path().join("meta")),
name,
);
}
assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0);
std::fs::create_dir(temp.path().join("a".repeat(64))).unwrap();
assert!(unique_instance_name(&"a".repeat(64), temp.path()).is_err());
for path in [
"../escape",
"mods/../../escape",
"C:victim",
r"\\server\share\file",
"/absolute",
"mods/C:victim",
"mods/NUL.jar",
"mods/trailing. ",
"mods/./file",
"mods//file",
] {
assert!(portable_pack_path(path).is_err(), "{path}");
}
assert_eq!(
portable_pack_path(r"config\nested\pack.toml").unwrap(),
"config/nested/pack.toml"
);
assert_eq!(
portable_pack_path(".config/pack.toml").unwrap(),
".config/pack.toml"
);
}
#[tokio::test]
async fn format_import_entry_points_validate_names_before_opening_archives() {
let temp = tempfile::tempdir().unwrap();
let manager = InstanceManager::new(temp.path().join("instances"), temp.path().join("meta"));
let config = serde_json::from_value(serde_json::json!({
"name": "C:victim", "game_version": "1.21", "loader": "vanilla", "created": "2026-01-01T00:00:00Z"
})).unwrap();
let summary = ImportSummary {
name: "Pack".to_owned(),
pack_version: "1".to_owned(),
game_version: "1.21".to_owned(),
loader: crate::instance::ModLoader::Vanilla,
loader_version: None,
mod_count: 0,
override_count: 0,
format: PackFormat::Mrpack,
archive_path: temp.path().join("missing.zip"),
source: None,
};
for error in [
mrpack::execute_import(&summary, &manager, &config)
.await
.unwrap_err(),
curseforge::execute_import(&summary, &manager, &config)
.await
.unwrap_err(),
mmc::execute_import(&summary, &manager, &config)
.await
.unwrap_err(),
] {
assert!(
error.to_string().contains("Invalid instance name"),
"{error}"
);
}
assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0);
}
#[test] #[test]
fn failed_import_cleanup_removes_the_partial_instance() { fn failed_import_cleanup_removes_the_partial_instance() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
+25
View File
@@ -127,3 +127,28 @@ fn extract_mmc_archive_rejects_path_traversal() {
assert!(error.to_string().contains("archive path")); assert!(error.to_string().contains("archive path"));
assert!(!tmp.path().join("escaped.txt").exists()); assert!(!tmp.path().join("escaped.txt").exists());
} }
#[test]
fn mmc_extraction_rejects_windows_reserved_components_on_every_platform() {
use std::io::Write;
let temp = tempfile::tempdir().unwrap();
for entry in [
"Pack/.minecraft/config/NUL.txt",
"Pack/.minecraft/config/file:stream",
r"Pack/.minecraft/config\..\..\escaped.txt",
] {
let path = temp.path().join("pack.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
let options = zip::write::SimpleFileOptions::default();
zip.start_file("Pack/mmc-pack.json", options).unwrap();
zip.write_all(b"{}").unwrap();
zip.start_file(entry, options).unwrap();
zip.write_all(b"unsafe").unwrap();
zip.finish().unwrap();
assert!(
extract_mmc_archive(&path, &temp.path().join("minecraft")).is_err(),
"{entry}"
);
assert!(!temp.path().join("escaped.txt").exists());
}
}
+20 -1
View File
@@ -194,6 +194,25 @@ fn extraction_rejects_path_traversal() {
assert!(!tmp.path().join("escaped.txt").exists()); assert!(!tmp.path().join("escaped.txt").exists());
} }
#[test]
fn overrides_reject_windows_reserved_and_escaping_components_on_every_platform() {
let temp = tempfile::tempdir().unwrap();
for entry in [
"overrides/config/NUL.txt",
"overrides/config/file:stream",
"overrides/config/trailing.",
r"overrides/config\..\..\escaped.txt",
] {
let path = make_mrpack(temp.path(), &[(entry, b"unsafe")]);
assert!(owned_files(&path).is_err(), "{entry}");
assert!(
extract_overrides(&path, &temp.path().join("minecraft")).is_err(),
"{entry}"
);
assert!(!temp.path().join("escaped.txt").exists());
}
}
#[test] #[test]
fn mod_files_download_to_their_manifest_paths() { fn mod_files_download_to_their_manifest_paths() {
let _guard = crate::tests::TEST_LOCK let _guard = crate::tests::TEST_LOCK
@@ -383,7 +402,7 @@ fn mod_file_removes_downloads_with_invalid_metadata() {
#[test] #[test]
fn import_seeds_exact_modrinth_content_identity() { fn import_seeds_exact_modrinth_content_identity() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let paths = crate::storage::InstancePaths::new(tmp.path()); let paths = crate::storage::InstancePaths::new(tmp.path().join("Indexed"));
let relative_path = PathBuf::from("resourcepacks/example.zip"); let relative_path = PathBuf::from("resourcepacks/example.zip");
std::fs::create_dir_all(paths.minecraft().join("resourcepacks")).unwrap(); std::fs::create_dir_all(paths.minecraft().join("resourcepacks")).unwrap();
std::fs::write(paths.minecraft().join(&relative_path), b"resource pack").unwrap(); std::fs::write(paths.minecraft().join(&relative_path), b"resource pack").unwrap();
+327 -37
View File
@@ -5,9 +5,6 @@ use super::*;
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use tempfile::TempDir; use tempfile::TempDir;
// tmp owns the temp directory; its Drop impl cleans up everything when
// the test ends. the returned InstanceManager points at tmp.path() so
// tests can join("name") off of either to refer to the same locations.
fn test_manager() -> (InstanceManager, TempDir) { fn test_manager() -> (InstanceManager, TempDir) {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta"); let meta = tmp.path().join("meta");
@@ -55,6 +52,135 @@ fn validate_name_rejects_empty_traversal_and_hidden() {
assert!(validate_name("line\nbreak").is_err()); assert!(validate_name("line\nbreak").is_err());
} }
#[test]
fn instance_names_are_portable_components() {
for name in [
"C:victim",
"C:",
"a:b",
"CON",
"con.txt",
"CON .txt",
"AUX.jar",
"NUL",
"PRN",
"COM1",
"lpt9.log",
"COM¹",
"LPT².txt",
"CLOCK$",
"CONIN$",
"CONOUT$",
"trailing.",
"trailing ",
"bad?name",
"bad*name",
"bad\"name",
"bad<name",
"bad>name",
"bad|name",
r"path\name",
".",
"..",
] {
assert!(validate_name(name).is_err(), "{name}");
}
for name in ["CONifer", "COM0", "COM10", "世界", "%USERNAME%", "My Pack"] {
assert!(validate_name(name).is_ok(), "{name}");
}
}
#[tokio::test]
async fn all_manager_entry_points_reject_nonportable_names_before_io() {
let temp = tempfile::tempdir().unwrap();
let manager = InstanceManager::new(temp.path().join("instances"), temp.path().join("meta"));
for name in ["C:victim", "CON.txt", "trailing.", "bad?name"] {
let config = dummy_config(name);
assert!(matches!(
manager.create(name, "1.21", ModLoader::Vanilla, None).await,
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.repair_runtime_cache(&config).await,
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.delete(name),
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.rename(name, "safe"),
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.rename("safe", name),
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.load_one(name),
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.save(&config),
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.save_config_sync_profile(name, Some("shared".to_owned())),
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
manager.touch_last_played(name),
Err(InstanceError::InvalidName(_))
));
assert!(matches!(
crate::instance::runtime::lock_instance(&manager.instances_dir, name),
Err(InstanceError::InvalidName(_))
));
}
assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0);
}
#[cfg(windows)]
#[test]
fn drive_relative_deletion_preserves_an_external_directory() {
const ROOT: &str = "RMCL_NAME_BOUNDARY_ROOT";
if let Some(root) = std::env::var_os(ROOT) {
let cwd = std::env::current_dir().unwrap();
let std::path::Component::Prefix(prefix) = cwd.components().next().unwrap() else {
panic!("Expected a Windows drive");
};
let drive = match prefix.kind() {
std::path::Prefix::Disk(drive) | std::path::Prefix::VerbatimDisk(drive) => drive,
other => panic!("Expected a local drive, got {other:?}"),
};
let name = format!("{}:victim", char::from(drive));
let manager = InstanceManager::new(&root, cwd.join("meta"));
assert!(matches!(
manager.delete(&name),
Err(InstanceError::InvalidName(_))
));
assert_eq!(std::fs::read(cwd.join("victim/keep")).unwrap(), b"keep");
assert!(!cwd.join("victim.lock").exists());
return;
}
let temp = tempfile::tempdir().unwrap();
let cwd = temp.path().join("outside");
std::fs::create_dir_all(cwd.join("victim")).unwrap();
std::fs::write(cwd.join("victim/keep"), b"keep").unwrap();
let status = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"instance::manager::tests::drive_relative_deletion_preserves_an_external_directory",
"--nocapture",
])
.env(ROOT, temp.path().join("instances"))
.current_dir(&cwd)
.status()
.unwrap();
assert!(status.success());
assert_eq!(std::fs::read(cwd.join("victim/keep")).unwrap(), b"keep");
}
#[test] #[test]
fn delete_missing_instance_returns_not_found() { fn delete_missing_instance_returns_not_found() {
let (manager, _tmp) = test_manager(); let (manager, _tmp) = test_manager();
@@ -80,6 +206,51 @@ fn running_instance_cannot_be_deleted_or_renamed() {
assert!(!tmp.path().join("changed").exists()); assert!(!tmp.path().join("changed").exists());
} }
#[test]
fn instance_lock_child() {
use std::io::Write;
let Some(root) = std::env::var_os("RMCL_INSTANCE_LOCK_TEST") else {
return;
};
let _lock =
crate::instance::runtime::lock_instance(std::path::Path::new(&root), "locked").unwrap();
println!("LOCKED");
std::io::stdout().flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(10));
}
#[test]
fn another_process_protects_the_instance_from_mutation_and_duplicate_launch() {
use std::io::BufRead;
let (manager, temp) = test_manager();
std::fs::create_dir_all(temp.path().join("locked")).unwrap();
manager.save(&dummy_config("locked")).unwrap();
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"instance::manager::tests::instance_lock_child",
"--nocapture",
])
.env("RMCL_INSTANCE_LOCK_TEST", temp.path())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
let ready = std::io::BufReader::new(child.stdout.take().unwrap())
.lines()
.any(|line| line.unwrap() == "LOCKED");
let deletion = manager.delete("locked");
let rename = manager.rename("locked", "new");
let launch = crate::instance::runtime::lock_instance(&manager.instances_dir, "locked");
let _ = child.kill();
child.wait().unwrap();
assert!(ready);
assert!(matches!(deletion, Err(InstanceError::InstanceRunning(_))));
assert!(matches!(rename, Err(InstanceError::InstanceRunning(_))));
assert!(matches!(launch, Err(InstanceError::InstanceRunning(_))));
assert!(temp.path().join("locked").is_dir());
manager.delete("locked").unwrap();
}
#[test] #[test]
fn copied_instance_uses_its_directory_as_identity() { fn copied_instance_uses_its_directory_as_identity() {
let (manager, tmp) = test_manager(); let (manager, tmp) = test_manager();
@@ -101,6 +272,45 @@ fn copied_instance_uses_its_directory_as_identity() {
); );
} }
#[test]
fn configuration_locks_survive_instance_directory_replacement() {
let (manager, temp) = test_manager();
let name = "replaced";
std::fs::create_dir(temp.path().join(name)).unwrap();
manager.save(&dummy_config(name)).unwrap();
let held = manager.config_lock(name).unwrap();
std::fs::rename(temp.path().join(name), temp.path().join("backup")).unwrap();
std::fs::create_dir(temp.path().join(name)).unwrap();
let root = manager.instances_dir.clone();
let meta = manager.meta_dir.clone();
let (sender, receiver) = std::sync::mpsc::channel();
let contender = std::thread::spawn(move || {
let manager = InstanceManager::new(root, meta);
sender.send("attempting").unwrap();
let _held = manager.config_lock(name).unwrap();
sender.send("acquired").unwrap();
});
assert_eq!(
receiver
.recv_timeout(std::time::Duration::from_secs(5))
.unwrap(),
"attempting"
);
let while_locked = receiver.recv_timeout(std::time::Duration::from_millis(100));
drop(held);
assert!(matches!(
while_locked,
Err(std::sync::mpsc::RecvTimeoutError::Timeout)
));
assert_eq!(
receiver
.recv_timeout(std::time::Duration::from_secs(5))
.unwrap(),
"acquired"
);
contender.join().unwrap();
}
#[tokio::test] #[tokio::test]
async fn create_preserves_directory_without_instance_config() { async fn create_preserves_directory_without_instance_config() {
let (manager, tmp) = test_manager(); let (manager, tmp) = test_manager();
@@ -193,6 +403,54 @@ fn rename_moves_dir_and_updates_config_name() {
assert_eq!(reloaded.name, "new-name"); assert_eq!(reloaded.name, "new-name");
} }
#[test]
fn case_only_rename_uses_the_actual_volume_and_updates_directory_spelling() {
let (manager, temp) = test_manager();
let old = format!(
"CasePack-{}",
temp.path().file_name().unwrap().to_str().unwrap()
);
let new = old.to_lowercase();
std::fs::create_dir(temp.path().join(&old)).unwrap();
manager.save(&dummy_config(&old)).unwrap();
let aliases = temp.path().join(&new).exists();
assert_eq!(
paths_alias(&temp.path().join(&old), &temp.path().join(&new)).unwrap(),
aliases
);
manager.rename(&old, &new).unwrap();
let names: Vec<_> = std::fs::read_dir(temp.path())
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert!(names.iter().any(|name| name.to_str() == Some(new.as_str())));
assert!(!names.iter().any(|name| name.to_str() == Some(old.as_str())));
let raw: InstanceConfig = serde_json::from_slice(
&std::fs::read(temp.path().join(&new).join("instance.json")).unwrap(),
)
.unwrap();
assert_eq!(raw.name, new);
if !aliases {
std::fs::create_dir(temp.path().join(&old)).unwrap();
manager.save(&dummy_config(&old)).unwrap();
assert!(matches!(
manager.rename(&new, &old),
Err(InstanceError::AlreadyExists(_))
));
}
}
#[test]
fn temporary_rename_rolls_back_when_the_second_step_fails() {
let temp = tempfile::tempdir().unwrap();
let source = temp.path().join("Pack");
std::fs::create_dir(&source).unwrap();
std::fs::write(source.join("keep"), b"keep").unwrap();
assert!(rename_path(&source, &temp.path().join("missing/pack"), true).is_err());
assert_eq!(std::fs::read(source.join("keep")).unwrap(), b"keep");
assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
}
#[test] #[test]
fn rename_to_same_name_is_noop() { fn rename_to_same_name_is_noop() {
let (manager, tmp) = test_manager(); let (manager, tmp) = test_manager();
@@ -275,41 +533,73 @@ fn touch_last_played_updates_field() {
} }
#[test] #[test]
fn instance_names_are_portable_components() { fn ordinary_settings_saves_preserve_profile_selection_and_malformed_config() {
for name in [ let (manager, temp) = test_manager();
"C:victim", let name = "settings";
"C:", std::fs::create_dir(temp.path().join(name)).unwrap();
"a:b", let mut stale = dummy_config(name);
"CON", manager.save(&stale).unwrap();
"con.txt", manager
"CON .txt", .save_config_sync_profile(name, Some("shared".to_owned()))
"AUX.jar", .unwrap();
"NUL", stale.memory_max = Some("8G".to_owned());
"PRN", manager.save(&stale).unwrap();
"COM1", let current = manager.load_one(name).unwrap();
"lpt9.log", assert_eq!(current.config_sync_profile.as_deref(), Some("shared"));
"COM¹", assert_eq!(current.memory_max.as_deref(), Some("8G"));
"LPT².txt", let path = temp.path().join(name).join("instance.json");
"CLOCK$", std::fs::write(&path, b"invalid json").unwrap();
"CONIN$", assert!(matches!(manager.save(&stale), Err(InstanceError::Json(_))));
"CONOUT$", assert_eq!(std::fs::read(path).unwrap(), b"invalid json");
"trailing.", }
"trailing ",
"bad?name", #[test]
"bad*name", fn config_sync_profile_save_preserves_authoritative_settings_and_last_played() {
"bad\"name", let (manager, temp) = test_manager();
"bad<name", let name = "sync-profile";
"bad>name", let directory = temp.path().join(name);
"bad|name", std::fs::create_dir(&directory).unwrap();
r"path\name", manager.save(&dummy_config(name)).unwrap();
".", let staged = manager.load_one(name).unwrap();
"..",
] { let mut latest = staged.clone();
assert!(validate_name(name).is_err(), "{name}"); latest.config_sync_profile = Some("previous".to_owned());
} latest.memory_max = Some("8G".to_owned());
for name in ["CONifer", "COM0", "COM10", "世界", "%USERNAME%", "My Pack"] { latest.jvm_args.push("-Dlocal.setting=new".to_owned());
assert!(validate_name(name).is_ok(), "{name}"); latest
.environment
.insert("LOCAL_SETTING".to_owned(), "new".to_owned());
manager.save(&latest).unwrap();
manager
.save_config_sync_profile(name, latest.config_sync_profile.clone())
.unwrap();
manager.touch_last_played(name).unwrap();
let mut expected = manager.load_one(name).unwrap();
let before: serde_json::Value =
serde_json::from_slice(&std::fs::read(directory.join("instance.json")).unwrap()).unwrap();
for profile in [Some("shared".to_owned()), None] {
expected.config_sync_profile = profile.clone();
let saved = manager
.save_config_sync_profile(&staged.name, profile)
.unwrap();
assert_eq!(saved, expected);
assert_eq!(manager.load_one(name).unwrap(), expected);
let after: serde_json::Value =
serde_json::from_slice(&std::fs::read(directory.join("instance.json")).unwrap())
.unwrap();
assert_eq!(after["last_played"], before["last_played"]);
} }
std::fs::write(directory.join("instance.json"), b"invalid json").unwrap();
assert!(matches!(
manager.save_config_sync_profile(name, Some("shared".to_owned())),
Err(InstanceError::Json(_))
));
assert_eq!(
std::fs::read(directory.join("instance.json")).unwrap(),
b"invalid json"
);
} }
#[cfg(unix)] #[cfg(unix)]