use crate::Result;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
};
#[cfg(windows)]
pub const DEFAULT_INSTALL_DIRS: [&str; 2] = [
"C:/Program Files (x86)/Steam/steamapps/common/Factorio",
"C:/Program Files/Factorio",
];
#[cfg(target_os = "linux")]
pub const DEFAULT_INSTALL_DIRS: [&str; 1] = ["/opt/factorio"];
#[cfg(target_os = "macos")]
pub const DEFAULT_INSTALL_DIRS: [&str; 1] = ["/Applications/factorio.app/Contents"];
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
pub const DEFAULT_INSTALL_DIRS: [&str; 0] = [];
/// Below the game folder of a Steam or standalone macOS install. Its `data/` lives here.
pub const MACOS_BUNDLE_ROOT: &str = "factorio.app/Contents";
/// macOS keeps `data/` inside the app bundle, so also accept the bundle or the folder holding it.
pub fn game_dir(dir: &Path) -> PathBuf {
if cfg!(target_os = "macos") {
for candidate in [dir.join("Contents"), dir.join(MACOS_BUNDLE_ROOT)] {
if candidate.join("data/base/info.json").is_file() {
return candidate;
}
}
}
dir.to_path_buf()
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FactorioPaths {
pub install_dir: PathBuf,
pub user_dir: PathBuf,
pub mods_dir: PathBuf,
pub mod_list_path: PathBuf,
pub game_version: String,
}
pub fn read_game_version(install_dir: &Path) -> Result<String> {
#[derive(Deserialize)]
struct Info {
version: String,
}
let info: Info = serde_json::from_slice(&fs::read(install_dir.join("data/base/info.json"))?)?;
Ok(info.version)
}
#[cfg(not(target_os = "linux"))]
fn setting<'a>(text: &'a str, key: &str) -> Option<&'a str> {
text.lines().find_map(|line| line.strip_prefix(key))
}
#[cfg(not(target_os = "linux"))]
pub fn resolve_user_dir(install_dir: &Path, env: &HashMap<String, String>) -> Result<PathBuf> {
let system_dir = default_user_dir(env);
let cfg = install_dir.join("config-path.cfg");
let mut use_system = true;
if cfg.exists()
&& let Some(flag) = setting(
&fs::read_to_string(cfg)?,
"use-system-read-write-data-directories=",
)
{
let flag: String = flag
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
if !flag.is_empty() {
use_system = flag == "true";
}
}
let base = if use_system {
system_dir
} else {
install_dir.to_path_buf()
};
let ini = base.join("config/config.ini");
if ini.exists()
&& let Some(value) = setting(&fs::read_to_string(ini)?, "write-data=")
{
let value = value.trim();
if !value.is_empty() && !value.starts_with("__PATH__") {
return Ok(value.into());
}
}
Ok(base)
}
pub fn default_user_dir(env: &HashMap<String, String>) -> PathBuf {
#[cfg(target_os = "linux")]
{
crate::app_dirs::absolute(env, "HOME")
.map(|p| p.join(".factorio"))
.unwrap_or_default()
}
#[cfg(not(target_os = "linux"))]
let home = PathBuf::from(
env.get("HOME")
.or_else(|| env.get("USERPROFILE"))
.cloned()
.unwrap_or_default(),
);
#[cfg(not(target_os = "linux"))]
if cfg!(target_os = "windows") {
env.get("APPDATA")
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData/Roaming"))
.join("Factorio")
} else if cfg!(target_os = "macos") {
home.join("Library/Application Support/factorio")
} else {
home.join(".factorio")
}
}
pub fn find_factorio(install_dir: Option<&Path>) -> Result<Option<FactorioPaths>> {
find_factorio_with_env(install_dir, &std::env::vars().collect())
}
pub fn find_factorio_with_env(
install_dir: Option<&Path>,
env: &HashMap<String, String>,
) -> Result<Option<FactorioPaths>> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
let candidates = install_dir
.map(|p| vec![game_dir(p)])
.unwrap_or_else(|| crate::discovery::detect(env).installs);
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let candidates: Vec<_> = install_dir
.map(|p| vec![p.to_path_buf()])
.unwrap_or_else(|| DEFAULT_INSTALL_DIRS.iter().map(PathBuf::from).collect());
#[cfg(target_os = "linux")]
if let Some(explicit) = install_dir {
read_game_version(explicit).map_err(|e| {
format!(
"Invalid explicit Factorio install {}: {e}",
explicit.display()
)
})?;
}
for dir in candidates {
if !dir.join("data/base/info.json").exists() {
continue;
}
let user_dir = resolve_user_dir(&dir, env)?;
let mods_dir = user_dir.join("mods");
return Ok(Some(FactorioPaths {
game_version: read_game_version(&dir)?,
install_dir: dir,
user_dir,
mod_list_path: mods_dir.join("mod-list.json"),
mods_dir,
}));
}
Ok(None)
}
#[cfg(target_os = "linux")]
pub fn resolve_user_dir(install: &Path, env: &HashMap<String, String>) -> Result<PathBuf> {
fn entries(text: &str, section: Option<&str>) -> Vec<(String, String)> {
let mut active = true;
text.lines()
.filter_map(|line| {
let line = line.split([';', '#']).next().unwrap_or("").trim();
if line.starts_with('[') && line.ends_with(']') {
active = section.is_none_or(|s| &line[1..line.len() - 1] == s);
return None;
}
let (k, v) = line.split_once('=')?;
active.then(|| (k.trim().into(), v.trim().into()))
})
.collect()
}
fn read(path: &Path) -> Result<String> {
match fs::read_to_string(path) {
Ok(s) => Ok(s),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
Err(e) => Err(e.into()),
}
}
fn expand(value: &str, install: &Path, system: &Path) -> Result<PathBuf> {
let expanded = value
.replace("__PATH__system-write-data__", &system.to_string_lossy())
.replace(
"__PATH__system-read-data__",
&install.join("data").to_string_lossy(),
)
.replace(
"__PATH__executable__",
&install.join("bin/x64").to_string_lossy(),
);
if expanded.is_empty()
|| expanded.contains("__PATH__")
|| !Path::new(&expanded).is_absolute()
{
return Err(format!(
"Unresolved Factorio path {value:?}; select an absolute data folder in Settings"
)
.into());
}
let mut path = PathBuf::new();
for c in Path::new(&expanded).components() {
match c {
std::path::Component::ParentDir => {
path.pop();
}
_ => path.push(c),
}
}
Ok(path)
}
if !install.is_absolute() {
return Err("The install folder must be absolute".into());
}
let cfg = entries(&read(&install.join("config-path.cfg"))?, None);
let value = |key| {
cfg.iter()
.rev()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
};
let system = match value("use-system-read-write-data-directories").unwrap_or("true") {
"true" => crate::discovery::install_home(install, env)
.map(|p| p.join(".factorio"))
.ok_or("No absolute HOME; select a data folder in Settings")?,
"false" => install.to_path_buf(),
_ => return Err("Invalid use-system-read-write-data-directories boolean".into()),
};
let config = match value("config-path") {
Some(v) => expand(v, install, &system)?,
None => system.join("config"),
};
let ini = entries(&read(&config.join("config.ini"))?, Some("path"));
match ini.iter().rev().find(|(k, _)| k == "write-data") {
Some((_, v)) => expand(v, install, &system),
None => Ok(system),
}
}