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, FileStage};
11use crate::game::Game;
12use crate::parse::ParserMemory;
13use crate::pdxfile::PdxFile;
14use crate::report::{ErrorKey, untidy, warn};
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(
77            pathname.to_path_buf(),
78            FileStage::NoStage,
79            FileKind::Mod,
80            pathname.to_path_buf(),
81        );
82        let block = PdxFile::read_optional_bom(&entry, &ParserMemory::default())
83            .with_context(|| format!("Could not read .mod file {}", pathname.display()))?;
84        Ok(validate_modfile(&block))
85    }
86
87    /// Return the full path to the mod root.
88    #[allow(clippy::missing_panics_doc)] // the panic can't happen
89    pub fn modpath(&self) -> PathBuf {
90        let modpathname = self.block.loc.pathname();
91
92        // Get the path of the directory the modfile is in.
93        let mut dirpath = modpathname.parent().unwrap_or_else(|| Path::new("."));
94        if dirpath.components().count() == 0 {
95            dirpath = Path::new(".");
96        }
97
98        // descriptor.mod is always in the mod's root and does not contain a path field.
99        if modpathname.file_name() == Some(OsStr::new("descriptor.mod")) {
100            return dirpath.to_path_buf();
101        }
102
103        // If the modfile is in a directory called "mod", assume that that's the paradox mod dir and the
104        // modpath will be relative to the paradox game dir above it.
105        if dirpath.ends_with("mod") {
106            // unwrap is safe here because we just checked that dirpath contains a component to strip.
107            dirpath = dirpath.parent().unwrap();
108        }
109
110        let modpath = if let Some(path) = &self.path {
111            fix_slashes_for_target_platform(dirpath.join(path.as_str()))
112        } else {
113            eprintln!("No mod path found in modfile {}", modpathname.display());
114            dirpath.to_path_buf()
115        };
116
117        if modpath.exists() {
118            modpath
119        } else {
120            eprintln!("Deduced mod path not found: {}", modpath.display());
121            dirpath.to_path_buf()
122        }
123    }
124
125    /// Return the paths that this mod fully replaces, according to its `.mod` file.
126    pub fn replace_paths(&self) -> Vec<PathBuf> {
127        self.replace_paths.iter().map(|t| PathBuf::from(t.as_str())).collect()
128    }
129
130    /// The mod's name in human-friendly form, if available.
131    pub fn display_name(&self) -> Option<String> {
132        self.name.as_ref().map(ToString::to_string)
133    }
134}