roxide 0.2.18

A better rm command for your terminal
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
#![allow(unused_labels, unused_imports)]


use std::env::current_dir;
use std::fs::{self, remove_dir, File};
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use log::*;

use crate::core::checks::check_cross_device;
use crate::utils::config::init_config;
use crate::{
    core::{
        error::Error,
        filter::PathFilter,
        helpers::trash_dir,
        history::{History, LogId, TrashMeta},
        trash::Trash,
    },
    prompt_yes, show_error, verbose,
};

use super::args::{Cli, InteractiveMode};
use super::checks::check_root;

pub type RoError<'a, T> = Result<T, super::error::Error<'a>>;

fn init_checks(item: &Path) -> RoError<()> {
    if item.parent().is_none() && item.has_root() {
        return Err(Error::IsRoot(item));
    }
    Ok(())
}

fn init_force_remove_with_prompt(item: &Path) {
    if prompt_yes!("remove it PERMANENTLY?") {
        if item.is_file() {
            if let Err(e) = fs::remove_file(item) {
                show_error!("Failed to remove file: {}", e);
            }
        } else if item.is_dir() {
            if let Err(e) = fs::remove_dir_all(item) {
                show_error!("Failed to remove directory: {}", e);
            }
        }
    }
}

fn init_force_remove_without_prompt(item: &Path) {
    if item.is_file() {
        if let Err(e) = fs::remove_file(item) {
            show_error!("Failed to remove file: {}", e);
        }
    } else if item.is_dir() {
        if let Err(e) = fs::remove_dir_all(item) {
            show_error!("Failed to remove directory: {}", e);
        }
    }
}

fn core_remove(args: &Cli, item: &Path) {
    let trash = Trash { file: item };
    let id = trash.get_log_id();
    let item_path = current_dir().unwrap().join(item);
    let trash_path = trash_dir().join(trash.trash_name(id.1));

    let config = init_config();

    if check_root() {
        trace!("is root user");
        show_error!("Can't move item to trash dir while using sudo.");
        init_force_remove_with_prompt(item);
    } else {
        trace!("is normal user");

        // we can't move items from an another device.
        // only option is to copy or delete
        // So. we will prompt for force remove
        match check_cross_device(&item_path) {
            Ok(()) => match config.settings.check_sha256 {
                Some(true) if trash.compute_sha256(args) && item.is_file() => {
                    init_force_remove_without_prompt(&item_path);
                    verbose!(
                        args.verbose,
                        "roxide: removed {} permanently",
                        &item_path.display()
                    );
                }
                _ => {
                    let rename_result = fs::rename(
                        &item_path,
                        trash_dir().join(trash.trash_name(trash.get_log_id().1)),
                    );
                    match rename_result {
                        Ok(_) => {
                            if args.pattern.is_none() {
                                verbose!(
                                    args.verbose,
                                    "Trashed {} to {}",
                                    item.display(),
                                    trash_dir()
                                        .join(trash.trash_name(trash.get_log_id().1))
                                        .display()
                                );
                                let history = History {
                                    log_id: LogId::from_str(id.0.to_string().as_str()).unwrap(),
                                    metadata: TrashMeta {
                                        file_path: item_path,
                                        trash_path,
                                    },
                                };
                                History::write(history).unwrap();
                            }
                        }
                        Err(err) => match err.kind() {
                            io::ErrorKind::PermissionDenied => {
                                show_error!(
                                    "Don't have enough permission to remove `{}`.",
                                    item.display()
                                );
                            }
                            io::ErrorKind::ResourceBusy => {
                                show_error!(
                                    "Resource is busy and cannot be moved: {}",
                                    item.display()
                                );
                            }
                            io::ErrorKind::ReadOnlyFilesystem => {
                                show_error!(
                                    "can't move. error: ReadOnly Filesystem: {}",
                                    item.display()
                                );
                                init_force_remove_with_prompt(item);
                            }
                            _ => {
                                println!("Error: {}", err);
                                init_force_remove_with_prompt(item);
                            }
                        },
                    }
                }
            },
            Err(err) => {
                show_error!("{}", err);
                init_force_remove_with_prompt(item);
            }
        }
    }
}

pub fn init_remove(items: Vec<PathBuf>, args: &Cli) -> RoError<()> {
    let entries = match PathFilter::init(items, args) {
        Ok(filtered) => filtered,
        Err(e) => {
            eprintln!("{}", e);
            Vec::with_capacity(0)
        }
    };
    handle_interactive_once(args);
    for item in &entries {
        if args.list {
            println!("{}", item.display());
        } else if let Err(e) = init_checks(item) {
            eprintln!("Error: {}", e); // prints Error::IsRoot
            continue;
        } else {
            handle_interactive(args, item)
        }
    }
    trace!("{:#?}", entries);
    Ok(())
}

fn handle_interactive_once(args: &Cli) -> bool {
    let items = args.file.as_ref().unwrap();
    if args.interactive == Some(InteractiveMode::Once) && (items.len() > 3 || args.recursive) {
        let msg: String = format!(
            "remove {} {}{}",
            items.len(),
            if items.len() > 1 {
                "arguments"
            } else {
                "argument"
            },
            if args.recursive { " recursively?" } else { "?" }
        );
        if prompt_yes!("{}", msg) {
            return true;
        }
    }
    false
}

fn remove_empty_dir(path: &Path) {
    if path.exists() && path.is_dir() {
        let result = remove_dir(path);
        match result {
            Ok(_) => {}
            Err(_) => {
                eprintln!("{}", Error::DirectoryNotEmpty)
            }
        }
    } else if !path.exists() {
        eprintln!("{}", Error::NoSuchFile(path))
    } else if path.is_file() {
        eprintln!("{}", Error::NotADirectory(path))
    }
}

fn handle_interactive(args: &Cli, item: &Path) {
    // File::open(path) doesn't open the file in write mode
    // So, we need to use file options to open it in write mode to check if we have write permission
    #[cfg(feature = "extra_commands")]
    let file_write_permission = File::options().read(true).write(true).open(item).is_ok();
    // not including InteractiveMode::once and InteractiveMode::Never here
    match args.interactive {
        Some(InteractiveMode::Always) => {
            if args.dir {
                if prompt_yes!("remove normal empty dir: `{}`?", &item.display()) {
                    remove_empty_dir(item)
                }
            } else if prompt_yes!("remove: `{}`?", &item.display()) {
                core_remove(args, item)
            }
        }
        #[cfg(feature = "extra_commands")]
        Some(InteractiveMode::PromptProtected) => {
            if !file_write_permission
                && prompt_yes!("write protected file, remove: `{}`?", &item.display())
            {
                core_remove(args, item);
            }
        }
        Some(_) => {
            if args.dir {
                remove_empty_dir(item)
            } else {
                core_remove(args, item)
            }
        }
        None => {
            if args.dir {
                remove_empty_dir(item)
            } else {
                core_remove(args, item)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::borrow::Cow;
    use std::fs::{remove_dir_all, File};
    use std::path::{Path, PathBuf};
    use std::thread::sleep;
    use std::time::Duration;
    use std::{fs, path};

    use dirs::data_dir;
    use tempdir::TempDir;

    use crate::core::args::Cli;
    use crate::core::helpers::trash_dir;
    use crate::core::rm::check_root;
    use crate::utils::config::init_config;

    use super::init_remove;

    /// will create a empty dir2 and a dir1 with 3 files
    fn make_dirs_for_test(basedir_name: &Path) -> (Vec<PathBuf>, Vec<PathBuf>) {
        let base_dir = std::env::current_dir()
            .unwrap()
            .join("trash/tests")
            .join(basedir_name);
        if !base_dir.exists() {
            fs::create_dir_all(&base_dir).unwrap();
        }
        let dirs = vec![base_dir.join("dir1"), base_dir.join("dir2")];
        let dirs_cow = Cow::Borrowed(&dirs);
        for dirs in dirs_cow.iter() {
            if !base_dir.join(dirs).exists() {
                fs::create_dir(base_dir.join(dirs)).unwrap();
            }
        }
        let files = vec![
            base_dir.join("dir1/file1.txt"),
            base_dir.join("dir1/file2.pdf"),
            base_dir.join("dir1/file3"),
        ];
        let files_cow = Cow::Borrowed(&files);
        for filename in files_cow.iter() {
            if !filename.exists() {
                fs::write(filename, "some contents").unwrap();
            }
        }
        for dirname in dirs_cow.iter() {
            assert!(path::Path::new(&dirname).exists())
        }
        for filename in &files {
            assert!(path::Path::new(&filename).exists())
        }
        (dirs_cow.to_vec(), files_cow.to_vec())
    }
    fn remove_test_dir(basedir_name: &Path) {
        let base_dir = std::env::current_dir()
            .unwrap()
            .join("trash/tests")
            .join(basedir_name);
        remove_dir_all(&base_dir).unwrap();
        assert!(!path::Path::new(&base_dir).exists())
    }

    #[test]
    fn test_check_root() {
        // This test assumes a non-root environment.
        let is_root = check_root();
        assert!(!is_root);
    }

    #[test]
    // #[ignore = "i have no idea why this is failing. It works on manual tests"]
    fn check_sha256_01() {
        let items = make_dirs_for_test(Path::new("check_sha256_01"));
        let dirs = items.0;
        let files = items.1;
        let _files_cow = Cow::Borrowed(&files);
        let dirs_cow = Cow::Borrowed(&dirs);

        let args = Cli {
            file: Some(dirs_cow.to_vec()),
            interactive: None,
            recursive: true,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: false,
            force: None,
            list: false,
            verbose: true,
            pattern: None,
            command: None,
        };
        // panic!("{:#?}", dirs_cow);
        sleep(Duration::from_secs(1));
        init_remove(dirs_cow.to_vec(), &args).unwrap();
        for filename in &files {
            assert!(!path::Path::new(&filename).exists())
        }
        for dirname in dirs_cow.iter() {
            assert!(!path::Path::new(&dirname).exists())
        }
        remove_test_dir(Path::new("check_sha256_01"));
    }

    /// no flag test
    /// only files as input no dirs
    #[test]
    fn revome_files_only_01() {
        let items = make_dirs_for_test(Path::new("revome_files_only_01"));
        let _dirs = items.0;
        let files = items.1;

        let args = Cli {
            file: Some(files.to_vec()),
            interactive: None,
            recursive: false,
            #[cfg(feature = "extra_commands")]
            check: false,
            force: None,
            list: false,
            verbose: false,
            pattern: None,
            command: None,
            dir: false,
        };

        sleep(Duration::from_secs(1));
        init_remove(files.clone(), &args).unwrap();
        for filename in &files {
            assert!(!path::Path::new(&filename).exists())
        }
        remove_test_dir(Path::new("revome_files_only_01"));
    }
    /// recursive flags test
    /// revome_dirs_in_some_dir_from_root
    #[test]
    fn recursive_remove_01() {
        let items = make_dirs_for_test(Path::new("recursive_remove_01"));
        let dirs = items.0;
        let files = items.1;
        let dirs_cow = Cow::Borrowed(&dirs);

        let args = Cli {
            file: Some(dirs_cow.to_vec()),
            interactive: None,
            recursive: true,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: false,
            force: None,
            list: false,
            verbose: false,
            pattern: None,
            command: None,
        };

        sleep(Duration::from_secs(1));
        init_remove(dirs_cow.to_vec(), &args).unwrap();

        for filename in files {
            assert!(!path::Path::new(&filename).exists())
        }
        // remove_test_dir(Path::new("recursive_remove_01"));
    }
    #[test]
    fn force_revome_dirs() {
        let items = make_dirs_for_test(Path::new("force_revome_dirs"));
        let dirs = items.0;
        let _files = items.1;
        let dirs_cow = Cow::Borrowed(&dirs);

        // force flags test
        let args = Cli {
            file: None,
            interactive: None,
            recursive: false,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: false,
            force: Some(dirs_cow.to_vec()),
            list: false,
            verbose: false,
            pattern: None,
            command: None,
        };

        if let Some(forece_file) = args.force {
            for item in forece_file {
                if Path::new(&item).exists() {
                    if item.is_dir() {
                        fs::remove_dir_all(item).expect("Error while removing dirs");
                    } else {
                        fs::remove_file(item).expect("Error while removing files");
                    }
                } else {
                    println!("Path didnt exists");
                }
            }
        }
        for filename in &dirs {
            assert!(!path::Path::new(&filename).exists())
        }
        remove_test_dir(Path::new("force_revome_dirs"));
    }
    #[test]
    fn list_files_flag() {
        let items = make_dirs_for_test(Path::new("list_files_flag"));
        let dirs = items.0;
        let files = items.1;
        let files_cow = Cow::Borrowed(&files);

        let args = Cli {
            file: Some(files_cow.to_vec()),
            interactive: None,
            recursive: true,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: false,
            force: None,
            list: true,
            verbose: false,
            pattern: None,
            command: None,
        };

        sleep(Duration::from_secs(1));
        init_remove(files_cow.to_vec(), &args).unwrap();
        for filename in &files {
            assert!(path::Path::new(&filename).exists())
        }
        for dirname in &dirs {
            assert!(path::Path::new(&dirname).exists())
        }
        remove_test_dir(Path::new("list_files_flag"));
    }
    #[test]
    fn pattern_flag() {
        let items = make_dirs_for_test(Path::new("pattern_flag"));
        let _dirs = items.0;
        let files = items.1;
        let files_cow = Cow::Borrowed(&files);

        // no flags test
        let args = Cli {
            file: Some(files_cow.to_vec()),
            interactive: None,
            recursive: false,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: false,
            force: None,
            list: false,
            verbose: false,
            pattern: Some("txt".to_string()),
            command: None,
        };

        sleep(Duration::from_secs(1));
        init_remove(files_cow.to_vec(), &args).unwrap();
        let f = files.clone();
        assert!(!path::Path::new(&f[0]).exists()); // this one matches the pattern
        assert!(path::Path::new(&f[1]).exists());
        assert!(path::Path::new(&f[2]).exists());
        remove_test_dir(Path::new("pattern_flag"));
    }
    #[test]
    fn dir_flag_01() {
        let items = make_dirs_for_test(Path::new("dir_flag_01"));
        let dirs = items.0;
        let files = items.1;
        let _files_cow = Cow::Borrowed(&files);
        let dirs_cow = Cow::Borrowed(&dirs);

        // recursive flags test
        let args = Cli {
            file: Some(dirs_cow.to_vec()),
            interactive: None,
            recursive: false,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: true,
            force: None,
            list: false,
            verbose: false,
            pattern: None,
            command: None,
        };

        sleep(Duration::from_secs(1));
        init_remove(dirs_cow.to_vec(), &args).unwrap();

        let d = dirs.clone();
        assert!(path::Path::new(&d[0]).exists());
        assert!(!path::Path::new(&d[1]).exists()); // this one is the empty one
        remove_test_dir(Path::new("dir_flag_01"));
    }
    #[test]
    fn dir_flag_02() {
        // -> Not an empty directory Error
        let items = make_dirs_for_test(Path::new("dir_flag_02"));
        let dirs = items.0;
        let files = items.1;
        let _files_cow = Cow::Borrowed(&files);
        let dirs_cow = Cow::Borrowed(&dirs);

        let args = Cli {
            file: Some(dirs_cow.to_vec()),
            interactive: None,
            recursive: false,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: true,
            force: None,
            list: false,
            verbose: false,
            pattern: None,
            command: None,
        };

        sleep(Duration::from_secs(1));
        init_remove(dirs_cow.to_vec(), &args).unwrap();

        let d = dirs.clone();
        assert!(path::Path::new(&d[0]).exists());
        assert!(!path::Path::new(&d[1]).exists()); // this one is the empty one
        remove_test_dir(Path::new("dir_flag_02"));
    }
    #[test]
    fn dir_flag_03() {
        // -> Not an empty directory Error
        let items = make_dirs_for_test(Path::new("dir_flag_03"));
        let dirs = items.0;
        let files = items.1;
        let _files_cow = Cow::Borrowed(&files);
        let dirs_cow = Cow::Borrowed(&dirs);

        let args = Cli {
            file: Some(dirs_cow.to_vec()),
            interactive: None,
            recursive: false,
            #[cfg(feature = "extra_commands")]
            check: false,
            dir: true,
            force: None,
            list: false,
            verbose: false,
            pattern: None,
            command: None,
        };
        sleep(Duration::from_secs(1));
        let result = init_remove(dirs_cow.to_vec(), &args);
        assert!(result.is_ok());
        let d = dirs.clone();
        assert!(path::Path::new(&d[0]).exists());
        assert!(!path::Path::new(&d[1]).exists()); // this one is the empty one
        remove_test_dir(Path::new("dir_flag_03"));
    }
}