fix: guard content commits and settle dependency constraints
This commit is contained in:
1 parent
00ba2faffe
commit
eb53c7164e
17 files changed
+2985
-503
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -60,16 +60,5 @@ pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_entry_path(entry: &ContentEntry) -> Result<Option<PathBuf>, std::io::Error> {
|
||||
let Some(file_name) = entry.path.file_name().and_then(|name| name.to_str()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let new_name = if entry.enabled {
|
||||
format!("{file_name}.disabled")
|
||||
} else {
|
||||
file_name.trim_end_matches(".disabled").to_owned()
|
||||
};
|
||||
let mut new_path = entry.path.clone();
|
||||
new_path.set_file_name(new_name);
|
||||
std::fs::rename(&entry.path, &new_path)?;
|
||||
Ok(Some(new_path))
|
||||
super::local::toggle(entry)
|
||||
}
|
||||
@@ -42,7 +42,7 @@ pub(crate) fn make_icon_pixels_from_image(
|
||||
let [tr, tg, tb] = rgb.get_pixel(u32::from(column), top_y).0;
|
||||
let [br, bg, bb] = rgb.get_pixel(u32::from(column), bottom_y).0;
|
||||
columns.push(IconCell {
|
||||
symbol: '\u{2584}',
|
||||
symbol: '\u{2580}',
|
||||
bg_r: br,
|
||||
bg_g: bg,
|
||||
bg_b: bb,
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::entry::ContentEntry;
|
||||
use super::manifest::{
|
||||
ContentFileRecord, ContentLock, ContentManifest, FileFingerprint, fingerprint,
|
||||
fingerprint_metadata,
|
||||
};
|
||||
|
||||
pub(crate) struct StagingDirectory {
|
||||
path: PathBuf,
|
||||
retained: bool,
|
||||
}
|
||||
|
||||
impl StagingDirectory {
|
||||
pub(crate) fn new(minecraft_dir: &Path) -> io::Result<Self> {
|
||||
std::fs::create_dir_all(minecraft_dir)?;
|
||||
Ok(Self {
|
||||
path: tempfile::Builder::new()
|
||||
.prefix(".rmcl-install-")
|
||||
.tempdir_in(minecraft_dir)?
|
||||
.keep(),
|
||||
retained: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StagingDirectory {
|
||||
fn drop(&mut self) {
|
||||
if !self.retained
|
||||
&& !std::thread::panicking()
|
||||
&& let Err(error) = std::fs::remove_dir_all(&self.path)
|
||||
&& error.kind() != io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!(
|
||||
"Could not remove content staging '{}': {error}",
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FileTransaction {
|
||||
staging: StagingDirectory,
|
||||
moves: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
impl FileTransaction {
|
||||
pub(crate) fn new(staging: StagingDirectory) -> Self {
|
||||
Self {
|
||||
staging,
|
||||
moves: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn staging(&self) -> &Path {
|
||||
self.staging.path()
|
||||
}
|
||||
|
||||
pub(crate) fn move_path(&mut self, from: &Path, to: &Path) -> io::Result<()> {
|
||||
require_absent(to)?;
|
||||
std::fs::rename(from, to)?;
|
||||
self.moves.push((from.to_owned(), to.to_owned()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn finish<T, E: From<io::Error> + std::fmt::Display>(
|
||||
&mut self,
|
||||
result: Result<T, E>,
|
||||
) -> Result<T, E> {
|
||||
match result {
|
||||
Ok(value) => {
|
||||
self.moves.clear();
|
||||
Ok(value)
|
||||
}
|
||||
Err(error) => match self.rollback() {
|
||||
Ok(()) => Err(error),
|
||||
Err(rollback) => Err(io::Error::other(format!("{error}; {rollback}")).into()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn rollback(&mut self) -> io::Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for (from, to) in self.moves.iter().rev() {
|
||||
if let Err(error) = require_absent(from).and_then(|()| std::fs::rename(to, from)) {
|
||||
errors.push(format!(
|
||||
"restore '{}' from '{}': {error}",
|
||||
from.display(),
|
||||
to.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
self.moves.clear();
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
self.staging.retained = true;
|
||||
Err(io::Error::other(format!(
|
||||
"Content rollback failed: {}; recovery staging retained at '{}'",
|
||||
errors.join("; "),
|
||||
self.staging.path.display()
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FileTransaction {
|
||||
fn drop(&mut self) {
|
||||
if !self.moves.is_empty()
|
||||
&& let Err(error) = self.rollback()
|
||||
{
|
||||
tracing::error!("{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn require_absent(path: &Path) -> io::Result<()> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(_) => Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
format!("'{}' already exists", path.display()),
|
||||
)),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn relative_path(minecraft_dir: &Path, path: &Path) -> io::Result<PathBuf> {
|
||||
let relative = path.strip_prefix(minecraft_dir).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("'{}' is outside the Minecraft directory", path.display()),
|
||||
)
|
||||
})?;
|
||||
if !crate::storage::safe_relative_path(relative) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("Invalid content path '{}'", path.display()),
|
||||
));
|
||||
}
|
||||
let root = minecraft_dir.canonicalize()?;
|
||||
let mut parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("Content path has no parent"))?;
|
||||
loop {
|
||||
match parent.canonicalize() {
|
||||
Ok(parent) if parent.starts_with(&root) => break,
|
||||
Ok(_) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"Content path '{}' escapes through a symlink",
|
||||
path.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
parent = parent.parent().ok_or(error)?;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(relative.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_record(minecraft_dir: &Path, record: &ContentFileRecord) -> io::Result<()> {
|
||||
let path = minecraft_dir.join(&record.relative_path);
|
||||
relative_path(minecraft_dir, &path)?;
|
||||
if current_fingerprint(&path, &record.fingerprint)? != record.fingerprint {
|
||||
return Err(io::Error::other(format!(
|
||||
"Content '{}' changed; refresh before retrying",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn current_fingerprint(
|
||||
path: &Path,
|
||||
expected: &FileFingerprint,
|
||||
) -> io::Result<FileFingerprint> {
|
||||
let metadata = std::fs::symlink_metadata(path)?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("Content '{}' is a symlink", path.display()),
|
||||
));
|
||||
}
|
||||
if metadata.is_dir() {
|
||||
directory_fingerprint_metadata(path)
|
||||
} else if metadata.is_file() && expected.hashes.is_empty() {
|
||||
fingerprint_metadata(path)
|
||||
} else if metadata.is_file() {
|
||||
fingerprint(path)
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("Content '{}' is not a file or directory", path.display()),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn directory_fingerprint_metadata(path: &Path) -> io::Result<FileFingerprint> {
|
||||
fn accumulate(path: &Path, size: &mut u64, modified_ns: &mut u128) -> io::Result<()> {
|
||||
for entry in std::fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
let metadata = std::fs::symlink_metadata(entry.path())?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let modified = metadata
|
||||
.modified()
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos();
|
||||
*modified_ns = (*modified_ns).max(modified);
|
||||
if metadata.is_dir() {
|
||||
accumulate(&entry.path(), size, modified_ns)?;
|
||||
} else if metadata.is_file() {
|
||||
*size = size.saturating_add(metadata.len());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut size = 0;
|
||||
let mut modified_ns = 0;
|
||||
accumulate(path, &mut size, &mut modified_ns)?;
|
||||
Ok(FileFingerprint {
|
||||
size,
|
||||
modified_ns,
|
||||
hashes: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn toggle(entry: &ContentEntry) -> io::Result<Option<PathBuf>> {
|
||||
let Some(name) = entry.path.file_name().and_then(|name| name.to_str()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let disabled = name.ends_with(".disabled");
|
||||
if disabled == entry.enabled {
|
||||
return Err(io::Error::other(format!(
|
||||
"Enabled state of '{}' changed; refresh before retrying",
|
||||
entry.path.display()
|
||||
)));
|
||||
}
|
||||
let new_name = if entry.enabled {
|
||||
format!("{name}.disabled")
|
||||
} else {
|
||||
name.trim_end_matches(".disabled").to_owned()
|
||||
};
|
||||
let new_path = entry.path.with_file_name(new_name);
|
||||
let instance_minecraft = entry.path.ancestors().find(|path| {
|
||||
path.file_name()
|
||||
.is_some_and(|name| name == crate::storage::MINECRAFT_DIR_NAME)
|
||||
&& entry.path.strip_prefix(path).is_ok_and(|relative| {
|
||||
relative.components().next().is_some_and(|component| {
|
||||
matches!(component, std::path::Component::Normal(name)
|
||||
if name == "mods" || name == "resourcepacks" || name == "shaderpacks" || name == "saves")
|
||||
})
|
||||
})
|
||||
});
|
||||
let minecraft_dir = instance_minecraft
|
||||
.or_else(|| entry.path.parent())
|
||||
.ok_or_else(|| io::Error::other("Content path has no parent"))?;
|
||||
let manifest_path = if let Some(minecraft) = instance_minecraft {
|
||||
crate::storage::InstancePaths::new(
|
||||
minecraft
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("Minecraft directory has no instance parent"))?,
|
||||
)
|
||||
.content_manifest()
|
||||
} else {
|
||||
minecraft_dir.join(".rmcl-content.json")
|
||||
};
|
||||
let lock = ContentLock::acquire(&manifest_path).map_err(io::Error::other)?;
|
||||
let mut manifest = if instance_minecraft.is_some() {
|
||||
lock.load().map_err(io::Error::other)?
|
||||
} else {
|
||||
ContentManifest::default()
|
||||
};
|
||||
let relative = relative_path(minecraft_dir, &entry.path)?;
|
||||
let new_relative = relative_path(minecraft_dir, &new_path)?;
|
||||
require_absent(&new_path)?;
|
||||
if manifest.record(&new_relative).is_some() {
|
||||
return Err(io::Error::other(format!(
|
||||
"Content manifest already owns '{}'",
|
||||
new_path.display()
|
||||
)));
|
||||
}
|
||||
let record = manifest.record(&relative).cloned();
|
||||
let previous = manifest.clone();
|
||||
if let Some(project) = &entry.provider_project
|
||||
&& record
|
||||
.as_ref()
|
||||
.and_then(|record| record.project_for_provider(&project.provider, &project.project_id))
|
||||
!= Some(project)
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"Ownership of '{}' changed; refresh before retrying",
|
||||
entry.path.display()
|
||||
)));
|
||||
}
|
||||
if let Some(record) = &record {
|
||||
if record.enabled != entry.enabled {
|
||||
return Err(io::Error::other(format!(
|
||||
"Enabled state of '{}' changed; refresh before retrying",
|
||||
entry.path.display()
|
||||
)));
|
||||
}
|
||||
validate_record(minecraft_dir, record)?;
|
||||
} else {
|
||||
current_fingerprint(
|
||||
&entry.path,
|
||||
&FileFingerprint {
|
||||
size: 0,
|
||||
modified_ns: 0,
|
||||
hashes: Default::default(),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(minecraft_dir)?);
|
||||
let result = (|| {
|
||||
transaction.move_path(&entry.path, &new_path)?;
|
||||
if let Some(mut record) = record {
|
||||
manifest.remove(&relative);
|
||||
record.relative_path = new_relative;
|
||||
record.enabled = !entry.enabled;
|
||||
manifest.upsert(record);
|
||||
lock.save_if_unchanged(&manifest, &previous)
|
||||
.map_err(io::Error::other)?;
|
||||
}
|
||||
Ok(Some(new_path))
|
||||
})();
|
||||
transaction.finish(result)
|
||||
}
|
||||
|
||||
pub(crate) fn record_toggle(
|
||||
manifest: &mut ContentManifest,
|
||||
minecraft_dir: &Path,
|
||||
old_path: &Path,
|
||||
new_path: &Path,
|
||||
enabled: bool,
|
||||
) -> io::Result<bool> {
|
||||
let old_relative = relative_path(minecraft_dir, old_path)?;
|
||||
let new_relative = relative_path(minecraft_dir, new_path)?;
|
||||
match std::fs::symlink_metadata(old_path) {
|
||||
Ok(_) => return Ok(false),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
if let Some(record) = manifest.record(&new_relative) {
|
||||
if manifest.record(&old_relative).is_some() || record.enabled != enabled {
|
||||
return Ok(false);
|
||||
}
|
||||
validate_record(minecraft_dir, record)?;
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(record) = manifest.record(&old_relative) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let fresh = match current_fingerprint(new_path, &record.fingerprint) {
|
||||
Ok(fresh) => fresh,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(
|
||||
fresh == record.fingerprint
|
||||
&& manifest.rename_record(&old_relative, &new_relative, enabled),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn remove(
|
||||
manifest_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
path: &Path,
|
||||
expected: &[ContentFileRecord],
|
||||
orphan_only: bool,
|
||||
) -> io::Result<(ContentManifest, Vec<PathBuf>)> {
|
||||
let lock = ContentLock::acquire(manifest_path).map_err(io::Error::other)?;
|
||||
let mut manifest = lock.load().map_err(io::Error::other)?;
|
||||
let previous = manifest.clone();
|
||||
let relative = relative_path(minecraft_dir, path)?;
|
||||
if manifest
|
||||
.files
|
||||
.iter()
|
||||
.filter(|record| record.relative_path.starts_with(&relative))
|
||||
.ne(expected.iter())
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"Ownership of '{}' changed; refresh before retrying",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
if orphan_only && !manifest.orphaned_dependencies().contains(&relative) {
|
||||
return Err(io::Error::other(format!(
|
||||
"'{}' is no longer an unused dependency",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
for record in expected {
|
||||
match validate_record(minecraft_dir, record) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(minecraft_dir)?);
|
||||
let result = (|| {
|
||||
let backup = transaction.staging().join("removed");
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(_) => transaction.move_path(path, &backup)?,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
manifest
|
||||
.files
|
||||
.retain(|record| !record.relative_path.starts_with(&relative));
|
||||
let orphans = manifest
|
||||
.orphaned_dependencies()
|
||||
.into_iter()
|
||||
.map(|relative| minecraft_dir.join(relative))
|
||||
.collect();
|
||||
lock.save_if_unchanged(&manifest, &previous)
|
||||
.map_err(io::Error::other)?;
|
||||
Ok((manifest, orphans))
|
||||
})();
|
||||
transaction.finish(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/content/local.rs"]
|
||||
mod tests;
|
||||
@@ -1,18 +1,120 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Seek};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha1::Digest as _;
|
||||
|
||||
const MANIFEST_VERSION: u32 = 1;
|
||||
static MANIFEST_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) struct ContentLock {
|
||||
file: File,
|
||||
instance_lock: Option<File>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl ContentLock {
|
||||
pub(crate) fn acquire(path: &Path) -> Result<Self, ManifestError> {
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
||||
})?;
|
||||
let instance_dir = parent
|
||||
.parent()
|
||||
.filter(|state| {
|
||||
path.file_name().is_some_and(|name| name == "manifest.json")
|
||||
&& parent.file_name().is_some_and(|name| name == "content")
|
||||
&& state
|
||||
.file_name()
|
||||
.is_some_and(|name| name == crate::storage::INSTANCE_STATE_DIR_NAME)
|
||||
})
|
||||
.and_then(Path::parent);
|
||||
let instance_lock = if let Some(instance_dir) = instance_dir {
|
||||
let root = instance_dir.parent().ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no instance root", path.display()))
|
||||
})?;
|
||||
let name = instance_dir
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no instance name", path.display()))
|
||||
})?;
|
||||
Some(crate::instance::runtime::lock_instance(root, name).map_err(
|
||||
|error| match error {
|
||||
crate::instance::manager::InstanceError::InstanceRunning(_) => {
|
||||
ManifestError::Busy(path.to_owned())
|
||||
}
|
||||
error => ManifestError::Io(std::io::Error::other(error)),
|
||||
},
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(path.with_extension("lock"))?;
|
||||
if let Err(error) = fs2::FileExt::try_lock_exclusive(&file) {
|
||||
if error.raw_os_error() == fs2::lock_contended_error().raw_os_error() {
|
||||
return Err(ManifestError::Busy(path.to_owned()));
|
||||
}
|
||||
return Err(error.into());
|
||||
}
|
||||
Ok(Self {
|
||||
file,
|
||||
instance_lock,
|
||||
path: path.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn load(&self) -> Result<ContentManifest, ManifestError> {
|
||||
ContentManifest::load(&self.path)
|
||||
}
|
||||
|
||||
pub(crate) fn save(&self, manifest: &ContentManifest) -> Result<(), ManifestError> {
|
||||
let bytes = serde_json::to_vec_pretty(manifest)?;
|
||||
crate::storage::write_atomic(&self.path, &bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn save_if_unchanged(
|
||||
&self,
|
||||
manifest: &ContentManifest,
|
||||
previous: &ContentManifest,
|
||||
) -> Result<(), ManifestError> {
|
||||
let current = self.load()?;
|
||||
if current.version != previous.version || current.files != previous.files {
|
||||
return Err(ManifestError::Changed(self.path.clone()));
|
||||
}
|
||||
self.save(manifest)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ContentLock {
|
||||
fn drop(&mut self) {
|
||||
if let Err(error) = fs2::FileExt::unlock(&self.file) {
|
||||
tracing::warn!(
|
||||
"Could not release content lock '{}': {error}",
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
if let Some(file) = &self.instance_lock
|
||||
&& let Err(error) = file.unlock()
|
||||
{
|
||||
tracing::warn!(
|
||||
"Could not release instance lock for '{}': {error}",
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -120,10 +222,13 @@ impl Default for ContentManifest {
|
||||
|
||||
impl ContentManifest {
|
||||
pub fn load(path: &Path) -> Result<Self, ManifestError> {
|
||||
if !path.exists() {
|
||||
return Ok(Self::default());
|
||||
}
|
||||
let bytes = std::fs::read(path)?;
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
return Ok(Self::default());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let mut manifest: Self = serde_json::from_slice(&bytes)?;
|
||||
if manifest.version != MANIFEST_VERSION {
|
||||
return Err(ManifestError::UnsupportedVersion(manifest.version));
|
||||
@@ -133,36 +238,32 @@ impl ContentManifest {
|
||||
manifest
|
||||
.files
|
||||
.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
|
||||
for (index, record) in manifest.files.iter().enumerate() {
|
||||
if !crate::storage::safe_relative_path(&record.relative_path)
|
||||
|| index > 0 && manifest.files[index - 1].relative_path == record.relative_path
|
||||
{
|
||||
return Err(ManifestError::InvalidPath(format!(
|
||||
"Unsafe or duplicate content path '{}'",
|
||||
record.relative_path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
pub fn save(&self, path: &Path) -> Result<(), ManifestError> {
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let bytes = serde_json::to_vec_pretty(self)?;
|
||||
crate::storage::write_atomic(path, &bytes)?;
|
||||
Ok(())
|
||||
ContentLock::acquire(path)?.save(self)
|
||||
}
|
||||
|
||||
pub fn update<T>(
|
||||
path: &Path,
|
||||
update: impl FnOnce(&mut Self) -> Result<T, ManifestError>,
|
||||
) -> Result<T, ManifestError> {
|
||||
let lock = {
|
||||
let mut locks = MANIFEST_LOCKS
|
||||
.lock()
|
||||
.map_err(|_| ManifestError::LockPoisoned)?;
|
||||
locks
|
||||
.entry(path.to_owned())
|
||||
.or_insert_with(|| Arc::new(Mutex::new(())))
|
||||
.clone()
|
||||
};
|
||||
let _guard = lock.lock().map_err(|_| ManifestError::LockPoisoned)?;
|
||||
let mut manifest = Self::load(path)?;
|
||||
let lock = ContentLock::acquire(path)?;
|
||||
let mut manifest = lock.load()?;
|
||||
let previous = manifest.clone();
|
||||
let result = update(&mut manifest)?;
|
||||
manifest.save(path)?;
|
||||
lock.save_if_unchanged(&manifest, &previous)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -200,10 +301,13 @@ impl ContentManifest {
|
||||
}
|
||||
|
||||
pub fn rename_record(&mut self, from: &Path, to: &Path, enabled: bool) -> bool {
|
||||
if from != to && self.record(to).is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(index) = self
|
||||
.files
|
||||
.iter()
|
||||
.position(|record| record.relative_path == from || record.relative_path == to)
|
||||
.position(|record| record.relative_path == from)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
@@ -362,8 +466,10 @@ pub enum ManifestError {
|
||||
UnsupportedVersion(u32),
|
||||
#[error("Invalid manifest path: {0}")]
|
||||
InvalidPath(String),
|
||||
#[error("Content manifest lock was poisoned")]
|
||||
LockPoisoned,
|
||||
#[error("Content is being changed by another operation: {0}")]
|
||||
Busy(PathBuf),
|
||||
#[error("Content manifest changed during the operation; refresh before retrying: {0}")]
|
||||
Changed(PathBuf),
|
||||
}
|
||||
|
||||
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod datapacks;
|
||||
pub mod dependencies;
|
||||
pub mod entry;
|
||||
pub mod icons;
|
||||
pub(crate) mod local;
|
||||
pub mod manifest;
|
||||
pub mod mods;
|
||||
mod packs;
|
||||
|
||||
+104
-102
@@ -4,12 +4,12 @@
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::local::{current_fingerprint, directory_fingerprint_metadata, relative_path};
|
||||
use crate::feedback::progress::{ProgressTask, ProgressTaskHandle};
|
||||
use crate::instance::InstanceConfig;
|
||||
use crate::instance::content::manifest::{
|
||||
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
|
||||
ContentFileRecord, ContentKind, ContentLock, ContentManifest, ProviderProject, Resolution,
|
||||
fingerprint, fingerprint_metadata,
|
||||
};
|
||||
use crate::instance::content::provider::{FingerprintQuery, ProviderRegistry};
|
||||
@@ -188,38 +188,31 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
|
||||
inventory.queries.len() as u64,
|
||||
);
|
||||
}
|
||||
match resolution_result {
|
||||
Ok(()) => match save_reconciled_manifest(
|
||||
let saved = tokio::task::spawn_blocking(move || {
|
||||
save_reconciled_manifest(
|
||||
&manifest_path,
|
||||
&minecraft_dir,
|
||||
inventory.manifest,
|
||||
) {
|
||||
Ok(manifest) => ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest,
|
||||
error: None,
|
||||
},
|
||||
Err(error) => ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: ContentManifest::default(),
|
||||
error: Some(error.to_string()),
|
||||
},
|
||||
},
|
||||
Err(error) => {
|
||||
let saved = save_reconciled_manifest(
|
||||
&manifest_path,
|
||||
&minecraft_dir,
|
||||
inventory.manifest,
|
||||
);
|
||||
ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: saved.unwrap_or_default(),
|
||||
error: Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
&inventory.previous,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|error| {
|
||||
Err(std::io::Error::other(format!("Content save task failed: {error}")).into())
|
||||
});
|
||||
let error = match (resolution_result, &saved) {
|
||||
(Ok(()), Ok(_)) => None,
|
||||
(Err(error), Ok(_)) => Some(error.to_string()),
|
||||
(Ok(()), Err(error)) => Some(error.to_string()),
|
||||
(Err(error), Err(save_error)) => Some(format!(
|
||||
"Provider matching failed: {error}; could not save content inventory: {save_error}"
|
||||
)),
|
||||
};
|
||||
ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: saved.unwrap_or_default(),
|
||||
error,
|
||||
}
|
||||
}
|
||||
Ok(Err(error)) => ReconcileResult {
|
||||
@@ -241,18 +234,46 @@ fn save_reconciled_manifest(
|
||||
manifest_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
reconciled: ContentManifest,
|
||||
previous: &ContentManifest,
|
||||
) -> Result<ContentManifest, crate::instance::content::manifest::ManifestError> {
|
||||
let reconciled_paths = reconciled
|
||||
.files
|
||||
.iter()
|
||||
.map(|record| record.relative_path.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
ContentManifest::update(manifest_path, |current| {
|
||||
current.files.retain(|record| {
|
||||
reconciled_paths.contains(&record.relative_path)
|
||||
|| minecraft_dir.join(&record.relative_path).exists()
|
||||
});
|
||||
for record in reconciled.files {
|
||||
for record in current.files.clone() {
|
||||
relative_path(minecraft_dir, &minecraft_dir.join(&record.relative_path))?;
|
||||
match std::fs::symlink_metadata(minecraft_dir.join(&record.relative_path)) {
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
current.remove(&record.relative_path)
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
for mut record in reconciled.files {
|
||||
let path = minecraft_dir.join(&record.relative_path);
|
||||
relative_path(minecraft_dir, &path)?;
|
||||
if current.record(&record.relative_path) != previous.record(&record.relative_path) {
|
||||
continue;
|
||||
}
|
||||
let metadata = match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
if metadata.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let fresh = current_fingerprint(&path, &record.fingerprint)?;
|
||||
if fresh != record.fingerprint {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = current.record(&record.relative_path)
|
||||
&& existing.fingerprint == record.fingerprint
|
||||
{
|
||||
record
|
||||
.required_dependencies
|
||||
.clone_from(&existing.required_dependencies);
|
||||
record.automatic_dependency = existing.automatic_dependency;
|
||||
record.cleanup_eligible = existing.cleanup_eligible;
|
||||
}
|
||||
let keep_resolved = current
|
||||
.record(&record.relative_path)
|
||||
.is_some_and(|existing| {
|
||||
@@ -273,6 +294,7 @@ fn save_reconciled_manifest(
|
||||
}
|
||||
|
||||
struct Inventory {
|
||||
previous: ContentManifest,
|
||||
manifest: ContentManifest,
|
||||
queries: Vec<FingerprintQuery>,
|
||||
}
|
||||
@@ -299,7 +321,8 @@ fn reconcile_inventory(
|
||||
max_fingerprint_size_mib: u64,
|
||||
task: &impl InventoryProgress,
|
||||
) -> Result<Inventory, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let previous = ContentManifest::load(manifest_path)?;
|
||||
let lock = ContentLock::acquire(manifest_path)?;
|
||||
let previous = lock.load()?;
|
||||
let files = content_files(minecraft_dir)?;
|
||||
let file_count = files.len() as u64;
|
||||
if file_count == 0 {
|
||||
@@ -319,7 +342,7 @@ fn reconcile_inventory(
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("content"),
|
||||
);
|
||||
let relative_path = path.strip_prefix(minecraft_dir)?.to_path_buf();
|
||||
let relative_path = relative_path(minecraft_dir, &path)?;
|
||||
let enabled = !path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
@@ -443,7 +466,11 @@ fn reconcile_inventory(
|
||||
manifest.files.push(record);
|
||||
task.set_progress(index as u64 + 1, file_count);
|
||||
}
|
||||
Ok(Inventory { manifest, queries })
|
||||
Ok(Inventory {
|
||||
previous,
|
||||
manifest,
|
||||
queries,
|
||||
})
|
||||
}
|
||||
|
||||
fn provider_was_not_checked(record: &ContentFileRecord, provider: &str) -> bool {
|
||||
@@ -609,27 +636,26 @@ fn content_files(minecraft_dir: &Path) -> std::io::Result<Vec<(ContentKind, Path
|
||||
ContentKind::Shader,
|
||||
] {
|
||||
let directory = minecraft_dir.join(kind.directory());
|
||||
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let entries = read_content_directory(&directory)?;
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if supported_content_path(kind, &path) {
|
||||
if supported_content_path(kind, &path)? {
|
||||
files.push((kind, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(worlds) = std::fs::read_dir(minecraft_dir.join("saves")) {
|
||||
for world in worlds
|
||||
.flatten()
|
||||
.filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
|
||||
{
|
||||
let Ok(entries) = std::fs::read_dir(world.path().join("datapacks")) else {
|
||||
{
|
||||
for world in read_content_directory(&minecraft_dir.join("saves"))? {
|
||||
let world = world?;
|
||||
if !world.file_type()?.is_dir() {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
}
|
||||
let entries = read_content_directory(&world.path().join("datapacks"))?;
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if supported_content_path(ContentKind::DataPack, &path) {
|
||||
if supported_content_path(ContentKind::DataPack, &path)? {
|
||||
files.push((ContentKind::DataPack, path));
|
||||
}
|
||||
}
|
||||
@@ -639,64 +665,40 @@ fn content_files(minecraft_dir: &Path) -> std::io::Result<Vec<(ContentKind, Path
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn supported_content_path(kind: ContentKind, path: &Path) -> bool {
|
||||
let Ok(metadata) = std::fs::symlink_metadata(path) else {
|
||||
return false;
|
||||
};
|
||||
fn read_content_directory(
|
||||
path: &Path,
|
||||
) -> std::io::Result<impl Iterator<Item = std::io::Result<std::fs::DirEntry>> + use<>> {
|
||||
match std::fs::read_dir(path) {
|
||||
Ok(entries) => Ok(Some(entries).into_iter().flatten()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
Ok(None.into_iter().flatten())
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn supported_content_path(kind: ContentKind, path: &Path) -> std::io::Result<bool> {
|
||||
let metadata = std::fs::symlink_metadata(path)?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
return false;
|
||||
return Ok(false);
|
||||
}
|
||||
if metadata.is_dir() {
|
||||
return matches!(
|
||||
return Ok(matches!(
|
||||
kind,
|
||||
ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack
|
||||
);
|
||||
));
|
||||
}
|
||||
if !metadata.is_file() {
|
||||
return false;
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
|
||||
return false;
|
||||
return Ok(false);
|
||||
};
|
||||
match kind {
|
||||
Ok(match kind {
|
||||
ContentKind::Mod => name.ends_with(".jar") || name.ends_with(".jar.disabled"),
|
||||
ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack => {
|
||||
name.ends_with(".zip") || name.ends_with(".zip.disabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn directory_fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||
fn accumulate(path: &Path, size: &mut u64, modified_ns: &mut u128) -> std::io::Result<()> {
|
||||
for entry in std::fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
let metadata = std::fs::symlink_metadata(entry.path())?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let modified = metadata
|
||||
.modified()
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos();
|
||||
*modified_ns = (*modified_ns).max(modified);
|
||||
if metadata.is_dir() {
|
||||
accumulate(&entry.path(), size, modified_ns)?;
|
||||
} else if metadata.is_file() {
|
||||
*size = size.saturating_add(metadata.len());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let mut size = 0;
|
||||
let mut modified_ns = 0;
|
||||
accumulate(path, &mut size, &mut modified_ns)?;
|
||||
Ok(FileFingerprint {
|
||||
size,
|
||||
modified_ns,
|
||||
hashes: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+113
-71
@@ -182,7 +182,6 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda
|
||||
.collect();
|
||||
|
||||
let slots = Arc::new(tokio::sync::Semaphore::new(8));
|
||||
// one registry (and therefore one pooled http client) for the whole scan
|
||||
let registry = Arc::new(
|
||||
crate::instance::content::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
@@ -293,83 +292,125 @@ pub async fn plan_bulk(
|
||||
manifest: &ContentManifest,
|
||||
minecraft_dir: &std::path::Path,
|
||||
requests: Vec<UpdateRequest>,
|
||||
mut conflicts: Vec<UpdateConflict>,
|
||||
conflicts: Vec<UpdateConflict>,
|
||||
) -> BulkUpdatePlan {
|
||||
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
);
|
||||
let projected_manifest = project_updates(manifest, minecraft_dir, &requests);
|
||||
let mut accepted = Vec::new();
|
||||
let mut roots = Vec::new();
|
||||
for request in requests {
|
||||
let root = InstallRoot {
|
||||
provider: request.update.installed.provider.clone(),
|
||||
project_id: request.update.installed.project_id.clone(),
|
||||
title: request.title.clone(),
|
||||
version: request.update.target.clone(),
|
||||
installed_path: Some(request.installed_path.clone()),
|
||||
kind: request.update.kind,
|
||||
target_world: request.target_world.clone(),
|
||||
force_reinstall: false,
|
||||
};
|
||||
let mut resolution_manifest = projected_manifest.clone();
|
||||
if let Ok(relative_path) = request.installed_path.strip_prefix(minecraft_dir)
|
||||
&& let Some(current) = manifest.record(relative_path)
|
||||
&& let Some(projected) = resolution_manifest
|
||||
.files
|
||||
.iter_mut()
|
||||
.find(|record| record.relative_path == relative_path)
|
||||
{
|
||||
projected.resolution = current.resolution.clone();
|
||||
}
|
||||
let plan = match super::dependencies::resolve(
|
||||
®istry,
|
||||
&resolution_manifest,
|
||||
minecraft_dir,
|
||||
instance,
|
||||
root,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plan) => plan,
|
||||
Err(error) => {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut proposed = accepted.clone();
|
||||
proposed.push(plan.clone());
|
||||
if let Err(error) = super::dependencies::merge(proposed) {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
roots.push(PlannedRootUpdate {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
current_version: request.update.current.as_ref().map_or_else(
|
||||
|| request.update.installed.version_id.clone(),
|
||||
|version| version.version_number.clone(),
|
||||
),
|
||||
target: request.update.target,
|
||||
});
|
||||
accepted.push(plan);
|
||||
}
|
||||
BulkUpdatePlan {
|
||||
dependency_plan: super::dependencies::merge(accepted).unwrap_or(DependencyPlan {
|
||||
plan_bulk_with_registry(
|
||||
®istry,
|
||||
instance,
|
||||
manifest,
|
||||
minecraft_dir,
|
||||
requests,
|
||||
conflicts,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn plan_bulk_with_registry(
|
||||
registry: &super::provider::ProviderRegistry,
|
||||
instance: &InstanceConfig,
|
||||
manifest: &ContentManifest,
|
||||
minecraft_dir: &std::path::Path,
|
||||
mut requests: Vec<UpdateRequest>,
|
||||
mut conflicts: Vec<UpdateConflict>,
|
||||
) -> BulkUpdatePlan {
|
||||
loop {
|
||||
let request_count = requests.len();
|
||||
let projected_manifest = project_updates(manifest, minecraft_dir, &requests);
|
||||
let mut accepted = Vec::new();
|
||||
let mut survivors = Vec::new();
|
||||
let mut dependency_plan = DependencyPlan {
|
||||
items: Vec::new(),
|
||||
root_count: 0,
|
||||
optional_dependencies: 0,
|
||||
}),
|
||||
roots,
|
||||
conflicts,
|
||||
};
|
||||
for request in requests {
|
||||
let root = InstallRoot {
|
||||
provider: request.update.installed.provider.clone(),
|
||||
project_id: request.update.installed.project_id.clone(),
|
||||
title: request.title.clone(),
|
||||
version: request.update.target.clone(),
|
||||
installed_path: Some(request.installed_path.clone()),
|
||||
kind: request.update.kind,
|
||||
target_world: request.target_world.clone(),
|
||||
force_reinstall: false,
|
||||
};
|
||||
let mut resolution_manifest = projected_manifest.clone();
|
||||
if let Ok(relative_path) = request.installed_path.strip_prefix(minecraft_dir)
|
||||
&& let Some(current) = manifest.record(relative_path)
|
||||
&& let Some(projected) = resolution_manifest
|
||||
.files
|
||||
.iter_mut()
|
||||
.find(|record| record.relative_path == relative_path)
|
||||
{
|
||||
*projected = current.clone();
|
||||
}
|
||||
let mut plan = match super::dependencies::resolve(
|
||||
registry,
|
||||
&resolution_manifest,
|
||||
minecraft_dir,
|
||||
instance,
|
||||
root,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plan) => plan,
|
||||
Err(error) => {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for item in &mut plan.items {
|
||||
item.expected_record = item
|
||||
.installed_path
|
||||
.as_ref()
|
||||
.and_then(|path| path.strip_prefix(minecraft_dir).ok())
|
||||
.and_then(|relative| manifest.record(relative))
|
||||
.cloned();
|
||||
}
|
||||
let mut proposed = accepted.clone();
|
||||
proposed.push(plan.clone());
|
||||
match super::dependencies::merge(proposed) {
|
||||
Ok(merged) => dependency_plan = merged,
|
||||
Err(error) => {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
accepted.push(plan);
|
||||
survivors.push(request);
|
||||
}
|
||||
if survivors.len() != request_count {
|
||||
requests = survivors;
|
||||
continue;
|
||||
}
|
||||
let roots = survivors
|
||||
.into_iter()
|
||||
.map(|request| PlannedRootUpdate {
|
||||
current_version: request.update.current.as_ref().map_or_else(
|
||||
|| request.update.installed.version_id.clone(),
|
||||
|version| version.version_number.clone(),
|
||||
),
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
target: request.update.target,
|
||||
})
|
||||
.collect();
|
||||
return BulkUpdatePlan {
|
||||
dependency_plan,
|
||||
roots,
|
||||
conflicts,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,6 +438,7 @@ fn project_updates(
|
||||
version_id: request.update.target.id.clone(),
|
||||
},
|
||||
};
|
||||
record.provider_aliases.clear();
|
||||
}
|
||||
projected
|
||||
}
|
||||
|
||||
@@ -157,7 +157,8 @@ impl WorldMetadata {
|
||||
fn read_world_metadata(world_dir: &Path) -> Option<WorldMetadata> {
|
||||
let path = world_dir.join("level.dat");
|
||||
let file = File::open(&path).ok()?;
|
||||
match fastnbt::from_reader::<_, LevelDat>(GzDecoder::new(file)) {
|
||||
let bytes = super::read_local_metadata(GzDecoder::new(file))?;
|
||||
match fastnbt::from_bytes::<LevelDat>(&bytes) {
|
||||
Ok(level) => Some(level.data),
|
||||
Err(error) => {
|
||||
tracing::debug!(
|
||||
|
||||
@@ -16,8 +16,10 @@ use crate::net::modrinth::{
|
||||
|
||||
#[test]
|
||||
fn concurrent_installs_use_distinct_staging_directories() {
|
||||
let minecraft = Path::new("/instance/minecraft");
|
||||
assert_ne!(staging_directory(minecraft), staging_directory(minecraft));
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let first = StagingDirectory::new(temp.path()).unwrap();
|
||||
let second = StagingDirectory::new(temp.path()).unwrap();
|
||||
assert_ne!(first.path(), second.path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -35,6 +37,7 @@ fn merge_keeps_replacement_when_a_dependency_is_also_an_update_root() {
|
||||
title: "Library".to_owned(),
|
||||
version: selected.clone(),
|
||||
installed_path: Some(PathBuf::from("/minecraft/mods/library.jar")),
|
||||
expected_record: None,
|
||||
kind: ContentKind::Mod,
|
||||
destination: PathBuf::from("/minecraft/mods"),
|
||||
provider_aliases: Vec::new(),
|
||||
@@ -87,6 +90,7 @@ async fn invalid_manifest_does_not_replace_installed_content() {
|
||||
title: "Root".to_owned(),
|
||||
version: selected.clone(),
|
||||
installed_path: Some(old.clone()),
|
||||
expected_record: None,
|
||||
kind: ContentKind::Mod,
|
||||
destination: mods.clone(),
|
||||
provider_aliases: Vec::new(),
|
||||
@@ -122,6 +126,9 @@ struct FakeProvider {
|
||||
resolved: HashMap<String, ProviderProject>,
|
||||
fail_project: Option<String>,
|
||||
fail_download: Option<String>,
|
||||
download_barrier: Option<std::sync::Arc<tokio::sync::Barrier>>,
|
||||
download_pause: Option<std::sync::Arc<tokio::sync::Notify>>,
|
||||
download_filename: Option<String>,
|
||||
}
|
||||
|
||||
impl FakeProvider {
|
||||
@@ -253,8 +260,18 @@ impl ContentProvider for FakeProvider {
|
||||
} else {
|
||||
"jar"
|
||||
};
|
||||
let path = destination.join(format!("{}.{extension}", version.id));
|
||||
let path = destination.join(
|
||||
self.download_filename
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("{}.{extension}", version.id)),
|
||||
);
|
||||
tokio::fs::write(&path, version.id.as_bytes()).await?;
|
||||
if let Some(barrier) = &self.download_barrier {
|
||||
barrier.wait().await;
|
||||
}
|
||||
if let Some(pause) = &self.download_pause {
|
||||
pause.notified().await;
|
||||
}
|
||||
Ok(crate::net::modrinth::DownloadOutcome::Downloaded(path))
|
||||
}
|
||||
}
|
||||
@@ -384,6 +401,9 @@ fn provider(versions: Vec<VersionInfo>) -> FakeProvider {
|
||||
resolved: HashMap::new(),
|
||||
fail_project: None,
|
||||
fail_download: None,
|
||||
download_barrier: None,
|
||||
download_pause: None,
|
||||
download_filename: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1137,5 +1157,788 @@ async fn failed_dependency_download_leaves_no_partial_install() {
|
||||
.is_err()
|
||||
);
|
||||
assert!(!manifest_path.exists());
|
||||
assert_eq!(std::fs::read_dir(&mods).unwrap().count(), 0);
|
||||
match std::fs::read_dir(&mods) {
|
||||
Ok(entries) => assert_eq!(entries.count(), 0),
|
||||
Err(error) => assert_eq!(error.kind(), std::io::ErrorKind::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn required(project: &str, pin: Option<&str>) -> VersionDependency {
|
||||
VersionDependency {
|
||||
version_id: pin.map(str::to_owned),
|
||||
..dependency(project, DependencyType::Required)
|
||||
}
|
||||
}
|
||||
|
||||
fn release(id: &str, project: &str, dependencies: Vec<VersionDependency>) -> VersionInfo {
|
||||
version(
|
||||
id,
|
||||
project,
|
||||
VersionType::Release,
|
||||
if id.ends_with('2') {
|
||||
"2026-02-01"
|
||||
} else {
|
||||
"2026-01-01"
|
||||
},
|
||||
dependencies,
|
||||
)
|
||||
}
|
||||
|
||||
async fn resolve_graph(versions: Vec<VersionInfo>) -> Result<DependencyPlan, NetError> {
|
||||
let selected = versions[0].clone();
|
||||
resolve(
|
||||
&provider(versions).registry(),
|
||||
&ContentManifest::default(),
|
||||
Path::new("/minecraft"),
|
||||
&instance(),
|
||||
root(selected),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn matching_exact_requirement_remains_binding() {
|
||||
let error = resolve_graph(vec![
|
||||
release(
|
||||
"r1",
|
||||
"root",
|
||||
vec![
|
||||
required("c", None),
|
||||
required("d", None),
|
||||
required("e", None),
|
||||
],
|
||||
),
|
||||
release("d1", "d", vec![required("c", Some("c2"))]),
|
||||
release("e1", "e", vec![required("c", Some("c1"))]),
|
||||
release("c1", "c", Vec::new()),
|
||||
release("c2", "c", Vec::new()),
|
||||
])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("Conflicting required versions"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replacing_a_parent_retracts_its_exact_requirements() {
|
||||
let plan = resolve_graph(vec![
|
||||
release("r1", "root", vec![required("d", None), required("e", None)]),
|
||||
release("d1", "d", vec![required("b", None)]),
|
||||
release("e1", "e", vec![required("f", None)]),
|
||||
release("f1", "f", vec![required("b", Some("b1"))]),
|
||||
release("b2", "b", vec![required("c", Some("c1"))]),
|
||||
release("b1", "b", vec![required("c", Some("c2"))]),
|
||||
release("c1", "c", Vec::new()),
|
||||
release("c2", "c", Vec::new()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
plan.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "b")
|
||||
.unwrap()
|
||||
.version
|
||||
.id,
|
||||
"b1"
|
||||
);
|
||||
let c = plan
|
||||
.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "c")
|
||||
.unwrap();
|
||||
assert_eq!(c.version.id, "c2");
|
||||
assert!(
|
||||
plan.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "b")
|
||||
.unwrap()
|
||||
.required_dependencies
|
||||
.contains(&c.identity())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settling_retries_a_pin_after_its_competitor_disappears() {
|
||||
let plan = resolve_graph(vec![
|
||||
release("r1", "root", vec![required("d", None), required("e", None)]),
|
||||
release("d1", "d", vec![required("b", None)]),
|
||||
release("e1", "e", vec![required("f", None)]),
|
||||
release(
|
||||
"f1",
|
||||
"f",
|
||||
vec![required("c", Some("c2")), required("g", None)],
|
||||
),
|
||||
release("g1", "g", vec![required("b", Some("b1"))]),
|
||||
release("b2", "b", vec![required("c", Some("c1"))]),
|
||||
release("b1", "b", Vec::new()),
|
||||
release("c1", "c", Vec::new()),
|
||||
release("c2", "c", Vec::new()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
plan.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "c")
|
||||
.unwrap()
|
||||
.version
|
||||
.id,
|
||||
"c2"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreachable_parents_do_not_keep_exact_requirements() {
|
||||
let plan = resolve_graph(vec![
|
||||
release("r1", "root", vec![required("d", None), required("e", None)]),
|
||||
release("d1", "d", vec![required("b", None)]),
|
||||
release("e1", "e", vec![required("f", None)]),
|
||||
release("f1", "f", vec![required("g", None)]),
|
||||
release(
|
||||
"g1",
|
||||
"g",
|
||||
vec![required("c", Some("c2")), required("h", None)],
|
||||
),
|
||||
release("h1", "h", vec![required("b", Some("b1"))]),
|
||||
release("b2", "b", vec![required("orphan", None)]),
|
||||
release("orphan1", "orphan", vec![required("c", Some("c1"))]),
|
||||
release("b1", "b", Vec::new()),
|
||||
release("c1", "c", Vec::new()),
|
||||
release("c2", "c", Vec::new()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!plan.items.iter().any(|item| item.project_id == "orphan"));
|
||||
assert_eq!(
|
||||
plan.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "c")
|
||||
.unwrap()
|
||||
.version
|
||||
.id,
|
||||
"c2"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn superseded_parent_errors_and_cycles_do_not_reject_the_final_graph() {
|
||||
for old_dependencies in [vec![required("missing", None)], vec![required("c", None)]] {
|
||||
let plan = resolve_graph(vec![
|
||||
release("r1", "root", vec![required("d", None), required("e", None)]),
|
||||
release("d1", "d", vec![required("b", None)]),
|
||||
release("e1", "e", vec![required("f", None)]),
|
||||
release("f1", "f", vec![required("b", Some("b1"))]),
|
||||
release("b2", "b", old_dependencies),
|
||||
release("b1", "b", Vec::new()),
|
||||
release("c1", "c", vec![required("b", None)]),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
plan.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "b")
|
||||
.unwrap()
|
||||
.version
|
||||
.id,
|
||||
"b1"
|
||||
);
|
||||
assert!(!plan.items.iter().any(|item| item.project_id == "c"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cycles_through_reused_nodes_are_rejected_but_diamonds_are_valid() {
|
||||
for cycle in [false, true] {
|
||||
let result = resolve_graph(vec![
|
||||
release("r1", "root", vec![required("b", None), required("c", None)]),
|
||||
release("b1", "b", vec![required("d", None)]),
|
||||
release("c1", "c", vec![required("d", None)]),
|
||||
release(
|
||||
"d1",
|
||||
"d",
|
||||
if cycle {
|
||||
vec![required("c", None)]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
),
|
||||
])
|
||||
.await;
|
||||
if cycle {
|
||||
assert!(result.unwrap_err().to_string().contains("cycle"));
|
||||
} else {
|
||||
assert_eq!(
|
||||
result
|
||||
.unwrap()
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.project_id == "d")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn changing_version_cycles_terminate_with_a_diagnostic() {
|
||||
let error = resolve_graph(vec![
|
||||
release("r1", "root", vec![required("a", None)]),
|
||||
release("a2", "a", vec![required("b", Some("b2"))]),
|
||||
release("b2", "b", vec![required("a", Some("a1"))]),
|
||||
release("a1", "a", vec![required("b", Some("b1"))]),
|
||||
release("b1", "b", vec![required("a", Some("a2"))]),
|
||||
])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("did not converge"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replaced_incompatible_versions_are_absent_from_the_final_inventory() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let mut record = installed_record("b", "b1", true);
|
||||
let old = minecraft.join(&record.relative_path);
|
||||
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
|
||||
std::fs::write(&old, b"b1").unwrap();
|
||||
record.fingerprint = super::super::manifest::fingerprint(&old).unwrap();
|
||||
let manifest = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record],
|
||||
};
|
||||
manifest.save(&manifest_path).unwrap();
|
||||
let mut a = release("a2", "a", vec![required("b", Some("b2"))]);
|
||||
a.dependencies.push(VersionDependency {
|
||||
version_id: Some("b1".to_owned()),
|
||||
..dependency("b", DependencyType::Incompatible)
|
||||
});
|
||||
let registry = provider(vec![
|
||||
a.clone(),
|
||||
release("b1", "b", Vec::new()),
|
||||
release("b2", "b", Vec::new()),
|
||||
])
|
||||
.registry();
|
||||
let plan = resolve(®istry, &manifest, &minecraft, &instance(), root(a))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
plan.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "b")
|
||||
.unwrap()
|
||||
.replacement
|
||||
);
|
||||
install(®istry, &manifest_path, &minecraft, &plan)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!old.exists());
|
||||
assert_eq!(std::fs::read(minecraft.join("mods/b2.jar")).unwrap(), b"b2");
|
||||
let final_manifest = ContentManifest::load(&manifest_path).unwrap();
|
||||
assert!(
|
||||
final_manifest
|
||||
.files
|
||||
.iter()
|
||||
.all(|record| record.resolved_project().unwrap().version_id != "b1")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreplaced_duplicate_incompatible_file_still_blocks_the_plan() {
|
||||
let mut a = release("a2", "a", vec![required("b", Some("b2"))]);
|
||||
a.dependencies.push(VersionDependency {
|
||||
version_id: Some("b1".to_owned()),
|
||||
..dependency("b", DependencyType::Incompatible)
|
||||
});
|
||||
let registry = provider(vec![
|
||||
a.clone(),
|
||||
release("b1", "b", Vec::new()),
|
||||
release("b2", "b", Vec::new()),
|
||||
])
|
||||
.registry();
|
||||
let first = installed_record("b", "b1", true);
|
||||
let mut duplicate = first.clone();
|
||||
duplicate.relative_path = "mods/z-b.jar".into();
|
||||
let manifest = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![first, duplicate],
|
||||
};
|
||||
let error = resolve(
|
||||
®istry,
|
||||
&manifest,
|
||||
Path::new("/minecraft"),
|
||||
&instance(),
|
||||
root(a),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("incompatible"));
|
||||
}
|
||||
|
||||
fn update_request(
|
||||
minecraft: &Path,
|
||||
current: &VersionInfo,
|
||||
target: &VersionInfo,
|
||||
) -> super::super::updates::UpdateRequest {
|
||||
super::super::updates::UpdateRequest {
|
||||
title: target.project_id.clone(),
|
||||
installed_path: minecraft.join(format!("mods/{}.jar", current.project_id)),
|
||||
target_world: None,
|
||||
update: super::super::updates::AvailableUpdate {
|
||||
installed: ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: current.project_id.clone(),
|
||||
version_id: current.id.clone(),
|
||||
},
|
||||
current: Some(current.clone()),
|
||||
target: target.clone(),
|
||||
kind: ContentKind::Mod,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_bulk_roots_are_removed_from_survivor_projections() {
|
||||
let minecraft = Path::new("/minecraft");
|
||||
let a1 = release("a1", "a", Vec::new());
|
||||
let mut a2 = release("a2", "a", Vec::new());
|
||||
a2.dependencies.push(VersionDependency {
|
||||
version_id: Some("b1".to_owned()),
|
||||
..dependency("b", DependencyType::Incompatible)
|
||||
});
|
||||
let b1 = release("b1", "b", Vec::new());
|
||||
let b2 = release("b2", "b", vec![required("missing", None)]);
|
||||
let c1 = release("c1", "c", Vec::new());
|
||||
let c2 = release("c2", "c", Vec::new());
|
||||
let requests = vec![
|
||||
update_request(minecraft, &a1, &a2),
|
||||
update_request(minecraft, &b1, &b2),
|
||||
update_request(minecraft, &c1, &c2),
|
||||
];
|
||||
let registry = provider(vec![a1, a2, b1, b2, c1, c2]).registry();
|
||||
let manifest = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![
|
||||
installed_record("a", "a1", true),
|
||||
installed_record("b", "b1", true),
|
||||
installed_record("c", "c1", true),
|
||||
],
|
||||
};
|
||||
let plan = super::super::updates::plan_bulk_with_registry(
|
||||
®istry,
|
||||
&instance(),
|
||||
&manifest,
|
||||
minecraft,
|
||||
requests,
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(plan.roots.len(), 1);
|
||||
assert_eq!(plan.roots[0].target.id, "c2");
|
||||
assert_eq!(plan.dependency_plan.items.len(), 1);
|
||||
assert_eq!(plan.conflicts.len(), 2);
|
||||
assert!(
|
||||
plan.conflicts
|
||||
.iter()
|
||||
.any(|conflict| conflict.title == "a" && conflict.reason.contains("incompatible"))
|
||||
);
|
||||
assert!(
|
||||
plan.conflicts
|
||||
.iter()
|
||||
.any(|conflict| conflict.title == "b" && conflict.reason.contains("missing"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepted_bulk_dependencies_keep_actual_old_ownership_and_replace_files() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
std::fs::create_dir_all(minecraft.join("mods")).unwrap();
|
||||
let a1 = release("a1", "a", Vec::new());
|
||||
let a2 = release("a2", "a", vec![required("b", None)]);
|
||||
let b1 = release("b1", "b", Vec::new());
|
||||
let b2 = release("b2", "b", Vec::new());
|
||||
let requests = vec![
|
||||
update_request(&minecraft, &a1, &a2),
|
||||
update_request(&minecraft, &b1, &b2),
|
||||
];
|
||||
let registry = provider(vec![a1, a2, b1, b2]).registry();
|
||||
let mut manifest = ContentManifest::default();
|
||||
for (project, version) in [("a", "a1"), ("b", "b1")] {
|
||||
let mut record = installed_record(project, version, true);
|
||||
let path = minecraft.join(&record.relative_path);
|
||||
std::fs::write(&path, version.as_bytes()).unwrap();
|
||||
record.fingerprint = super::super::manifest::fingerprint(&path).unwrap();
|
||||
record.provider_aliases.push(ProviderProject {
|
||||
provider: "curseforge".to_owned(),
|
||||
project_id: project.to_owned(),
|
||||
version_id: format!("cf-{version}"),
|
||||
});
|
||||
manifest.upsert(record);
|
||||
}
|
||||
manifest.save(&manifest_path).unwrap();
|
||||
let plan = super::super::updates::plan_bulk_with_registry(
|
||||
®istry,
|
||||
&instance(),
|
||||
&manifest,
|
||||
&minecraft,
|
||||
requests,
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
assert!(plan.conflicts.is_empty());
|
||||
assert_eq!(plan.dependency_plan.root_count, 2);
|
||||
let b = plan
|
||||
.dependency_plan
|
||||
.items
|
||||
.iter()
|
||||
.find(|item| item.project_id == "b")
|
||||
.unwrap();
|
||||
assert!(b.replacement);
|
||||
assert_eq!(
|
||||
b.expected_record
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.resolved_project()
|
||||
.unwrap()
|
||||
.version_id,
|
||||
"b1"
|
||||
);
|
||||
assert!(b.provider_aliases.is_empty());
|
||||
install(®istry, &manifest_path, &minecraft, &plan.dependency_plan)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(minecraft.join("mods/a2.jar")).unwrap(), b"a2");
|
||||
assert_eq!(std::fs::read(minecraft.join("mods/b2.jar")).unwrap(), b"b2");
|
||||
assert!(!minecraft.join("mods/a.jar").exists());
|
||||
assert!(!minecraft.join("mods/b.jar").exists());
|
||||
assert!(
|
||||
ContentManifest::load(&manifest_path)
|
||||
.unwrap()
|
||||
.files
|
||||
.iter()
|
||||
.all(|record| record.provider_aliases.is_empty())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn merged_plans_recheck_incompatibilities_between_selected_roots() {
|
||||
let mut a = release("a2", "a", Vec::new());
|
||||
a.dependencies.push(VersionDependency {
|
||||
version_id: Some("b2".to_owned()),
|
||||
..dependency("b", DependencyType::Incompatible)
|
||||
});
|
||||
let b = release("b2", "b", Vec::new());
|
||||
let registry = provider(vec![a.clone(), b.clone()]).registry();
|
||||
let mut plans = Vec::new();
|
||||
for selected in [a, b] {
|
||||
plans.push(
|
||||
resolve(
|
||||
®istry,
|
||||
&ContentManifest::default(),
|
||||
Path::new("/minecraft"),
|
||||
&instance(),
|
||||
root(selected),
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
merge(plans)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("incompatible")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_installs_revalidate_target_names_and_project_ownership() {
|
||||
for same_project in [false, true] {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let first = release("a1", "a", Vec::new());
|
||||
let second = release("b2", if same_project { "a" } else { "b" }, Vec::new());
|
||||
let mut fake = provider(vec![first.clone(), second.clone()]);
|
||||
fake.download_barrier = Some(std::sync::Arc::new(tokio::sync::Barrier::new(2)));
|
||||
if !same_project {
|
||||
fake.download_filename = Some("shared.jar".to_owned());
|
||||
}
|
||||
let registry = fake.registry();
|
||||
let first = resolve(
|
||||
®istry,
|
||||
&ContentManifest::default(),
|
||||
&minecraft,
|
||||
&instance(),
|
||||
root(first),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let second = resolve(
|
||||
®istry,
|
||||
&ContentManifest::default(),
|
||||
&minecraft,
|
||||
&instance(),
|
||||
root(second),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (left, right) = tokio::join!(
|
||||
install(®istry, &manifest_path, &minecraft, &first),
|
||||
install(®istry, &manifest_path, &minecraft, &second)
|
||||
);
|
||||
assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1);
|
||||
let manifest = ContentManifest::load(&manifest_path).unwrap();
|
||||
assert_eq!(manifest.files.len(), 1);
|
||||
let installed = &manifest.files[0];
|
||||
assert_eq!(
|
||||
std::fs::read(minecraft.join(&installed.relative_path)).unwrap(),
|
||||
installed.resolved_project().unwrap().version_id.as_bytes()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_dir(minecraft.join("mods")).unwrap().count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn install_rejects_changed_old_bytes_and_new_incompatible_inventory() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
std::fs::create_dir_all(minecraft.join("mods")).unwrap();
|
||||
let a1 = release("a1", "a", Vec::new());
|
||||
let a2 = release("a2", "a", Vec::new());
|
||||
let registry = provider(vec![a1, a2.clone()]).registry();
|
||||
let mut record = installed_record("a", "a1", true);
|
||||
let old = minecraft.join(&record.relative_path);
|
||||
std::fs::write(&old, b"original").unwrap();
|
||||
record.fingerprint = super::super::manifest::fingerprint(&old).unwrap();
|
||||
let manifest = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record.clone()],
|
||||
};
|
||||
manifest.save(&manifest_path).unwrap();
|
||||
let mut selected = root(a2);
|
||||
selected.installed_path = Some(old.clone());
|
||||
let plan = resolve(®istry, &manifest, &minecraft, &instance(), selected)
|
||||
.await
|
||||
.unwrap();
|
||||
let modified = std::fs::metadata(&old).unwrap().modified().unwrap();
|
||||
std::fs::write(&old, b"external").unwrap();
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&old)
|
||||
.unwrap()
|
||||
.set_times(std::fs::FileTimes::new().set_modified(modified))
|
||||
.unwrap();
|
||||
assert!(
|
||||
install(®istry, &manifest_path, &minecraft, &plan)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("changed")
|
||||
);
|
||||
assert_eq!(std::fs::read(&old).unwrap(), b"external");
|
||||
assert!(!minecraft.join("mods/a2.jar").exists());
|
||||
|
||||
let mut b = release("b2", "b", Vec::new());
|
||||
b.dependencies
|
||||
.push(dependency("a", DependencyType::Incompatible));
|
||||
let registry = provider(vec![b.clone()]).registry();
|
||||
let plan = resolve(
|
||||
®istry,
|
||||
&ContentManifest::default(),
|
||||
&minecraft,
|
||||
&instance(),
|
||||
root(b),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
install(®istry, &manifest_path, &minecraft, &plan)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("incompatible")
|
||||
);
|
||||
assert_eq!(std::fs::read(old).unwrap(), b"external");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_a_download_removes_staging_without_changing_live_content() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
std::fs::create_dir_all(minecraft.join("mods")).unwrap();
|
||||
let old = minecraft.join("mods/a.jar");
|
||||
std::fs::write(&old, b"old").unwrap();
|
||||
let mut record = installed_record("a", "a1", true);
|
||||
record.fingerprint = super::super::manifest::fingerprint(&old).unwrap();
|
||||
let manifest = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record],
|
||||
};
|
||||
manifest.save(&manifest_path).unwrap();
|
||||
let a2 = release("a2", "a", Vec::new());
|
||||
let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
|
||||
let mut fake = provider(vec![a2.clone()]);
|
||||
fake.download_barrier = Some(barrier.clone());
|
||||
fake.download_pause = Some(std::sync::Arc::new(tokio::sync::Notify::new()));
|
||||
let registry = std::sync::Arc::new(fake.registry());
|
||||
let mut selected = root(a2);
|
||||
selected.installed_path = Some(old.clone());
|
||||
let plan = resolve(®istry, &manifest, &minecraft, &instance(), selected)
|
||||
.await
|
||||
.unwrap();
|
||||
let job_minecraft = minecraft.clone();
|
||||
let job_manifest = manifest_path.clone();
|
||||
let job =
|
||||
tokio::spawn(async move { install(®istry, &job_manifest, &job_minecraft, &plan).await });
|
||||
barrier.wait().await;
|
||||
job.abort();
|
||||
assert!(matches!(job.await, Err(error) if error.is_cancelled()));
|
||||
assert_eq!(std::fs::read(old).unwrap(), b"old");
|
||||
assert_eq!(
|
||||
ContentManifest::load(&manifest_path).unwrap().files,
|
||||
manifest.files
|
||||
);
|
||||
assert!(!minecraft.join("mods/a2.jar").exists());
|
||||
assert!(!std::fs::read_dir(&minecraft).unwrap().any(|entry| {
|
||||
entry
|
||||
.unwrap()
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.starts_with(".rmcl-install-")
|
||||
}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replacing_a_disabled_root_keeps_its_disabled_filename_and_record() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let mut record = installed_record("a", "a1", false);
|
||||
record.relative_path = "mods/a.jar.disabled".into();
|
||||
let old = minecraft.join(&record.relative_path);
|
||||
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
|
||||
std::fs::write(&old, b"old").unwrap();
|
||||
record.fingerprint = super::super::manifest::fingerprint(&old).unwrap();
|
||||
let manifest = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record],
|
||||
};
|
||||
manifest.save(&manifest_path).unwrap();
|
||||
let a2 = release("a2", "a", Vec::new());
|
||||
let registry = provider(vec![a2.clone()]).registry();
|
||||
let mut selected = root(a2);
|
||||
selected.installed_path = Some(old.clone());
|
||||
let plan = resolve(®istry, &manifest, &minecraft, &instance(), selected)
|
||||
.await
|
||||
.unwrap();
|
||||
let installed = install(®istry, &manifest_path, &minecraft, &plan)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(installed.root_path, minecraft.join("mods/a2.jar.disabled"));
|
||||
assert_eq!(std::fs::read(&installed.root_path).unwrap(), b"a2");
|
||||
assert!(!old.exists());
|
||||
assert!(!ContentManifest::load(&manifest_path).unwrap().files[0].enabled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn installation_rejects_a_target_owned_by_another_record_even_when_missing() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let a2 = release("a2", "a", Vec::new());
|
||||
let registry = provider(vec![a2.clone()]).registry();
|
||||
let plan = resolve(
|
||||
®istry,
|
||||
&ContentManifest::default(),
|
||||
&minecraft,
|
||||
&instance(),
|
||||
root(a2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut record = installed_record("foreign", "foreign1", true);
|
||||
record.relative_path = "mods/a2.jar".into();
|
||||
let manifest = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record],
|
||||
};
|
||||
manifest.save(&manifest_path).unwrap();
|
||||
let error = install(®istry, &manifest_path, &minecraft, &plan)
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.to_string().contains("already owns"));
|
||||
assert_eq!(
|
||||
ContentManifest::load(&manifest_path).unwrap().files,
|
||||
manifest.files
|
||||
);
|
||||
assert!(!minecraft.join("mods/a2.jar").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn installation_rejects_linked_destinations_and_dangling_targets() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let outside = temp.path().join("outside");
|
||||
std::fs::create_dir_all(&minecraft).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let a2 = release("a2", "a", Vec::new());
|
||||
let registry = provider(vec![a2.clone()]).registry();
|
||||
let plan = resolve(
|
||||
®istry,
|
||||
&ContentManifest::default(),
|
||||
&minecraft,
|
||||
&instance(),
|
||||
root(a2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink(&outside, minecraft.join("mods")).unwrap();
|
||||
assert!(
|
||||
install(®istry, &manifest_path, &minecraft, &plan)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("symlink")
|
||||
);
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
std::fs::remove_file(minecraft.join("mods")).unwrap();
|
||||
std::fs::create_dir(minecraft.join("mods")).unwrap();
|
||||
let target = minecraft.join("mods/a2.jar");
|
||||
std::os::unix::fs::symlink(outside.join("missing"), &target).unwrap();
|
||||
assert!(
|
||||
install(®istry, &manifest_path, &minecraft, &plan)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("already exists")
|
||||
);
|
||||
assert!(
|
||||
std::fs::symlink_metadata(target)
|
||||
.unwrap()
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
);
|
||||
assert!(
|
||||
ContentManifest::load(&manifest_path)
|
||||
.unwrap()
|
||||
.files
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,22 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn half_block_pixels_keep_the_top_and_bottom_colors() {
|
||||
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(1, 2, |_, y| {
|
||||
if y == 0 {
|
||||
image::Rgb([255, 0, 0])
|
||||
} else {
|
||||
image::Rgb([0, 0, 255])
|
||||
}
|
||||
}));
|
||||
let rows = make_icon_pixels_from_image(&image, 1, 1);
|
||||
let cell = &rows[0][0];
|
||||
assert_eq!(cell.symbol, '▀');
|
||||
assert_eq!((cell.fg_r, cell.fg_g, cell.fg_b), (255, 0, 0));
|
||||
assert_eq!((cell.bg_r, cell.bg_g, cell.bg_b), (0, 0, 255));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quadrant_raster_has_requested_dimensions() {
|
||||
let image =
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn failed_publication_restores_the_current_backup_and_prior_moves() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let old = temp.path().join("old.jar");
|
||||
let prior = temp.path().join("prior.jar");
|
||||
let occupied = temp.path().join("occupied.jar");
|
||||
std::fs::write(&old, b"original").unwrap();
|
||||
std::fs::write(&prior, b"prior").unwrap();
|
||||
std::fs::create_dir(&occupied).unwrap();
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(temp.path()).unwrap());
|
||||
let first_backup = transaction.staging().join("first-backup");
|
||||
let backup = transaction.staging().join("backup");
|
||||
let download = transaction.staging().join("download");
|
||||
let first_download = transaction.staging().join("first-download");
|
||||
std::fs::write(&download, b"new").unwrap();
|
||||
std::fs::write(&first_download, b"new-prior").unwrap();
|
||||
transaction.move_path(&prior, &first_backup).unwrap();
|
||||
transaction.move_path(&first_download, &prior).unwrap();
|
||||
transaction.move_path(&old, &backup).unwrap();
|
||||
let error = transaction.move_path(&download, &occupied).unwrap_err();
|
||||
let result: io::Result<()> = transaction.finish(Err(error));
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read(old).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(prior).unwrap(), b"prior");
|
||||
assert!(occupied.is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollback_failure_keeps_backups_and_reports_both_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let old = temp.path().join("old.jar");
|
||||
std::fs::write(&old, b"original").unwrap();
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(temp.path()).unwrap());
|
||||
let staging = transaction.staging().to_owned();
|
||||
let backup = staging.join("backup");
|
||||
transaction.move_path(&old, &backup).unwrap();
|
||||
std::fs::write(&old, b"foreign").unwrap();
|
||||
let result: io::Result<()> = transaction.finish(Err(io::Error::other("publication failed")));
|
||||
let message = result.unwrap_err().to_string();
|
||||
assert!(message.contains("publication failed"));
|
||||
assert!(message.contains("rollback failed"));
|
||||
assert!(message.contains(&old.display().to_string()));
|
||||
assert!(message.contains(&backup.display().to_string()));
|
||||
drop(transaction);
|
||||
assert_eq!(std::fs::read(backup).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(old).unwrap(), b"foreign");
|
||||
assert!(staging.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_publication_undo_keeps_its_backup_and_restores_independent_files() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let first = temp.path().join("first.jar");
|
||||
let second = temp.path().join("second.jar");
|
||||
std::fs::write(&first, b"old-first").unwrap();
|
||||
std::fs::write(&second, b"old-second").unwrap();
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(temp.path()).unwrap());
|
||||
let staging = transaction.staging().to_owned();
|
||||
let first_download = staging.join("first-download");
|
||||
let second_download = staging.join("second-download");
|
||||
let first_backup = staging.join("first-backup");
|
||||
let second_backup = staging.join("second-backup");
|
||||
std::fs::write(&first_download, b"new-first").unwrap();
|
||||
std::fs::write(&second_download, b"new-second").unwrap();
|
||||
transaction.move_path(&first, &first_backup).unwrap();
|
||||
transaction.move_path(&first_download, &first).unwrap();
|
||||
transaction.move_path(&second, &second_backup).unwrap();
|
||||
transaction.move_path(&second_download, &second).unwrap();
|
||||
std::fs::write(&second_download, b"foreign").unwrap();
|
||||
|
||||
let result: io::Result<()> =
|
||||
transaction.finish(Err(io::Error::other("manifest publication failed")));
|
||||
let message = result.unwrap_err().to_string();
|
||||
assert!(message.contains("manifest publication failed"));
|
||||
assert!(message.contains(&second_download.display().to_string()));
|
||||
assert!(message.contains(&second_backup.display().to_string()));
|
||||
drop(transaction);
|
||||
assert_eq!(std::fs::read(first).unwrap(), b"old-first");
|
||||
assert_eq!(std::fs::read(second_backup).unwrap(), b"old-second");
|
||||
assert_eq!(std::fs::read(second).unwrap(), b"new-second");
|
||||
assert_eq!(std::fs::read(second_download).unwrap(), b"foreign");
|
||||
assert!(staging.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwinding_restores_files_and_retains_the_recovery_directory() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let old = temp.path().join("old.jar");
|
||||
std::fs::write(&old, b"old").unwrap();
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(temp.path()).unwrap());
|
||||
let staging = transaction.staging().to_owned();
|
||||
let backup = staging.join("backup");
|
||||
let result = std::panic::catch_unwind(move || {
|
||||
transaction.move_path(&old, &backup).unwrap();
|
||||
panic!("commit failed");
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read(temp.path().join("old.jar")).unwrap(), b"old");
|
||||
assert!(staging.exists());
|
||||
}
|
||||
|
||||
fn managed_mod(instance_dir: &Path) -> (PathBuf, PathBuf, ContentFileRecord) {
|
||||
let paths = crate::storage::InstancePaths::new(instance_dir.join("instance"));
|
||||
let minecraft = paths.minecraft();
|
||||
let manifest_path = paths.content_manifest();
|
||||
let path = minecraft.join("mods/example.jar");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
let record = ContentFileRecord {
|
||||
relative_path: "mods/example.jar".into(),
|
||||
kind: super::super::manifest::ContentKind::Mod,
|
||||
enabled: true,
|
||||
fingerprint: fingerprint(&path).unwrap(),
|
||||
resolution: crate::instance::Resolution::Resolved {
|
||||
project: super::super::manifest::ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: "example".to_owned(),
|
||||
version_id: "old".to_owned(),
|
||||
},
|
||||
},
|
||||
provider_aliases: Vec::new(),
|
||||
provider_checks: vec!["modrinth".to_owned()],
|
||||
required_dependencies: Vec::new(),
|
||||
automatic_dependency: true,
|
||||
cleanup_eligible: true,
|
||||
};
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record.clone()],
|
||||
}
|
||||
.save(&manifest_path)
|
||||
.unwrap();
|
||||
(minecraft, manifest_path, record)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggles_and_removals_share_the_install_guard_and_preserve_record_metadata() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, record) = managed_mod(temp.path());
|
||||
let old = minecraft.join(&record.relative_path);
|
||||
let mut entry = super::super::mods::scan_one_mod(&old, "example", true);
|
||||
entry.provider_project = record.resolved_project().cloned();
|
||||
let lock = ContentLock::acquire(&manifest_path).unwrap();
|
||||
assert!(
|
||||
toggle(&entry)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("another operation")
|
||||
);
|
||||
assert!(
|
||||
remove(
|
||||
&manifest_path,
|
||||
&minecraft,
|
||||
&old,
|
||||
std::slice::from_ref(&record),
|
||||
false
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("another operation")
|
||||
);
|
||||
assert_eq!(std::fs::read(&old).unwrap(), b"original");
|
||||
drop(lock);
|
||||
|
||||
let disabled = toggle(&entry).unwrap().unwrap();
|
||||
let mut expected = record;
|
||||
expected.relative_path = "mods/example.jar.disabled".into();
|
||||
expected.enabled = false;
|
||||
assert_eq!(
|
||||
ContentManifest::load(&manifest_path).unwrap().files,
|
||||
vec![expected.clone()]
|
||||
);
|
||||
assert_eq!(std::fs::read(&disabled).unwrap(), b"original");
|
||||
assert!(!old.exists());
|
||||
let (manifest, _) = remove(&manifest_path, &minecraft, &disabled, &[expected], true).unwrap();
|
||||
assert!(manifest.files.is_empty());
|
||||
assert!(!disabled.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_mutations_coordinate_with_the_instance_lifetime_guard() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, record) = managed_mod(temp.path());
|
||||
let instance_lock = crate::instance::runtime::lock_instance(temp.path(), "instance").unwrap();
|
||||
assert!(matches!(
|
||||
ContentLock::acquire(&manifest_path),
|
||||
Err(super::super::manifest::ManifestError::Busy(_))
|
||||
));
|
||||
let path = minecraft.join(&record.relative_path);
|
||||
assert!(remove(&manifest_path, &minecraft, &path, &[record], false).is_err());
|
||||
drop(instance_lock);
|
||||
let content_lock = ContentLock::acquire(&manifest_path).unwrap();
|
||||
assert!(crate::instance::runtime::lock_instance(temp.path(), "instance").is_err());
|
||||
drop(content_lock);
|
||||
crate::instance::runtime::lock_instance(temp.path(), "instance").unwrap();
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"original");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_content_actions_reject_new_ownership_and_changed_bytes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, record) = managed_mod(temp.path());
|
||||
let path = minecraft.join(&record.relative_path);
|
||||
let mut entry = super::super::mods::scan_one_mod(&path, "example", true);
|
||||
entry.provider_project = record.resolved_project().cloned();
|
||||
let mut current = record.clone();
|
||||
current.resolution = crate::instance::Resolution::Pending;
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![current],
|
||||
}
|
||||
.save(&manifest_path)
|
||||
.unwrap();
|
||||
assert!(
|
||||
toggle(&entry)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Ownership")
|
||||
);
|
||||
assert!(
|
||||
remove(
|
||||
&manifest_path,
|
||||
&minecraft,
|
||||
&path,
|
||||
std::slice::from_ref(&record),
|
||||
false
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Ownership")
|
||||
);
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record.clone()],
|
||||
}
|
||||
.save(&manifest_path)
|
||||
.unwrap();
|
||||
let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
|
||||
std::fs::write(&path, b"external").unwrap();
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap()
|
||||
.set_times(std::fs::FileTimes::new().set_modified(modified))
|
||||
.unwrap();
|
||||
assert!(toggle(&entry).unwrap_err().to_string().contains("changed"));
|
||||
assert!(
|
||||
remove(&manifest_path, &minecraft, &path, &[record], false)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("changed")
|
||||
);
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"external");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_world_validates_and_removes_its_descendant_records() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, mut record) = managed_mod(temp.path());
|
||||
let path = minecraft.join("saves/world/datapacks/example.zip");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"pack").unwrap();
|
||||
record.relative_path = "saves/world/datapacks/example.zip".into();
|
||||
record.kind = super::super::manifest::ContentKind::DataPack;
|
||||
record.fingerprint = fingerprint(&path).unwrap();
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record.clone()],
|
||||
}
|
||||
.save(&manifest_path)
|
||||
.unwrap();
|
||||
let world = minecraft.join("saves/world");
|
||||
assert!(
|
||||
remove(&manifest_path, &minecraft, &world, &[], false)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Ownership")
|
||||
);
|
||||
let (manifest, _) = remove(&manifest_path, &minecraft, &world, &[record], false).unwrap();
|
||||
assert!(manifest.files.is_empty());
|
||||
assert!(!world.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orphan_cleanup_rechecks_new_dependents_before_removing_a_library() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, record) = managed_mod(temp.path());
|
||||
let path = minecraft.join(&record.relative_path);
|
||||
let mut dependent = record.clone();
|
||||
dependent.relative_path = "mods/dependent.jar".into();
|
||||
dependent.automatic_dependency = false;
|
||||
dependent.cleanup_eligible = false;
|
||||
dependent.required_dependencies = vec![record.resolved_project().unwrap().clone()];
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![dependent, record.clone()],
|
||||
}
|
||||
.save(&manifest_path)
|
||||
.unwrap();
|
||||
assert!(
|
||||
remove(&manifest_path, &minecraft, &path, &[record], true)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("no longer an unused dependency")
|
||||
);
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"original");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_named_minecraft_uses_the_instance_manifest_and_lock() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, original) = managed_mod(temp.path());
|
||||
for (relative, kind, directory) in [
|
||||
(
|
||||
"saves/minecraft/datapacks/example.zip",
|
||||
super::super::manifest::ContentKind::DataPack,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"resourcepacks/minecraft",
|
||||
super::super::manifest::ContentKind::ResourcePack,
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let path = minecraft.join(relative);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
if directory {
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
std::fs::write(path.join("pack.mcmeta"), b"{}").unwrap();
|
||||
} else {
|
||||
std::fs::write(&path, b"pack").unwrap();
|
||||
}
|
||||
let mut record = original.clone();
|
||||
record.relative_path = relative.into();
|
||||
record.kind = kind;
|
||||
record.fingerprint = if directory {
|
||||
directory_fingerprint_metadata(&path).unwrap()
|
||||
} else {
|
||||
fingerprint(&path).unwrap()
|
||||
};
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record.clone()],
|
||||
}
|
||||
.save(&manifest_path)
|
||||
.unwrap();
|
||||
let mut entry = super::super::mods::scan_one_mod(&path, "example", true);
|
||||
entry.provider_project = record.resolved_project().cloned();
|
||||
let lock = ContentLock::acquire(&manifest_path).unwrap();
|
||||
assert!(
|
||||
toggle(&entry)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("another operation")
|
||||
);
|
||||
drop(lock);
|
||||
let new_path = toggle(&entry).unwrap().unwrap();
|
||||
let updated = ContentManifest::load(&manifest_path).unwrap();
|
||||
assert_eq!(minecraft.join(&updated.files[0].relative_path), new_path);
|
||||
assert!(!updated.files[0].enabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_manifest_publication_rolls_back_live_file_moves() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, record) = managed_mod(temp.path());
|
||||
let old = minecraft.join(&record.relative_path);
|
||||
let target = minecraft.join("mods/new.jar");
|
||||
let lock = ContentLock::acquire(&manifest_path).unwrap();
|
||||
let previous = lock.load().unwrap();
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(&minecraft).unwrap());
|
||||
let backup = transaction.staging().join("backup");
|
||||
let download = transaction.staging().join("download");
|
||||
std::fs::write(&download, b"new").unwrap();
|
||||
transaction.move_path(&old, &backup).unwrap();
|
||||
transaction.move_path(&download, &target).unwrap();
|
||||
std::fs::remove_file(&manifest_path).unwrap();
|
||||
std::fs::create_dir(&manifest_path).unwrap();
|
||||
let result = lock.save_if_unchanged(&previous, &previous);
|
||||
assert!(transaction.finish(result).is_err());
|
||||
assert_eq!(std::fs::read(old).unwrap(), b"original");
|
||||
assert!(!target.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_the_await_keeps_the_blocking_transaction_guard_until_completion() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (minecraft, manifest_path, record) = managed_mod(temp.path());
|
||||
let job_manifest = manifest_path.clone();
|
||||
let job_minecraft = minecraft.clone();
|
||||
let old = minecraft.join(&record.relative_path);
|
||||
let disabled = old.with_file_name("example.jar.disabled");
|
||||
let new_path = disabled.clone();
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel();
|
||||
let (finished_tx, finished_rx) = tokio::sync::oneshot::channel();
|
||||
let caller = tokio::spawn(async move {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let lock = ContentLock::acquire(&job_manifest).unwrap();
|
||||
let previous = lock.load().unwrap();
|
||||
let mut transaction =
|
||||
FileTransaction::new(StagingDirectory::new(&job_minecraft).unwrap());
|
||||
transaction.move_path(&old, &new_path).unwrap();
|
||||
started_tx.send(()).unwrap();
|
||||
release_rx
|
||||
.recv_timeout(std::time::Duration::from_secs(10))
|
||||
.unwrap();
|
||||
let mut manifest = previous.clone();
|
||||
assert!(manifest.rename_record(
|
||||
Path::new("mods/example.jar"),
|
||||
Path::new("mods/example.jar.disabled"),
|
||||
false
|
||||
));
|
||||
let result = lock.save_if_unchanged(&manifest, &previous);
|
||||
transaction.finish(result).unwrap();
|
||||
drop(transaction);
|
||||
drop(lock);
|
||||
let _ = finished_tx.send(());
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
started_rx.await.unwrap();
|
||||
caller.abort();
|
||||
assert!(caller.await.unwrap_err().is_cancelled());
|
||||
assert!(ContentLock::acquire(&manifest_path).is_err());
|
||||
release_tx.send(()).unwrap();
|
||||
finished_rx.await.unwrap();
|
||||
ContentLock::acquire(&manifest_path).unwrap();
|
||||
assert_eq!(std::fs::read(disabled).unwrap(), b"original");
|
||||
assert!(!ContentManifest::load(&manifest_path).unwrap().files[0].enabled);
|
||||
}
|
||||
@@ -3,6 +3,106 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn content_lock_excludes_independent_handles_until_drop() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("manifest.json");
|
||||
let lock = ContentLock::acquire(&path).unwrap();
|
||||
assert!(matches!(
|
||||
ContentLock::acquire(&path),
|
||||
Err(ManifestError::Busy(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
ContentManifest::update(&path, |_| Ok(())),
|
||||
Err(ManifestError::Busy(_))
|
||||
));
|
||||
drop(lock);
|
||||
assert!(path.with_extension("lock").exists());
|
||||
ContentLock::acquire(&path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_guard_releases_locks_with_duplicated_handles() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("instance/rmcl/content/manifest.json");
|
||||
let lock = ContentLock::acquire(&path).unwrap();
|
||||
let _manifest_handle = lock.file.try_clone().unwrap();
|
||||
let _instance_handle = lock.instance_lock.as_ref().unwrap().try_clone().unwrap();
|
||||
drop(lock);
|
||||
ContentLock::acquire(&path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_lock_excludes_other_processes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("manifest.json");
|
||||
let lock = ContentLock::acquire(&path).unwrap();
|
||||
let child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"instance::content::manifest::tests::content_lock_probe",
|
||||
])
|
||||
.env("RMCL_TEST_CONTENT_MANIFEST", &path)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
child.status.success(),
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&child.stdout),
|
||||
String::from_utf8_lossy(&child.stderr)
|
||||
);
|
||||
assert!(String::from_utf8_lossy(&child.stdout).contains("1 passed"));
|
||||
drop(lock);
|
||||
ContentLock::acquire(&path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_lock_probe() {
|
||||
if let Some(path) = std::env::var_os("RMCL_TEST_CONTENT_MANIFEST") {
|
||||
assert!(matches!(
|
||||
ContentLock::acquire(Path::new(&path)),
|
||||
Err(ManifestError::Busy(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guarded_publication_rejects_an_uncooperative_manifest_change() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("manifest.json");
|
||||
let previous = ContentManifest::default();
|
||||
previous.save(&path).unwrap();
|
||||
let lock = ContentLock::acquire(&path).unwrap();
|
||||
std::fs::write(&path, br#"{"version":1,"files":[{"relative_path":"mods/foreign.jar","kind":"mod","enabled":true,"fingerprint":{"size":1,"modified_ns":0,"hashes":{}}}]}"#).unwrap();
|
||||
assert!(matches!(
|
||||
lock.save_if_unchanged(&previous, &previous),
|
||||
Err(ManifestError::Changed(_))
|
||||
));
|
||||
assert_eq!(
|
||||
ContentManifest::load(&path).unwrap().files[0].relative_path,
|
||||
Path::new("mods/foreign.jar")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_rejects_duplicate_and_escaping_ownership_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("manifest.json");
|
||||
for (relative, copies) in [("../escape.jar", 1), ("mods/a.jar", 2)] {
|
||||
let record = serde_json::json!({
|
||||
"relative_path": relative, "kind": "mod", "enabled": true,
|
||||
"fingerprint": { "size": 0, "modified_ns": 0, "hashes": {} },
|
||||
});
|
||||
let files = vec![record; copies];
|
||||
let manifest = serde_json::json!({ "version": 1, "files": files });
|
||||
std::fs::write(&path, serde_json::to_vec(&manifest).unwrap()).unwrap();
|
||||
assert!(matches!(
|
||||
ContentManifest::load(&path),
|
||||
Err(ManifestError::InvalidPath(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curseforge_fingerprint_ignores_whitespace() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
@@ -21,7 +121,7 @@ fn curseforge_fingerprint_ignores_whitespace() {
|
||||
#[test]
|
||||
fn manifest_round_trip_and_lookup_are_exact() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("rmcl/content/manifest.json");
|
||||
let path = temp.path().join("instance/rmcl/content/manifest.json");
|
||||
let record = ContentFileRecord {
|
||||
relative_path: PathBuf::from("mods/fabric-api.jar"),
|
||||
kind: ContentKind::Mod,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use super::*;
|
||||
use crate::instance::FileFingerprint;
|
||||
|
||||
struct NoopProgress;
|
||||
|
||||
@@ -20,6 +21,24 @@ fn linked_pack_contents_cannot_recurse_into_themselves() {
|
||||
assert_eq!(directory_fingerprint_metadata(&pack).unwrap().size, 4);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn inventory_rejects_content_directories_linked_outside_the_instance() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let outside = temp.path().join("outside");
|
||||
std::fs::create_dir_all(&minecraft).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(outside.join("foreign.jar"), b"foreign").unwrap();
|
||||
std::os::unix::fs::symlink(&outside, minecraft.join("mods")).unwrap();
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let error = reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.to_string().contains("symlink"));
|
||||
assert!(!manifest_path.exists());
|
||||
}
|
||||
|
||||
impl InventoryProgress for NoopProgress {
|
||||
fn set_sub_action(&self, _text: &str) {}
|
||||
|
||||
@@ -164,17 +183,98 @@ fn newly_configured_provider_retries_an_unmatched_record() {
|
||||
assert!(!provider_was_not_checked(&record, "curseforge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconciliation_keeps_newer_provider_ownership_for_unchanged_bytes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let path = minecraft.join("mods/example.jar");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
let mut record = resolved_record();
|
||||
record.fingerprint = fingerprint(&path).unwrap();
|
||||
let previous = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![record.clone()],
|
||||
};
|
||||
let mut current = previous.clone();
|
||||
current.files[0].resolution = Resolution::Resolved {
|
||||
project: ProviderProject {
|
||||
provider: "curseforge".to_owned(),
|
||||
project_id: "chosen".to_owned(),
|
||||
version_id: "new".to_owned(),
|
||||
},
|
||||
};
|
||||
current.files[0].provider_aliases = vec![record.resolved_project().unwrap().clone()];
|
||||
current.save(&manifest_path).unwrap();
|
||||
let saved =
|
||||
save_reconciled_manifest(&manifest_path, &minecraft, previous.clone(), &previous).unwrap();
|
||||
assert_eq!(saved.files, current.files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconciliation_revalidates_hashes_after_provider_matching() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let path = minecraft.join("mods/example.jar");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
let mut inventory =
|
||||
reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
|
||||
inventory.manifest.files[0].resolution = resolved_record().resolution;
|
||||
let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
|
||||
std::fs::write(&path, b"external").unwrap();
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap()
|
||||
.set_times(std::fs::FileTimes::new().set_modified(modified))
|
||||
.unwrap();
|
||||
let saved = save_reconciled_manifest(
|
||||
&manifest_path,
|
||||
&minecraft,
|
||||
inventory.manifest,
|
||||
&inventory.previous,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(saved.files.is_empty());
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"external");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_incomplete_directory_scan_does_not_publish_a_partial_inventory() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let pack = minecraft.join("resourcepacks/example.zip");
|
||||
std::fs::create_dir_all(pack.parent().unwrap()).unwrap();
|
||||
std::fs::write(&pack, b"pack").unwrap();
|
||||
let first = reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
|
||||
first.manifest.save(&manifest_path).unwrap();
|
||||
let saved_bytes = std::fs::read(&manifest_path).unwrap();
|
||||
std::fs::write(minecraft.join("mods"), b"not a directory").unwrap();
|
||||
assert!(reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).is_err());
|
||||
assert_eq!(std::fs::read(manifest_path).unwrap(), saved_bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconciliation_saves_provider_aliases_for_an_existing_resolution() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let manifest_path = temp.path().join("manifest.json");
|
||||
let minecraft = temp.path().join("minecraft");
|
||||
let mut record = resolved_record();
|
||||
let path = minecraft.join(&record.relative_path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
record.fingerprint = fingerprint(&path).unwrap();
|
||||
let current = ContentManifest {
|
||||
version: 1,
|
||||
files: vec![resolved_record()],
|
||||
files: vec![record.clone()],
|
||||
};
|
||||
current.save(&manifest_path).unwrap();
|
||||
|
||||
let mut enriched = resolved_record();
|
||||
let mut enriched = record;
|
||||
enriched.provider_aliases.push(ProviderProject {
|
||||
provider: "curseforge".to_owned(),
|
||||
project_id: "42".to_owned(),
|
||||
@@ -183,15 +283,41 @@ fn reconciliation_saves_provider_aliases_for_an_existing_resolution() {
|
||||
enriched.provider_checks = vec!["modrinth".to_owned(), "curseforge".to_owned()];
|
||||
let saved = save_reconciled_manifest(
|
||||
&manifest_path,
|
||||
&temp.path().join("minecraft"),
|
||||
&minecraft,
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![enriched.clone()],
|
||||
},
|
||||
¤t,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(saved.files, vec![enriched]);
|
||||
let stale = saved.clone();
|
||||
let mut managed = saved;
|
||||
managed.files[0].automatic_dependency = true;
|
||||
managed.files[0].cleanup_eligible = true;
|
||||
managed.save(&manifest_path).unwrap();
|
||||
let merged =
|
||||
save_reconciled_manifest(&manifest_path, &minecraft, stale.clone(), &stale).unwrap();
|
||||
assert!(merged.files[0].automatic_dependency);
|
||||
std::fs::write(&path, b"replacement").unwrap();
|
||||
let mut newer = merged.clone();
|
||||
newer.files[0].fingerprint = fingerprint(&path).unwrap();
|
||||
newer.save(&manifest_path).unwrap();
|
||||
assert_eq!(
|
||||
save_reconciled_manifest(&manifest_path, &minecraft, stale.clone(), &stale)
|
||||
.unwrap()
|
||||
.files,
|
||||
newer.files
|
||||
);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
assert!(
|
||||
save_reconciled_manifest(&manifest_path, &minecraft, stale.clone(), &stale)
|
||||
.unwrap()
|
||||
.files
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,6 +7,24 @@ use flate2::{Compression, write::GzEncoder};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn oversized_and_malformed_world_metadata_fall_back() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
for bytes in [
|
||||
vec![0; (super::super::MAX_LOCAL_METADATA_BYTES + 1) as usize],
|
||||
// Root compound, unknown byte array with a huge declared length and no payload.
|
||||
vec![10, 0, 0, 7, 0, 1, b'x', 0x7f, 0xff, 0xff, 0xff],
|
||||
] {
|
||||
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(&bytes).unwrap();
|
||||
std::fs::write(temp.path().join("level.dat"), encoder.finish().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
scan_one_world(temp.path(), "fallback", true).name,
|
||||
"fallback"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_scan_uses_level_dat_metadata_and_falls_back_cleanly() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in new issue
Block a user