//! Pure planning and auditable M2 file operations. One batch at a time per mods directory.
use crate::{
Result,
download::{self, Progress, VerifiedTemp},
local_mods::{BUILTIN_ORDER, LocalMod, ModSource, builtin_rank},
mod_list::{self, ModList, ModListEntry},
net::Stream,
portal::{PortalModFull, Release},
store::{self, Snapshot},
updates::newest_compatible_release,
version::{
Dependency, DependencyKind, compare_versions, game_line, parse_dependency, satisfies,
},
};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::{Path, PathBuf},
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
#[derive(Clone, Debug)]
pub struct Action {
pub name: String,
/// None means removal. Installation and update both carry the full portal release.
pub release: Option<Release>,
pub previous: Vec<LocalMod>,
pub required: Vec<Dependency>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Outcome {
pub name: String,
pub ok: bool,
pub message: String,
}
impl Outcome {
fn failed(name: &str, error: impl std::fmt::Display) -> Self {
Self {
name: name.into(),
ok: false,
message: error.to_string(),
}
}
}
#[derive(Clone, Debug)]
pub struct Plan {
actions: Vec<Action>,
failures: Vec<Outcome>,
warnings: Vec<String>,
optional: Vec<String>,
snapshot: Snapshot,
}
impl Plan {
pub fn actions(&self) -> &[Action] {
&self.actions
}
pub fn failures(&self) -> &[Outcome] {
&self.failures
}
pub fn warnings(&self) -> &[String] {
&self.warnings
}
pub fn optional(&self) -> &[String] {
&self.optional
}
/// `/full` has no archive size field. GET progress supplies Content-Length later.
pub fn total_download_bytes(&self) -> Option<u64> {
self.actions
.iter()
.all(|a| a.release.is_none())
.then_some(0)
}
}
/// The lookup must supply `/full`, not the namelist's dependency-free info_json.
pub fn plan_install(
names: &[String],
snapshot: &Snapshot,
lookup: &dyn Fn(&str) -> Result<PortalModFull>,
game_version: &str,
) -> Plan {
plan_downloads(names, snapshot, lookup, game_version, false, &[])
}
pub fn plan_updates_selected(
names: &[String],
snapshot: &Snapshot,
lookup: &dyn Fn(&str) -> Result<PortalModFull>,
game_version: &str,
) -> Plan {
plan_downloads(names, snapshot, lookup, game_version, true, &[])
}
/// M3's missing-dependency action retains the same M2 apply pipeline and applies
/// every requesting constraint, including when a compatible older version is needed.
pub fn plan_dependencies(
dependencies: &[Dependency],
snapshot: &Snapshot,
lookup: &dyn Fn(&str) -> Result<PortalModFull>,
game_version: &str,
) -> Plan {
let names = dependencies
.iter()
.map(|d| d.name.clone())
.collect::<Vec<_>>();
plan_downloads(&names, snapshot, lookup, game_version, false, dependencies)
}
fn empty_plan(snapshot: &Snapshot) -> Plan {
Plan {
actions: vec![],
failures: vec![],
warnings: vec![],
optional: vec![],
snapshot: snapshot.clone(),
}
}
fn plan_downloads(
names: &[String],
snapshot: &Snapshot,
lookup: &dyn Fn(&str) -> Result<PortalModFull>,
game: &str,
updates_only: bool,
constraints: &[Dependency],
) -> Plan {
let mut plan = empty_plan(snapshot);
if game_line(game) != game_line(&snapshot.paths.game_version) {
plan.failures = names
.iter()
.map(|name| {
Outcome::failed(
name,
"Requested game line does not match the installed game",
)
})
.collect();
return plan;
}
let mut roots = BTreeMap::new();
let mut metadata = BTreeMap::new();
for name in names.iter().collect::<BTreeSet<_>>() {
let result: Result<_> = (|| {
if updates_only && installed(snapshot, name).is_empty() {
return Err("Mod is not installed".into());
}
reject_builtin(snapshot, name)?;
let previous = installed(snapshot, name);
let mut full = full_metadata(name, lookup, &mut metadata)?;
let requirements: Vec<_> = constraints.iter().filter(|d| d.name == *name).collect();
if let Some(releases) = full.mod_.releases.as_mut() {
releases.retain(|r| requirements.iter().all(|d| satisfies(&r.version, d)));
}
let release = newest_compatible_release(&full.mod_, game)
.ok_or_else(|| format!("No compatible release for {name}"))?
.clone();
if current(snapshot, name).is_some_and(|m| {
!compare_versions(&release.version, &m.version).is_gt()
&& requirements.iter().all(|d| satisfies(&m.version, d))
}) {
return Ok(None);
}
let action = make_action(name, release, previous)?;
let mut candidate = roots.clone();
candidate.insert(name.clone(), action);
let actions = resolve_graph(&candidate, snapshot, lookup, &mut metadata, game)?;
Ok(Some((candidate, actions)))
})();
match result {
Ok(Some((candidate, actions))) => {
roots = candidate;
plan.actions = actions;
}
Ok(None) => {}
Err(error) => plan.failures.push(Outcome::failed(name, error)),
}
}
for action in &plan.actions {
for text in action
.release
.as_ref()
.unwrap()
.info_json
.dependencies
.as_ref()
.unwrap()
{
let dep = parse_dependency(text).expect("validated dependency");
match dep.kind {
// Only optional mods the owner doesn't have; built-ins and installed mods aren't news.
DependencyKind::Optional | DependencyKind::HiddenOptional
if !snapshot
.mods
.iter()
.chain(&snapshot.builtin)
.any(|m| m.name == dep.name) =>
{
plan.optional.push(text.clone())
}
DependencyKind::Incompatible
if snapshot
.mods
.iter()
.chain(&snapshot.builtin)
.any(|m| m.name == dep.name && satisfies(&m.version, &dep))
&& mod_list::is_enabled(&snapshot.mod_list, &dep.name) =>
{
plan.warnings.push(format!(
"{} is incompatible with enabled mod {}",
action.name, dep.name
));
}
_ => {}
}
}
}
plan.optional.sort();
plan.optional.dedup();
plan.warnings.sort();
plan.warnings.dedup();
plan
}
fn installed(snapshot: &Snapshot, name: &str) -> Vec<LocalMod> {
snapshot
.mods
.iter()
.filter(|m| m.name == name)
.cloned()
.collect()
}
fn current<'a>(snapshot: &'a Snapshot, name: &str) -> Option<&'a LocalMod> {
let pin = snapshot
.mod_list
.mods
.iter()
.find(|m| m.name == name)
.and_then(|m| m.version.as_deref());
snapshot
.mods
.iter()
.filter(|m| m.name == name && pin.is_none_or(|p| m.version == p))
.max_by(|a, b| compare_versions(&a.version, &b.version))
}
fn is_builtin(snapshot: &Snapshot, name: &str) -> bool {
builtin_rank(name) < BUILTIN_ORDER.len()
|| snapshot
.builtin
.iter()
.chain(&snapshot.mods)
.any(|m| m.name == name && m.source == ModSource::Builtin)
}
fn reject_builtin(snapshot: &Snapshot, name: &str) -> Result<()> {
download::safe_component(name)?;
if is_builtin(snapshot, name) {
return Err("Built-in mods cannot be installed or updated".into());
}
Ok(())
}
fn full_metadata(
name: &str,
lookup: &dyn Fn(&str) -> Result<PortalModFull>,
cache: &mut BTreeMap<String, PortalModFull>,
) -> Result<PortalModFull> {
download::safe_component(name)?;
if let Some(full) = cache.get(name) {
return Ok(full.clone());
}
let full = lookup(name)?;
if full.mod_.name != name {
return Err("Portal metadata name mismatch".into());
}
if full.mod_.releases.is_none() {
return Err("Expected /full release list".into());
}
cache.insert(name.into(), full.clone());
Ok(full)
}
fn make_action(name: &str, release: Release, previous: Vec<LocalMod>) -> Result<Action> {
download::validate_identity(name, &release)?;
let mut required = Vec::new();
for text in release
.info_json
.dependencies
.as_ref()
.ok_or("Expected dependencies from /full metadata")?
{
let dep = parse_dependency(text).ok_or_else(|| format!("Invalid dependency: {text}"))?;
download::safe_component(&dep.name)?;
if matches!(
dep.kind,
DependencyKind::Required | DependencyKind::NoLoadOrder
) {
required.push(dep);
}
}
Ok(Action {
name: name.into(),
release: Some(release),
previous,
required,
})
}
fn signature(actions: &BTreeMap<String, Action>) -> Vec<(String, String)> {
actions
.iter()
.map(|(n, a)| (n.clone(), a.release.as_ref().unwrap().version.clone()))
.collect()
}
fn resolve_graph(
roots: &BTreeMap<String, Action>,
snapshot: &Snapshot,
lookup: &dyn Fn(&str) -> Result<PortalModFull>,
cache: &mut BTreeMap<String, PortalModFull>,
game: &str,
) -> Result<Vec<Action>> {
let mut actions = roots.clone();
let mut seen = BTreeSet::new();
loop {
let state = signature(&actions);
if !seen.insert(state.clone()) {
return Err("Dependency constraints do not have a stable compatible plan".into());
}
let mut constraints: BTreeMap<String, Vec<Dependency>> = BTreeMap::new();
for action in actions.values() {
for dep in &action.required {
constraints
.entry(dep.name.clone())
.or_default()
.push(dep.clone());
}
}
let mut next = roots.clone();
for (name, required) in constraints {
let accepts = |version: &str| required.iter().all(|d| satisfies(version, d));
if is_builtin(snapshot, &name) {
if !snapshot
.builtin
.iter()
.any(|m| m.name == name && accepts(&m.version))
{
return Err(format!(
"Missing required built-in or unsupported version: {name}"
)
.into());
}
} else if let Some(root) = roots.get(&name) {
if !accepts(&root.release.as_ref().unwrap().version) {
return Err(format!(
"Conflicting dependency constraints for requested mod {name}"
)
.into());
}
} else if !current(snapshot, &name).is_some_and(|m| accepts(&m.version)) {
let previous = installed(snapshot, &name);
let mut full = full_metadata(&name, lookup, cache)?;
full.mod_
.releases
.as_mut()
.unwrap()
.retain(|r| accepts(&r.version));
let release = newest_compatible_release(&full.mod_, game)
.ok_or_else(|| {
format!(
"No compatible release satisfying all dependency constraints for {name}"
)
})?
.clone();
next.insert(name.clone(), make_action(&name, release, previous)?);
}
}
if signature(&next) == state {
let mut ordered = Vec::new();
let mut visiting = BTreeSet::new();
let mut done = BTreeSet::new();
for name in roots.keys() {
order_actions(name, &next, &mut visiting, &mut done, &mut ordered)?;
}
return Ok(ordered);
}
actions = next;
}
}
fn order_actions(
name: &str,
actions: &BTreeMap<String, Action>,
visiting: &mut BTreeSet<String>,
done: &mut BTreeSet<String>,
ordered: &mut Vec<Action>,
) -> Result<()> {
if done.contains(name) {
return Ok(());
}
let Some(action) = actions.get(name) else {
return Ok(());
};
if !visiting.insert(name.into()) {
return Err(format!("Required dependency cycle involving {name}").into());
}
for dep in &action.required {
order_actions(&dep.name, actions, visiting, done, ordered)?;
}
visiting.remove(name);
done.insert(name.into());
ordered.push(action.clone());
Ok(())
}
pub fn plan_remove(names: &[String], snapshot: &Snapshot) -> Plan {
let mut plan = empty_plan(snapshot);
for name in names.iter().collect::<BTreeSet<_>>() {
let previous: Vec<_> = snapshot
.mods
.iter()
.filter(|m| m.name == *name)
.cloned()
.collect();
let result: Result<()> = (|| {
download::safe_component(name)?;
if builtin_rank(name) < BUILTIN_ORDER.len()
|| snapshot.builtin.iter().any(|m| m.name == *name)
|| previous.iter().any(|m| m.source == ModSource::Builtin)
{
return Err("Built-in mods cannot be removed".into());
}
if previous.is_empty() {
return Err("Mod is not installed".into());
}
Ok(())
})();
match result {
Ok(()) => plan.actions.push(Action {
name: name.clone(),
release: None,
previous,
required: vec![],
}),
Err(error) => plan.failures.push(Outcome::failed(name, error)),
}
}
plan
}
#[derive(Debug, Default)]
pub struct Report {
pub mods: Vec<Outcome>,
}
impl Report {
pub fn summary(&self) -> String {
let ok = self.mods.iter().filter(|m| m.ok).count();
let failures: Vec<_> = self
.mods
.iter()
.filter(|m| !m.ok)
.map(|m| format!("{}: {}", m.name, m.message))
.collect();
if failures.is_empty() {
format!("{ok} mods completed")
} else {
format!(
"{ok} mods completed, {} failed: {}",
failures.len(),
failures.join("; ")
)
}
}
}
/// Injection boundary for every move and the single metadata commit. Implementations must
/// never replace an existing destination, and a failed write must leave mod-list unchanged.
pub trait FileOps {
fn rename(&self, from: &Path, to: &Path) -> Result<()>;
fn trash(&self, path: &Path) -> Result<()>;
fn write_mod_list(&self, path: &Path, list: &ModList) -> Result<()>;
}
/// Desktop terminology shared by confirmations and operation/recovery results.
pub const TRASH_NAME: &str = if cfg!(any(target_os = "linux", target_os = "macos")) {
"Trash"
} else {
"Recycle Bin"
};
pub struct Disk;
impl FileOps for Disk {
fn trash(&self, path: &Path) -> Result<()> {
let parent = path.parent().ok_or("Missing trash parent")?;
if !matches!(
parent.file_name().and_then(|n| n.to_str()),
Some("mods" | "mod-backups")
) {
return Err("Refusing trash outside mods or mod-backups".into());
}
download::ordinary(parent)?;
#[cfg(target_os = "linux")]
{
crate::linux::trash(path)
}
#[cfg(target_os = "macos")]
{
crate::macos::trash(path)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
trash_windows(path)
}
}
fn rename(&self, from: &Path, to: &Path) -> Result<()> {
// Decision 4: also used in rollback, so no branch may overwrite a mod or backup.
if fs::symlink_metadata(to).is_ok() {
return Err(format!("Destination already exists: {}", to.display()).into());
}
rename_no_replace(from, to)
}
fn write_mod_list(&self, path: &Path, list: &ModList) -> Result<()> {
mod_list::write_mod_list(path, list)
}
}
#[cfg(windows)]
fn trash_windows(path: &Path) -> Result<()> {
#[repr(C)]
struct FileOperation {
hwnd: *mut std::ffi::c_void,
function: u32,
from: *const u16,
to: *const u16,
flags: u16,
aborted: i32,
mappings: *mut std::ffi::c_void,
title: *const u16,
}
#[link(name = "shell32")]
unsafe extern "system" {
fn SHFileOperationW(operation: *mut FileOperation) -> i32;
}
download::ordinary(path)?;
// SHFileOperation does not accept extended-length paths. Resolve the parent only;
// never follow a link at the target. The caller validates the allowed directory.
let path = fs::canonicalize(path.parent().ok_or("Missing trash parent")?)?
.join(path.file_name().ok_or("Missing trash filename")?);
let wide = shell_trash_path(&path)?;
let mut operation = FileOperation {
hwnd: std::ptr::null_mut(),
function: 3, // FO_DELETE
from: wide.as_ptr(),
to: std::ptr::null(),
// ALLOWUNDO | NOCONFIRMATION | SILENT | WANTNUKEWARNING. Windows must
// ask before an item too large for the Recycle Bin is deleted permanently.
flags: 0x0040 | 0x0010 | 0x0004 | 0x4000,
aborted: 0,
mappings: std::ptr::null_mut(),
title: std::ptr::null(),
};
let code = unsafe { SHFileOperationW(&mut operation) };
if code != 0 || operation.aborted != 0 {
return Err(format!("Recycle Bin operation failed or cancelled (code {code})").into());
}
Ok(())
}
#[cfg(windows)]
fn shell_trash_path(path: &Path) -> Result<Vec<u16>> {
use std::os::windows::ffi::OsStrExt;
let mut wide: Vec<_> = path.as_os_str().encode_wide().collect();
if wide.starts_with(&[92, 92, 63, 92, 85, 78, 67, 92]) {
wide.splice(..8, [92, 92]);
} else if wide.starts_with(&[92, 92, 63, 92]) {
if wide.get(5) != Some(&58) || wide.get(6) != Some(&92) {
return Err("Unsupported extended trash path".into());
}
wide.drain(..4);
}
if !path.is_absolute() || wide.iter().any(|c| [0, 42, 63].contains(c)) {
return Err("Invalid trash path".into());
}
wide.extend([0, 0]);
Ok(wide)
}
#[cfg(all(test, windows))]
mod trash_path_tests {
use super::*;
use std::{
ffi::OsString,
os::windows::ffi::{OsStrExt, OsStringExt},
};
#[test]
fn shell_paths_preserve_utf16_unc_roots_and_double_nul() {
for (source, expected) in [
(r"\\?\C:\user\mods\a.zip", r"C:\user\mods\a.zip"),
(
r"\\?\UNC\server\share\mods\a.zip",
r"\\server\share\mods\a.zip",
),
] {
let mut expected: Vec<_> = OsString::from(expected).encode_wide().collect();
expected.extend([0, 0]);
assert_eq!(shell_trash_path(Path::new(source)).unwrap(), expected);
}
let mut units: Vec<_> = r"C:\user\mods\".encode_utf16().collect();
units.push(0xd800);
units.extend(".zip".encode_utf16());
let source = OsString::from_wide(&units);
units.extend([0, 0]);
assert_eq!(shell_trash_path(Path::new(&source)).unwrap(), units);
for source in [
r"C:\mods\*.zip",
r"relative\mods\a.zip",
r"\\?\Volume{abc}\mods\a.zip",
] {
assert!(shell_trash_path(Path::new(source)).is_err());
}
}
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn trash_windows(_path: &Path) -> Result<()> {
Err("Recycle Bin is implemented for Windows only".into())
}
fn trash_inside(
path: &Path,
directory: &Path,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
) -> Result<()> {
if path.parent() != Some(directory)
|| !matches!(
directory.file_name().and_then(|n| n.to_str()),
Some("mods" | "mod-backups")
)
{
return Err("Refusing trash outside mods or mod-backups".into());
}
download::ordinary(directory)?;
download::ordinary(path)?;
download::stopped(running)?;
disk.trash(path)
}
#[cfg(windows)]
fn rename_no_replace(from: &Path, to: &Path) -> Result<()> {
use std::os::windows::ffi::OsStrExt;
#[link(name = "kernel32")]
unsafe extern "system" {
fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32;
}
let wide = |path: &Path| -> Result<Vec<u16>> {
let parent = fs::canonicalize(path.parent().ok_or("Missing move parent")?)?;
let path = parent.join(path.file_name().ok_or("Missing move filename")?);
let mut value: Vec<_> = path.as_os_str().encode_wide().collect();
if value.contains(&0) {
return Err("NUL in move path".into());
}
value.push(0);
Ok(value)
};
let from = wide(from)?;
let to = wide(to)?;
// Decision 4: std::fs::rename uses REPLACE_EXISTING on Windows. Flags 0 refuse
// replacement atomically, including a destination appearing after our existence check.
if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 0) } == 0 {
return Err(std::io::Error::last_os_error().into());
}
Ok(())
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn rename_no_replace(_from: &Path, _to: &Path) -> Result<()> {
Err("Safe mod moves are implemented for Windows only".into())
}
pub struct DownloadOutcome {
pub name: String,
pub result: Result<VerifiedTemp>,
}
/// One immutable token per planned mod: dependencies never share cancellation state.
#[derive(Clone, Default)]
pub struct DownloadQueue(BTreeMap<String, Arc<AtomicBool>>);
impl DownloadQueue {
pub fn new(plan: &Plan) -> Self {
Self(
plan.actions
.iter()
.filter(|a| a.release.is_some())
.map(|a| (a.name.clone(), Arc::new(AtomicBool::new(false))))
.collect(),
)
}
pub fn cancel(&self, name: &str) {
if let Some(token) = self.0.get(name) {
token.store(true, Ordering::Relaxed);
}
}
pub fn cancelled(&self, name: &str) -> bool {
self.0.get(name).is_some_and(|t| t.load(Ordering::Relaxed))
}
}
/// Convenience entry point: one download in flight, checks before downloads and apply.
pub fn run_batch(
plan: &Plan,
transport: &dyn Stream,
progress: &mut dyn FnMut(&str, Progress),
cancel: &AtomicBool,
) -> Report {
run_batch_with(
plan,
transport,
progress,
cancel,
&store::is_factorio_running,
&Disk,
)
}
pub fn run_queue_with_checks(
plan: &Plan,
transport: &dyn Stream,
progress: &mut dyn FnMut(&str, Progress),
queue: &DownloadQueue,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
verify_sha1: bool,
) -> Report {
run_batch_tokens(
plan,
transport,
progress,
&|name| &queue.0[name],
running,
disk,
verify_sha1,
)
}
pub fn run_batch_with(
plan: &Plan,
transport: &dyn Stream,
progress: &mut dyn FnMut(&str, Progress),
cancel: &AtomicBool,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
) -> Report {
run_batch_with_checks(plan, transport, progress, cancel, running, disk, true)
}
pub fn run_batch_with_policy(
plan: &Plan,
transport: &dyn Stream,
progress: &mut dyn FnMut(&str, Progress),
cancel: &AtomicBool,
verify_sha1: bool,
) -> Report {
run_batch_with_checks(
plan,
transport,
progress,
cancel,
&store::is_factorio_running,
&Disk,
verify_sha1,
)
}
pub fn run_batch_with_checks(
plan: &Plan,
transport: &dyn Stream,
progress: &mut dyn FnMut(&str, Progress),
cancel: &AtomicBool,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
verify_sha1: bool,
) -> Report {
run_batch_tokens(
plan,
transport,
progress,
&|_| cancel,
running,
disk,
verify_sha1,
)
}
fn run_batch_tokens<'a>(
plan: &Plan,
transport: &dyn Stream,
progress: &mut dyn FnMut(&str, Progress),
token: &dyn Fn(&str) -> &'a AtomicBool,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
verify_sha1: bool,
) -> Report {
if let Err(error) = preflight(plan) {
return rejected(plan, error);
}
let downloads = plan
.actions
.iter()
.filter_map(|action| {
action.release.as_ref().map(|release| {
let guarded =
|| action_running(action, &plan.snapshot.paths.mod_list_path, running);
let result = download::download_with_policy(
&action.name,
release,
&plan.snapshot.paths.mods_dir,
transport,
&mut |p| progress(&action.name, p),
token(&action.name),
download::Checks {
sha1: verify_sha1,
running: &guarded,
},
);
DownloadOutcome {
name: action.name.clone(),
result,
}
})
})
.collect::<Vec<_>>();
// Completed transfers can still be cancelled while waiting for promotion.
apply_with_cancel(plan, downloads, running, disk, &|name| {
token(name).load(Ordering::Relaxed)
})
}
pub fn apply(plan: &Plan, downloads: Vec<DownloadOutcome>) -> Report {
apply_with(plan, downloads, &store::is_factorio_running, &Disk)
}
pub fn apply_with(
plan: &Plan,
downloads: Vec<DownloadOutcome>,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
) -> Report {
apply_with_cancel(plan, downloads, running, disk, &|_| false)
}
fn apply_with_cancel(
plan: &Plan,
downloads: Vec<DownloadOutcome>,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
cancelled: &dyn Fn(&str) -> bool,
) -> Report {
if let Err(error) = preflight(plan) {
return rejected(plan, error);
}
let mut downloads: BTreeMap<_, _> = downloads.into_iter().map(|d| (d.name, d.result)).collect();
let mut report = Report {
mods: plan.failures.clone(),
};
let mut applied = Vec::new();
for action in &plan.actions {
let result = (|| {
if action.release.is_some() && cancelled(&action.name) {
return Err("Download cancelled".into());
}
let temp = if let Some(release) = &action.release {
let temp = downloads
.remove(&action.name)
.ok_or("No verified download supplied")??;
if temp.name != action.name
|| temp.release.version != release.version
|| temp.release.sha1 != release.sha1
|| temp.path
!= plan
.snapshot
.paths
.mods_dir
.join(format!("{}_{}.zip.fmm-part", action.name, release.version))
{
return Err("Verified download does not match plan".into());
}
download::verify(&temp)?;
Some(temp)
} else {
None
};
if action.release.is_some() && cancelled(&action.name) {
return Err("Download cancelled".into());
}
let guarded = || action_running(action, &plan.snapshot.paths.mod_list_path, running);
apply_one(action, temp, &plan.snapshot.paths.mods_dir, &guarded, disk)
})();
match result {
Ok(change) => {
// A new archive is independent of mod-list.json, including commit recovery.
if !action.previous.is_empty() {
applied.push(change);
}
report.mods.push(Outcome {
name: action.name.clone(),
ok: true,
message: if action.release.is_none() {
format!("Moved to the {TRASH_NAME}")
} else {
"Installed".into()
},
});
}
Err(error) => {
report.mods.push(Outcome::failed(&action.name, error));
}
}
}
if !applied.is_empty() {
// Allowed removals never write while Factorio owns its list: retain saved
// disabled entries and leave unlisted mods absent until the game exits.
let game_running = running();
applied.retain(|change| {
let action = plan.actions.iter().find(|a| a.name == change.name).unwrap();
!(game_running
&& action.release.is_none()
&& !plan
.snapshot
.mod_list
.mods
.iter()
.any(|entry| entry.name == action.name && entry.enabled))
});
let mut list = plan.snapshot.mod_list.clone();
for change in &applied {
update_list(
&mut list,
plan.actions.iter().find(|a| a.name == change.name).unwrap(),
);
}
let result = if applied.is_empty() {
Ok(())
} else {
download::stopped(running)
.and_then(|_| {
if mod_list::read_mod_list(&plan.snapshot.paths.mod_list_path)?
!= plan.snapshot.mod_list
{
return Err("mod-list.json changed; rescan and plan again".into());
}
Ok(())
})
.and_then(|_| disk.write_mod_list(&plan.snapshot.paths.mod_list_path, &list))
};
if let Err(error) = result {
for change in applied.iter_mut().rev() {
let recovery = recover(change, running, disk);
if let Some(outcome) = report
.mods
.iter_mut()
.find(|o| o.name == change.name && o.ok)
{
*outcome = Outcome::failed(
&change.name,
format!("mod-list commit failed: {error}; {}", recovery),
);
}
}
}
}
report
}
fn action_running(action: &Action, list_path: &Path, running: &dyn Fn() -> bool) -> bool {
if action.previous.is_empty() || !running() {
return false;
}
if action.release.is_some() {
return true;
}
// Pending UI choices are deliberately ignored: the game loaded the saved state.
mod_list::read_mod_list(list_path)
.map(|list| {
list.mods
.iter()
.any(|entry| entry.name == action.name && entry.enabled)
})
.unwrap_or(true)
}
fn rejected(plan: &Plan, error: impl std::fmt::Display) -> Report {
let mut mods = plan.failures.clone();
mods.extend(
plan.actions
.iter()
.map(|a| Outcome::failed(&a.name, &error)),
);
Report { mods }
}
fn preflight(plan: &Plan) -> Result<()> {
let paths = &plan.snapshot.paths;
if paths.mods_dir != paths.user_dir.join("mods")
|| paths.mod_list_path != paths.mods_dir.join("mod-list.json")
{
return Err("Invalid user mods paths".into());
}
for path in [&paths.user_dir, &paths.mods_dir] {
download::ordinary(path)?;
}
if paths.install_dir.exists()
&& fs::canonicalize(&paths.mods_dir)?.starts_with(fs::canonicalize(&paths.install_dir)?)
{
return Err("Refusing writes inside the game install".into());
}
let backups = paths.user_dir.join("mod-backups");
if backups.exists() {
download::ordinary(&backups)?;
}
for suffix in ["", ".bak", ".tmp"] {
let path = mod_list::sibling(&paths.mod_list_path, suffix);
if fs::symlink_metadata(&path).is_ok() {
download::ordinary(&path)?;
}
}
if plan.actions.iter().any(|a| !a.previous.is_empty())
&& mod_list::read_mod_list(&paths.mod_list_path)? != plan.snapshot.mod_list
{
return Err("mod-list.json changed; rescan and plan again".into());
}
for action in &plan.actions {
if action
.release
.as_ref()
.is_some_and(|r| r.info_json.factorio_version != game_line(&paths.game_version))
{
return Err("Release does not match the installed game line".into());
}
for local in &action.previous {
if local.path.parent() != Some(paths.mods_dir.as_path())
|| local.source == ModSource::Builtin
{
return Err("Installed mod path is outside the user mods directory".into());
}
download::ordinary(&local.path)?;
}
}
// Detect versions/folders appearing after confirmation, rather than replacing unseen work.
let scan = crate::local_mods::scan_mods_dir(&paths.mods_dir, None)?;
let live = Snapshot {
mods: scan.mods.clone(),
..plan.snapshot.clone()
};
for action in &plan.actions {
let identity = |mods: &[LocalMod]| {
mods.iter()
.filter(|m| m.name == action.name)
.map(|m| (m.path.clone(), m.version.clone(), format!("{:?}", m.source)))
.collect::<BTreeSet<_>>()
};
if identity(&scan.mods) != identity(&action.previous) {
return Err("Installed mods changed; rescan and plan again".into());
}
for dep in &action.required {
let planned = plan
.actions
.iter()
.find(|a| a.name == dep.name)
.and_then(|a| a.release.as_ref());
let version = planned
.map(|r| r.version.as_str())
.or_else(|| current(&live, &dep.name).map(|m| m.version.as_str()))
.or_else(|| {
live.builtin
.iter()
.find(|m| m.name == dep.name)
.map(|m| m.version.as_str())
});
if !version.is_some_and(|v| satisfies(v, dep)) {
return Err(format!(
"Required dependency {} changed; rescan and plan again",
dep.name
)
.into());
}
}
}
Ok(())
}
struct Applied {
name: String,
backups: Vec<(PathBuf, PathBuf)>,
promoted: Option<PathBuf>,
temp: Option<VerifiedTemp>,
trashed: Vec<PathBuf>,
}
fn apply_one(
action: &Action,
temp: Option<VerifiedTemp>,
mods: &Path,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
) -> Result<Applied> {
let mut change = Applied {
name: action.name.clone(),
backups: vec![],
promoted: None,
temp,
trashed: vec![],
};
let result: Result<()> = (|| {
// Decision 4/10: immediately before the first move or rename, after sha1 verification.
download::stopped(running)?;
let backups = mods
.parent()
.ok_or("Missing user directory")?
.join("mod-backups");
if action.release.is_some() && !action.previous.is_empty() {
fs::create_dir_all(&backups)?;
}
for local in &action.previous {
if action.release.is_none() {
if let Err(error) = trash_inside(&local.path, mods, running, disk) {
return Err(format!(
"Couldn't move {} to the {TRASH_NAME}: {error}. The mod was left in place.",
action.name
)
.into());
}
change.trashed.push(local.path.clone());
} else {
backup_one(&local.path, &backups, &mut change, running, disk)?;
}
}
if let Some(temp) = &change.temp {
download::stopped(running)?;
let target = mods.join(format!("{}_{}.zip", action.name, temp.release.version));
promote(temp, &target, disk)?;
change.promoted = Some(target);
}
Ok(())
})();
match result {
Ok(()) => Ok(change),
Err(error) => {
if change.promoted.is_none() && change.backups.is_empty() && change.trashed.is_empty() {
return Err(error);
}
let recovery = recover(&mut change, running, disk);
Err(format!("{error}; {recovery}").into())
}
}
}
fn backup_one(
source: &Path,
backups: &Path,
change: &mut Applied,
running: &dyn Fn() -> bool,
disk: &dyn FileOps,
) -> Result<()> {
let destination = backups.join(source.file_name().ok_or("Missing mod filename")?);
if fs::symlink_metadata(&destination).is_ok() {
trash_inside(&destination, backups, running, disk)
.map_err(|e| format!("{e}; backup {} was left in place", destination.display()))?;
}
download::stopped(running)?;
download::ordinary(source)?;
disk.rename(source, &destination)?;
change.backups.push((source.into(), destination));
Ok(())
}
fn promote(temp: &VerifiedTemp, target: &Path, disk: &dyn FileOps) -> Result<()> {
// Decision 4: this is the only operation that exposes downloaded bytes as a mod.
disk.rename(&temp.path, target)
}
fn rollback(change: &mut Applied, running: &dyn Fn() -> bool, disk: &dyn FileOps) -> Result<()> {
// Decision 4: demote a new zip before restoring the old name. Delete only its temp.
if let Some(target) = &change.promoted {
download::stopped(running)?;
let temp = &change.temp.as_ref().ok_or("Missing rollback temp")?.path;
disk.rename(target, temp).map_err(|e| {
format!(
"Cannot move {} back to {}: {e}",
target.display(),
temp.display()
)
})?;
change.promoted = None;
}
let mut errors = Vec::new();
for (source, backup) in change.backups.iter().rev() {
if let Err(error) = download::stopped(running).and_then(|_| disk.rename(backup, source)) {
errors.push(format!(
"Restore {} from {}: {error}",
source.display(),
backup.display()
));
}
}
if errors.is_empty() {
change.backups.clear();
Ok(())
} else {
Err(errors.join("; ").into())
}
}
fn recover(change: &mut Applied, running: &dyn Fn() -> bool, disk: &dyn FileOps) -> String {
let mut messages = Vec::new();
if change.promoted.is_some() || !change.backups.is_empty() {
messages.push(match rollback(change, running, disk) {
Ok(()) => "previous files restored".into(),
Err(error) => format!("ROLLBACK FAILED; files preserved: {error}"),
});
}
if !change.trashed.is_empty() {
messages.push(format!(
"Check/restore removed mods from the {TRASH_NAME}: {}",
change
.trashed
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
));
}
messages.join("; ")
}
fn update_list(list: &mut ModList, action: &Action) {
// Decision 6: removal drops disabled entries too; updates preserve enabled and move pins.
let Some(release) = &action.release else {
list.mods.retain(|m| m.name != action.name);
return;
};
if list.mods.iter().any(|m| m.name == action.name) {
for entry in list.mods.iter_mut().filter(|m| m.name == action.name) {
if entry.version.is_some() {
entry.version = Some(release.version.clone());
}
}
} else {
list.mods.push(ModListEntry {
name: action.name.clone(),
enabled: true,
version: None,
});
}
}
/// Linux renameat2(RENAME_NOREPLACE) or macOS renameatx_np(RENAME_EXCL): the kernel refuses an
/// existing destination atomically, and a cross-device move fails instead of copying.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn rename_no_replace(from: &Path, to: &Path) -> Result<()> {
download::ordinary(from)?;
let from_parent = from.parent().ok_or("Missing move source parent")?;
let to_parent = to.parent().ok_or("Missing move destination parent")?;
download::ordinary(from_parent)?;
download::ordinary(to_parent)?;
rustix::fs::renameat_with(
rustix::fs::CWD,
from,
rustix::fs::CWD,
to,
rustix::fs::RenameFlags::NOREPLACE,
)?;
Ok(())
}