rip2 0.9.6

rip: a safe and ergonomic alternative to rm
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use clap::CommandFactory;
use fs_extra::dir::get_size;
use std::fs::Metadata;
use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::{env, fs};
use walkdir::WalkDir;

/// Information needed to create a directory with specific permissions
#[derive(Debug, Clone)]
pub struct DirToCreate {
    pub path: PathBuf,
    pub permissions: Option<fs::Permissions>,
}

// Platform-specific imports
#[cfg(unix)]
use nix::libc;
#[cfg(unix)]
use nix::sys::stat::Mode;
#[cfg(unix)]
use nix::unistd::mkfifo;
#[cfg(unix)]
use std::os::unix::fs::{symlink, FileTypeExt, PermissionsExt};

#[cfg(target_os = "windows")]
use std::os::windows::fs::symlink_file as symlink;

pub mod args;
pub mod completions;
pub mod record;
pub mod util;

use args::Args;
use record::{Record, RecordItem, DEFAULT_FILE_LOCK};

const LINES_TO_INSPECT: usize = 6;
const FILES_TO_INSPECT: usize = 6;
pub const BIG_FILE_THRESHOLD: u64 = 500_000_000; // 500 MB

pub fn run(cli: &Args, mode: impl util::TestingMode, stream: &mut impl Write) -> Result<(), Error> {
    args::validate_args(cli)?;
    let graveyard: &PathBuf = &get_graveyard(cli.graveyard.clone());

    if !graveyard.exists() {
        fs::create_dir_all(graveyard)?;

        #[cfg(unix)]
        {
            fs::set_permissions(graveyard, fs::Permissions::from_mode(0o700))?;
        }
    }

    // Stores the deleted files
    let record = Record::<DEFAULT_FILE_LOCK>::new(graveyard);
    let cwd = &env::current_dir()?;

    // If the user wishes to restore everything
    if cli.decompose {
        // In force mode, skip the prompt to decompose
        if cli.force || util::prompt_yes("Really unlink the entire graveyard?", &mode, stream)? {
            fs::remove_dir_all(graveyard)?;
        }
    } else if let Some(ref mut graves_to_exhume) = cli.unbury.clone() {
        // Vector to hold the grave path of items we want to unbury.
        // This will be used to determine which items to remove from the
        // record following the unbury.
        // Initialize it with the targets passed to -r

        // If -s is also passed, push all files found by seance onto
        // the graves_to_exhume.
        if cli.seance && record.open().is_ok() {
            let gravepath = util::join_absolute(graveyard, dunce::canonicalize(cwd)?);
            for grave in record.seance(&gravepath)? {
                graves_to_exhume.push(grave.dest);
            }
        }

        // Otherwise, add the last deleted file
        if graves_to_exhume.is_empty() {
            if let Ok(s) = record.get_last_bury() {
                graves_to_exhume.push(s);
            }
        }

        let allow_rename = util::allow_rename();

        // Go through the graveyard and exhume all the graves
        for line in record.lines_of_graves(graves_to_exhume) {
            let entry = RecordItem::new(&line);
            let orig: PathBuf = if util::symlink_exists(&entry.orig) {
                util::rename_grave(&entry.orig)
            } else {
                PathBuf::from(&entry.orig)
            };
            let dirs_to_create = build_dirs_to_create_from_graveyard(&entry.dest, &orig);

            move_target(
                &entry.dest,
                &orig,
                allow_rename,
                &mode,
                stream,
                cli.force,
                &dirs_to_create,
            )
            .map_err(|e| {
                Error::new(
                    e.kind(),
                    format!(
                        "Unbury failed: couldn't copy files from {} to {}",
                        entry.dest.display(),
                        orig.display()
                    ),
                )
            })?;
            writeln!(
                stream,
                "Returned {} to {}",
                entry.dest.display(),
                orig.display()
            )?;
        }
        record.log_exhumed_graves(graves_to_exhume)?;
    } else if cli.seance {
        let gravepath = util::join_absolute(graveyard, dunce::canonicalize(cwd)?);
        writeln!(stream, "{: <19}\tpath", "deletion_time")?;
        for grave in record.seance(&gravepath)? {
            let formatted_time = grave.format_time_for_display()?;
            writeln!(stream, "{}\t{}", formatted_time, grave.dest.display())?;
        }
    } else if cli.targets.is_empty() {
        Args::command().print_help()?;
    } else {
        let allow_rename = util::allow_rename();
        for target in &cli.targets {
            bury_target(
                target,
                graveyard,
                &record,
                cwd,
                cli.inspect,
                allow_rename,
                &mode,
                stream,
                cli.force,
            )?;
        }
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn bury_target<const FILE_LOCK: bool>(
    target: &PathBuf,
    graveyard: &PathBuf,
    record: &Record<FILE_LOCK>,
    cwd: &Path,
    inspect: bool,
    allow_rename: bool,
    mode: &impl util::TestingMode,
    stream: &mut impl Write,
    force: bool,
) -> Result<(), Error> {
    // Check if source exists
    let metadata = &fs::symlink_metadata(target).map_err(|_| {
        Error::new(
            ErrorKind::NotFound,
            format!(
                "Cannot remove {}: no such file or directory",
                target.to_str().unwrap()
            ),
        )
    })?;
    // Canonicalize the path unless it's a symlink
    let source = &if metadata.file_type().is_symlink() {
        cwd.join(target)
    } else {
        dunce::canonicalize(cwd.join(target))
            .map_err(|e| Error::new(e.kind(), "Failed to canonicalize path"))?
    };

    if inspect && !should_we_bury_this(target, source, metadata, mode, stream)? {
        // User chose to not bury the file
    } else if source.starts_with(
        dunce::canonicalize(graveyard)
            .map_err(|e| Error::new(e.kind(), "Failed to canonicalize graveyard path"))?,
    ) {
        // If rip is called on a file already in the graveyard, prompt
        // to permanently delete it instead.
        if force
            || util::prompt_yes(
                format!(
                    "{} is already in the graveyard.\nPermanently unlink it?",
                    source.display()
                ),
                mode,
                stream,
            )?
        {
            if fs::remove_dir_all(source).is_err() {
                fs::remove_file(source).map_err(|e| {
                    Error::new(e.kind(), format!("Couldn't unlink {}", source.display()))
                })?;
            }
        } else {
            writeln!(stream, "Skipping {}", source.display())?;
            // TODO: In the original code, this was a hard return from the entire
            // method (i.e., `run`). I think it should just be a return from the bury
            // (meaning a `continue` in the original code's loop). But I'm not sure.
        }
    } else {
        let (dest, dirs_to_create) = build_graveyard_dest(graveyard, source);
        let dest: &Path = &{
            // Resolve a name conflict if necessary
            if util::symlink_exists(&dest) {
                util::rename_grave(dest)
            } else {
                dest
            }
        };

        let moved = move_target(
            source,
            dest,
            allow_rename,
            mode,
            stream,
            force,
            &dirs_to_create,
        )
        .map_err(|e| {
            fs::remove_dir_all(dest).ok();
            Error::new(e.kind(), "Failed to bury file")
        })?;

        if moved {
            // Clean up any partial buries due to permission error
            record.write_log(source, dest)?;
        }
    }

    Ok(())
}

fn should_we_bury_this(
    target: &Path,
    source: &PathBuf,
    metadata: &Metadata,
    mode: &impl util::TestingMode,
    stream: &mut impl Write,
) -> Result<bool, Error> {
    if metadata.is_dir() {
        // Get the size of the directory and all its contents
        {
            let num_bytes = get_size(source).map_err(|_| {
                Error::other(format!(
                    "Failed to get size of directory: {}",
                    source.display()
                ))
            })?;
            writeln!(
                stream,
                "{}: directory, {} including:",
                target.to_str().unwrap(),
                util::humanize_bytes(num_bytes)
            )?;
        }

        // Print the first few top-level files in the directory
        for entry in WalkDir::new(source)
            .sort_by(|a, b| a.file_name().cmp(b.file_name()))
            .min_depth(1)
            .max_depth(1)
            .into_iter()
            .filter_map(Result::ok)
            .take(FILES_TO_INSPECT)
        {
            writeln!(stream, "{}", entry.path().display())?;
        }
    } else {
        writeln!(
            stream,
            "{}: file, {}",
            &target.to_str().unwrap(),
            util::humanize_bytes(metadata.len())
        )?;
        // Read the file and print the first few lines
        if let Ok(source_file) = fs::File::open(source) {
            for line in BufReader::new(source_file)
                .lines()
                .take(LINES_TO_INSPECT)
                .filter_map(Result::ok)
            {
                writeln!(stream, "> {line}")?;
            }
        } else {
            writeln!(stream, "Error reading {}", source.display())?;
        }
    }
    util::prompt_yes(
        format!("Send {} to the graveyard?", target.to_str().unwrap()),
        mode,
        stream,
    )
}

/// Plan graveyard directory structure and permissions
fn build_graveyard_dest(graveyard: &Path, source: &Path) -> (PathBuf, Vec<DirToCreate>) {
    let mut dest = graveyard.to_path_buf();
    let mut dirs_to_create = Vec::new();
    let mut cumulative_source = PathBuf::new();

    for component in source.components() {
        // Build cumulative source path
        cumulative_source.push(component.as_os_str());

        // Process component for destination using shared logic
        if util::push_component_to_dest(&mut dest, &component) {
            // Only add directories to the list (skip the final file component)
            if cumulative_source.is_dir() {
                let permissions = fs::metadata(&cumulative_source)
                    .map(|m| m.permissions())
                    .ok();
                dirs_to_create.push(DirToCreate {
                    path: dest.clone(),
                    permissions,
                });
            }
        }
    }

    (dest, dirs_to_create)
}

/// Plan source directory structure and permissions
fn build_dirs_to_create_from_graveyard(
    graveyard_path: &Path,
    orig_path: &Path,
) -> Vec<DirToCreate> {
    let mut dirs_to_create = Vec::new();

    // Walk from file to root and collect permissions to propagate
    let mut graveyard_current = graveyard_path.parent();
    let mut orig_current = orig_path.parent();

    while let (Some(g), Some(o)) = (graveyard_current, orig_current) {
        let permissions = fs::metadata(g).map(|m| m.permissions()).ok();
        dirs_to_create.push(DirToCreate {
            path: o.to_path_buf(),
            permissions,
        });

        // Move up one level
        graveyard_current = g.parent();
        orig_current = o.parent();
    }
    dirs_to_create.reverse();
    dirs_to_create
}

/// Create the missing directories needed for a copy operation.
///
/// Important: permissions are applied *after* the copy finishes; otherwise a non-writable parent
/// (e.g. mode 0555) can prevent creating deeper directories or writing the file itself.
fn create_dirs_for_copy(dirs_to_create: &[DirToCreate]) -> Result<Vec<DirToCreate>, Error> {
    let mut created = Vec::new();

    // Create directories one by one in order (parent to child).
    // This assumes `dirs_to_create` is ordered from root to leaf.
    for dir in dirs_to_create {
        if dir.path.exists() {
            continue;
        }

        fs::create_dir(&dir.path).map_err(|e| {
            Error::new(
                e.kind(),
                format!("Failed to create directory {}: {}", dir.path.display(), e),
            )
        })?;
        created.push(dir.clone());
    }

    Ok(created)
}

fn apply_dir_permissions(dirs: &[DirToCreate]) -> Result<(), Error> {
    for dir in dirs.iter().rev() {
        if let Some(perms) = &dir.permissions {
            fs::set_permissions(&dir.path, perms.clone()).map_err(|e| {
                Error::new(
                    e.kind(),
                    format!("Failed to set permissions on {}: {}", dir.path.display(), e),
                )
            })?;
        }
    }
    Ok(())
}

/// Move a target to a given destination, copying if necessary.
/// Returns true if the target was moved, false if it was not (due to
/// user input)
pub fn move_target(
    target: &Path,
    dest: &Path,
    allow_rename: bool,
    mode: &impl util::TestingMode,
    stream: &mut impl Write,
    force: bool,
    dirs_to_create: &[DirToCreate],
) -> Result<bool, Error> {
    // Try a simple rename, which will only work within the same mount point.
    // Trying to rename across filesystems will throw errno 18.
    if allow_rename && fs::rename(target, dest).is_ok() {
        return Ok(true);
    }

    // If that didn't work, then we need to copy and rm.
    let created_dirs = create_dirs_for_copy(dirs_to_create)?;

    if fs::symlink_metadata(target)?.is_dir() {
        let moved = move_dir(target, dest, mode, stream, force)?;
        apply_dir_permissions(&created_dirs)?;
        Ok(moved)
    } else {
        let moved = copy_file(target, dest, mode, stream, force).map_err(|e| {
            Error::new(
                e.kind(),
                format!(
                    "Failed to copy file from {} to {}",
                    target.display(),
                    dest.display()
                ),
            )
        })?;
        fs::remove_file(target).map_err(|e| {
            Error::new(
                e.kind(),
                format!("Failed to remove file: {}", target.display()),
            )
        })?;
        apply_dir_permissions(&created_dirs)?;
        Ok(moved)
    }
}

/// Move a target which is a directory to a given destination, copying if necessary.
/// Returns true *always*, as the creation of the directory is enough to mark it as successful.
pub fn move_dir(
    target: &Path,
    dest: &Path,
    mode: &impl util::TestingMode,
    stream: &mut impl Write,
    force: bool,
) -> Result<bool, Error> {
    let mut dest_dirs_and_perms: Vec<(PathBuf, fs::Permissions)> = Vec::new();

    // Walk the source, creating directories and copying files as needed
    for entry in WalkDir::new(target).into_iter().filter_map(Result::ok) {
        // Path without the top-level directory
        let orphan = entry
            .path()
            .strip_prefix(target)
            .map_err(|_| Error::other("Parent directory isn't a prefix of child directories?"))?;

        if entry.file_type().is_dir() {
            let dest_dir = dest.join(orphan);
            fs::create_dir_all(&dest_dir).map_err(|e| {
                Error::new(
                    e.kind(),
                    format!(
                        "Failed to create dir: {} in {}",
                        entry.path().display(),
                        dest_dir.display()
                    ),
                )
            })?;

            // Preserve directory permissions, but apply after traversal so we can
            // still create children under non-writable directories.
            let source_metadata = fs::metadata(entry.path()).map_err(|e| {
                Error::new(
                    e.kind(),
                    format!("Failed to get metadata for: {}", entry.path().display()),
                )
            })?;
            dest_dirs_and_perms.push((dest_dir, source_metadata.permissions()));
        } else {
            copy_file(entry.path(), &dest.join(orphan), mode, stream, force).map_err(|e| {
                Error::new(
                    e.kind(),
                    format!(
                        "Failed to copy file from {} to {}",
                        entry.path().display(),
                        dest.join(orphan).display()
                    ),
                )
            })?;
        }
    }
    fs::remove_dir_all(target).map_err(|e| {
        Error::new(
            e.kind(),
            format!("Failed to remove dir: {}", target.display()),
        )
    })?;

    // Apply collected perms from leaf to root to minimize traversal surprises.
    for (dest_dir, perms) in dest_dirs_and_perms.into_iter().rev() {
        fs::set_permissions(&dest_dir, perms).map_err(|e| {
            Error::new(
                e.kind(),
                format!("Failed to set permissions on: {}", dest_dir.display()),
            )
        })?;
    }

    Ok(true)
}

pub fn copy_file(
    source: &Path,
    dest: &Path,
    mode: &impl util::TestingMode,
    stream: &mut impl Write,
    force: bool,
) -> Result<bool, Error> {
    let metadata = fs::symlink_metadata(source)?;
    let filetype = metadata.file_type();

    if metadata.len() > BIG_FILE_THRESHOLD {
        // In force mode, we default to copying big files
        if !force
            && util::prompt_yes(
                format!(
                    "About to copy a big file ({} is {})\nPermanently delete this file instead?",
                    source.display(),
                    util::humanize_bytes(metadata.len())
                ),
                mode,
                stream,
            )?
        {
            return Ok(false);
        }
    }

    if filetype.is_file() {
        fs::copy(source, dest)?;
        return Ok(true);
    }

    #[cfg(unix)]
    if filetype.is_fifo() {
        let perm: libc::mode_t = (metadata.permissions().mode() & 0o777) as libc::mode_t;
        let mode = Mode::from_bits_truncate(perm);

        mkfifo(dest, mode)?;
        return Ok(true);
    }

    if filetype.is_symlink() {
        let target = fs::read_link(source)?;
        symlink(target, dest)?;
        return Ok(true);
    }

    match fs::copy(source, dest) {
        Err(e) => {
            // Special file: Try copying it as normal, but this probably won't work
            // In force mode, we don't delete special files, we error
            if !force
                && util::prompt_yes(
                    format!(
                        "Non-regular file or directory: {}\nPermanently delete the file?",
                        source.display()
                    ),
                    mode,
                    stream,
                )?
            {
                Ok(false)
            } else {
                Err(e)
            }
        }
        Ok(_) => Ok(true),
    }
}

pub fn get_graveyard(graveyard: Option<PathBuf>) -> PathBuf {
    graveyard.unwrap_or_else(|| {
        if let Ok(env_graveyard) = env::var("RIP_GRAVEYARD") {
            PathBuf::from(env_graveyard)
        } else if let Ok(mut env_graveyard) = env::var("XDG_DATA_HOME") {
            if !env_graveyard.ends_with(std::path::MAIN_SEPARATOR) {
                env_graveyard.push(std::path::MAIN_SEPARATOR);
            }
            env_graveyard.push_str("graveyard");
            PathBuf::from(env_graveyard)
        } else {
            let user = util::get_user();
            env::temp_dir().join(format!("graveyard-{user}"))
        }
    })
}

/// Testing module for exposing internal functions to unit tests.
/// This module is only used for testing purposes and should not be used in production code.
pub mod testing {
    use super::{should_we_bury_this, util, Error, Metadata, Path, PathBuf, Write};

    pub fn testable_should_we_bury_this(
        target: &Path,
        source: &PathBuf,
        metadata: &Metadata,
        stream: &mut impl Write,
    ) -> Result<bool, Error> {
        should_we_bury_this(target, source, metadata, &util::TestMode, stream)
    }
}