1use std::fs;
4use std::io;
5
6use camino::{Utf8Path, Utf8PathBuf};
7use ltk_hashtable::{Collision, Hashtable, HashtableReadError, HashtableSet};
8
9use super::plan::{PackPlan, PlannedFile, PlannedHashtable, PlannedLayer, PlannedLicense};
10use super::progress::{PackProgress, PackReporter};
11use super::{IgnoreMode, PackFormat, PackOptions};
12use crate::{
13 canonical_license_file_name, find_license_file, ContentWalkError, ModIgnore, ModIgnoreError,
14 ModProject, ModProjectError, ModProjectLayer, CONTENT_DIR_NAME, MODIGNORE_FILE_NAME,
15};
16
17#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum PackError<E> {
26 #[error(transparent)]
28 GameData(#[from] ltk_game_data::Error),
29 #[error("Failed to scan {path}")]
31 Scan {
32 path: Utf8PathBuf,
33 #[source]
34 source: io::Error,
35 },
36
37 #[error("Path is not valid UTF-8: {}", .0.display())]
39 NonUtf8Path(std::path::PathBuf),
40
41 #[error("Layer directory missing: {layer} at {path}")]
43 LayerDirMissing { layer: String, path: Utf8PathBuf },
44
45 #[error("Base layer must have priority 0, got: {0}")]
47 InvalidBaseLayerPriority(i32),
48
49 #[error(transparent)]
53 Ignore(#[from] ModIgnoreError),
54
55 #[error(transparent)]
57 Walk(#[from] ContentWalkError),
58
59 #[error("Hashtable {path} declares a key width of {bits} bits; a key holds 1 to 64")]
62 HashtableWidth {
63 path: Utf8PathBuf,
65 bits: u8,
67 },
68
69 #[error("Failed to read the hashtable at {path}")]
72 Hashtable {
73 path: Utf8PathBuf,
75 #[source]
76 source: HashtableReadError,
77 },
78
79 #[error(
84 "The {} tables collide: {:?} and {:?} share the key {}",
85 .0.category, .0.first, .0.second, .0.key
86 )]
87 HashtableCollision(Box<Collision>),
88
89 #[error("Ignore filter is rooted at {filter_root}, but the project's content dir is {project_content_dir}")]
93 IgnoreRootMismatch {
94 filter_root: Utf8PathBuf,
95 project_content_dir: Utf8PathBuf,
96 },
97
98 #[error(transparent)]
101 Format(E),
102}
103
104impl<E> PackError<E> {
105 fn scan(path: impl Into<Utf8PathBuf>, source: io::Error) -> Self {
106 Self::Scan {
107 path: path.into(),
108 source,
109 }
110 }
111}
112
113#[derive(Debug, Clone, PartialEq)]
115pub struct PackReport {
116 ignored: Vec<Utf8PathBuf>,
117 trimmed_game_names: usize,
118}
119
120impl PackReport {
121 pub fn ignored_files(&self) -> &[Utf8PathBuf] {
125 &self.ignored
126 }
127
128 pub fn ignored_count(&self) -> usize {
130 self.ignored.len()
131 }
132
133 pub fn trimmed_game_names(&self) -> usize {
140 self.trimmed_game_names
141 }
142}
143
144#[derive(Debug, Clone)]
152pub struct ProjectPacker {
153 project: ModProject,
154 project_root: Utf8PathBuf,
155 options: PackOptions,
156}
157
158impl ProjectPacker {
159 pub fn from_dir(project_root: impl Into<Utf8PathBuf>) -> Result<Self, ModProjectError> {
168 let project_root = project_root.into();
169 let project = ModProject::load(&project_root)?;
170 Ok(Self::new(project, project_root))
171 }
172
173 pub fn new(project: ModProject, project_root: impl Into<Utf8PathBuf>) -> Self {
179 Self {
180 project,
181 project_root: project_root.into(),
182 options: PackOptions::default(),
183 }
184 }
185
186 #[must_use]
188 pub fn with_options(mut self, options: PackOptions) -> Self {
189 self.options = options;
190 self
191 }
192
193 pub fn project(&self) -> &ModProject {
195 &self.project
196 }
197
198 pub fn project_root(&self) -> &Utf8Path {
200 &self.project_root
201 }
202
203 pub fn options(&self) -> &PackOptions {
205 &self.options
206 }
207
208 pub fn pack<F: PackFormat>(&self, format: F) -> Result<PackReport, PackError<F::Error>> {
223 self.pack_reporting(format, PackReporter::new(None))
224 }
225
226 pub fn pack_with_progress<F: PackFormat>(
240 &self,
241 format: F,
242 progress: &mut dyn FnMut(PackProgress<'_>),
243 ) -> Result<PackReport, PackError<F::Error>> {
244 self.pack_reporting(format, PackReporter::new(Some(progress)))
245 }
246
247 fn pack_reporting<F: PackFormat>(
248 &self,
249 format: F,
250 mut progress: PackReporter<'_>,
251 ) -> Result<PackReport, PackError<F::Error>> {
252 let layers = self.layer_set();
253 self.validate_layers(&layers)?;
254
255 let loaded;
258 let ignore = match &self.options.ignore {
259 IgnoreMode::FromProject => {
260 loaded = ModIgnore::load(&self.project_root)?;
261 &loaded
262 }
263 IgnoreMode::Disabled => {
264 loaded = ModIgnore::empty(&self.project_root);
265 &loaded
266 }
267 IgnoreMode::Explicit(ignore) => {
268 let expected = self.project_root.join(CONTENT_DIR_NAME);
269 if ignore.content_dir() != expected {
270 return Err(PackError::IgnoreRootMismatch {
271 filter_root: ignore.content_dir().to_owned(),
272 project_content_dir: expected,
273 });
274 }
275 ignore
276 }
277 };
278
279 let content_dir = self.project_root.join(CONTENT_DIR_NAME);
280 let layer_count = layers.len() as u32;
281 let mut ignored = Vec::new();
282 let mut planned = Vec::with_capacity(layers.len());
283 for (index, layer) in layers.into_iter().enumerate() {
284 progress.report_layer(&layer.name, index as u32, layer_count);
285 let declarations =
286 crate::game_data::load_layer(&self.project_root, &layer.name, ignore);
287 let mut files = scan_layer(&content_dir, &layer, ignore, &mut ignored)?;
288 files.retain(|file| !declarations.is_declaration_input(file.source()));
289 let override_files = declarations.override_files().to_vec();
290 let declarations = declarations.declarations?;
291 planned.push(
292 PlannedLayer::new(layer, files).with_game_data(declarations, override_files)?,
293 );
294 }
295
296 progress.set_total(planned.iter().map(|layer| layer.files().len() as u32).sum());
297
298 let plan = PackPlan::new(
299 &self.project,
300 &self.project_root,
301 planned,
302 self.find_readme(),
303 self.find_license(),
304 self.find_thumbnail(),
305 self.resolve_hashtables()?,
306 );
307
308 let format_report = format
309 .pack(&plan, &mut progress)
310 .map_err(PackError::Format)?;
311
312 progress.report_complete();
313
314 Ok(PackReport {
315 ignored,
316 trimmed_game_names: format_report.trimmed_game_names,
317 })
318 }
319
320 fn layer_set(&self) -> Vec<ModProjectLayer> {
323 let base = self
324 .project
325 .layers
326 .iter()
327 .find(|layer| layer.is_base())
328 .cloned()
329 .unwrap_or_else(ModProjectLayer::base);
330
331 std::iter::once(base)
332 .chain(
333 self.project
334 .layers
335 .iter()
336 .filter(|layer| !layer.is_base())
337 .cloned(),
338 )
339 .collect()
340 }
341
342 fn validate_layers<E>(&self, layers: &[ModProjectLayer]) -> Result<(), PackError<E>> {
343 for layer in layers {
344 if layer.is_base() && layer.priority != 0 {
345 return Err(PackError::InvalidBaseLayerPriority(layer.priority));
346 }
347 let layer_dir = ModProjectLayer::content_path(&self.project_root, &layer.name);
348 if !layer_dir.exists() {
349 return Err(PackError::LayerDirMissing {
350 layer: layer.name.clone(),
351 path: layer_dir,
352 });
353 }
354 }
355 Ok(())
356 }
357
358 fn find_readme(&self) -> Option<Utf8PathBuf> {
359 let path = self.project_root.join("README.md");
360 path.exists().then_some(path)
361 }
362
363 fn find_license(&self) -> Option<PlannedLicense> {
364 let path = find_license_file(&self.project_root)?;
365 let canonical = path
366 .file_name()
367 .and_then(canonical_license_file_name)
368 .unwrap_or("LICENSE");
369 Some(PlannedLicense::new(path, canonical))
370 }
371
372 fn resolve_hashtables<E>(&self) -> Result<Vec<PlannedHashtable>, PackError<E>> {
380 let mut planned = Vec::with_capacity(self.project.hashtables.len());
381 for manifest in &self.project.hashtables {
382 let Some(entry) = manifest.to_entry() else {
383 return Err(PackError::HashtableWidth {
384 path: manifest.path.clone().into(),
385 bits: manifest.bits,
386 });
387 };
388 let source = self.project_root.join(&manifest.path);
389 let table = fs::File::open(source.as_std_path())
390 .map_err(HashtableReadError::from)
391 .and_then(|file| Hashtable::from_reader(io::BufReader::new(file)))
392 .map_err(|error| PackError::Hashtable {
393 path: source.clone(),
394 source: error,
395 })?;
396 planned.push(PlannedHashtable::new(source, entry, table));
397 }
398
399 let merged = HashtableSet::build(
400 planned
401 .iter()
402 .map(|table| (table.entry().clone(), table.table().clone())),
403 );
404 if let Some(collision) = merged.collisions().first() {
405 return Err(PackError::HashtableCollision(Box::new(collision.clone())));
406 }
407
408 Ok(planned)
409 }
410
411 fn find_thumbnail(&self) -> Option<Utf8PathBuf> {
412 let path = match &self.project.thumbnail {
413 Some(configured) => self.project_root.join(configured),
414 None => self.project_root.join("thumbnail.webp"),
415 };
416 path.exists().then_some(path)
417 }
418}
419
420fn scan_layer<E>(
423 content_dir: &Utf8Path,
424 layer: &ModProjectLayer,
425 ignore: &ModIgnore,
426 ignored: &mut Vec<Utf8PathBuf>,
427) -> Result<Vec<PlannedFile>, PackError<E>> {
428 let layer_dir = content_dir.join(&layer.name);
429 let mut files = Vec::new();
430
431 let entries = fs::read_dir(layer_dir.as_std_path())
432 .map_err(|source| PackError::scan(&layer_dir, source))?;
433 let mut entry_paths = Vec::new();
434 for entry in entries {
435 let entry = entry.map_err(|source| PackError::scan(&layer_dir, source))?;
436 entry_paths.push(Utf8PathBuf::from_path_buf(entry.path()).map_err(PackError::NonUtf8Path)?);
437 }
438 entry_paths.sort();
439
440 for entry_path in entry_paths {
441 if entry_path
443 .file_name()
444 .is_some_and(|name| name.eq_ignore_ascii_case(MODIGNORE_FILE_NAME))
445 {
446 continue;
447 }
448
449 if entry_path.is_dir() {
450 scan_directory(&layer_dir, &entry_path, ignore, ignored, &mut files)?;
451 } else if entry_path.is_file() {
452 if ignore.matched_with_parents(&entry_path, false).is_ignored() {
455 ignored.push(entry_path);
456 continue;
457 }
458
459 let rel_path = rel_path_normalized(&entry_path, &layer_dir);
460 files.push(PlannedFile::new(entry_path, rel_path, None));
461 }
462 }
463
464 Ok(files)
465}
466
467fn scan_directory<E>(
468 layer_dir: &Utf8Path,
469 dir_path: &Utf8Path,
470 ignore: &ModIgnore,
471 ignored: &mut Vec<Utf8PathBuf>,
472 files: &mut Vec<PlannedFile>,
473) -> Result<(), PackError<E>> {
474 let dir_name = dir_path.file_name().expect("directory entry has a name");
476
477 let is_wad = dir_name.to_ascii_lowercase().ends_with(".wad.client");
479 let wad_name = is_wad.then(|| dir_name.to_string());
480
481 let strip_base = if is_wad { dir_path } else { layer_dir };
484
485 let mut walk = ignore.walk(dir_path);
486 for file in walk.by_ref() {
487 let file_path = file?;
488 let rel_path = rel_path_normalized(&file_path, strip_base);
489 files.push(PlannedFile::new(file_path, rel_path, wad_name.clone()));
490 }
491
492 ignored.extend(walk.into_skipped());
493
494 Ok(())
495}
496
497fn rel_path_normalized(path: &Utf8Path, base: &Utf8Path) -> String {
498 path.strip_prefix(base)
499 .expect("scanned path must sit under the scanned directory")
500 .as_str()
501 .replace('\\', "/")
502}