Skip to main content

ltk_mod_project/pack/
packer.rs

1//! [`ProjectPacker`]: the format-neutral packing driver.
2
3use 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/// Failure to pack a mod project.
18///
19/// The variants here are the driver's: they can occur whatever format is
20/// being packed. Format-specific failures arrive through the transparent
21/// [`Format`](Self::Format) variant, so matching on a concrete format's
22/// error is one level deep: `PackError::Format(inner)`.
23#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum PackError<E> {
26    /// A layer's declarations cannot be loaded.
27    #[error(transparent)]
28    GameData(#[from] ltk_game_data::Error),
29    /// A project directory could not be read during the scan.
30    #[error("Failed to scan {path}")]
31    Scan {
32        path: Utf8PathBuf,
33        #[source]
34        source: io::Error,
35    },
36
37    /// A scanned path is not valid UTF-8, which no archive format stores.
38    #[error("Path is not valid UTF-8: {}", .0.display())]
39    NonUtf8Path(std::path::PathBuf),
40
41    /// A configured layer has no directory under `content/`.
42    #[error("Layer directory missing: {layer} at {path}")]
43    LayerDirMissing { layer: String, path: Utf8PathBuf },
44
45    /// The base layer is configured with a priority other than 0.
46    #[error("Base layer must have priority 0, got: {0}")]
47    InvalidBaseLayerPriority(i32),
48
49    /// The project's `.modignore` could not be loaded: the file is
50    /// unreadable, or a pattern in it does not parse. A broken pattern fails
51    /// the pack rather than silently shipping files the author excluded.
52    #[error(transparent)]
53    Ignore(#[from] ModIgnoreError),
54
55    /// A content directory or file could not be read during the scan.
56    #[error(transparent)]
57    Walk(#[from] ContentWalkError),
58
59    /// A declared hashtable's key width is not one a key can have; the
60    /// standard requires 1 to 64 bits.
61    #[error("Hashtable {path} declares a key width of {bits} bits; a key holds 1 to 64")]
62    HashtableWidth {
63        /// The table's declared path, relative to the project root.
64        path: Utf8PathBuf,
65        /// The width the manifest declares.
66        bits: u8,
67    },
68
69    /// A declared hashtable file is missing, or does not fit the table
70    /// grammar.
71    #[error("Failed to read the hashtable at {path}")]
72    Hashtable {
73        /// The table's path on disk.
74        path: Utf8PathBuf,
75        #[source]
76        source: HashtableReadError,
77    },
78
79    /// Two different names in one category truncate to one key, so one of
80    /// them could never be resolved again. Only the author can fix it - by
81    /// renaming a file - so the pack fails rather than shipping a broken
82    /// table.
83    #[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    /// An [`IgnoreMode::Explicit`] filter was built for a different project
90    /// root than the packer was given, so it would relate every scanned path
91    /// to the wrong content dir and quietly filter wrong.
92    #[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    /// The format failed to write the archive; see the format's own error
99    /// type for the cases.
100    #[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/// Result of a successful pack operation.
114#[derive(Debug, Clone, PartialEq)]
115pub struct PackReport {
116    ignored: Vec<Utf8PathBuf>,
117    trimmed_game_names: usize,
118}
119
120impl PackReport {
121    /// The entries `.modignore` excluded from the archive, in traversal
122    /// order. A pruned directory appears once; the files beneath it are not
123    /// enumerated.
124    pub fn ignored_files(&self) -> &[Utf8PathBuf] {
125        &self.ignored
126    }
127
128    /// `ignored_files().len()`, for reporting.
129    pub fn ignored_count(&self) -> usize {
130        self.ignored.len()
131    }
132
133    /// `game` hashtable names the format omitted because the package's own
134    /// chunk table already recovers them.
135    ///
136    /// A silent trim and an empty table look identical from outside, and
137    /// only one of them is correct - report this to the user when it is not
138    /// zero. Only the modpkg format trims; every other format reports 0.
139    pub fn trimmed_game_names(&self) -> usize {
140        self.trimmed_game_names
141    }
142}
143
144/// Packs a mod project directory into an archive format.
145///
146/// The packer is format-neutral: it owns everything about reading the
147/// project (config, validation, the single `.modignore`-filtered walk of
148/// `content/`), and hands the result to a [`PackFormat`] implementation,
149/// which owns everything about writing its archive. See the
150/// [module docs](crate::pack) for an example.
151#[derive(Debug, Clone)]
152pub struct ProjectPacker {
153    project: ModProject,
154    project_root: Utf8PathBuf,
155    options: PackOptions,
156}
157
158impl ProjectPacker {
159    /// Create a packer by loading the mod project config from a directory.
160    ///
161    /// Looks for `mod.config.json` or `mod.config.toml` in `project_root`.
162    ///
163    /// # Errors
164    ///
165    /// Fails with [`ModProjectError`] when the directory holds no config
166    /// file, or the config does not parse.
167    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    /// Create a packer with an already-loaded mod project config.
174    ///
175    /// Use this when you have a [`ModProject`] from another source (e.g. an
176    /// in-memory config or a workshop import). For the common case of packing
177    /// from a project directory, prefer [`from_dir`](Self::from_dir).
178    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    /// Replace the pack options.
187    #[must_use]
188    pub fn with_options(mut self, options: PackOptions) -> Self {
189        self.options = options;
190        self
191    }
192
193    /// The project being packed.
194    pub fn project(&self) -> &ModProject {
195        &self.project
196    }
197
198    /// The project's root directory.
199    pub fn project_root(&self) -> &Utf8Path {
200        &self.project_root
201    }
202
203    /// The options the pack will run with.
204    pub fn options(&self) -> &PackOptions {
205        &self.options
206    }
207
208    /// Pack the project into `format`.
209    ///
210    /// Validates the layer layout, walks `content/` once with the
211    /// `.modignore` filter, and hands the resulting [`PackPlan`] to the
212    /// format. The report carries what the filter excluded.
213    ///
214    /// Use [`pack_with_progress`](Self::pack_with_progress) to watch a long
215    /// pack as it runs.
216    ///
217    /// # Errors
218    ///
219    /// Driver failures (scanning, `.modignore`, layer layout) surface as
220    /// [`PackError`]'s own variants; a failure inside `format` surfaces as
221    /// [`PackError::Format`].
222    pub fn pack<F: PackFormat>(&self, format: F) -> Result<PackReport, PackError<F::Error>> {
223        self.pack_reporting(format, PackReporter::new(None))
224    }
225
226    /// Pack the project into `format`, reporting each step to `progress`.
227    ///
228    /// The scan reports a layer at a time and the write reports a file at a
229    /// time, both on the packing thread. See [`PackProgress`] for what the
230    /// counters mean.
231    ///
232    /// The callback is borrowed rather than owned because a pack is one-shot:
233    /// there is nothing to keep it alive past this call, and a caller drawing a
234    /// bar usually wants to write straight into state it already holds.
235    ///
236    /// # Errors
237    ///
238    /// As [`pack`](Self::pack).
239    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        // Owned storage for the modes that build their filter here; the
256        // explicit mode borrows the caller's.
257        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    /// The layers a pack covers: the base layer first (synthesized when the
321    /// config omits it), then the configured non-base layers in config order.
322    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    /// Read and validate the hashtables the config declares, in manifest
373    /// order.
374    ///
375    /// Every declared table is read here, whatever format the pack targets:
376    /// collisions are judged over the merged category, which is what a reader
377    /// of the packed archive will see, and a table the driver cannot read is
378    /// a table no archive should ship.
379    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
420// -- scanning ---------------------------------------------------------------
421
422fn 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        // Ignore files are filter metadata, never content.
442        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            // Parents matter here: ignoring the layer directory itself must
453            // drop its loose files too.
454            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    // read_dir entries always carry a final component.
475    let dir_name = dir_path.file_name().expect("directory entry has a name");
476
477    // Case-insensitive: `Aatrox.WAD.Client` is still a WAD directory.
478    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    // WAD content is addressed relative to the WAD directory (the WAD name
482    // travels separately); other directories keep their name in the path.
483    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}