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