modde-cli 0.1.0

CLI interface for modde
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
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result};
use tracing::{info, warn};

use modde_core::db::ModdeDb;
use modde_core::fs::walk_files_relative;
use modde_core::paths;
use modde_core::profile::ProfileManager;

use super::load_profile_or_default;

/// Run an external tool and capture any new files it writes into the game directory
/// as an "Overwrite" mod.
pub async fn handle_run(
    executable: PathBuf,
    args: Vec<String>,
    profile_name: Option<String>,
    game_id: Option<String>,
) -> Result<()> {
    let pm = ProfileManager::open().context("failed to open profile database")?;
    let profile = load_profile_or_default(&pm, profile_name.as_deref(), game_id.as_deref())?;

    let game_plugin = modde_games::resolve_game_plugin(&profile.game_id)
        .ok_or_else(|| anyhow::anyhow!("unsupported game: '{}'", profile.game_id))?;

    let install_dir = game_plugin.detect_install().ok_or_else(|| {
        anyhow::anyhow!(
            "could not detect install directory for {}",
            game_plugin.display_name()
        )
    })?;

    let mod_dir = game_plugin.mod_directory(&install_dir);

    // Step 1: Snapshot current state of mod directory
    info!(mod_dir = %mod_dir.display(), "snapshotting mod directory before tool run");
    let before = snapshot_dir(&mod_dir)?;

    // Step 2: Run the tool
    println!("Running: {} {}", executable.display(), args.join(" "));
    let status = Command::new(&executable)
        .args(&args)
        .current_dir(&install_dir)
        .status()
        .with_context(|| format!("failed to execute: {}", executable.display()))?;

    if !status.success() {
        warn!(
            exit_code = status.code(),
            "tool exited with non-zero status"
        );
    }

    // Step 3: Diff to find new files
    let after = snapshot_dir(&mod_dir)?;
    let new_files: Vec<String> = after
        .difference(&before)
        .cloned()
        .collect();

    if new_files.is_empty() {
        println!("Tool completed. No new files written to mod directory.");
        return Ok(());
    }

    // Step 4: Move new files to the Overwrite mod
    let overwrite_dir = paths::store_dir().join("__overwrite__");
    std::fs::create_dir_all(&overwrite_dir)?;

    println!(
        "\nTool wrote {} new file(s). Moving to Overwrite mod:",
        new_files.len()
    );

    for rel_path in &new_files {
        let src = mod_dir.join(rel_path);
        let dst = overwrite_dir.join(rel_path);

        if let Some(parent) = dst.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::rename(&src, &dst)
            .or_else(|_| {
                // Cross-device: copy + remove
                std::fs::copy(&src, &dst)?;
                std::fs::remove_file(&src)
            })
            .with_context(|| format!("failed to move {} to overwrite", rel_path))?;

        println!("  {rel_path}");
    }

    println!(
        "\nOverwrite mod: {}",
        overwrite_dir.display()
    );
    println!("Add '__overwrite__' to your profile mod list to include these files in future deploys.");

    Ok(())
}

/// List known tools for a game.
pub fn handle_list(game_id: &str) -> Result<()> {
    let game_plugin = modde_games::resolve_game_plugin(game_id)
        .ok_or_else(|| anyhow::anyhow!("unsupported game: '{game_id}'"))?;

    let install_dir = game_plugin.detect_install().ok_or_else(|| {
        anyhow::anyhow!("could not detect install directory for {}", game_plugin.display_name())
    })?;

    println!("Game: {} ({})", game_plugin.display_name(), game_id);
    println!("Install: {}", install_dir.display());
    println!("\nDetected tools:");

    // Scan for common tool executables
    let common_tools = [
        ("xEdit", &["SSEEdit.exe", "FO4Edit.exe", "xEdit.exe"][..]),
        ("FNIS", &["GenerateFNISforUsers.exe"]),
        ("Nemesis", &["Nemesis Unlimited Behavior Engine.exe"]),
        ("BodySlide", &["BodySlide.exe", "BodySlide x64.exe"]),
        ("Creation Kit", &["CreationKit.exe"]),
        ("LOOT", &["LOOT.exe"]),
        ("zEdit", &["zEdit.exe"]),
    ];

    let mut found = false;
    for (name, executables) in &common_tools {
        for exe in *executables {
            let path = install_dir.join(exe);
            if path.exists() {
                println!("  {name}: {}", path.display());
                found = true;
            }
        }
    }

    if !found {
        println!("  (none detected)");
    }

    println!("\nRun tools with: modde tool run <executable> [-- args...]");

    Ok(())
}

// ── Gaming tool/overlay management ──────────────────────────────────────

/// Show status of all gaming tools for a game.
pub fn handle_status(game_id: &str) -> Result<()> {
    let db = ModdeDb::open().context("failed to open database")?;
    let stored = db.load_tool_configs(game_id)?;

    println!("Game: {game_id}\n");
    println!("{:<14} {:<14} {:<10} {}", "Tool", "Category", "Status", "Available");
    println!("{}", "-".repeat(60));

    for tool in modde_games::tools::all_tools() {
        let avail = tool.detect_available();
        let avail_str = match &avail {
            modde_games::tools::ToolAvailability::Available { version } => {
                match version {
                    Some(v) => format!("yes ({v})"),
                    None => "yes".into(),
                }
            }
            modde_games::tools::ToolAvailability::NotInstalled { .. } => "not installed".into(),
        };

        let enabled = stored
            .iter()
            .find(|r| r.tool_id == tool.tool_id())
            .map_or(false, |r| r.enabled);

        let status = if enabled { "enabled" } else { "disabled" };

        // Check if files are applied
        let applied_count = db
            .load_applied_files(game_id, tool.tool_id())
            .map(|f| f.len())
            .unwrap_or(0);

        let status_str = if applied_count > 0 {
            format!("{status} ({applied_count} files)")
        } else {
            status.to_string()
        };

        println!(
            "{:<14} {:<14} {:<10} {}",
            tool.display_name(),
            tool.category(),
            status_str,
            avail_str,
        );
    }

    Ok(())
}

/// Enable a tool for a game.
pub fn handle_enable(tool_id: &str, game_id: &str) -> Result<()> {
    let tool = modde_games::tools::resolve_tool(tool_id)
        .ok_or_else(|| anyhow::anyhow!(
            "unknown tool: '{tool_id}'\nAvailable: {}",
            modde_games::tools::all_tools()
                .iter()
                .map(|t| t.tool_id())
                .collect::<Vec<_>>()
                .join(", ")
        ))?;

    let db = ModdeDb::open().context("failed to open database")?;

    // Load existing or use defaults
    let mut config = match db.load_tool_config(game_id, tool_id)? {
        Some(row) => modde_games::tools::ToolConfig {
            tool_id: row.tool_id,
            enabled: true,
            settings: serde_json::from_str(&row.settings_json).unwrap_or_default(),
        },
        None => {
            let mut cfg = tool.default_config();
            cfg.enabled = true;
            cfg
        }
    };

    config.enabled = true;

    let settings_json = serde_json::to_string(&config.settings)?;
    db.save_tool_config(game_id, tool_id, true, &settings_json)?;

    println!("Enabled {} for {game_id}", tool.display_name());

    // Generate config file if applicable
    config.set("_game_id", serde_json::json!(game_id));
    if let Some(generated) = tool.generate_config(&config) {
        if let Some(parent) = generated.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&generated.path, &generated.content)?;
        println!("  Config: {}", generated.path.display());
    }

    Ok(())
}

/// Disable a tool for a game.
pub fn handle_disable(tool_id: &str, game_id: &str) -> Result<()> {
    let tool = modde_games::tools::resolve_tool(tool_id)
        .ok_or_else(|| anyhow::anyhow!("unknown tool: '{tool_id}'"))?;

    let db = ModdeDb::open().context("failed to open database")?;

    // Load existing config to preserve settings
    let settings_json = db
        .load_tool_config(game_id, tool_id)?
        .map(|r| r.settings_json)
        .unwrap_or_else(|| "{}".into());

    db.save_tool_config(game_id, tool_id, false, &settings_json)?;

    println!("Disabled {} for {game_id}", tool.display_name());

    Ok(())
}

/// Configure a tool's settings.
pub fn handle_configure(tool_id: &str, game_id: &str, settings: &[String]) -> Result<()> {
    let tool = modde_games::tools::resolve_tool(tool_id)
        .ok_or_else(|| anyhow::anyhow!("unknown tool: '{tool_id}'"))?;

    let db = ModdeDb::open().context("failed to open database")?;

    // Load existing or defaults
    let mut config = match db.load_tool_config(game_id, tool_id)? {
        Some(row) => modde_games::tools::ToolConfig {
            tool_id: row.tool_id,
            enabled: row.enabled,
            settings: serde_json::from_str(&row.settings_json).unwrap_or_default(),
        },
        None => tool.default_config(),
    };

    // Parse key=value pairs
    for setting in settings {
        let (key, value) = setting
            .split_once('=')
            .ok_or_else(|| anyhow::anyhow!("invalid setting format: '{setting}' (expected key=value)"))?;

        // Try to parse as bool, number, or fallback to string
        let json_value = if value == "true" {
            serde_json::json!(true)
        } else if value == "false" {
            serde_json::json!(false)
        } else if let Ok(n) = value.parse::<f64>() {
            serde_json::json!(n)
        } else {
            serde_json::json!(value)
        };

        config.set(key, json_value);
        println!("  {key} = {value}");
    }

    let settings_json = serde_json::to_string(&config.settings)?;
    db.save_tool_config(game_id, tool_id, config.enabled, &settings_json)?;

    // Regenerate config file
    config.set("_game_id", serde_json::json!(game_id));
    if let Some(generated) = tool.generate_config(&config) {
        if let Some(parent) = generated.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&generated.path, &generated.content)?;
        println!("  Config written: {}", generated.path.display());
    }

    println!("Updated {} config for {game_id}", tool.display_name());

    Ok(())
}

/// Apply tool patches to the game directory.
pub fn handle_apply(tool_id: &str, game_id: &str) -> Result<()> {
    let tool = modde_games::tools::resolve_tool(tool_id)
        .ok_or_else(|| anyhow::anyhow!("unknown tool: '{tool_id}'"))?;

    let game_plugin = modde_games::resolve_game_plugin(game_id)
        .ok_or_else(|| anyhow::anyhow!("unsupported game: '{game_id}'"))?;

    let install_dir = game_plugin
        .detect_install()
        .ok_or_else(|| anyhow::anyhow!("could not detect install dir for {}", game_plugin.display_name()))?;

    let db = ModdeDb::open().context("failed to open database")?;

    let config = match db.load_tool_config(game_id, tool_id)? {
        Some(row) => modde_games::tools::ToolConfig {
            tool_id: row.tool_id,
            enabled: row.enabled,
            settings: serde_json::from_str(&row.settings_json).unwrap_or_default(),
        },
        None => tool.default_config(),
    };

    let applied = tool.apply(&install_dir, &config)?;

    if applied.files.is_empty() {
        println!("No files to apply for {}", tool.display_name());
        return Ok(());
    }

    // Record applied files in the database
    let rel_paths: Vec<String> = applied
        .files
        .iter()
        .map(|p| p.to_string_lossy().to_string())
        .collect();

    db.save_applied_files(game_id, tool_id, &rel_paths)?;

    println!(
        "Applied {} ({} files) to {}",
        tool.display_name(),
        applied.files.len(),
        install_dir.display(),
    );
    for f in &applied.files {
        println!("  {}", f.display());
    }

    Ok(())
}

/// Revert tool patches from the game directory.
pub fn handle_revert(tool_id: &str, game_id: &str) -> Result<()> {
    let tool = modde_games::tools::resolve_tool(tool_id)
        .ok_or_else(|| anyhow::anyhow!("unknown tool: '{tool_id}'"))?;

    let game_plugin = modde_games::resolve_game_plugin(game_id)
        .ok_or_else(|| anyhow::anyhow!("unsupported game: '{game_id}'"))?;

    let install_dir = game_plugin
        .detect_install()
        .ok_or_else(|| anyhow::anyhow!("could not detect install dir for {}", game_plugin.display_name()))?;

    let db = ModdeDb::open().context("failed to open database")?;

    let files = db.load_applied_files(game_id, tool_id)?;
    if files.is_empty() {
        println!("No applied files to revert for {}", tool.display_name());
        return Ok(());
    }

    let applied = modde_games::tools::AppliedFiles {
        files: files.iter().map(PathBuf::from).collect(),
    };

    tool.revert(&install_dir, &applied)?;
    db.clear_applied_files(game_id, tool_id)?;

    println!(
        "Reverted {} ({} files) from {}",
        tool.display_name(),
        files.len(),
        install_dir.display(),
    );

    Ok(())
}

/// Snapshot a directory's file listing (relative paths).
fn snapshot_dir(dir: &Path) -> Result<HashSet<String>> {
    if !dir.exists() {
        return Ok(HashSet::new());
    }

    let files = walk_files_relative(dir)
        .with_context(|| format!("failed to walk directory: {}", dir.display()))?;

    Ok(files.into_iter().map(|(rel, _)| rel).collect())
}