nrip 0.8.9

Safe rm with a graveyard (MVP: rm, ls, prune, resurrect)
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
use std::collections::{HashMap, HashSet};
use std::io::{self, Write};
use std::path;
use std::path::PathBuf;

use crate::index::{Entry, Kind};

use anyhow::{Context, Result};
use chrono::{Local, TimeZone, Utc};
use fs_err as fs;
use std::ffi::OsString;
use yansi::{Color, Paint};

use crate::fs_safemove::safe_move_unique;
use crate::safety::{SafetyCtx, guard_path};

use crate::index; // pour appeler les shims

fn display_id(e: &index::Entry) -> String {
    e.trashed_path
        .file_name()
        .and_then(|n| n.to_str())
        .and_then(|s| s.split("__").nth(1))
        .map(|s| s.chars().take(7).collect::<String>())
        .unwrap_or_else(|| "-".to_string())
}

fn kind_letter(k: Kind) -> char {
    match k {
        Kind::File => 'F',
        Kind::Dir => 'D',
        Kind::Symlink => 'L',
        Kind::Other => '?',
    }
}

fn kind_icon(k: Kind) -> &'static str {
    match k {
        Kind::File => "📄",
        Kind::Dir => "📁",
        Kind::Symlink => "🔗",
        Kind::Other => "",
    }
}

/// Durée compacte (2 unités max) ex: "1m47s", "3h12m", "2d"
fn compact_age(mut secs: u64) -> String {
    const MIN: u64 = 60;
    const H: u64 = 60 * MIN;
    const D: u64 = 24 * H;
    const W: u64 = 7 * D;
    let units = [(W, "w"), (D, "d"), (H, "h"), (MIN, "m"), (1, "s")];
    let mut out = String::new();
    let mut parts = 0;
    for (u, suf) in units {
        if secs >= u {
            let v = secs / u;
            secs %= u;
            out.push_str(&format!("{v}{suf}"));
            parts += 1;
            if parts == 2 {
                break;
            }
        }
    }
    if out.is_empty() { "0s".into() } else { out }
}

fn graveyard_dir() -> Result<PathBuf> {
    Ok(crate::paths::data_dir()?.join("graveyard"))
}

fn journal_path() -> Result<PathBuf> {
    Ok(graveyard_dir()?.join(".journal"))
}

fn append_journal(line: &str) -> Result<()> {
    use std::io::Write;
    let jp = journal_path()?;
    let mut f = fs::OpenOptions::new().create(true).append(true).open(&jp)?;
    writeln!(f, "{line}")?;
    f.sync_all()?;
    Ok(())
}

fn path_depth(p: &std::path::Path) -> usize {
    p.components().count()
}

///build a map from original_path -> (index position)
fn build_original_map(entries: &[index::Entry]) -> HashMap<PathBuf, usize> {
    let mut map = HashMap::with_capacity(entries.len());
    for (i, e) in entries.iter().enumerate() {
        map.insert(e.original_path.clone(), i);
    }
    map
}

pub fn resurrect(items: &[PathBuf]) -> Result<()> {
    index::with_index_mut(|idx| {
        for gy_path in items {
            if let Some(pos) = idx.items.iter().position(|e| e.trashed_path == *gy_path) {
                let original = idx.items[pos].original_path.clone();

                append_journal(&format!(
                    "RESTORE_PENDING\t{}\t{}",
                    gy_path.display(),
                    original.display()
                ))?;

                if let Some(parent) = original.parent() {
                    fs::create_dir_all(parent)?;
                }
                if original.exists() {
                    anyhow::bail!("Target already exists: {}", original.display());
                }

                match fs::rename(gy_path, &original) {
                    Ok(()) => {}
                    Err(e) if super::fs_safemove::is_exdev(&e) => {
                        super::fs_safemove::copy_recursively(gy_path, &original)?;
                        super::fs_safemove::remove_recursively(gy_path)?;
                    }
                    Err(e) => {
                        return Err(e).with_context(|| {
                            format!("rename {} -> {}", gy_path.display(), original.display())
                        });
                    }
                }

                append_journal(&format!(
                    "RESTORE_DONE\t{}\t{}",
                    gy_path.display(),
                    original.display()
                ))?;
                idx.items.remove(pos);
            }
        }
        Ok(())
    })
}

pub fn resurrect_cmd(target: Option<String>, dry_run: bool, yes: bool) -> anyhow::Result<()> {
    use std::io::{self, Write};

    let entries = index::load_entries().unwrap_or_default();
    let original_map = build_original_map(&entries);

    // 1) Construire la sélection (to_restore)
    let to_restore: Vec<index::Entry> = if let Some(ref q0) = target {
        let q = q0.to_lowercase();

        let matches: Vec<index::Entry> = entries
            .iter()
            .filter(|&e| {
                let base = index::basename_of_original(e).to_lowercase();
                let id = display_id(e).to_lowercase(); // derived id
                base.contains(&q) || id.starts_with(&q)
            })
            .cloned()
            .collect();

        if matches.is_empty() {
            println!("No graveyard entry matches '{q0}'.");
            return Ok(());
        }
        if matches.len() > 1 && !yes {
            println!("Multiple matches (use TAB completion or add -y to restore all of them):");
            for m in &matches {
                let id = display_id(m);
                println!("  {:7}  {}", id, index::basename_of_original(m));
            }
            return Ok(());
        }
        matches
    } else {
        // --- MODE INTERACTIF (fzf) ---
        let idx = index::load_index()?;
        if idx.items.is_empty() {
            println!("Graveyard is empty.");
            return Ok(());
        }

        let picks = crate::ui::pick_entries_with_fzf(&idx, /*preview=*/ false)?;
        if picks.is_empty() {
            println!("Aborted.");
            return Ok(());
        }

        let to_restore: Vec<index::Entry> =
            picks.into_iter().map(|i| idx.items[i].clone()).collect();

        // on “remplace” la variable to_restore de ton flux actuel :
        to_restore
    };
    // 1.b) Etendre la sélection : ajouter les parents enterrés nécessaires
    // (si un parent est lui-même dans le graveyard, on le restaure AVANT l'enfant)
    let mut wanted: HashSet<PathBuf> = to_restore.iter().map(|e| e.original_path.clone()).collect();
    let mut added_any = true;
    while added_any {
        added_any = false;
        let current: Vec<PathBuf> = wanted.iter().cloned().collect();
        for p in current {
            if let Some(mut cur) = p.parent().map(|x| x.to_path_buf()) {
                while cur.parent().is_some() {
                    if original_map.contains_key(&cur) && !wanted.contains(&cur) {
                        wanted.insert(cur.clone());
                        added_any = true;
                        break; // on insère ce parent; on regardera ses parents à l'itération suivante
                    }
                    if let Some(next) = cur.parent() {
                        cur = next.to_path_buf();
                    } else {
                        break;
                    }
                }
            }
        }
    }

    // Reconstruire la liste finale d'entrées à restaurer (parents inclus)
    let mut final_list: Vec<index::Entry> = Vec::with_capacity(wanted.len());
    let mut auto_added: Vec<PathBuf> = Vec::new();
    for p in &wanted {
        if let Some(&i) = original_map.get(p) {
            // si pas déjà dans to_restore explicite, on note qu'on l'a ajouté
            if !to_restore.iter().any(|e| &e.original_path == p) {
                auto_added.push(p.clone());
            }
            final_list.push(entries[i].clone());
        }
    }
    // Trier par profondeur croissante (parents → enfants)
    final_list.sort_by_key(|e| path_depth(&e.original_path));

    if !auto_added.is_empty() {
        println!(
            "Including {} parent path(s) for consistency:",
            auto_added.len()
        );
        for p in auto_added.iter().take(10) {
            // évite le spam
            println!("  {}", p.display());
        }
        if auto_added.len() > 10 {
            println!("  ...");
        }
    }

    // 2) Bilan & confirmations
    let is_all = final_list.len() == entries.len();
    if is_all {
        println!(
            "About to restore ALL graveyard items: {} item(s).",
            final_list.len()
        );
        if dry_run {
            println!("--dry-run: nothing restored.");
            return Ok(());
        }
        if !yes {
            print!("Type YES to confirm: ");
            io::stdout().flush()?;
            let mut buf = String::new();
            io::stdin().read_line(&mut buf)?;
            if buf.trim() != "YES" {
                println!("Aborted.");
                return Ok(());
            }
        }
    } else {
        println!("About to restore {} item(s).", to_restore.len());
        if dry_run {
            println!("--dry-run: nothing restored.");
            return Ok(());
        }
        if !yes && to_restore.len() == 1 {
            print!("Confirm (y/N): ");
            io::stdout().flush()?;
            let mut buf = String::new();
            io::stdin().read_line(&mut buf)?;
            if buf.trim().to_lowercase() != "y" {
                println!("Aborted.");
                return Ok(());
            }
        }
    }

    // 3) Exécution
    let paths: Vec<PathBuf> = final_list.iter().map(|e| e.trashed_path.clone()).collect();
    if paths.is_empty() {
        println!("Nothing to restore.");
        return Ok(());
    }

    // On réutilise ta fonction existante (journal, checks, msg "Restored to ...")
    resurrect(&paths)?;

    println!("Restored {} item(s).", paths.len());
    Ok(())
}

pub fn bury(paths: &[PathBuf], force: bool) -> Result<()> {
    let gy = graveyard_dir()?;
    let ctx = SafetyCtx {
        graveyard: gy.clone(),
        preserve_root: true,
        force,
    };

    index::with_index_mut(|idx| {
        for src in paths {
            let original_abs =
                path::absolute(src).with_context(|| format!("absolutize {}", src.display()))?;
            guard_path(&original_abs, &ctx)?;
            let base: OsString = src.file_name().unwrap_or_default().to_os_string();

            append_journal(&format!(
                "PENDING\t{}\t{}",
                original_abs.display(),
                base.to_string_lossy()
            ))?;
            // Détection du "kind" au moment du déplacement (fiable)
            let md = fs::symlink_metadata(src)?;
            let kind = if md.file_type().is_dir() {
                Kind::Dir
            } else if md.file_type().is_file() {
                Kind::File
            } else if md.file_type().is_symlink() {
                Kind::Symlink
            } else {
                Kind::Other
            };

            let dst = safe_move_unique(src, &gy, &base)
                .with_context(|| format!("move {} -> graveyard", src.display()))?;
            append_journal(&format!(
                "DONE\t{}\t{}",
                original_abs.display(),
                dst.display()
            ))?;

            idx.items.push(Entry {
                original_path: original_abs,
                trashed_path: dst,
                deleted_at: Utc::now().timestamp(),
                kind,
            });
            // Petit retour utilisateur : "<name> buried" avec icône
            let name = base.to_string_lossy();
            // Couleurs sobres (gérées par yansi::enable/disable dans main.rs)
            println!(
                "{} {}",
                Paint::new("🪦").fg(Color::Magenta),
                Paint::new(format!("{name} buried")).bold()
            );
        }
        Ok(())
    })
}

pub fn list() -> anyhow::Result<()> {
    let entries = index::load_entries().unwrap_or_default();
    for e in entries {
        let id = display_id(&e);
        let base = index::basename_of_original(&e);
        // horodatage local lisible
        let dt = Local
            .timestamp_opt(e.deleted_at, 0)
            .single()
            .unwrap_or_else(|| Local.timestamp_opt(0, 0).single().unwrap());
        let absolute = dt.format("%Y-%m-%d %H:%M:%S").to_string();
        // âge relatif compact
        let now_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let rel = compact_age(now_secs.saturating_sub(e.deleted_at as u64));
        let k = kind_letter(e.kind);
        let ico = kind_icon(e.kind);

        // Couleurs sobres (respectées/neutralisées par yansi::enable/disable dans main.rs)
        let id_p = Paint::new(format!("{id:7}")).dim();
        let icon_p = Paint::new(ico).fg(Color::Cyan);
        let k_p = Paint::new(k).fg(Color::Cyan);
        let date_p = Paint::new(format!("({absolute})")).dim();
        let name_p = Paint::new(base).bold();
        let path_p = Paint::new(e.original_path.display()).dim();
        let age_p = Paint::new(format!("({rel})")).italic().dim();

        println!("{id_p}  {icon_p} {k_p}  {date_p}  {name_p}  {path_p}  {age_p}");
    }
    Ok(())
}

/// `cremate` sans cible = vider tout ; avec cible = supprimer les matches.
pub fn cremate(target: Option<String>, dry_run: bool, yes: bool) -> anyhow::Result<()> {
    // --- 1) SNAPSHOT & SÉLECTION (hors verrou) ---
    let snap = index::load_index()?; // snapshot
    if snap.items.is_empty() {
        println!("Graveyard is empty.");
        return Ok(());
    }

    // Construire la sélection "to_delete" depuis le snapshot
    let to_delete: Vec<index::Entry> = if let Some(ref q0) = target {
        let q = q0.to_lowercase();
        let matches: Vec<index::Entry> = snap
            .items
            .iter()
            .filter(|&e| {
                let base = index::basename_of_original(e).to_lowercase();
                let id = display_id(e).to_lowercase();
                base.contains(&q) || id.starts_with(&q)
            })
            .cloned()
            .collect();
        if matches.is_empty() {
            println!("No graveyard entry matches '{q0}'.");
            return Ok(());
        }
        if matches.len() > 1 && !yes {
            println!("Multiple matches (use TAB completion or add -y to cremate all of them):");
            for m in &matches {
                let id = display_id(m);
                println!("  {:7}  {}", id, index::basename_of_original(m));
            }
            return Ok(());
        }
        matches
    } else {
        // Interactif (fzf) sur le snapshot
        let picks = crate::ui::pick_entries_with_fzf(&snap, /*preview=*/ false)?;
        if picks.is_empty() {
            println!("Aborted.");
            return Ok(());
        }
        picks.into_iter().map(|i| snap.items[i].clone()).collect()
    };

    // Rien ?
    if to_delete.is_empty() {
        println!("Nothing to delete.");
        return Ok(());
    }

    // Bilan (hors verrou)
    let mut total_bytes: u64 = 0;
    for e in &to_delete {
        if let Ok(meta) = fs::metadata(&e.trashed_path) {
            total_bytes = total_bytes.saturating_add(meta.len());
        }
    }
    let mb = (total_bytes as f64) / (1024.0 * 1024.0);

    let is_all = to_delete.len() == snap.items.len();
    if is_all {
        println!(
            "About to remove ALL graveyard items: {} items (~{:.2} MiB)",
            to_delete.len(),
            mb
        );
        if dry_run {
            println!("--dry-run: nothing deleted.");
            return Ok(());
        }
        if !yes {
            print!("Type YES to confirm: ");
            io::stdout().flush()?;
            let mut buf = String::new();
            io::stdin().read_line(&mut buf)?;
            if buf.trim() != "YES" {
                println!("Aborted.");
                return Ok(());
            }
        }
    } else {
        println!(
            "About to remove {} item(s) (~{:.2} MiB).",
            to_delete.len(),
            mb
        );
        if dry_run {
            println!("--dry-run: nothing deleted.");
            return Ok(());
        }
        if !yes && to_delete.len() == 1 {
            print!("Confirm (y/N): ");
            io::stdout().flush()?;
            let mut buf = String::new();
            io::stdin().read_line(&mut buf)?;
            if buf.trim().to_lowercase() != "y" {
                println!("Aborted.");
                return Ok(());
            }
        }
    }

    // --- 2) COMMIT ATOMIQUE (sous verrou unique) ---
    let set: HashSet<PathBuf> = to_delete.iter().map(|e| e.trashed_path.clone()).collect();

    let removed = index::with_index_mut(|idx| {
        // Revalide la sélection côté index courant (au cas où ça a bougé)
        let mut remaining: Vec<Entry> = Vec::with_capacity(idx.items.len());
        let mut removed_count = 0usize;

        for e in idx.items.drain(..) {
            if set.contains(&e.trashed_path) {
                // Supprimer la cible (fichier/dir)
                let p = &e.trashed_path;
                let res = if p.is_dir() {
                    fs::remove_dir_all(p)
                } else {
                    fs::remove_file(p).or_else(|err| {
                        if err.kind() == std::io::ErrorKind::IsADirectory {
                            fs::remove_dir_all(p)
                        } else {
                            Err(err)
                        }
                    })
                };
                match res {
                    Ok(_) => removed_count += 1,
                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => removed_count += 1,
                    Err(err) => {
                        eprintln!("warn: cannot remove {}: {}", p.display(), err);
                        // Échec : on conserve l’entrée
                        remaining.push(e);
                        continue;
                    }
                }
                // Succès → on ne remet pas l'entrée (deleted)
            } else {
                remaining.push(e);
            }
        }

        // Si la sélection couvrait "tout", on peut en plus nettoyer les résidus
        // du graveyard sans toucher aux méta (.journal/.index.lock)
        if is_all {
            let gy = crate::paths::data_dir()?.join("graveyard");
            if let Ok(rd) = fs::read_dir(&gy) {
                for ent in rd.filter_map(|r| r.ok()) {
                    let p = ent.path();
                    let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("");
                    if name == ".journal" || name == ".index.lock" {
                        continue;
                    }
                    let _ = if p.is_dir() {
                        fs::remove_dir_all(&p)
                    } else {
                        fs::remove_file(&p)
                    };
                }
            }
            remaining.resetting();
        }

        idx.items = remaining;
        Ok(removed_count)
    })?;

    println!("Removed {removed} item(s).");
    Ok(())
}

/// Candidats pour l’auto-complétion de `cremate` (basenames + IDs)
pub fn completion_candidates(prefix: Option<&str>) -> anyhow::Result<Vec<String>> {
    let entries = index::load_entries().unwrap_or_default();
    let mut out = Vec::with_capacity(entries.len() * 2);
    for e in entries {
        out.push(display_id(&e)); // <- id dérivé (7 chars)
        out.push(index::basename_of_original(&e)); // <- basename
    }
    if let Some(p) = prefix {
        let p = p.to_lowercase();
        out.retain(|s| s.to_lowercase().contains(&p));
    }
    out.sort();
    out.dedup();
    Ok(out)
}