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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Stage files from a temporary extraction directory into a mod's store
//! directory, according to an [`InstallPlan`].
//!
//! Execution is deliberately dumb: it copies files, records their paths,
//! and returns the manifest. It does not touch the database — the caller
//! wires the returned `Vec<StagedFile>` into `ModdeDb::record_install`.
//!
//! Variants that need user input (`Fomod` with no config, `Bain` with no
//! selection) return [`InstallerError::RequiresUserInput`] so the UI can
//! route to its wizard.

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

use super::fs::walk_files;
use super::types::{InstallMethod, InstallPlan, InstallerError, InstallerResult, StagedFile};

/// Execute `plan`, staging files from `extracted_dir` into
/// `store_mod_dir`. On success, mutates `plan.staged_files` with the
/// final manifest and returns it by value for the caller to persist.
///
/// `extracted_dir` is the temp directory the archive was unzipped into.
/// `store_mod_dir` is the canonical per-mod directory in the store (the
/// caller decides the naming, typically `{domain}_{mod_id}_{file_id}`).
pub fn execute(
    plan: &mut InstallPlan,
    extracted_dir: &Path,
    store_mod_dir: &Path,
) -> InstallerResult<Vec<StagedFile>> {
    let source_root = if let Some(ref strip) = plan.strip_prefix {
        extracted_dir.join(strip)
    } else {
        extracted_dir.to_path_buf()
    };

    fs::create_dir_all(store_mod_dir)?;

    let files = match &plan.method {
        InstallMethod::BareExtract => stage_tree(&source_root, store_mod_dir, None)?,

        InstallMethod::StripContentRoot { root } => {
            let content_root = source_root.join(root);
            if !content_root.is_dir() {
                return Err(InstallerError::MissingFile(root.clone()));
            }
            stage_tree_into(
                &content_root,
                store_mod_dir,
                store_mod_dir,
                Some(PathBuf::from(root)),
            )?
        }

        InstallMethod::DirectoryMod { directory_name } => {
            let dir_name = directory_name
                .clone()
                .unwrap_or_else(|| store_dir_name(store_mod_dir));
            let nested = store_mod_dir.join(&dir_name);
            fs::create_dir_all(&nested)?;
            stage_tree_into(&source_root, &nested, store_mod_dir, None)?
        }

        InstallMethod::DirectoryModFromXml {
            marker,
            id_attr,
            fallback_name,
        } => {
            let marker_path = source_root.join(marker);
            if !marker_path.is_file() {
                return Err(InstallerError::MissingFile(
                    marker.to_string_lossy().to_string(),
                ));
            }
            let dir_name = read_xml_attr(&marker_path, id_attr)
                .or_else(|| fallback_name.clone())
                .unwrap_or_else(|| store_dir_name(store_mod_dir));
            let nested = store_mod_dir.join(&dir_name);
            fs::create_dir_all(&nested)?;
            stage_tree_into(&source_root, &nested, store_mod_dir, None)?
        }

        InstallMethod::MultiRootOverlay { roots } => {
            let mut out = Vec::new();
            for root in roots {
                let root_src = source_root.join(root);
                if root_src.exists() {
                    out.extend(stage_tree_into(
                        &root_src,
                        &store_mod_dir.join(root),
                        store_mod_dir,
                        Some(PathBuf::from(root)),
                    )?);
                }
            }
            out
        }

        InstallMethod::SingleFileSet => {
            let mut out = Vec::new();
            for entry in fs::read_dir(&source_root)? {
                let entry = entry?;
                let path = entry.path();
                if !path.is_file() {
                    continue;
                }
                let dest = store_mod_dir.join(entry.file_name());
                if fs::rename(&path, &dest).is_err() {
                    fs::copy(&path, &dest)?;
                    let _ = fs::remove_file(&path);
                }
                let size = fs::metadata(&dest).map_or(0, |m| m.len());
                out.push(StagedFile {
                    rel_path: dest_rel(store_mod_dir, &dest),
                    origin_rel_path: entry.file_name().to_string_lossy().to_string(),
                    size,
                    merge_group: None,
                });
            }
            out
        }

        InstallMethod::REDmod { manifest: _ } => {
            // REDmod layout already ships under a top-level dir the game
            // expects; we stage everything under `mods/<mod-name>/`. The
            // store dir name is used as the mod name so the caller can
            // pick a stable identifier.
            let mod_name = store_mod_dir
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("redmod");
            let nested = store_mod_dir.join("mods").join(mod_name);
            fs::create_dir_all(&nested)?;
            stage_tree(
                &source_root,
                &nested,
                Some(PathBuf::from("mods").join(mod_name)),
            )?
        }

        InstallMethod::DllOverlay { .. } => {
            // Stage under a flagged subdir; deploy decides the final
            // destination using the game plugin's `executable_dir`.
            let overlay_dir = store_mod_dir.join("__dll_overlay__");
            fs::create_dir_all(&overlay_dir)?;
            stage_tree(
                &source_root,
                &overlay_dir,
                Some(PathBuf::from("__dll_overlay__")),
            )?
        }

        InstallMethod::Fomod {
            module_config,
            config_toml,
        } => {
            let config_str = match config_toml {
                Some(s) => s,
                None => return Err(InstallerError::RequiresUserInput { method: "fomod" }),
            };

            // Parse the declarative config (TOML-serialized).
            let decl: fomod_oxide::DeclarativeConfig = toml::from_str(config_str)
                .map_err(|e| InstallerError::FomodError(format!("invalid config TOML: {e}")))?;

            // Read and parse the ModuleConfig.xml.
            let xml_path = source_root.join(module_config);
            let xml = fs::read_to_string(&xml_path).map_err(|e| {
                InstallerError::FomodError(format!("cannot read {}: {e}", xml_path.display()))
            })?;
            let module_cfg = fomod_oxide::ModuleConfig::parse(&xml)
                .map_err(|e| InstallerError::FomodError(format!("FOMOD parse error: {e}")))?;

            // Create installer, apply selections, resolve file operations.
            let mut installer = fomod_oxide::Installer::new(module_cfg);
            decl.apply(&xml, &mut installer)
                .map_err(|e| InstallerError::FomodError(format!("FOMOD apply error: {e}")))?;
            let fomod_plan = installer.resolve();

            // Execute the FOMOD plan: copy selected files into the store.
            let mut out = Vec::new();
            for op in &fomod_plan.operations {
                let src_path = source_root.join(&op.source);
                if op.is_folder {
                    if src_path.is_dir() {
                        let dest_base = if op.destination.is_empty() {
                            store_mod_dir.join(&op.source)
                        } else {
                            store_mod_dir.join(&op.destination)
                        };
                        out.extend(stage_tree(&src_path, &dest_base, None)?);
                    }
                } else if src_path.is_file() {
                    let dest = if op.destination.is_empty() {
                        store_mod_dir.join(&op.source)
                    } else {
                        store_mod_dir.join(&op.destination)
                    };
                    if let Some(parent) = dest.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    if fs::rename(&src_path, &dest).is_err() {
                        fs::copy(&src_path, &dest)?;
                        let _ = fs::remove_file(&src_path);
                    }
                    let size = fs::metadata(&dest).map_or(0, |m| m.len());
                    out.push(StagedFile {
                        rel_path: dest_rel(store_mod_dir, &dest),
                        origin_rel_path: op.source.clone(),
                        size,
                        merge_group: None,
                    });
                }
            }
            out
        }

        InstallMethod::Bain { selected_subdirs } => {
            if selected_subdirs.is_empty() {
                return Err(InstallerError::RequiresUserInput { method: "bain" });
            }
            let mut out = Vec::new();
            for subdir in selected_subdirs {
                let sub_src = source_root.join(subdir);
                if !sub_src.exists() {
                    return Err(InstallerError::MissingFile(subdir.clone()));
                }
                let sub_dest = store_mod_dir;
                out.extend(stage_tree(&sub_src, sub_dest, Some(PathBuf::from(subdir)))?);
            }
            out
        }

        InstallMethod::ScriptMerge { merge_group, base } => {
            // Execute the base method, then tag every staged file with
            // the merge group. Actual merging is deferred until the
            // script-merge feature lands.
            let mut inner_plan = InstallPlan {
                method: (**base).clone(),
                strip_prefix: plan.strip_prefix.clone(),
                source_archive_hash: plan.source_archive_hash.clone(),
                staged_files: Vec::new(),
            };
            let mut files = execute(&mut inner_plan, extracted_dir, store_mod_dir)?;
            for f in &mut files {
                f.merge_group = Some(merge_group.clone());
            }
            files
        }

        InstallMethod::UserConfigOverlay { .. } => {
            // Stage like `BareExtract`: the alternate routing only
            // matters at deploy time, where the deploy command reads
            // back the install method and resolves the target id.
            stage_tree(&source_root, store_mod_dir, None)?
        }

        InstallMethod::Unknown { reason } => {
            return Err(InstallerError::UnknownMethod {
                reason: reason.clone(),
            });
        }
    };

    plan.staged_files = files.clone();
    Ok(files)
}

/// Copy every file under `src` into `dest`, preserving subdirs. Returns
/// the staged manifest with origin paths relative to `src` (optionally
/// prefixed by `origin_prefix` so callers can reconstruct the archive
/// path when the plan nests the source into a subdir).
fn stage_tree(
    src: &Path,
    dest: &Path,
    origin_prefix: Option<PathBuf>,
) -> InstallerResult<Vec<StagedFile>> {
    stage_tree_into(src, dest, dest, origin_prefix)
}

fn stage_tree_into(
    src: &Path,
    dest: &Path,
    manifest_root: &Path,
    origin_prefix: Option<PathBuf>,
) -> InstallerResult<Vec<StagedFile>> {
    let mut out = Vec::new();
    let files = walk_files(src)?;
    for (abs, rel) in files {
        let dest_path = dest.join(&rel);
        if let Some(parent) = dest_path.parent() {
            fs::create_dir_all(parent)?;
        }
        // Prefer rename when src/dest are on the same filesystem; fall
        // back to copy+remove otherwise.
        if fs::rename(&abs, &dest_path).is_err() {
            fs::copy(&abs, &dest_path)?;
            let _ = fs::remove_file(&abs);
        }
        let size = fs::metadata(&dest_path).map_or(0, |m| m.len());
        let origin_rel_path = match &origin_prefix {
            Some(p) => p.join(&rel).to_string_lossy().to_string(),
            None => rel.to_string_lossy().to_string(),
        };
        out.push(StagedFile {
            rel_path: dest_rel(manifest_root, &dest_path),
            origin_rel_path,
            size,
            merge_group: None,
        });
    }
    Ok(out)
}

fn dest_rel(dest_root: &Path, dest_path: &Path) -> String {
    dest_path.strip_prefix(dest_root).map_or_else(
        |_| dest_path.to_string_lossy().to_string(),
        |p| p.to_string_lossy().to_string(),
    )
}

fn store_dir_name(store_mod_dir: &Path) -> String {
    store_mod_dir
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("mod")
        .to_string()
}

fn read_xml_attr(path: &Path, attr: &str) -> Option<String> {
    let content = fs::read_to_string(path).ok()?;
    if let Some((element, attr)) = attr.split_once('.') {
        let marker = format!("<{element}");
        let start = content.find(&marker)?;
        let rest = &content[start..];
        return read_attr_from_str(rest, attr);
    }
    read_attr_from_str(&content, attr)
}

fn read_attr_from_str(content: &str, attr: &str) -> Option<String> {
    let needle = format!("{attr}=\"");
    let start = content.find(&needle)? + needle.len();
    let rest = &content[start..];
    let end = rest.find('"')?;
    let value = rest[..end].trim();
    (!value.is_empty()).then(|| value.to_string())
}

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

    fn touch(p: &Path, body: &[u8]) {
        if let Some(parent) = p.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        let mut f = fs::File::create(p).unwrap();
        f.write_all(body).unwrap();
    }

    #[test]
    fn bare_extract_moves_files_into_store() {
        let tmp = tempfile::tempdir().unwrap();
        let staging = tmp.path().join("staging");
        let store = tmp.path().join("store");
        touch(&staging.join("Data").join("foo.esp"), b"hello");
        touch(&staging.join("readme.md"), b"hi");

        let mut plan = InstallPlan {
            method: InstallMethod::BareExtract,
            strip_prefix: None,
            source_archive_hash: "h".into(),
            staged_files: vec![],
        };
        let files = execute(&mut plan, &staging, &store).unwrap();
        assert_eq!(files.len(), 2);
        assert!(store.join("Data/foo.esp").exists());
        assert!(store.join("readme.md").exists());
        assert!(plan.staged_files.len() == 2);
    }

    #[test]
    fn strip_prefix_is_applied() {
        let tmp = tempfile::tempdir().unwrap();
        let staging = tmp.path().join("staging");
        let store = tmp.path().join("store");
        touch(&staging.join("ModName-1.0/Data/foo.esp"), b"hello");

        let mut plan = InstallPlan {
            method: InstallMethod::BareExtract,
            strip_prefix: Some(PathBuf::from("ModName-1.0")),
            source_archive_hash: "h".into(),
            staged_files: vec![],
        };
        let files = execute(&mut plan, &staging, &store).unwrap();
        assert_eq!(files.len(), 1);
        assert!(store.join("Data/foo.esp").exists());
        assert_eq!(files[0].rel_path, "Data/foo.esp");
    }

    #[test]
    fn fomod_without_config_requires_user_input() {
        let tmp = tempfile::tempdir().unwrap();
        let staging = tmp.path().join("staging");
        let store = tmp.path().join("store");
        touch(&staging.join("fomod/ModuleConfig.xml"), b"<config/>");
        touch(&staging.join("Data/foo.esp"), b"hello");

        let mut plan = InstallPlan {
            method: InstallMethod::Fomod {
                module_config: PathBuf::from("fomod/ModuleConfig.xml"),
                config_toml: None,
            },
            strip_prefix: None,
            source_archive_hash: "h".into(),
            staged_files: vec![],
        };
        let err = execute(&mut plan, &staging, &store).unwrap_err();
        assert!(matches!(err, InstallerError::RequiresUserInput { .. }));
    }

    #[test]
    fn unknown_returns_unknown_method() {
        let tmp = tempfile::tempdir().unwrap();
        let staging = tmp.path().join("staging");
        let store = tmp.path().join("store");
        touch(&staging.join("blob.bin"), b"x");

        let mut plan = InstallPlan {
            method: InstallMethod::Unknown {
                reason: "test".into(),
            },
            strip_prefix: None,
            source_archive_hash: "h".into(),
            staged_files: vec![],
        };
        let err = execute(&mut plan, &staging, &store).unwrap_err();
        assert!(matches!(err, InstallerError::UnknownMethod { .. }));
    }

    #[test]
    fn script_merge_tags_files() {
        let tmp = tempfile::tempdir().unwrap();
        let staging = tmp.path().join("staging");
        let store = tmp.path().join("store");
        touch(&staging.join("Data/foo.esp"), b"hello");

        let mut plan = InstallPlan {
            method: InstallMethod::ScriptMerge {
                merge_group: "quest-scripts".into(),
                base: Box::new(InstallMethod::BareExtract),
            },
            strip_prefix: None,
            source_archive_hash: "h".into(),
            staged_files: vec![],
        };
        let files = execute(&mut plan, &staging, &store).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].merge_group.as_deref(), Some("quest-scripts"));
    }
}