1use std::cmp::Ordering;
4use std::ffi::OsStr;
5use std::fmt::{Display, Formatter};
6use std::path::{Path, PathBuf};
7use std::string::ToString;
8use std::sync::RwLock;
9
10use anyhow::{bail, Result};
11use rayon::prelude::*;
12use walkdir::WalkDir;
13
14use crate::block::Block;
15use crate::everything::{Everything, FilesError};
16use crate::game::Game;
17use crate::helpers::TigerHashSet;
18use crate::item::Item;
19#[cfg(feature = "vic3")]
20use crate::mod_metadata::ModMetadata;
21#[cfg(any(feature = "ck3", feature = "imperator"))]
22use crate::modfile::ModFile;
23use crate::parse::ParserMemory;
24use crate::pathtable::{PathTable, PathTableIndex};
25use crate::report::{
26 add_loaded_dlc_root, add_loaded_mod_root, err, fatal, report, warn_abbreviated, warn_header,
27 will_maybe_log, ErrorKey, Severity,
28};
29use crate::token::Token;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub enum FileKind {
37 Internal,
39 Clausewitz,
41 Jomini,
42 Vanilla,
44 Dlc(u8),
46 LoadedMod(u8),
48 Mod,
50}
51
52impl FileKind {
53 pub fn counts_as_vanilla(&self) -> bool {
54 match self {
55 FileKind::Clausewitz | FileKind::Jomini | FileKind::Vanilla | FileKind::Dlc(_) => true,
56 FileKind::Internal | FileKind::LoadedMod(_) | FileKind::Mod => false,
57 }
58 }
59}
60
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct FileEntry {
63 path: PathBuf,
66 kind: FileKind,
68 idx: Option<PathTableIndex>,
72 fullpath: PathBuf,
74}
75
76impl FileEntry {
77 pub fn new(path: PathBuf, kind: FileKind, fullpath: PathBuf) -> Self {
78 assert!(path.file_name().is_some());
79 Self { path, kind, idx: None, fullpath }
80 }
81
82 pub fn kind(&self) -> FileKind {
83 self.kind
84 }
85
86 pub fn path(&self) -> &Path {
87 &self.path
88 }
89
90 pub fn fullpath(&self) -> &Path {
91 &self.fullpath
92 }
93
94 #[allow(clippy::missing_panics_doc)]
97 pub fn filename(&self) -> &OsStr {
98 self.path.file_name().unwrap()
99 }
100
101 fn store_in_pathtable(&mut self) {
102 assert!(self.idx.is_none());
103 self.idx = Some(PathTable::store(self.path.clone(), self.fullpath.clone()));
104 }
105
106 pub fn path_idx(&self) -> Option<PathTableIndex> {
107 self.idx
108 }
109}
110
111impl Display for FileEntry {
112 fn fmt(&self, fmt: &mut Formatter) -> Result<(), std::fmt::Error> {
113 write!(fmt, "{}", self.path.display())
114 }
115}
116
117impl PartialOrd for FileEntry {
118 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
119 Some(self.cmp(other))
120 }
121}
122
123impl Ord for FileEntry {
124 fn cmp(&self, other: &Self) -> Ordering {
125 let path_ord = if self.idx.is_some() && other.idx.is_some() {
127 self.idx.unwrap().cmp(&other.idx.unwrap())
128 } else {
129 self.path.cmp(&other.path)
130 };
131
132 if path_ord == Ordering::Equal {
134 self.kind.cmp(&other.kind)
135 } else {
136 path_ord
137 }
138 }
139}
140
141pub trait FileHandler<T: Send>: Sync + Send {
143 fn config(&mut self, _config: &Block) {}
145
146 fn subpath(&self) -> PathBuf;
150
151 fn load_file(&self, entry: &FileEntry, parser: &ParserMemory) -> Option<T>;
156
157 fn handle_file(&mut self, entry: &FileEntry, loaded: T);
160
161 fn finalize(&mut self) {}
164}
165
166#[derive(Clone, Debug)]
167pub struct LoadedMod {
168 kind: FileKind,
170
171 #[allow(dead_code)]
173 label: String,
174
175 root: PathBuf,
177
178 replace_paths: Vec<PathBuf>,
180}
181
182impl LoadedMod {
183 fn new_main_mod(root: PathBuf, replace_paths: Vec<PathBuf>) -> Self {
184 Self { kind: FileKind::Mod, label: "MOD".to_string(), root, replace_paths }
185 }
186
187 fn new(kind: FileKind, label: String, root: PathBuf, replace_paths: Vec<PathBuf>) -> Self {
188 Self { kind, label, root, replace_paths }
189 }
190
191 pub fn root(&self) -> &Path {
192 &self.root
193 }
194
195 pub fn kind(&self) -> FileKind {
196 self.kind
197 }
198
199 pub fn should_replace(&self, path: &Path) -> bool {
200 self.replace_paths.iter().any(|p| p == path)
201 }
202}
203
204#[derive(Debug)]
205pub struct Fileset {
206 vanilla_root: Option<PathBuf>,
208
209 clausewitz_root: Option<PathBuf>,
211
212 jomini_root: Option<PathBuf>,
214
215 the_mod: LoadedMod,
217
218 pub loaded_mods: Vec<LoadedMod>,
220
221 loaded_dlcs: Vec<LoadedMod>,
223
224 config: Option<Block>,
226
227 files: Vec<FileEntry>,
229
230 ordered_files: Vec<FileEntry>,
232
233 filename_tokens: Vec<Token>,
236
237 filenames: TigerHashSet<PathBuf>,
239
240 directories: RwLock<TigerHashSet<PathBuf>>,
242
243 used: RwLock<TigerHashSet<String>>,
245}
246
247impl Fileset {
248 pub fn new(vanilla_dir: Option<&Path>, mod_root: PathBuf, replace_paths: Vec<PathBuf>) -> Self {
249 let vanilla_root = vanilla_dir.map(|dir| dir.join("game"));
250 let clausewitz_root = vanilla_dir.map(|dir| dir.join("clausewitz"));
251 let jomini_root = vanilla_dir.map(|dir| dir.join("jomini"));
252
253 Fileset {
254 vanilla_root,
255 clausewitz_root,
256 jomini_root,
257 the_mod: LoadedMod::new_main_mod(mod_root, replace_paths),
258 loaded_mods: Vec::new(),
259 loaded_dlcs: Vec::new(),
260 config: None,
261 files: Vec::new(),
262 ordered_files: Vec::new(),
263 filename_tokens: Vec::new(),
264 filenames: TigerHashSet::default(),
265 directories: RwLock::new(TigerHashSet::default()),
266 used: RwLock::new(TigerHashSet::default()),
267 }
268 }
269
270 pub fn config(&mut self, config: Block) -> Result<()> {
271 let config_path = config.loc.fullpath();
272 for block in config.get_field_blocks("load_mod") {
273 let mod_idx;
274 if let Ok(idx) = u8::try_from(self.loaded_mods.len()) {
275 mod_idx = idx;
276 } else {
277 bail!("too many loaded mods, cannot process more");
278 }
279
280 let default_label = || format!("MOD{mod_idx}");
281 let label =
282 block.get_field_value("label").map_or_else(default_label, ToString::to_string);
283 if Game::is_ck3() || Game::is_imperator() {
284 #[cfg(any(feature = "ck3", feature = "imperator"))]
285 if let Some(path) = block.get_field_value("modfile") {
286 let path = config_path
287 .parent()
288 .unwrap() .join(path.as_str());
290 let modfile = ModFile::read(&path)?;
291 eprintln!(
292 "Loading secondary mod {label} from: {}{}",
293 modfile.modpath().display(),
294 modfile
295 .display_name()
296 .map_or_else(String::new, |name| format!(" \"{name}\"")),
297 );
298 let kind = FileKind::LoadedMod(mod_idx);
299 let loaded_mod = LoadedMod::new(
300 kind,
301 label.clone(),
302 modfile.modpath().clone(),
303 modfile.replace_paths(),
304 );
305 add_loaded_mod_root(label);
306 self.loaded_mods.push(loaded_mod);
307 } else {
308 bail!("could not load secondary mod from config; missing `modfile` field");
309 }
310 } else if Game::is_vic3() {
311 #[cfg(feature = "vic3")]
312 if let Some(path) = block.get_field_value("mod") {
313 let pathdir = config_path
314 .parent()
315 .unwrap() .join(path.as_str());
317 if let Ok(metadata) = ModMetadata::read(&pathdir) {
318 eprintln!(
319 "Loading secondary mod {label} from: {}{}",
320 pathdir.display(),
321 metadata
322 .display_name()
323 .map_or_else(String::new, |name| format!(" \"{name}\"")),
324 );
325 let kind = FileKind::LoadedMod(mod_idx);
326 let loaded_mod =
327 LoadedMod::new(kind, label.clone(), pathdir, metadata.replace_paths());
328 add_loaded_mod_root(label);
329 self.loaded_mods.push(loaded_mod);
330 } else {
331 bail!("does not look like a mod dir: {}", pathdir.display());
332 }
333 } else {
334 bail!("could not load secondary mod from config; missing `mod` field");
335 }
336 }
337 }
338 self.config = Some(config);
339 Ok(())
340 }
341
342 fn should_replace(&self, path: &Path, kind: FileKind) -> bool {
343 if kind == FileKind::Mod {
344 return false;
345 }
346 if kind < FileKind::Mod && self.the_mod.should_replace(path) {
347 return true;
348 }
349 for loaded_mod in &self.loaded_mods {
350 if kind < loaded_mod.kind && loaded_mod.should_replace(path) {
351 return true;
352 }
353 }
354 false
355 }
356
357 fn scan(&mut self, path: &Path, kind: FileKind) -> Result<(), walkdir::Error> {
358 for entry in WalkDir::new(path) {
359 let entry = entry?;
360 if entry.depth() == 0 || !entry.file_type().is_file() {
361 continue;
362 }
363 let inner_path = entry.path().strip_prefix(path).unwrap();
365 if inner_path.starts_with(".git") {
366 continue;
367 }
368 let inner_dir = inner_path.parent().unwrap_or_else(|| Path::new(""));
369 if self.should_replace(inner_dir, kind) {
370 continue;
371 }
372 self.files.push(FileEntry::new(
373 inner_path.to_path_buf(),
374 kind,
375 entry.path().to_path_buf(),
376 ));
377 }
378 Ok(())
379 }
380
381 pub fn scan_all(&mut self) -> Result<(), FilesError> {
382 if let Some(clausewitz_root) = self.clausewitz_root.clone() {
383 self.scan(&clausewitz_root.clone(), FileKind::Clausewitz).map_err(|e| {
384 FilesError::VanillaUnreadable { path: clausewitz_root.clone(), source: e }
385 })?;
386 }
387 if let Some(jomini_root) = &self.jomini_root.clone() {
388 self.scan(&jomini_root.clone(), FileKind::Jomini).map_err(|e| {
389 FilesError::VanillaUnreadable { path: jomini_root.clone(), source: e }
390 })?;
391 }
392 if let Some(vanilla_root) = &self.vanilla_root.clone() {
393 self.scan(&vanilla_root.clone(), FileKind::Vanilla).map_err(|e| {
394 FilesError::VanillaUnreadable { path: vanilla_root.clone(), source: e }
395 })?;
396 let dlc_root = vanilla_root.join("dlc");
397 for entry in
398 WalkDir::new(dlc_root).max_depth(1).sort_by_file_name().into_iter().flatten()
399 {
400 if entry.depth() == 1 && entry.file_type().is_dir() {
401 let label = entry.file_name().to_string_lossy().to_string();
402 let idx =
403 u8::try_from(self.loaded_dlcs.len()).expect("more than 256 DLCs installed");
404 let dlc = LoadedMod::new(
405 FileKind::Dlc(idx),
406 label.clone(),
407 entry.path().to_path_buf(),
408 Vec::new(),
409 );
410 self.scan(dlc.root(), dlc.kind()).map_err(|e| {
411 FilesError::VanillaUnreadable { path: dlc.root().to_path_buf(), source: e }
412 })?;
413 self.loaded_dlcs.push(dlc);
414 add_loaded_dlc_root(label);
415 }
416 }
417 }
418 for loaded_mod in &self.loaded_mods.clone() {
420 self.scan(loaded_mod.root(), loaded_mod.kind()).map_err(|e| {
421 FilesError::ModUnreadable { path: loaded_mod.root().to_path_buf(), source: e }
422 })?;
423 }
424 #[allow(clippy::unnecessary_to_owned)] self.scan(&self.the_mod.root().to_path_buf(), FileKind::Mod).map_err(|e| {
426 FilesError::ModUnreadable { path: self.the_mod.root().to_path_buf(), source: e }
427 })?;
428 Ok(())
429 }
430
431 pub fn finalize(&mut self) {
432 self.files.sort();
435
436 for entry in self.files.drain(..) {
438 if let Some(prev) = self.ordered_files.last_mut() {
439 if entry.path == prev.path {
440 *prev = entry;
441 } else {
442 self.ordered_files.push(entry);
443 }
444 } else {
445 self.ordered_files.push(entry);
446 }
447 }
448
449 for entry in &mut self.ordered_files {
450 let token = Token::new(&entry.filename().to_string_lossy(), (&*entry).into());
451 self.filename_tokens.push(token);
452 entry.store_in_pathtable();
453 self.filenames.insert(entry.path.clone());
454 }
455 }
456
457 pub fn get_files_under<'a>(&'a self, subpath: &'a Path) -> &'a [FileEntry] {
458 let start = self.ordered_files.partition_point(|entry| entry.path < subpath);
459 let end = start
460 + self.ordered_files[start..].partition_point(|entry| entry.path.starts_with(subpath));
461 &self.ordered_files[start..end]
462 }
463
464 pub fn filter_map_under<F, T>(&self, subpath: &Path, f: F) -> Vec<T>
465 where
466 F: Fn(&FileEntry) -> Option<T> + Sync + Send,
467 T: Send,
468 {
469 self.get_files_under(subpath).par_iter().filter_map(f).collect()
470 }
471
472 pub fn handle<T: Send, H: FileHandler<T>>(&self, handler: &mut H, parser: &ParserMemory) {
473 if let Some(config) = &self.config {
474 handler.config(config);
475 }
476 let subpath = handler.subpath();
477 let entries = self.filter_map_under(&subpath, |entry| {
478 handler.load_file(entry, parser).map(|loaded| (entry.clone(), loaded))
479 });
480 for (entry, loaded) in entries {
481 handler.handle_file(&entry, loaded);
482 }
483 handler.finalize();
484 }
485
486 pub fn mark_used(&self, file: &str) {
487 let file = file.strip_prefix('/').unwrap_or(file);
488 self.used.write().unwrap().insert(file.to_string());
489 }
490
491 pub fn exists(&self, key: &str) -> bool {
492 let key = key.strip_prefix('/').unwrap_or(key);
493 let filepath = PathBuf::from(key);
494 self.filenames.contains(&filepath)
495 }
496
497 pub fn iter_keys(&self) -> impl Iterator<Item = &Token> {
498 self.filename_tokens.iter()
499 }
500
501 pub fn entry_exists(&self, key: &str) -> bool {
502 if self.exists(key) {
504 return true;
505 }
506
507 let dir = key.strip_prefix('/').unwrap_or(key);
509 let dirpath = Path::new(dir);
510
511 if self.directories.read().unwrap().contains(dirpath) {
512 return true;
513 }
514
515 match self.ordered_files.binary_search_by_key(&dirpath, |fe| fe.path.as_path()) {
516 Ok(_) => unreachable!(),
518 Err(idx) => {
519 if self.ordered_files[idx].path.starts_with(dirpath) {
521 self.directories.write().unwrap().insert(dirpath.to_path_buf());
522 return true;
523 }
524 }
525 }
526 false
527 }
528
529 pub fn verify_entry_exists(&self, entry: &str, token: &Token, max_sev: Severity) {
530 self.mark_used(&entry.replace("//", "/"));
531 if !self.entry_exists(entry) {
532 let msg = format!("file or directory {entry} does not exist");
533 report(ErrorKey::MissingFile, Item::File.severity().at_most(max_sev))
534 .msg(msg)
535 .loc(token)
536 .push();
537 }
538 }
539
540 #[cfg(feature = "ck3")] pub fn verify_exists(&self, file: &Token) {
542 self.mark_used(&file.as_str().replace("//", "/"));
543 if !self.exists(file.as_str()) {
544 let msg = "referenced file does not exist";
545 report(ErrorKey::MissingFile, Item::File.severity()).msg(msg).loc(file).push();
546 }
547 }
548
549 pub fn verify_exists_implied(&self, file: &str, t: &Token, max_sev: Severity) {
550 self.mark_used(&file.replace("//", "/"));
551 if !self.exists(file) {
552 let msg = format!("file {file} does not exist");
553 report(ErrorKey::MissingFile, Item::File.severity().at_most(max_sev))
554 .msg(msg)
555 .loc(t)
556 .push();
557 }
558 }
559
560 pub fn verify_exists_implied_crashes(&self, file: &str, t: &Token) {
561 self.mark_used(&file.replace("//", "/"));
562 if !self.exists(file) {
563 let msg = format!("file {file} does not exist");
564 fatal(ErrorKey::Crash).msg(msg).loc(t).push();
565 }
566 }
567
568 pub fn validate(&self, _data: &Everything) {
569 let common_dirs = match Game::game() {
570 #[cfg(feature = "ck3")]
571 Game::Ck3 => crate::ck3::tables::misc::COMMON_DIRS,
572 #[cfg(feature = "vic3")]
573 Game::Vic3 => crate::vic3::tables::misc::COMMON_DIRS,
574 #[cfg(feature = "imperator")]
575 Game::Imperator => crate::imperator::tables::misc::COMMON_DIRS,
576 };
577 let common_subdirs_ok = match Game::game() {
578 #[cfg(feature = "ck3")]
579 Game::Ck3 => crate::ck3::tables::misc::COMMON_SUBDIRS_OK,
580 #[cfg(feature = "vic3")]
581 Game::Vic3 => crate::vic3::tables::misc::COMMON_SUBDIRS_OK,
582 #[cfg(feature = "imperator")]
583 Game::Imperator => crate::imperator::tables::misc::COMMON_SUBDIRS_OK,
584 };
585 let mut warned: Vec<&Path> = Vec::new();
587 'outer: for entry in &self.ordered_files {
588 if !entry.path.to_string_lossy().ends_with(".txt") {
589 continue;
590 }
591 if entry.path == PathBuf::from("common/achievement_groups.txt") {
592 continue;
593 }
594 let dirname = entry.path.parent().unwrap();
595 if warned.contains(&dirname) {
596 continue;
597 }
598 if !entry.path.starts_with("common") {
599 let joined = Path::new("common").join(&entry.path);
601 for valid in common_dirs {
602 if joined.starts_with(valid) {
603 let msg = format!("file in unexpected directory {}", dirname.display());
604 let info = format!("did you mean common/{} ?", dirname.display());
605 err(ErrorKey::Filename).msg(msg).info(info).loc(entry).push();
606 warned.push(dirname);
607 continue 'outer;
608 }
609 }
610 continue;
611 }
612
613 for valid in common_subdirs_ok {
614 if entry.path.starts_with(valid) {
615 continue 'outer;
616 }
617 }
618
619 for valid in common_dirs {
620 if <&str as AsRef<Path>>::as_ref(valid) == dirname {
621 continue 'outer;
622 }
623 }
624
625 if entry.path.starts_with("common/scripted_values") {
626 let msg = "file should be in common/script_values/";
627 err(ErrorKey::Filename).msg(msg).loc(entry).push();
628 } else if (Game::is_ck3() || Game::is_imperator())
629 && entry.path.starts_with("common/on_actions")
630 {
631 let msg = "file should be in common/on_action/";
632 err(ErrorKey::Filename).msg(msg).loc(entry).push();
633 } else if Game::is_vic3() && entry.path.starts_with("common/on_action") {
634 let msg = "file should be in common/on_actions/";
635 err(ErrorKey::Filename).msg(msg).loc(entry).push();
636 } else if Game::is_vic3() && entry.path.starts_with("common/modifiers") {
637 let msg = "file should be in common/static_modifiers since 1.7";
638 err(ErrorKey::Filename).msg(msg).loc(entry).push();
639 } else {
640 let msg = format!("file in unexpected directory `{}`", dirname.display());
641 err(ErrorKey::Filename).msg(msg).loc(entry).push();
642 }
643 warned.push(dirname);
644 }
645 }
646
647 pub fn check_unused_dds(&self, _data: &Everything) {
648 let mut vec = Vec::new();
649 for entry in &self.ordered_files {
650 let pathname = entry.path.to_string_lossy();
651 if entry.path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("dds"))
652 && !entry.path.starts_with("gfx/interface/illustrations/loading_screens")
653 && !self.used.read().unwrap().contains(pathname.as_ref())
654 {
655 vec.push(entry);
656 }
657 }
658 let mut printed_header = false;
659 for entry in vec {
660 if !printed_header && will_maybe_log(entry, ErrorKey::UnusedFile) {
661 warn_header(ErrorKey::UnusedFile, "Unused DDS files:\n");
662 printed_header = true;
663 }
664 warn_abbreviated(entry, ErrorKey::UnusedFile);
665 }
666 if printed_header {
667 warn_header(ErrorKey::UnusedFile, "");
668 }
669 }
670}