use crate::{
Result,
local_mods::{LocalMod, ScanError, scan_builtin_mods, scan_mods_dir},
mod_list::{self, ModList, read_mod_list, write_mod_list},
paths::FactorioPaths,
};
use serde::{Deserialize, Serialize};
use std::path::Path;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
pub paths: FactorioPaths,
pub builtin: Vec<LocalMod>,
pub mods: Vec<LocalMod>,
pub scan_errors: Vec<ScanError>,
pub mod_list: ModList,
}
pub const RUNNING_MESSAGE: &str =
"Factorio is running and would overwrite mod-list.json. Close the game, then confirm again.";
pub fn load_snapshot(install_dir: Option<&Path>, cache_dir: &Path) -> Result<Snapshot> {
load_snapshot_with_data(install_dir, None, cache_dir)
}
pub fn load_snapshot_with_data(
install_dir: Option<&Path>,
data_dir: Option<&Path>,
cache_dir: &Path,
) -> Result<Snapshot> {
load_snapshot_with_environment(install_dir, data_dir, cache_dir, None)
}
#[cfg(target_os = "linux")]
pub fn load_snapshot_with_data_env(
install_dir: Option<&Path>,
data_dir: Option<&Path>,
cache_dir: &Path,
env: &std::collections::HashMap<String, String>,
) -> Result<Snapshot> {
load_snapshot_with_environment(install_dir, data_dir, cache_dir, Some(env))
}
fn load_snapshot_with_environment(
install_dir: Option<&Path>,
data_dir: Option<&Path>,
cache_dir: &Path,
env: Option<&std::collections::HashMap<String, String>>,
) -> Result<Snapshot> {
#[cfg(target_os = "linux")]
let env = env.cloned().unwrap_or_else(|| std::env::vars().collect());
#[cfg(target_os = "linux")]
let env_dir = env
.get("FACTORIO_DIR")
.filter(|p| !p.is_empty())
.map(std::path::PathBuf::from);
#[cfg(not(target_os = "linux"))]
let _ = env;
#[cfg(not(target_os = "linux"))]
let env_dir = std::env::var_os("FACTORIO_DIR")
.filter(|p| !p.is_empty())
.map(std::path::PathBuf::from);
#[cfg(not(target_os = "linux"))]
let found = crate::paths::find_factorio(install_dir.or(env_dir.as_deref()))?;
#[cfg(target_os = "linux")]
let found = {
let explicit = env_dir.as_deref().or(install_dir);
if let Some(data) = data_dir {
// A valid selected data folder can recover from unresolved config macros.
let install = explicit
.map(std::path::PathBuf::from)
.or_else(|| crate::discovery::detect(&env).installs.into_iter().next());
match install {
Some(install_dir) => Some(FactorioPaths {
game_version: crate::paths::read_game_version(&install_dir).map_err(|e| {
format!(
"Invalid explicit Factorio install {}: {e}",
install_dir.display()
)
})?,
install_dir,
user_dir: data.into(),
mods_dir: data.join("mods"),
mod_list_path: data.join("mods/mod-list.json"),
}),
None => None,
}
} else {
crate::paths::find_factorio_with_env(explicit, &env)?
}
};
let mut paths = match found {
Some(paths) => paths,
None if data_dir.is_some() => FactorioPaths {
install_dir: Default::default(),
user_dir: Default::default(),
mods_dir: Default::default(),
mod_list_path: Default::default(),
game_version: "unknown".into(),
},
None => {
return Err("Factorio install not found. Set FACTORIO_DIR to the game folder.".into());
}
};
if let Some(data) = data_dir {
crate::settings::validate_data_dir(data)?;
paths.user_dir = data.into();
paths.mods_dir = data.join("mods");
paths.mod_list_path = paths.mods_dir.join("mod-list.json");
}
let scan = scan_mods_dir(&paths.mods_dir, Some(&cache_dir.join("thumbs")))?;
Ok(Snapshot {
builtin: if paths.install_dir.as_os_str().is_empty() {
vec![]
} else {
scan_builtin_mods(&paths.install_dir)?
},
mods: scan.mods,
scan_errors: scan.errors,
mod_list: read_mod_list(&paths.mod_list_path)?,
paths,
})
}
pub fn is_factorio_running() -> bool {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
std::process::Command::new("tasklist.exe")
.args(["/FI", "IMAGENAME eq factorio.exe", "/NH"])
.creation_flags(0x08000000)
.output()
.map(|o| {
String::from_utf8_lossy(&o.stdout)
.to_lowercase()
.contains("factorio.exe")
})
.unwrap_or(false)
}
#[cfg(target_os = "linux")]
{
crate::linux::factorio_running_in(Path::new("/proc"))
}
#[cfg(target_os = "macos")]
{
crate::macos::factorio_running()
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
{
true
}
}
pub fn apply_enabled(snapshot: &Snapshot, pending: &[(String, bool)]) -> Result<ModList> {
apply_changes(snapshot, &pending.to_vec(), &vec![])
}
pub fn apply_changes(
snapshot: &Snapshot,
pending: &crate::enable::Pending,
pins: &crate::enable::Pins,
) -> Result<ModList> {
apply_changes_with(snapshot, pending, pins, &is_factorio_running)
}
pub fn apply_changes_with(
snapshot: &Snapshot,
pending: &crate::enable::Pending,
pins: &crate::enable::Pins,
running: &dyn Fn() -> bool,
) -> Result<ModList> {
let p = &snapshot.paths;
if p.mods_dir != p.user_dir.join("mods") || p.mod_list_path != p.mods_dir.join("mod-list.json")
{
return Err("Invalid user mods paths".into());
}
for dir in [&p.user_dir, &p.mods_dir] {
crate::download::ordinary(dir)?;
}
if p.install_dir.exists()
&& std::fs::canonicalize(&p.mods_dir)?.starts_with(std::fs::canonicalize(&p.install_dir)?)
{
return Err("Refusing writes inside the game install".into());
}
for suffix in ["", ".bak", ".tmp"] {
let file = mod_list::sibling(&p.mod_list_path, suffix);
if std::fs::symlink_metadata(&file).is_ok() {
crate::download::ordinary(&file)?;
}
}
if read_mod_list(&p.mod_list_path)? != snapshot.mod_list {
return Err("mod-list.json changed; rescan before confirming".into());
}
for (name, _) in pending {
if !snapshot
.mods
.iter()
.chain(&snapshot.builtin)
.any(|m| m.name == *name)
{
return Err("Mod is no longer installed".into());
}
}
for (name, choice) in pins {
crate::enable::set_pin(snapshot, &vec![], name, choice.clone())?;
}
let mut list = crate::enable::effective_list(snapshot, pending, pins);
for local in snapshot.builtin.iter().chain(&snapshot.mods) {
if !list.mods.iter().any(|entry| entry.name == local.name) {
list = mod_list::set_enabled(
&list,
&local.name,
crate::enable::enabled(snapshot, pending, &local.name),
);
}
}
crate::download::stopped(running)?;
write_mod_list(&p.mod_list_path, &list)?;
Ok(list)
}