tiger_lib/
modfile.rs

1//! Loader and validator for the `.mod` files themselves.
2
3use std::ffi::OsStr;
4use std::path::{Path, PathBuf};
5use std::string::ToString;
6
7use anyhow::{Context, Result};
8
9use crate::block::Block;
10use crate::fileset::{FileEntry, FileKind};
11use crate::game::Game;
12use crate::parse::ParserMemory;
13use crate::pdxfile::PdxFile;
14use crate::report::{untidy, warn, ErrorKey};
15use crate::token::Token;
16use crate::util::fix_slashes_for_target_platform;
17
18/// Representation of a `.mod` file and its contents.
19#[allow(dead_code)] // TODO, see below
20#[derive(Clone, Debug)]
21pub struct ModFile {
22    block: Block,
23    name: Option<Token>,
24    path: Option<Token>,
25    replace_paths: Vec<Token>,
26    version: Option<Token>,
27    // TODO: check that these are tags accepted by steam ?
28    tags: Option<Vec<Token>>,
29    // TODO: check if the version is compatible with the validator.
30    // (Newer means the validator is too old, older means it's not up to date
31    // with current CK3)
32    supported_version: Option<Token>,
33    picture: Option<Token>,
34}
35
36/// Validate the [`Block`] form of a `.mod` file and return it as a [`ModFile`].
37fn validate_modfile(block: &Block) -> ModFile {
38    let modfile = ModFile {
39        block: block.clone(),
40        name: block.get_field_value("name").cloned(),
41        path: block.get_field_value("path").cloned(),
42        replace_paths: block.get_field_values("replace_path").into_iter().cloned().collect(),
43        version: block.get_field_value("version").cloned(),
44        tags: block.get_field_list("tags"),
45        supported_version: block.get_field_value("supported_version").cloned(),
46        picture: block.get_field_value("picture").cloned(),
47    };
48
49    if let Some(picture) = &modfile.picture {
50        // TODO: reverify this for the other games as well
51        if !Game::is_hoi4() && !picture.is("thumbnail.png") {
52            let msg = "Steam ignores picture= and always uses thumbnail.png.";
53            warn(ErrorKey::Packaging).msg(msg).loc(picture).push();
54        }
55    }
56
57    for path in &modfile.replace_paths {
58        if path.is("history") {
59            let msg =
60                "replace_path only replaces the specific directory, not any directories below it";
61            let info =
62                "So replace_path = history is not useful, you should replace the paths under it.";
63            untidy(ErrorKey::Unneeded).msg(msg).info(info).loc(path).push();
64        }
65    }
66
67    // TODO: check if supported_version is newer than validator,
68    // or is older than known game version.
69
70    modfile
71}
72
73impl ModFile {
74    /// Take the path to a `.mod` file, validate it, and return its parsed structure.
75    pub fn read(pathname: &Path) -> Result<Self> {
76        let entry = FileEntry::new(pathname.to_path_buf(), FileKind::Mod, pathname.to_path_buf());
77        let block = PdxFile::read_optional_bom(&entry, &ParserMemory::default())
78            .with_context(|| format!("Could not read .mod file {}", pathname.display()))?;
79        Ok(validate_modfile(&block))
80    }
81
82    /// Return the full path to the mod root.
83    #[allow(clippy::missing_panics_doc)] // the panic can't happen
84    pub fn modpath(&self) -> PathBuf {
85        let modpathname = self.block.loc.pathname();
86
87        // Get the path of the directory the modfile is in.
88        let mut dirpath = modpathname.parent().unwrap_or_else(|| Path::new("."));
89        if dirpath.components().count() == 0 {
90            dirpath = Path::new(".");
91        }
92
93        // descriptor.mod is always in the mod's root and does not contain a path field.
94        if modpathname.file_name() == Some(OsStr::new("descriptor.mod")) {
95            return dirpath.to_path_buf();
96        }
97
98        // If the modfile is in a directory called "mod", assume that that's the paradox mod dir and the
99        // modpath will be relative to the paradox game dir above it.
100        if dirpath.ends_with("mod") {
101            // unwrap is safe here because we just checked that dirpath contains a component to strip.
102            dirpath = dirpath.parent().unwrap();
103        }
104
105        let modpath = if let Some(path) = &self.path {
106            fix_slashes_for_target_platform(dirpath.join(path.as_str()))
107        } else {
108            eprintln!("No mod path found in modfile {}", modpathname.display());
109            dirpath.to_path_buf()
110        };
111
112        if modpath.exists() {
113            modpath
114        } else {
115            eprintln!("Deduced mod path not found: {}", modpath.display());
116            dirpath.to_path_buf()
117        }
118    }
119
120    /// Return the paths that this mod fully replaces, according to its `.mod` file.
121    pub fn replace_paths(&self) -> Vec<PathBuf> {
122        self.replace_paths.iter().map(|t| PathBuf::from(t.as_str())).collect()
123    }
124
125    /// The mod's name in human-friendly form, if available.
126    pub fn display_name(&self) -> Option<String> {
127        self.name.as_ref().map(ToString::to_string)
128    }
129}