use crate::{
Result,
locale::Locale,
version::{Dependency, parse_dependencies},
};
use serde::{Deserialize, Serialize};
use std::{
fs,
io::Read,
path::{Path, PathBuf},
};
pub const BUILTIN_ORDER: [&str; 4] = ["base", "elevated-rails", "quality", "space-age"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ModSource {
Builtin,
Folder,
Zip,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalMod {
pub name: String,
pub version: String,
pub title: String,
pub author: String,
pub description: String,
pub factorio_version: String,
pub dependencies: Vec<Dependency>,
pub source: ModSource,
pub path: PathBuf,
pub thumbnail: Option<PathBuf>,
}
#[derive(Deserialize)]
struct ModInfo {
name: String,
version: String,
title: Option<String>,
author: Option<String>,
description: Option<String>,
factorio_version: Option<String>,
#[serde(default, deserialize_with = "dependency_strings")]
dependencies: Vec<String>,
}
fn dependency_strings<'de, D: serde::Deserializer<'de>>(
de: D,
) -> std::result::Result<Vec<String>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Strings {
One(String),
Many(Vec<String>),
}
Ok(match Strings::deserialize(de)? {
Strings::One(s) => vec![s],
Strings::Many(v) => v,
})
}
impl ModInfo {
/// `locale` holds the mod's `locale/en/*.cfg` texts; `[mod-name]` / `[mod-description]`
/// override info.json the way the game's Mods window does.
fn into_local(
self,
source: ModSource,
path: &Path,
thumbnail: Option<PathBuf>,
locale: &Locale,
) -> LocalMod {
let localized = |section: &str| locale.get(section, &self.name).map(str::to_owned);
LocalMod {
title: localized("mod-name")
.or(self.title)
.unwrap_or_else(|| self.name.clone()),
description: localized("mod-description")
.or(self.description)
.unwrap_or_default(),
name: self.name,
version: self.version,
author: self.author.unwrap_or_default(),
factorio_version: self.factorio_version.unwrap_or_else(|| "0.12".into()),
dependencies: parse_dependencies(&self.dependencies),
source,
path: path.into(),
thumbnail,
}
}
}
fn read_folder_mod(dir: &Path, source: ModSource) -> Result<Option<LocalMod>> {
let info = dir.join("info.json");
if !info.exists() {
return Ok(None);
}
let info: ModInfo = serde_json::from_slice(&fs::read(info)?)?;
let thumbnail = dir.join("thumbnail.png");
let mut locale = Locale::default();
if let Ok(entries) = fs::read_dir(dir.join("locale").join("en")) {
let mut files: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
files.sort();
for file in files
.iter()
.filter(|p| p.extension().is_some_and(|x| x == "cfg"))
{
if let Ok(text) = fs::read(file) {
locale.extend(&String::from_utf8_lossy(&text));
}
}
}
Ok(Some(info.into_local(
source,
dir,
thumbnail.exists().then_some(thumbnail),
&locale,
)))
}
fn read_zip_mod(file: &Path, cache: Option<&Path>) -> Result<Option<LocalMod>> {
let mut zip = zip::ZipArchive::new(fs::File::open(file)?)?;
let entry = |name: &str, leaf: &str| {
name.split_once('/')
.is_some_and(|(top, rest)| !top.is_empty() && rest == leaf)
};
let names: Vec<String> = zip
.file_names()
.map(|n| n.map(|n| n.into_owned()))
.collect::<zip::result::ZipResult<_>>()?;
let info_entry = names.iter().find(|n| entry(n, "info.json")).cloned();
let Some(info_entry) = info_entry else {
return Ok(None);
};
let info: ModInfo = serde_json::from_reader(zip.by_name(&info_entry)?)?;
let thumb_entry = names.iter().find(|n| entry(n, "thumbnail.png")).cloned();
let mut thumbnail = None;
if let (Some(entry), Some(cache)) = (thumb_entry, cache) {
// Metadata is untrusted; a thumbnail name must stay inside the cache.
for component in [&info.name, &info.version] {
if component.contains(['/', '\\', ':']) || component == "." || component == ".." {
return Err("Invalid thumbnail cache name".into());
}
}
fs::create_dir_all(cache)?;
let target = cache.join(format!("{}_{}.png", info.name, info.version));
if !target.exists() {
let mut bytes = Vec::new();
zip.by_name(&entry)?.read_to_end(&mut bytes)?;
crate::cache::atomic_write(&target, &bytes)?;
}
thumbnail = Some(target);
}
let mut locale = Locale::default();
let mut cfgs: Vec<String> = names
.into_iter()
.filter(|n| {
n.split_once('/').is_some_and(|(top, rest)| {
!top.is_empty()
&& rest
.strip_prefix("locale/en/")
.is_some_and(|f| f.ends_with(".cfg") && !f.contains('/'))
})
})
.collect();
cfgs.sort();
for name in cfgs {
let mut bytes = Vec::new();
if zip.by_name(&name)?.read_to_end(&mut bytes).is_ok() {
locale.extend(&String::from_utf8_lossy(&bytes));
}
}
Ok(Some(info.into_local(
ModSource::Zip,
file,
thumbnail,
&locale,
)))
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScanError {
pub path: PathBuf,
pub error: String,
}
#[derive(Default, Debug)]
pub struct ScanResult {
pub mods: Vec<LocalMod>,
pub errors: Vec<ScanError>,
}
pub fn builtin_rank(name: &str) -> usize {
BUILTIN_ORDER
.iter()
.position(|n| *n == name)
.unwrap_or(BUILTIN_ORDER.len())
}
pub fn scan_builtin_mods(install: &Path) -> Result<Vec<LocalMod>> {
let mut mods = Vec::new();
for entry in fs::read_dir(install.join("data"))? {
let entry = entry?;
if entry.file_name() == "core" || !entry.path().is_dir() {
continue;
}
if let Some(mod_) = read_folder_mod(&entry.path(), ModSource::Builtin)? {
mods.push(mod_);
}
}
mods.sort_by(|a, b| {
builtin_rank(&a.name)
.cmp(&builtin_rank(&b.name))
.then_with(|| crate::text::compare_english(&a.name, &b.name, false))
});
Ok(mods)
}
pub fn scan_mods_dir(mods_dir: &Path, cache: Option<&Path>) -> Result<ScanResult> {
let mut result = ScanResult::default();
if !mods_dir.exists() {
return Ok(result);
}
let mut entries: Vec<_> = fs::read_dir(mods_dir)?.collect::<std::io::Result<_>>()?;
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let full = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let is_dir = full.is_dir();
let read = if is_dir {
read_folder_mod(&full, ModSource::Folder)
} else if name.to_lowercase().ends_with(".zip") {
read_zip_mod(&full, cache)
} else {
continue;
};
match read {
Ok(Some(mod_)) => result.mods.push(mod_),
Ok(None) if is_dir || name.ends_with(".zip") => result.errors.push(ScanError {
path: full,
error: "no info.json".into(),
}),
Err(error) => result.errors.push(ScanError {
path: full,
error: error.to_string(),
}),
_ => (),
}
}
result
.mods
.sort_by(|a, b| crate::text::compare_english(&a.title, &b.title, true));
Ok(result)
}
/// A mod loads in the game only when its info.json `factorio_version` equals the game's `major.minor`.
/// Built-ins (base, Space Age, ...) ship with the game and are always compatible. A missing field
/// reads as the game's "0.12" default (see `into_local`), so it is incompatible with every real game.
pub fn compatible_with_game(mod_: &LocalMod, game_version: &str) -> bool {
mod_.source == ModSource::Builtin
|| crate::version::game_line(&mod_.factorio_version)
== crate::version::game_line(game_version)
}
#[cfg(test)]
mod compatibility_tests {
use super::*;
fn local(factorio_version: &str, source: ModSource) -> LocalMod {
LocalMod {
name: "x".into(),
version: "1.0.0".into(),
title: "X".into(),
author: String::new(),
description: String::new(),
factorio_version: factorio_version.into(),
dependencies: vec![],
source,
path: PathBuf::new(),
thumbnail: None,
}
}
#[test]
fn compares_major_minor_of_the_game_line() {
let game = "2.0.77";
assert!(compatible_with_game(&local("2.0", ModSource::Zip), game));
assert!(compatible_with_game(
&local("2.0.5", ModSource::Folder),
game
));
assert!(!compatible_with_game(&local("1.1", ModSource::Zip), game));
assert!(!compatible_with_game(&local("0.18", ModSource::Zip), game));
assert!(!compatible_with_game(&local("2.1", ModSource::Zip), game));
assert!(compatible_with_game(&local("2.1", ModSource::Zip), "2.1.3"));
}
#[test]
fn missing_field_is_incompatible_and_builtins_always_pass() {
let game = "2.0.77";
// The scanner fills a missing field with "0.12"; an empty string behaves the same.
assert!(!compatible_with_game(&local("0.12", ModSource::Zip), game));
assert!(!compatible_with_game(&local("", ModSource::Folder), game));
for builtin in ["", "2.0", "1.1"] {
assert!(compatible_with_game(
&local(builtin, ModSource::Builtin),
game
));
}
}
}