oxicode-cli 0.79.0

Terminal-based AI coding assistant — multi-provider, streaming-first, extensible
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
//! Reset subcommand handler and helper utilities.

use anyhow::Result;
use std::path::{Path, PathBuf};

/// Target descriptor for the reset command.
struct ResetTarget {
    label: String,
    path: PathBuf,
    description: String,
}

/// Handle `oxicode reset [--yes] [--include-project]`
///
/// Factory-reset: deletes ALL oxicode data.
/// Optionally also deletes the project-local `.oxicode/` directory.
pub fn handle_reset(yes: bool, include_project: bool) -> Result<()> {
    use std::io::{self, Write};

    // ── Collect targets ──────────────────────────────────────────
    // Canonical home (`$OXICODE_HOME`, else `$OXI_HOME/oxicode`, else
    // `~/.oxi/oxicode`). The legacy `~/.oxicode` is only touched when the
    // canonical home does not exist (pre-unified-layout installs).
    let oxicode_dir = oxicode_catalog::oxi_home::oxicode_home()
        .ok_or_else(|| anyhow::anyhow!("Cannot determine oxicode home directory"))?;
    let home =
        dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Cannot determine home directory"))?;

    let config_oxicode_dir = dirs::config_dir()
        .unwrap_or_else(|| home.join(".config"))
        .join("oxicode");
    let cache_oxicode_dir = dirs::cache_dir()
        .unwrap_or_else(|| home.join(".cache"))
        .join("oxicode");

    let project_oxicode = std::env::current_dir().unwrap_or_default().join(".oxicode");
    let (targets, project_target) = collect_reset_targets(
        &oxicode_dir,
        oxicode_catalog::oxi_home::legacy_home_dir().as_deref(),
        oxicode_catalog::oxi_home::migration_journal_path().as_deref(),
        &config_oxicode_dir,
        &cache_oxicode_dir,
        &project_oxicode,
        include_project,
    );

    let total_count = targets.len() + usize::from(project_target.is_some());
    if total_count == 0 {
        println!("Nothing to reset — no oxicode data found.");
        return Ok(());
    }

    // ── Calculate total size ─────────────────────────────────────
    let mut total_bytes: u64 = 0;
    for t in &targets {
        total_bytes += dir_size_bytes(&t.path);
    }
    if let Some(ref pt) = project_target {
        total_bytes += dir_size_bytes(&pt.path);
    }

    // ── Show what will be deleted ────────────────────────────────
    eprintln!();
    eprintln!("     ⚠ Warning: The following will be permanently deleted:");
    eprintln!();
    for (i, t) in targets.iter().enumerate() {
        eprintln!(
            "       {}. {} ({})",
            i + 1,
            display_path(&t.path),
            dir_size_human(&t.path)
        );
        eprintln!("          {}", t.description);
    }
    if let Some(ref pt) = project_target {
        eprintln!(
            "       {}. {} ({})",
            total_count,
            display_path(&pt.path),
            dir_size_human(&pt.path)
        );
        eprintln!("          {}", pt.description);
    }
    eprintln!();
    eprintln!(
        "     Total: {} item(s), {}",
        total_count,
        bytes_human(total_bytes)
    );
    eprintln!();
    eprintln!(
        "     This cannot be undone. All sessions, skills, extensions, and settings will be deleted."
    );
    eprintln!();

    if !yes {
        eprint!("     Type RESET to continue: ");
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        if input.trim() != "RESET" {
            eprintln!();
            eprintln!();
            eprintln!("     Cancelled.");
            return Ok(());
        }
    }

    // ── Delete ───────────────────────────────────────────────────
    eprintln!();
    let mut errors = Vec::new();

    for t in &targets {
        eprint!("     ● Deleting {}...", t.label);
        io::stdout().flush()?;
        match remove_path(&t.path) {
            Ok(()) => eprintln!(" done"),
            Err(e) => {
                eprintln!(" failed");
                eprintln!("{}: {}", t.label, e);
                errors.push(format!("{}: {}", t.label, e));
            }
        }
    }
    if let Some(ref pt) = project_target {
        eprint!("     ● Deleting {}...", pt.label);
        io::stdout().flush()?;
        match remove_path(&pt.path) {
            Ok(()) => eprintln!(" done"),
            Err(e) => {
                eprintln!(" failed");
                eprintln!("{}: {}", pt.label, e);
                errors.push(format!("{}: {}", pt.label, e));
            }
        }
    }

    eprintln!();
    if errors.is_empty() {
        eprintln!("     ✓ All oxicode data has been reset.");
        eprintln!("     → Run 'oxicode setup' to reconfigure.");
    } else {
        eprintln!("{} item(s) failed to delete:", errors.len());
        for err in &errors {
            eprintln!("{}", err);
        }
        eprintln!("     Some data may need manual cleanup.");
    }

    Ok(())
}

/// Pure target collection for the reset command (testable with injected
/// paths).
///
/// - The canonical oxicode home is reset when it exists; the legacy
///   `~/.oxicode` only when the canonical home is absent.
/// - The home-layout migration journal is collected when present (it is
///   stale once the canonical home is gone).
/// - `config_dir`/`cache_dir` handling is unchanged (always collected when
///   present).
/// - The project-local `.oxicode/` is collected only with `include_project`.
fn collect_reset_targets(
    oxicode_dir: &Path,
    legacy_dir: Option<&Path>,
    journal_path: Option<&Path>,
    config_dir: &Path,
    cache_dir: &Path,
    project_dir: &Path,
    include_project: bool,
) -> (Vec<ResetTarget>, Option<ResetTarget>) {
    let mut targets: Vec<ResetTarget> = vec![];

    // Canonical home (or legacy, when canonical is absent) — split into
    // sub-items for clarity.
    let home_dir_to_reset: Option<&Path> = if oxicode_dir.exists() {
        Some(oxicode_dir)
    } else {
        legacy_dir
    };
    if let Some(reset_dir) = home_dir_to_reset {
        let sub_items = [
            ("settings.toml", "global settings"),
            ("settings.json", "global settings (JSON)"),
            ("auth.json", "credentials (API keys, OAuth tokens)"),
            ("sessions", "session history"),
            ("skills", "skills"),
            ("extensions", "extensions"),
            ("packages", "packages"),
        ];
        let mut has_sub = false;
        for (name, desc) in &sub_items {
            let p = reset_dir.join(name);
            if p.exists() {
                has_sub = true;
                targets.push(ResetTarget {
                    label: display_path(&p),
                    path: p,
                    description: desc.to_string(),
                });
            }
        }
        // If no known sub-items found, target the whole directory
        if !has_sub {
            targets.push(ResetTarget {
                label: display_path(reset_dir),
                path: reset_dir.to_path_buf(),
                description: "oxicode home (settings, sessions, skills, extensions, packages)"
                    .to_string(),
            });
        }
    }

    // Home-layout migration journal.
    if let Some(journal) = journal_path
        && journal.exists()
    {
        targets.push(ResetTarget {
            label: display_path(journal),
            path: journal.to_path_buf(),
            description: "home-layout migration journal".to_string(),
        });
    }

    // ~/.config/oxicode/ — MCP config, alternative auth location
    if config_dir.exists() {
        targets.push(ResetTarget {
            label: display_path(config_dir),
            path: config_dir.to_path_buf(),
            description: "MCP config, credentials".to_string(),
        });
    }

    // ~/.cache/oxicode/ — logs
    if cache_dir.exists() {
        targets.push(ResetTarget {
            label: display_path(cache_dir),
            path: cache_dir.to_path_buf(),
            description: "logs, cache".to_string(),
        });
    }

    let mut project_target: Option<ResetTarget> = None;
    if include_project && project_dir.exists() {
        project_target = Some(ResetTarget {
            label: display_path(project_dir),
            path: project_dir.to_path_buf(),
            description: "project settings".to_string(),
        });
    }

    (targets, project_target)
}

/// Remove a file or directory (including all contents).
pub fn remove_path(path: &Path) -> Result<()> {
    if path.is_dir() {
        std::fs::remove_dir_all(path)?;
    } else {
        std::fs::remove_file(path)?;
    }
    Ok(())
}

/// Display path with ~/ abbreviation for home directory.
pub fn display_path(path: &Path) -> String {
    if let Some(home) = dirs::home_dir() {
        let home_str = home.to_string_lossy();
        let path_str = path.to_string_lossy();
        if let Some(rest) = path_str.strip_prefix(home_str.as_ref()) {
            return format!("~{}", rest);
        }
    }
    path.display().to_string()
}

/// Calculate total bytes in a directory or file.
pub fn dir_size_bytes(path: &Path) -> u64 {
    let mut total: u64 = 0;
    if path.is_dir() {
        if let Ok(entries) = walkdir_recursive(path) {
            for entry in entries {
                if let Ok(meta) = std::fs::metadata(&entry)
                    && meta.is_file()
                {
                    total += meta.len();
                }
            }
        }
    } else if let Ok(meta) = std::fs::metadata(path) {
        total = meta.len();
    }
    total
}

/// Calculate a human-readable directory or file size.
pub fn dir_size_human(path: &Path) -> String {
    bytes_human(dir_size_bytes(path))
}

/// Format bytes as a human-readable string.
pub fn bytes_human(bytes: u64) -> String {
    if bytes == 0 {
        return "0 B".to_string();
    }
    const KB: u64 = 1024;
    const MB: u64 = 1024 * KB;
    const GB: u64 = 1024 * MB;
    if bytes >= GB {
        format!("{:.1} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

/// Walk a directory recursively, collecting all file paths.
pub fn walkdir_recursive(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut result = Vec::new();
    if dir.is_dir() {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                result.extend(walkdir_recursive(&path)?);
            } else {
                result.push(path);
            }
        }
    }
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Canonical home present → legacy home is NOT targeted.
    #[test]
    fn canonical_home_wins_over_legacy() {
        let tmp = tempfile::tempdir().unwrap();
        let canonical = tmp.path().join("canonical-home");
        let legacy = tmp.path().join("legacy-home");
        let config = tmp.path().join("config");
        let cache = tmp.path().join("cache");
        let project = tmp.path().join("project").join(".oxicode");
        std::fs::create_dir_all(&canonical).unwrap();
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(canonical.join("auth.json"), "{}").unwrap();
        std::fs::write(legacy.join("auth.json"), "{}").unwrap();

        let (targets, _) = collect_reset_targets(
            &canonical,
            Some(&legacy),
            None,
            &config,
            &cache,
            &project,
            false,
        );

        let paths: Vec<&Path> = targets.iter().map(|t| t.path.as_path()).collect();
        assert!(paths.contains(&canonical.join("auth.json").as_path()));
        assert!(
            !paths.iter().any(|p| p.starts_with(&legacy)),
            "legacy home must not be reset while the canonical home exists"
        );
    }

    /// Canonical home absent → legacy home is targeted.
    #[test]
    fn legacy_home_targeted_when_canonical_absent() {
        let tmp = tempfile::tempdir().unwrap();
        let canonical = tmp.path().join("canonical-home");
        let legacy = tmp.path().join("legacy-home");
        let config = tmp.path().join("config");
        let cache = tmp.path().join("cache");
        let project = tmp.path().join("project").join(".oxicode");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("auth.json"), "{}").unwrap();

        let (targets, _) = collect_reset_targets(
            &canonical,
            Some(&legacy),
            None,
            &config,
            &cache,
            &project,
            false,
        );

        let paths: Vec<&Path> = targets.iter().map(|t| t.path.as_path()).collect();
        assert!(paths.contains(&legacy.join("auth.json").as_path()));
        assert!(!paths.iter().any(|p| p.starts_with(&canonical)));
    }

    /// Journal is collected when present; project dir only with the flag.
    #[test]
    fn journal_and_project_targeting() {
        let tmp = tempfile::tempdir().unwrap();
        let canonical = tmp.path().join("canonical-home");
        let config = tmp.path().join("config");
        let cache = tmp.path().join("cache");
        let project = tmp.path().join("project").join(".oxicode");
        std::fs::create_dir_all(&canonical).unwrap();
        let journal = tmp.path().join("oxicode.migration-journal.json");
        std::fs::write(&journal, "{}").unwrap();

        let (targets, project_target) = collect_reset_targets(
            &canonical,
            None,
            Some(&journal),
            &config,
            &cache,
            &project,
            false,
        );
        assert!(targets.iter().any(|t| t.path == journal));
        assert!(project_target.is_none());

        std::fs::create_dir_all(&project).unwrap();
        let (_, project_target) = collect_reset_targets(
            &canonical,
            None,
            Some(&journal),
            &config,
            &cache,
            &project,
            true,
        );
        assert!(project_target.is_some());
    }
}