garbage 0.4.3

CLI tool for interacting with the freedesktop trashcan
Documentation
use std::env;
use std::path::PathBuf;

use anyhow::{Context, Result};
use clap::ValueHint;
use garbage_fs::Filesystem;

use crate::dir::TrashDir;
use crate::list;

/// Options to pass to list
#[derive(Parser)]
pub struct ListOptions {
  /// The path to the trash directory to list.
  /// By default, this is your home directory's trash ($XDG_DATA_HOME/Trash)
  #[clap(long = "trash-dir", value_parser, value_hint(ValueHint::DirPath))]
  trash_dir: Option<PathBuf>,

  /// List all files in the trash (by default, only files in the current
  /// directory are listed)
  #[clap(short = 'a', long = "all")]
  all: bool,

  /// Output in machine-friendly JSON format.
  /// By default, prints a human-friendly table.
  #[clap(long = "json")]
  json: bool,
}

/// List the contents of a trash directory
pub fn list(options: ListOptions, fs: &impl Filesystem) -> Result<()> {
  let trash_dir = TrashDir::from_opt(options.trash_dir.as_ref());

  let current_dir = env::current_dir().context("Failed to get current dir")?;

  let mut files = trash_dir
    .iter(fs)?
    .collect::<Result<Vec<_>>>()?
    .into_iter()
    .filter_map(|info| {
      if !options.all && !info.path.starts_with(&current_dir) {
        None
      } else {
        Some(info)
      }
    })
    .collect::<Vec<_>>();
  files.sort_unstable_by_key(|info| info.deletion_date);

  if options.json {
    list::print_files_list_json(files.iter())?;
  } else {
    list::print_files_list(files.iter(), false)?;
  }

  Ok(())
}