modde-core 0.2.1

Core types and logic for the modde mod manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Archive structure detection.
//!
//! Given an extracted archive and a game-specific [`InstallProbe`], decide
//! which [`InstallMethod`] describes this mod. The pipeline is intentionally
//! ordered so game plugins can claim layouts authoritatively before the
//! generic probes kick in.
//!
//! Detection order:
//!
//! 1. **Normalize**: if the extracted dir contains exactly one wrapper
//!    directory and no files, recurse into that subdir and record the
//!    `strip_prefix` on the resulting plan.
//! 2. **Game plugin**: `probe.analyze(dir)` — plugin-specific rules (e.g.
//!    `REDmod` for Cyberpunk).
//! 3. **FOMOD**: presence of `fomod/ModuleConfig.xml`.
//! 4. **BAIN**: numbered option subdirs (`00 Core`, `01 Option`, ...).
//! 5. **DLL overlay**: top-level `.dll` with no nested asset dirs.
//! 6. **Bare extract**: `probe.recognizes_bare(dir)`.
//! 7. **Unknown**: fall through.
//!
//! On `Unknown`, the caller is expected to dump a dossier (see
//! [`super::dossier`]) and let the skill path extend this enum.

use std::fs;
use std::path::{Path, PathBuf};

use super::fs::find_fomod_config;
use super::probe::InstallProbe;
use super::types::{InstallMethod, InstallPlan, InstallerResult};

/// Classify `extracted_dir` and return an [`InstallPlan`] with the
/// detected method and `source_archive_hash` pre-populated.
///
/// `source_archive_hash` is the xxh64 hex digest of the original archive;
/// the caller computes it during download (it cannot be derived from the
/// extracted tree alone). The returned plan has an empty `staged_files`
/// — call [`super::execute::execute`] to populate it.
pub fn analyze(
    extracted_dir: &Path,
    probe: &InstallProbe,
    source_archive_hash: String,
) -> InstallerResult<InstallPlan> {
    let (effective_dir, strip_prefix) = normalize(extracted_dir)?;
    let target = if let Some(ref p) = strip_prefix {
        extracted_dir.join(p)
    } else {
        extracted_dir.to_path_buf()
    };
    let _ = effective_dir; // `target` is the authoritative path

    let method = detect_method(&target, probe);

    Ok(InstallPlan {
        method,
        strip_prefix,
        source_archive_hash,
        staged_files: Vec::new(),
    })
}

/// Follow single-directory wrappers (e.g. `ModName-1.0/<real contents>`)
/// until we reach either (a) a directory with multiple entries, (b) a
/// single non-directory entry, or (c) a directory whose only child is a
/// recognized mod-content dir like `Data/` or `r6/`. Case (c) is the
/// tricky one: `ModName-1.0/Data/mod.esp` looks like two nested
/// single-child wrappers from the filesystem's perspective, but `Data/`
/// is real content and should become the staging root.
fn normalize(extracted_dir: &Path) -> InstallerResult<(PathBuf, Option<PathBuf>)> {
    /// Lower-case names that, when seen as the ONLY child of a dir, mean
    /// "stop unwrapping — this child is the real mod content". Union of
    /// Bethesda and Cyberpunk content dirs plus generic installer
    /// markers. Kept centralized so a new game only has to edit this
    /// list to participate in prefix stripping.
    const CONTENT_DIR_NAMES: &[&str] = &[
        "data",
        "meshes",
        "textures",
        "scripts",
        "interface",
        "sound",
        "music",
        "materials",
        "seq",
        "shadersfx",
        "strings",
        "r6",
        "archive",
        "archives",
        "bin",
        "engine",
        "mods",
        "red4ext",
        "fomod",
    ];

    let mut current = extracted_dir.to_path_buf();
    let mut strip: Option<PathBuf> = None;

    loop {
        let entries: Vec<_> = match fs::read_dir(&current) {
            Ok(rd) => rd.flatten().collect(),
            Err(_) => break,
        };
        if entries.len() != 1 {
            break;
        }
        let only = &entries[0];
        if !only.path().is_dir() {
            break;
        }
        let name = only.file_name();
        let name_lc = name.to_string_lossy().to_lowercase();
        if CONTENT_DIR_NAMES.iter().any(|d| *d == name_lc) {
            break;
        }
        current = only.path();
        strip = Some(match strip {
            Some(p) => p.join(&name),
            None => PathBuf::from(&name),
        });
    }

    Ok((current, strip))
}

fn detect_method(dir: &Path, probe: &InstallProbe) -> InstallMethod {
    // 1. Game plugin gets first crack.
    if let Some(method) = (probe.analyze)(dir) {
        return method;
    }

    // 2. FOMOD.
    if let Some(module_config) = find_fomod_config(dir) {
        let rel = module_config
            .strip_prefix(dir)
            .unwrap_or(&module_config)
            .to_path_buf();
        return InstallMethod::Fomod {
            module_config: rel,
            config_toml: None,
        };
    }

    // 3. BAIN — numbered option subdirs.
    if looks_like_bain(dir) {
        return InstallMethod::Bain {
            selected_subdirs: Vec::new(),
        };
    }

    // 4. DLL overlay — .dll at top with no nested content dirs.
    if looks_like_dll_overlay(dir) {
        return InstallMethod::DllOverlay {
            target_dir_hint: "game root".to_string(),
        };
    }

    // 5. Game plugin's bare-layout recognizer.
    if (probe.recognizes_bare)(dir) {
        return InstallMethod::BareExtract;
    }

    // 6. User-config overlay — last fallback before Unknown.
    //
    // The plugin had to advertise a `UserConfig` deploy target for
    // this branch to fire (probe carries the id). We additionally
    // require *every* file in the tree to look like a config file:
    // an unrecognized layout that happens to ship one INI alongside
    // a binary blob should still be `Unknown` and prompt a dossier
    // dump rather than silently routing the binary into the user's
    // config dir.
    if let Some(target_id) = probe.user_config_target
        && tree_is_only_config(dir)
    {
        return InstallMethod::UserConfigOverlay {
            target_id: target_id.to_string(),
        };
    }

    // 7. Fall through to Unknown.
    InstallMethod::Unknown {
        reason: "no matching install method — dossier should be dumped".to_string(),
    }
}

/// Recognized config-file extensions for the `UserConfigOverlay` branch.
///
/// Kept conservative on purpose: an archive containing extensions
/// outside this list (e.g. `.dll`, `.pak`, `.exe`) is *not* a config
/// overlay even if it also contains an INI. Adding extensions here
/// expands what's considered "user config payload" everywhere at once.
const USER_CONFIG_EXTENSIONS: &[&str] =
    &["ini", "cfg", "conf", "json", "toml", "yaml", "yml", "xml"];

/// `true` when every regular file in `dir` (recursively) has an
/// extension in [`USER_CONFIG_EXTENSIONS`]. Empty directories return
/// `false` — there's no config payload to deploy.
fn tree_is_only_config(dir: &Path) -> bool {
    fn visit(dir: &Path, saw_any: &mut bool) -> bool {
        let Ok(rd) = fs::read_dir(dir) else {
            return false;
        };
        for entry in rd.flatten() {
            let path = entry.path();
            if path.is_dir() {
                if !visit(&path, saw_any) {
                    return false;
                }
                continue;
            }
            if !path.is_file() {
                continue;
            }
            *saw_any = true;
            let Some(ext) = path
                .extension()
                .and_then(|e| e.to_str())
                .map(str::to_ascii_lowercase)
            else {
                return false;
            };
            if !USER_CONFIG_EXTENSIONS.iter().any(|e| *e == ext) {
                return false;
            }
        }
        true
    }
    let mut saw_any = false;
    visit(dir, &mut saw_any) && saw_any
}

fn looks_like_bain(dir: &Path) -> bool {
    let Ok(entries) = fs::read_dir(dir) else {
        return false;
    };
    let mut numbered = 0;
    let mut total = 0;
    for entry in entries.flatten() {
        if !entry.path().is_dir() {
            continue;
        }
        total += 1;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        // BAIN convention: "00 Core", "01 Option A", ...
        if name_str.len() >= 3
            && name_str.as_bytes()[0].is_ascii_digit()
            && name_str.as_bytes()[1].is_ascii_digit()
            && (name_str.as_bytes()[2] == b' ' || name_str.as_bytes()[2] == b'_')
        {
            numbered += 1;
        }
    }
    total >= 2 && numbered >= 2
}

fn looks_like_dll_overlay(dir: &Path) -> bool {
    let Ok(entries) = fs::read_dir(dir) else {
        return false;
    };
    let mut has_dll = false;
    let mut has_asset_dir = false;
    let asset_dirs = [
        "data", "meshes", "textures", "scripts", "r6", "archive", "mods",
    ];
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            let name = entry.file_name().to_string_lossy().to_lowercase();
            if asset_dirs.iter().any(|d| *d == name) {
                has_asset_dir = true;
            }
        } else if let Some(ext) = path.extension().and_then(|e| e.to_str())
            && ext.eq_ignore_ascii_case("dll")
        {
            has_dll = true;
        }
    }
    has_dll && !has_asset_dir
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write as _;

    fn touch(p: &Path) {
        if let Some(parent) = p.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        let mut f = fs::File::create(p).unwrap();
        f.write_all(b"x").unwrap();
    }

    #[test]
    fn normalize_strips_single_wrapper() {
        let tmp = tempfile::tempdir().unwrap();
        let wrapper = tmp.path().join("ModName-1.0");
        touch(&wrapper.join("Data").join("mod.esp"));

        let (effective, strip) = normalize(tmp.path()).unwrap();
        assert_eq!(strip.as_deref(), Some(Path::new("ModName-1.0")));
        assert_eq!(effective, wrapper);
    }

    #[test]
    fn normalize_leaves_multi_entry_root_alone() {
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("Data").join("a.esp"));
        touch(&tmp.path().join("readme.txt"));

        let (effective, strip) = normalize(tmp.path()).unwrap();
        assert!(strip.is_none());
        assert_eq!(effective, tmp.path());
    }

    #[test]
    fn detects_fomod() {
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("fomod").join("ModuleConfig.xml"));
        touch(&tmp.path().join("Data").join("foo.esp"));

        let probe = InstallProbe::noop();
        let plan = analyze(tmp.path(), &probe, "deadbeef".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::Fomod { .. }));
    }

    #[test]
    fn detects_bain() {
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("00 Core").join("foo.esp"));
        touch(&tmp.path().join("01 Option A").join("foo.esp"));
        touch(&tmp.path().join("02 Option B").join("foo.esp"));

        let probe = InstallProbe::noop();
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::Bain { .. }));
    }

    #[test]
    fn detects_dll_overlay() {
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("hook.dll"));
        touch(&tmp.path().join("hook.ini"));

        let probe = InstallProbe::noop();
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::DllOverlay { .. }));
    }

    #[test]
    fn plugin_analyze_wins() {
        let tmp = tempfile::tempdir().unwrap();
        // Looks like FOMOD...
        touch(&tmp.path().join("fomod").join("ModuleConfig.xml"));
        // ...but the plugin claims REDmod first.
        let probe = InstallProbe::new(
            |_: &Path| {
                Some(InstallMethod::REDmod {
                    manifest: PathBuf::from("info.json"),
                })
            },
            |_: &Path| false,
        );
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::REDmod { .. }));
    }

    #[test]
    fn bare_fallback_when_plugin_says_so() {
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("Data").join("foo.esp"));

        let probe = InstallProbe::new(|_: &Path| None, |_: &Path| true);
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::BareExtract));
    }

    #[test]
    fn unknown_is_last_resort() {
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("mystery_blob.bin"));

        let probe = InstallProbe::noop();
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::Unknown { .. }));
    }

    #[test]
    fn detects_user_config_overlay() {
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("Engine.ini"));
        touch(&tmp.path().join("GameUserSettings.ini"));

        let probe = InstallProbe::noop().with_user_config_target("test-config");
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        match plan.method {
            InstallMethod::UserConfigOverlay { target_id } => assert_eq!(target_id, "test-config"),
            other => panic!("expected UserConfigOverlay, got {other:?}"),
        }
    }

    #[test]
    fn user_config_overlay_requires_plugin_target() {
        // Same archive, no plugin target advertised → must fall through
        // to Unknown rather than route INIs nowhere.
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("Engine.ini"));

        let probe = InstallProbe::noop();
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::Unknown { .. }));
    }

    #[test]
    fn user_config_overlay_rejects_mixed_payloads() {
        // INI alongside a binary blob is not a config overlay — we
        // refuse to silently route an unknown binary into the user's
        // config dir.
        let tmp = tempfile::tempdir().unwrap();
        touch(&tmp.path().join("Engine.ini"));
        touch(&tmp.path().join("payload.bin"));

        let probe = InstallProbe::noop().with_user_config_target("test-config");
        let plan = analyze(tmp.path(), &probe, "h".to_string()).unwrap();
        assert!(matches!(plan.method, InstallMethod::Unknown { .. }));
    }
}