trasher 3.3.2

A small command-line utility to replace 'rm' and 'del' by a trash system
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
use std::{
    cell::RefCell,
    collections::BTreeSet,
    ffi::OsStr,
    fs,
    path::Component,
    path::{Path, PathBuf},
    rc::Rc,
};

use anyhow::{bail, Context, Result};
use comfy_table::{presets::UTF8_FULL_CONDENSED, ContentArrangement, Table};
use fs_extra::dir::TransitProcessResult;
use indicatif::{ProgressBar, ProgressStyle};
use mountpoints::mountpaths;

use crate::{debug, Config};

use super::items::TrashItemInfos;

/// Name of the trash directory
const TRASH_DIR_NAME: &str = ".trasher";

/// Name of the transfer directory in the trash
pub const TRASH_TRANSFER_DIRNAME: &str = ".#PARTIAL";

/// Directories to never create a trash directory for
pub static ALWAYS_EXCLUDE_DIRS: &[&str] = &[
    "/bin",
    "/boot",
    "/dev",
    "/lost+found",
    "/usr",
    "/proc",
    "/sbin",
    "/snap",
    "/sys",
];

/// Determine path to the trash directory for a given item and create it if required
pub fn determine_trash_dir_for(item: &Path, config: &Config) -> Result<PathBuf> {
    debug!("Determining trasher directory for item: {}", item.display());

    let home_dir = dirs::home_dir().context("Failed to determine path to user's home directory")?;

    let mut exclude = config
        .exclude
        .iter()
        .filter_map(|dir| {
            if !dir.is_dir() {
                None
            } else {
                Some(fs::canonicalize(dir).with_context(|| {
                    format!(
                        "Failed to canonicalize excluded directory: {}",
                        dir.display()
                    )
                }))
            }
        })
        .collect::<Result<Vec<_>, _>>()?;

    // Add some directories to always exclude
    exclude.extend(
        ALWAYS_EXCLUDE_DIRS
            .iter()
            .map(Path::new)
            .map(Path::to_owned),
    );

    // Don't canonicalize excluded item paths
    // NOTE: Only works if item path is absolute
    if exclude.iter().any(|dir| item.starts_with(dir)) {
        return Ok(home_dir.join(TRASH_DIR_NAME));
    }

    let item = fs::canonicalize(item)
        .with_context(|| format!("Failed to canonicalize item path: {}\n\nTip: you can exclude this directory using --exclude.", item.display()))?;

    let mut mountpoints = mountpaths().context("Failed to list system mountpoints")?;

    // Add home directory for specialization
    // e.g. if "/home" is a mounted directory, and we delete an item instead "/home/$USER",
    // this line will allow the algorithm to pick the more specialized "/home/$USER" instead
    mountpoints.push(home_dir.clone());

    let mut found = None::<PathBuf>;

    for mountpoint in &mountpoints {
        if mountpoint.to_str() == Some("/") {
            continue;
        }

        let Ok(mt) = fs::metadata(mountpoint) else {
            continue;
        };

        if mt.permissions().readonly() {
            continue;
        }

        #[cfg(target_family = "unix")]
        {
            use std::os::unix::fs::PermissionsExt;

            // Skip directories without write permissions
            if mt.permissions().mode() & 0o222 == 0 {
                continue;
            }
        }

        let canon_mountpoint = fs::canonicalize(mountpoint).with_context(|| {
            format!(
                "Failed to canonicalize mountpoint: {}",
                mountpoint.display()
            )
        })?;

        if !item.starts_with(&canon_mountpoint) {
            continue;
        }

        if exclude.iter().any(|parent| item.starts_with(parent)) {
            found = None;
            break;
        }

        if found.is_none() || matches!(found, Some(ref prev) if canon_mountpoint.starts_with(prev))
        {
            found = Some(canon_mountpoint);
        }
    }

    Ok(found.unwrap_or(home_dir).join(TRASH_DIR_NAME))
}

/// List all trash directories
pub fn list_trash_dirs(config: &Config) -> Result<BTreeSet<PathBuf>> {
    let canon_root = fs::canonicalize("/").context("Failed to canonicalize the root directory")?;

    let trash_dirs = mountpaths()
        .context("Failed to list system mountpoints")?
        .iter()
        .chain([canon_root].iter())
        .map(|path| determine_trash_dir_for(path, config))
        .collect::<Result<Vec<_>, _>>()?;

    Ok(trash_dirs.into_iter().filter(|dir| dir.is_dir()).collect())
}

/// List and parse all items in the trash
pub fn list_trash_items(trash_dir: &Path) -> Result<Vec<TrashedItem>> {
    if !trash_dir.exists() {
        return Ok(vec![]);
    }

    let dir_entries = fs::read_dir(trash_dir)
        .context("Failed to read trash directory")?
        .collect::<Result<Vec<_>, _>>()?;

    let items = dir_entries
        .into_iter()
        .filter_map(|item| {
            match item.file_name().into_string() {
                Err(_) => eprintln!(
                    "WARN: Trash item '{}' does not have a valid UTF-8 filename!",
                    item.path().display()
                ),

                Ok(filename) => {
                    if filename == TRASH_TRANSFER_DIRNAME {
                        return None;
                    }

                    match TrashItemInfos::decode(&filename) {
                        Err(err) => {
                            eprintln!(
                                "WARN: Trash item '{}' does not have a valid trash filename!",
                                item.path().display()
                            );

                            super::debug!("Invalid trash item filename: {:?}", err);
                        }

                        Ok(item) => {
                            return Some(TrashedItem {
                                data: item,
                                trash_dir: trash_dir.to_path_buf(),
                            })
                        }
                    }
                }
            }

            None
        })
        .collect();

    Ok(items)
}

/// List all trash items
pub fn list_all_trash_items(config: &Config) -> Result<Vec<TrashedItem>> {
    let all_trash_items = list_trash_dirs(config)?
        .into_iter()
        .map(|trash_dir| list_trash_items(&trash_dir))
        .collect::<Result<Vec<_>, _>>()?;

    let mut items = all_trash_items.into_iter().flatten().collect::<Vec<_>>();

    items.sort_by(|a, b| a.data.datetime().cmp(b.data.datetime()));

    Ok(items)
}

/// Find a specific item in the trash (panic if not found)
pub fn expect_trash_item(
    filename: &str,
    id: Option<&str>,
    config: &Config,
) -> Result<FoundTrashItems> {
    let mut candidates = list_all_trash_items(config)?
        .into_iter()
        .filter(|trashed| trashed.data.filename() == filename)
        .collect::<Vec<_>>();

    if candidates.is_empty() {
        bail!("Specified item was not found in the trash.");
    } else if candidates.len() > 1 {
        match id {
            None => Ok(FoundTrashItems::Multi(candidates)),
            Some(id) => Ok(FoundTrashItems::Single(
                candidates
                    .into_iter()
                    .find(|c| c.data.id() == id)
                    .context("There is no trash item with the provided ID")?,
            )),
        }
    } else {
        Ok(FoundTrashItems::Single(candidates.remove(0)))
    }
}

/// Find a specific item in the trash, fail if none is found or if multiple candidates are found
pub fn expect_single_trash_item(
    filename: &str,
    id: Option<&str>,
    config: &Config,
) -> Result<TrashedItem> {
    match expect_trash_item(filename, id, config)? {
        FoundTrashItems::Single(item) => Ok(item),
        FoundTrashItems::Multi(candidates) => bail!(
            "Multiple items with this filename were found in the trash:\n\n{}",
            table_for_items(&candidates)
        ),
    }
}

/// Convert a size in bytes to a human-readable size
pub fn human_readable_size(bytes: u64) -> String {
    let names = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];

    if bytes < 1024 {
        return format!("{} B", bytes);
    }

    let mut compare = 1024;

    for name in names.iter() {
        compare *= 1024;

        if bytes <= compare {
            return format!("{:.2} {}", bytes as f64 * 1024f64 / compare as f64, name);
        }
    }

    format!(
        "{:.2} {}",
        bytes as f64 / compare as f64,
        names.last().unwrap()
    )
}

/// Trash item with the trash directory is contained into, generated by the [`list_trash_items`] function
#[derive(Debug, Clone)]
pub struct TrashedItem {
    pub data: TrashItemInfos,
    pub trash_dir: PathBuf,
}

impl TrashedItem {
    /// Get the trash path for an item that's going to be transferred to it
    pub fn transfer_trash_item_path(&self) -> PathBuf {
        self.trash_dir
            .join(TRASH_TRANSFER_DIRNAME)
            .join(self.data.trash_filename())
    }

    pub fn complete_trash_item_path(&self) -> PathBuf {
        self.trash_dir.join(self.data.trash_filename())
    }
}

/// Trash items found with the [`expect_trash_item`] function
pub enum FoundTrashItems {
    Single(TrashedItem),
    Multi(Vec<TrashedItem>),
}

// Check if a path is dangerous to delete
pub fn is_dangerous_path(path: &Path) -> bool {
    let mut components = path.components();

    match (
        components.next(),
        components.next(),
        components.next(),
        components.next(),
    ) {
        // The root directory (/)
        (Some(Component::RootDir), None, None, None) => true,

        // Root directories (/home, /bin, etc.)
        (Some(Component::RootDir), Some(_), None, None) => true,

        // Home directories (/home/username, etc.)
        (Some(Component::RootDir), Some(Component::Normal(dir)), Some(_), None) => {
            dir == OsStr::new("home")
        }

        // Non-dangerous paths
        _ => false,
    }
}

/// Move items around with a progressbar
pub fn move_item_pbr(path: &Path, target: &Path) -> Result<()> {
    let pbr = Rc::new(RefCell::new(None));

    let update_pbr = |copied, total, item_name: &str| {
        let mut pbr = pbr.borrow_mut();
        let pbr = pbr.get_or_insert_with(|| {
            let pbr = ProgressBar::new(total);
            pbr.set_style(ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
            .expect("Invalid progress bar template")
            .progress_chars("#>-"));
            pbr
        });

        pbr.set_position(copied);
        pbr.set_message(item_name.to_string());
    };

    if path.metadata()?.is_file() {
        let file_name = path.file_name().unwrap().to_string_lossy();

        fs_extra::file::move_file_with_progress(
            path,
            target,
            &fs_extra::file::CopyOptions::new(),
            |tp| {
                update_pbr(tp.copied_bytes, tp.total_bytes, &file_name);
            },
        )?;
    } else {
        let mut config = fs_extra::dir::CopyOptions::new();
        config.copy_inside = true;
        fs_extra::dir::move_dir_with_progress(path, target, &config, |tp| {
            update_pbr(tp.copied_bytes, tp.total_bytes, &tp.file_name);
            TransitProcessResult::ContinueOrAbort
        })?;
    }

    let mut pbr = pbr.borrow_mut();
    let pbr = pbr.as_mut();

    if let Some(pbr) = pbr {
        pbr.finish_with_message("Moving complete.")
    }

    Ok(())
}

pub fn table_for_items(items: &[TrashedItem]) -> Table {
    let mut table = Table::new();

    table
        .load_preset(UTF8_FULL_CONDENSED)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_header(vec![
            "Type",
            "Filename",
            "Size",
            "ID",
            "Deleted on",
            "Trash directory",
        ]);

    for item in items {
        let TrashedItem { data, trash_dir } = item;

        let TrashItemInfos {
            id,
            filename,
            datetime,
        } = data;

        let mt = fs::metadata(item.complete_trash_item_path());

        table.add_row(vec![
            match &mt {
                Ok(mt) => {
                    if mt.file_type().is_file() {
                        "File"
                    } else if mt.file_type().is_dir() {
                        "Directory"
                    } else {
                        "<Unknown>"
                    }
                }
                Err(_) => "ERROR",
            }
            .to_string(),
            filename.clone(),
            match &mt {
                Ok(mt) => human_readable_size(mt.len()),
                Err(_) => "ERROR".to_owned(),
            },
            id.clone(),
            datetime.to_rfc2822(),
            trash_dir.to_string_lossy().into_owned(),
        ]);
    }

    table
}

pub fn are_on_same_fs(a: &Path, b: &Path) -> Result<bool> {
    fn get_dev(item: &Path) -> Result<u64> {
        let mt = fs::metadata(item)?;

        #[cfg(target_family = "windows")]
        {
            use std::os::windows::fs::MetadataExt;
            mt.volume_serial_number()
                .map(u64::from)
                .context("Item does not have a volume serial number attached")
        }

        #[cfg(target_family = "unix")]
        {
            use std::os::unix::fs::MetadataExt;
            Ok(mt.dev())
        }
    }

    let a_fs_id = get_dev(a)
        .with_context(|| format!("Failed to get filesystem ID for item '{}'", a.display()))?;

    let b_fs_id = get_dev(b)
        .with_context(|| format!("Failed to get filesystem ID for item '{}'", b.display()))?;

    Ok(a_fs_id == b_fs_id)
}