fix(migration): harden layout transitions
This commit is contained in:
1 parent
8a2a562235
commit
c59228e1fd
7 files changed
+357
-100
No files matched your search
Generated
+11
@@ -1144,6 +1144,16 @@ dependencies = [
|
|||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fs2"
|
||||||
|
version = "0.4.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fsevent-sys"
|
name = "fsevent-sys"
|
||||||
version = "4.1.0"
|
version = "4.1.0"
|
||||||
@@ -3223,6 +3233,7 @@ dependencies = [
|
|||||||
"dirs",
|
"dirs",
|
||||||
"dirs-next",
|
"dirs-next",
|
||||||
"fast-strip-ansi",
|
"fast-strip-ansi",
|
||||||
|
"fs2",
|
||||||
"image",
|
"image",
|
||||||
"insta",
|
"insta",
|
||||||
"libcasr",
|
"libcasr",
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ notify = "8"
|
|||||||
regex = "1"
|
regex = "1"
|
||||||
fast-strip-ansi = "0.13"
|
fast-strip-ansi = "0.13"
|
||||||
libcasr = "2.13"
|
libcasr = "2.13"
|
||||||
|
fs2 = "0.4"
|
||||||
|
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
|
|||||||
+28
-16
@@ -298,29 +298,41 @@ impl InstanceManager {
|
|||||||
std::fs::create_dir_all(directory)?;
|
std::fs::create_dir_all(directory)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
|
|
||||||
let version_entry = manifest
|
|
||||||
.versions
|
|
||||||
.iter()
|
|
||||||
.find(|version| version.id == config.game_version)
|
|
||||||
.ok_or_else(|| {
|
|
||||||
InstanceError::InvalidName(format!(
|
|
||||||
"Minecraft version '{}' is no longer present in Mojang's manifest",
|
|
||||||
config.game_version
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
let (version_meta, raw_meta) =
|
|
||||||
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?;
|
|
||||||
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
|
|
||||||
.await?;
|
|
||||||
let meta_path = metadata_paths
|
let meta_path = metadata_paths
|
||||||
.versions()
|
.versions()
|
||||||
.join(&config.game_version)
|
.join(&config.game_version)
|
||||||
.join("meta.json");
|
.join("meta.json");
|
||||||
|
let (version_meta, raw_meta) = if meta_path.exists() {
|
||||||
|
let raw = std::fs::read(&meta_path)?;
|
||||||
|
let parsed = serde_json::from_slice(&raw).map_err(|error| {
|
||||||
|
InstanceError::InvalidName(format!(
|
||||||
|
"Cached metadata for Minecraft {} is invalid: {error}",
|
||||||
|
config.game_version
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
(parsed, raw)
|
||||||
|
} else {
|
||||||
|
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
|
||||||
|
let version_entry = manifest
|
||||||
|
.versions
|
||||||
|
.iter()
|
||||||
|
.find(|version| version.id == config.game_version)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
InstanceError::InvalidName(format!(
|
||||||
|
"Minecraft version '{}' is no longer present in Mojang's manifest",
|
||||||
|
config.game_version
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?
|
||||||
|
};
|
||||||
|
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
|
||||||
|
.await?;
|
||||||
if let Some(parent) = meta_path.parent() {
|
if let Some(parent) = meta_path.parent() {
|
||||||
std::fs::create_dir_all(parent)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
std::fs::write(meta_path, raw_meta)?;
|
if !meta_path.exists() {
|
||||||
|
crate::storage::write_atomic(&meta_path, &raw_meta)?;
|
||||||
|
}
|
||||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||||
|
|
||||||
|
|||||||
+195
-26
@@ -69,6 +69,14 @@ pub enum MigrationError {
|
|||||||
old: String,
|
old: String,
|
||||||
new: String,
|
new: String,
|
||||||
},
|
},
|
||||||
|
#[error("Cannot merge migration data because both paths contain {path}")]
|
||||||
|
MergeConflict { path: String },
|
||||||
|
#[error("Migration backup would be created inside the data being backed up: {0}")]
|
||||||
|
BackupOverlap(String),
|
||||||
|
#[error(
|
||||||
|
"Not enough free space for migration backup: need {required} bytes, have {available} bytes"
|
||||||
|
)]
|
||||||
|
InsufficientSpace { required: u64, available: u64 },
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool {
|
pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool {
|
||||||
@@ -165,6 +173,8 @@ pub fn run(
|
|||||||
current += 1;
|
current += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
validate_migration_conflicts(&instances, meta_dir)?;
|
||||||
|
|
||||||
for instance in &instances {
|
for instance in &instances {
|
||||||
let name = instance
|
let name = instance
|
||||||
.file_name()
|
.file_name()
|
||||||
@@ -297,38 +307,157 @@ fn backup_user_data(
|
|||||||
backup_dir: &Path,
|
backup_dir: &Path,
|
||||||
mut report: impl FnMut(u64, u64, &Path),
|
mut report: impl FnMut(u64, u64, &Path),
|
||||||
) -> Result<(), MigrationError> {
|
) -> Result<(), MigrationError> {
|
||||||
let profiles = meta_dir.join("config-sync").join("profiles");
|
if backup_dir.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let legacy_profiles = meta_dir.join("config-sync").join("profiles");
|
||||||
|
let current_profiles = MetadataPaths::new(meta_dir).profiles();
|
||||||
let total = tree_size(instances_dir)?
|
let total = tree_size(instances_dir)?
|
||||||
.saturating_add(file_size(config_file)?)
|
.saturating_add(file_size(config_file)?)
|
||||||
.saturating_add(tree_size(&profiles)?);
|
.saturating_add(tree_size(&legacy_profiles)?)
|
||||||
|
.saturating_add(tree_size(¤t_profiles)?);
|
||||||
|
validate_backup_destination(instances_dir, backup_dir, total)?;
|
||||||
|
let partial = backup_dir.with_extension("partial");
|
||||||
|
if partial.exists() {
|
||||||
|
fs::remove_dir_all(&partial)?;
|
||||||
|
}
|
||||||
let mut copied = 0;
|
let mut copied = 0;
|
||||||
report(copied, total, instances_dir);
|
report(copied, total, instances_dir);
|
||||||
fs::create_dir_all(backup_dir)?;
|
fs::create_dir_all(&partial)?;
|
||||||
copy_dir_recursive_with_progress(
|
copy_dir_recursive_with_progress(
|
||||||
instances_dir,
|
instances_dir,
|
||||||
&backup_dir.join("instances"),
|
&partial.join("instances"),
|
||||||
&mut |bytes, path| {
|
&mut |bytes, path| {
|
||||||
copied = copied.saturating_add(bytes);
|
copied = copied.saturating_add(bytes);
|
||||||
report(copied, total, path);
|
report(copied, total, path);
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
if config_file.exists() {
|
if config_file.exists() {
|
||||||
let destination = backup_dir.join("config").join("config.toml");
|
let destination = partial.join("config").join("config.toml");
|
||||||
fs::create_dir_all(destination.parent().unwrap())?;
|
fs::create_dir_all(destination.parent().unwrap())?;
|
||||||
let bytes = fs::copy(config_file, destination)?;
|
let bytes = fs::copy(config_file, destination)?;
|
||||||
copied = copied.saturating_add(bytes);
|
copied = copied.saturating_add(bytes);
|
||||||
report(copied, total, config_file);
|
report(copied, total, config_file);
|
||||||
}
|
}
|
||||||
if profiles.exists() {
|
if legacy_profiles.exists() {
|
||||||
copy_dir_recursive_with_progress(
|
copy_dir_recursive_with_progress(
|
||||||
&profiles,
|
&legacy_profiles,
|
||||||
&backup_dir.join("profiles"),
|
&partial.join("profiles/legacy"),
|
||||||
&mut |bytes, path| {
|
&mut |bytes, path| {
|
||||||
copied = copied.saturating_add(bytes);
|
copied = copied.saturating_add(bytes);
|
||||||
report(copied, total, path);
|
report(copied, total, path);
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
if current_profiles.exists() {
|
||||||
|
copy_dir_recursive_with_progress(
|
||||||
|
¤t_profiles,
|
||||||
|
&partial.join("profiles/current"),
|
||||||
|
&mut |bytes, path| {
|
||||||
|
copied = copied.saturating_add(bytes);
|
||||||
|
report(copied, total, path);
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
fs::rename(partial, backup_dir)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_migration_conflicts(
|
||||||
|
instances: &[PathBuf],
|
||||||
|
meta_dir: &Path,
|
||||||
|
) -> Result<(), MigrationError> {
|
||||||
|
for instance in instances {
|
||||||
|
let name = instance
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or("instance");
|
||||||
|
let paths = InstancePaths::new(instance);
|
||||||
|
for (legacy, destination) in [
|
||||||
|
(instance.join(LEGACY_MINECRAFT), paths.minecraft()),
|
||||||
|
(instance.join(LEGACY_STATE), paths.state()),
|
||||||
|
] {
|
||||||
|
if legacy.exists() && destination.exists() {
|
||||||
|
return Err(MigrationError::PathConflict {
|
||||||
|
instance: name.to_owned(),
|
||||||
|
old: legacy.display().to_string(),
|
||||||
|
new: destination.display().to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validate_merge(
|
||||||
|
&paths.state().join("config-sync").join("local-config"),
|
||||||
|
&paths.local_config(),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
let metadata = MetadataPaths::new(meta_dir);
|
||||||
|
for (source, destination) in [
|
||||||
|
(
|
||||||
|
meta_dir.join("config-sync").join("profiles"),
|
||||||
|
metadata.profiles(),
|
||||||
|
),
|
||||||
|
(meta_dir.join("versions"), metadata.versions()),
|
||||||
|
(meta_dir.join("libraries"), metadata.libraries()),
|
||||||
|
(meta_dir.join("assets"), metadata.assets()),
|
||||||
|
(meta_dir.join("loader-profiles"), metadata.loader_profiles()),
|
||||||
|
] {
|
||||||
|
validate_merge(&source, &destination)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_merge(source: &Path, destination: &Path) -> Result<(), MigrationError> {
|
||||||
|
if !source.exists() || !destination.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
for entry in fs::read_dir(source)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let target = destination.join(entry.file_name());
|
||||||
|
if !target.exists() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if entry.file_type()?.is_dir() && target.is_dir() {
|
||||||
|
validate_merge(&entry.path(), &target)?;
|
||||||
|
} else {
|
||||||
|
return Err(MigrationError::MergeConflict {
|
||||||
|
path: target.display().to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_backup_destination(
|
||||||
|
instances_dir: &Path,
|
||||||
|
backup_dir: &Path,
|
||||||
|
required: u64,
|
||||||
|
) -> Result<(), MigrationError> {
|
||||||
|
let instances = instances_dir.canonicalize()?;
|
||||||
|
let backup_parent = backup_dir
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "backup has no parent"))?;
|
||||||
|
fs::create_dir_all(backup_parent)?;
|
||||||
|
let backup_parent = backup_parent.canonicalize()?;
|
||||||
|
let backup_name = backup_dir
|
||||||
|
.file_name()
|
||||||
|
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "backup has no name"))?;
|
||||||
|
let canonical_backup = backup_parent.join(backup_name);
|
||||||
|
if canonical_backup.starts_with(&instances) {
|
||||||
|
return Err(MigrationError::BackupOverlap(
|
||||||
|
canonical_backup.display().to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let available = fs2::available_space(&backup_parent)?;
|
||||||
|
let margin = required / 20;
|
||||||
|
let required_with_margin = required
|
||||||
|
.saturating_add(margin)
|
||||||
|
.saturating_add(16 * 1024 * 1024);
|
||||||
|
if available < required_with_margin {
|
||||||
|
return Err(MigrationError::InsufficientSpace {
|
||||||
|
required: required_with_margin,
|
||||||
|
available,
|
||||||
|
});
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,13 +497,29 @@ fn move_or_merge(source: &Path, destination: &Path) -> Result<(), MigrationError
|
|||||||
fs::rename(source, destination)?;
|
fs::rename(source, destination)?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
copy_dir_recursive(source, destination)?;
|
merge_dir_without_overwrite(source, destination)?;
|
||||||
fs::remove_dir_all(source)?;
|
fs::remove_dir_all(source)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn copy_dir_recursive(source: &Path, destination: &Path) -> io::Result<()> {
|
fn merge_dir_without_overwrite(source: &Path, destination: &Path) -> Result<(), MigrationError> {
|
||||||
copy_dir_recursive_with_progress(source, destination, &mut |_, _| {})
|
fs::create_dir_all(destination)?;
|
||||||
|
for entry in fs::read_dir(source)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let target = destination.join(entry.file_name());
|
||||||
|
let file_type = entry.file_type()?;
|
||||||
|
if !target.exists() {
|
||||||
|
fs::rename(entry.path(), target)?;
|
||||||
|
} else if file_type.is_dir() && target.is_dir() {
|
||||||
|
merge_dir_without_overwrite(&entry.path(), &target)?;
|
||||||
|
fs::remove_dir(entry.path())?;
|
||||||
|
} else {
|
||||||
|
return Err(MigrationError::MergeConflict {
|
||||||
|
path: target.display().to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn copy_dir_recursive_with_progress(
|
fn copy_dir_recursive_with_progress(
|
||||||
@@ -419,15 +564,22 @@ fn load_or_create_journal(
|
|||||||
_instances_dir: &Path,
|
_instances_dir: &Path,
|
||||||
metadata: &MetadataPaths,
|
metadata: &MetadataPaths,
|
||||||
) -> Result<MigrationJournal, MigrationError> {
|
) -> Result<MigrationJournal, MigrationError> {
|
||||||
|
let legacy_journal = metadata.state().join("migration-v2.json");
|
||||||
if metadata.migration_journal().exists() {
|
if metadata.migration_journal().exists() {
|
||||||
return Ok(serde_json::from_slice(&fs::read(
|
return Ok(serde_json::from_slice(&fs::read(
|
||||||
metadata.migration_journal(),
|
metadata.migration_journal(),
|
||||||
)?)?);
|
)?)?);
|
||||||
}
|
}
|
||||||
|
if legacy_journal.exists() {
|
||||||
|
let journal = serde_json::from_slice(&fs::read(&legacy_journal)?)?;
|
||||||
|
write_json_atomic(&metadata.migration_journal(), &journal)?;
|
||||||
|
fs::remove_file(legacy_journal)?;
|
||||||
|
return Ok(journal);
|
||||||
|
}
|
||||||
let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();
|
let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();
|
||||||
let journal = MigrationJournal {
|
let journal = MigrationJournal {
|
||||||
version: LAYOUT_VERSION,
|
version: LAYOUT_VERSION,
|
||||||
backup_dir: metadata.backups().join(format!("layout-v2-{timestamp}")),
|
backup_dir: metadata.backups().join(format!("backup-{timestamp}")),
|
||||||
completed: Vec::new(),
|
completed: Vec::new(),
|
||||||
};
|
};
|
||||||
write_json_atomic(&metadata.migration_journal(), &journal)?;
|
write_json_atomic(&metadata.migration_journal(), &journal)?;
|
||||||
@@ -441,7 +593,8 @@ fn latest_layout_backup(metadata: &MetadataPaths) -> Option<PathBuf> {
|
|||||||
.filter_map(|entry| {
|
.filter_map(|entry| {
|
||||||
let file_type = entry.file_type().ok()?;
|
let file_type = entry.file_type().ok()?;
|
||||||
let name = entry.file_name();
|
let name = entry.file_name();
|
||||||
(file_type.is_dir() && name.to_string_lossy().starts_with("layout-v2-"))
|
let name = name.to_string_lossy();
|
||||||
|
(file_type.is_dir() && (name.starts_with("backup-") || name.starts_with("layout-v2-")))
|
||||||
.then(|| entry.path())
|
.then(|| entry.path())
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@@ -486,18 +639,7 @@ fn marker_version(path: &Path) -> Option<u32> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn write_json_atomic(path: &Path, value: &impl Serialize) -> Result<(), MigrationError> {
|
fn write_json_atomic(path: &Path, value: &impl Serialize) -> Result<(), MigrationError> {
|
||||||
let parent = path
|
crate::storage::write_atomic(path, &serde_json::to_vec_pretty(value)?)?;
|
||||||
.parent()
|
|
||||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
|
|
||||||
fs::create_dir_all(parent)?;
|
|
||||||
let temporary = parent.join(format!(
|
|
||||||
".{}.tmp",
|
|
||||||
path.file_name()
|
|
||||||
.and_then(|name| name.to_str())
|
|
||||||
.unwrap_or("state")
|
|
||||||
));
|
|
||||||
fs::write(&temporary, serde_json::to_vec_pretty(value)?)?;
|
|
||||||
fs::rename(temporary, path)?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -540,7 +682,14 @@ mod tests {
|
|||||||
b"options"
|
b"options"
|
||||||
);
|
);
|
||||||
assert!(backup.join("instances/Example/.minecraft").exists());
|
assert!(backup.join("instances/Example/.minecraft").exists());
|
||||||
assert!(backup.join("profiles/main/options.txt").exists());
|
assert!(backup.join("profiles/legacy/main/options.txt").exists());
|
||||||
|
assert!(
|
||||||
|
backup
|
||||||
|
.file_name()
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.starts_with("backup-")
|
||||||
|
);
|
||||||
assert!(!meta.join("config-sync").exists());
|
assert!(!meta.join("config-sync").exists());
|
||||||
assert!(progress.iter().any(|update| {
|
assert!(progress.iter().any(|update| {
|
||||||
update.item_total.is_some_and(|total| total > 0)
|
update.item_total.is_some_and(|total| total > 0)
|
||||||
@@ -565,4 +714,24 @@ mod tests {
|
|||||||
let error = migrate_instance(&instance, "Example").unwrap_err();
|
let error = migrate_instance(&instance, "Example").unwrap_err();
|
||||||
assert!(matches!(error, MigrationError::PathConflict { .. }));
|
assert!(matches!(error, MigrationError::PathConflict { .. }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merge_conflicts_do_not_overwrite_existing_profiles() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let source = temp.path().join("legacy");
|
||||||
|
let destination = temp.path().join("current");
|
||||||
|
fs::create_dir_all(&source).unwrap();
|
||||||
|
fs::create_dir_all(&destination).unwrap();
|
||||||
|
fs::write(source.join("options.txt"), b"legacy").unwrap();
|
||||||
|
fs::write(destination.join("options.txt"), b"current").unwrap();
|
||||||
|
|
||||||
|
let error = move_or_merge(&source, &destination).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(error, MigrationError::MergeConflict { .. }));
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(destination.join("options.txt")).unwrap(),
|
||||||
|
b"current"
|
||||||
|
);
|
||||||
|
assert_eq!(fs::read(source.join("options.txt")).unwrap(), b"legacy");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+20
-17
@@ -266,26 +266,28 @@ pub async fn download_assets_from(
|
|||||||
assets_base: &str,
|
assets_base: &str,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
set_action("Downloading assets...");
|
set_action("Downloading assets...");
|
||||||
tracing::debug!(
|
|
||||||
"Fetching asset index {} from {}",
|
|
||||||
meta.asset_index.id,
|
|
||||||
meta.asset_index.url
|
|
||||||
);
|
|
||||||
|
|
||||||
let asset_index: AssetIndexContent = match client.get_json(&meta.asset_index.url).await {
|
|
||||||
Ok(index) => index,
|
|
||||||
Err(e) => {
|
|
||||||
clear();
|
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let index_path = crate::storage::MetadataPaths::new(meta_dir)
|
let index_path = crate::storage::MetadataPaths::new(meta_dir)
|
||||||
.assets()
|
.assets()
|
||||||
.join("indexes")
|
.join("indexes")
|
||||||
.join(format!("{}.json", meta.asset_index.id));
|
.join(format!("{}.json", meta.asset_index.id));
|
||||||
if !index_path.exists() {
|
let asset_index: AssetIndexContent = if index_path.exists() {
|
||||||
match serde_json::to_string(&asset_index) {
|
let bytes = tokio::fs::read(&index_path).await?;
|
||||||
|
serde_json::from_slice(&bytes)
|
||||||
|
.map_err(|error| NetError::Parse(format!("Invalid cached asset index: {error}")))?
|
||||||
|
} else {
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetching asset index {} from {}",
|
||||||
|
meta.asset_index.id,
|
||||||
|
meta.asset_index.url
|
||||||
|
);
|
||||||
|
let index = match client.get_json(&meta.asset_index.url).await {
|
||||||
|
Ok(index) => index,
|
||||||
|
Err(e) => {
|
||||||
|
clear();
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match serde_json::to_string(&index) {
|
||||||
Ok(json) => {
|
Ok(json) => {
|
||||||
if let Some(parent) = index_path.parent() {
|
if let Some(parent) = index_path.parent() {
|
||||||
match tokio::fs::create_dir_all(parent).await {
|
match tokio::fs::create_dir_all(parent).await {
|
||||||
@@ -312,7 +314,8 @@ pub async fn download_assets_from(
|
|||||||
tracing::debug!("Failed to serialize asset index: {}", e);
|
tracing::debug!("Failed to serialize asset index: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
index
|
||||||
|
};
|
||||||
|
|
||||||
// assets are stored by hash with the first 2 chars as a directory prefix,
|
// assets are stored by hash with the first 2 chars as a directory prefix,
|
||||||
// e.g. "ab/ab1234..." - same layout mojang uses on their CDN
|
// e.g. "ab/ab1234..." - same layout mojang uses on their CDN
|
||||||
|
|||||||
+66
-1
@@ -1,4 +1,8 @@
|
|||||||
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
|
||||||
|
static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1);
|
||||||
|
|
||||||
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
|
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
|
||||||
pub const INSTANCE_STATE_DIR_NAME: &str = "rmcl";
|
pub const INSTANCE_STATE_DIR_NAME: &str = "rmcl";
|
||||||
@@ -114,7 +118,7 @@ impl MetadataPaths {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn migration_journal(&self) -> PathBuf {
|
pub fn migration_journal(&self) -> PathBuf {
|
||||||
self.state().join("migration-v2.json")
|
self.state().join("migration.json")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn cache_rebuild_pending(&self) -> PathBuf {
|
pub fn cache_rebuild_pending(&self) -> PathBuf {
|
||||||
@@ -122,6 +126,54 @@ impl MetadataPaths {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||||
|
let parent = path
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let name = path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or("data");
|
||||||
|
let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id));
|
||||||
|
let result = (|| {
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
let mut file = std::fs::OpenOptions::new()
|
||||||
|
.create_new(true)
|
||||||
|
.write(true)
|
||||||
|
.open(&temporary)?;
|
||||||
|
file.write_all(bytes)?;
|
||||||
|
file.sync_all()?;
|
||||||
|
replace_file(&temporary, path)
|
||||||
|
})();
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = std::fs::remove_file(&temporary);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
|
||||||
|
std::fs::rename(source, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
|
||||||
|
if !destination.exists() {
|
||||||
|
return std::fs::rename(source, destination);
|
||||||
|
}
|
||||||
|
let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let backup = destination.with_extension(format!("rmcl-replaced-{id}"));
|
||||||
|
std::fs::rename(destination, &backup)?;
|
||||||
|
if let Err(error) = std::fs::rename(source, destination) {
|
||||||
|
let _ = std::fs::rename(&backup, destination);
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
std::fs::remove_file(backup)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -155,5 +207,18 @@ mod tests {
|
|||||||
paths.versions(),
|
paths.versions(),
|
||||||
PathBuf::from("/meta/cache/minecraft/versions")
|
PathBuf::from("/meta/cache/minecraft/versions")
|
||||||
);
|
);
|
||||||
|
assert_eq!(
|
||||||
|
paths.migration_journal(),
|
||||||
|
PathBuf::from("/meta/state/migration.json")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn atomic_write_replaces_existing_file() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("state.json");
|
||||||
|
std::fs::write(&path, b"old").unwrap();
|
||||||
|
write_atomic(&path, b"new").unwrap();
|
||||||
|
assert_eq!(std::fs::read(path).unwrap(), b"new");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+36
-40
@@ -47,49 +47,45 @@ pub async fn show() -> color_eyre::Result<()> {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
// figure out the terminal's font cell size for rendering images.
|
let result = async {
|
||||||
// falls back to halfblock characters if the terminal doesn't respond
|
// figure out the terminal's font cell size for rendering images.
|
||||||
let mut picker = ratatui_image::picker::Picker::from_query_stdio()
|
// falls back to halfblock characters if the terminal doesn't respond
|
||||||
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
|
let mut picker = ratatui_image::picker::Picker::from_query_stdio()
|
||||||
let detected_protocol = picker.protocol_type();
|
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
|
||||||
let requested_protocol = match crate::config::SETTINGS.ui.image_protocol {
|
let detected_protocol = picker.protocol_type();
|
||||||
crate::config::settings::ImageProtocol::Halfblocks
|
let requested_protocol = match crate::config::SETTINGS.ui.image_protocol {
|
||||||
| crate::config::settings::ImageProtocol::Quadrants => {
|
crate::config::settings::ImageProtocol::Halfblocks
|
||||||
ratatui_image::picker::ProtocolType::Halfblocks
|
| crate::config::settings::ImageProtocol::Quadrants => {
|
||||||
}
|
ratatui_image::picker::ProtocolType::Halfblocks
|
||||||
crate::config::settings::ImageProtocol::Kitty
|
}
|
||||||
if detected_protocol == ratatui_image::picker::ProtocolType::Kitty =>
|
crate::config::settings::ImageProtocol::Kitty
|
||||||
{
|
if detected_protocol == ratatui_image::picker::ProtocolType::Kitty =>
|
||||||
ratatui_image::picker::ProtocolType::Kitty
|
{
|
||||||
}
|
ratatui_image::picker::ProtocolType::Kitty
|
||||||
crate::config::settings::ImageProtocol::Iterm2
|
}
|
||||||
if detected_protocol == ratatui_image::picker::ProtocolType::Iterm2 =>
|
crate::config::settings::ImageProtocol::Iterm2
|
||||||
{
|
if detected_protocol == ratatui_image::picker::ProtocolType::Iterm2 =>
|
||||||
ratatui_image::picker::ProtocolType::Iterm2
|
{
|
||||||
}
|
ratatui_image::picker::ProtocolType::Iterm2
|
||||||
_ => ratatui_image::picker::ProtocolType::Halfblocks,
|
}
|
||||||
};
|
_ => ratatui_image::picker::ProtocolType::Halfblocks,
|
||||||
picker.set_protocol_type(requested_protocol);
|
};
|
||||||
|
picker.set_protocol_type(requested_protocol);
|
||||||
|
|
||||||
let mut app = app::App::new(picker);
|
let mut app = app::App::new(picker);
|
||||||
match run_layout_migration_screen(&mut terminal, &mut app).await? {
|
match run_layout_migration_screen(&mut terminal, &mut app).await? {
|
||||||
MigrationScreenOutcome::NotNeeded => {}
|
MigrationScreenOutcome::NotNeeded => {}
|
||||||
MigrationScreenOutcome::Migrated => {
|
MigrationScreenOutcome::Migrated => {
|
||||||
// the modal uses pre-migration state as its background. rebuild the
|
// the modal uses pre-migration state as its background. rebuild the
|
||||||
// app after confirmation so no instance or profile data stays stale
|
// app after confirmation so no instance or profile data stays stale
|
||||||
let picker = app.into_picker();
|
let picker = app.into_picker();
|
||||||
app = app::App::new(picker);
|
app = app::App::new(picker);
|
||||||
}
|
}
|
||||||
MigrationScreenOutcome::Quit => {
|
MigrationScreenOutcome::Quit => return Ok(()),
|
||||||
let _ = crossterm::execute!(
|
|
||||||
std::io::stdout(),
|
|
||||||
crossterm::event::PopKeyboardEnhancementFlags
|
|
||||||
);
|
|
||||||
ratatui::restore();
|
|
||||||
return Ok(());
|
|
||||||
}
|
}
|
||||||
|
app.run(&mut terminal).await
|
||||||
}
|
}
|
||||||
let result = app.run(&mut terminal).await;
|
.await;
|
||||||
|
|
||||||
let _ = crossterm::execute!(
|
let _ = crossterm::execute!(
|
||||||
std::io::stdout(),
|
std::io::stdout(),
|
||||||
|
|||||||
Reference in new issue
Block a user