Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unify Glob arguments into one Argument #155

Merged
merged 16 commits into from
May 1, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 91 additions & 85 deletions README.md

Large diffs are not rendered by default.

13 changes: 2 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use render::{
Tree,
},
};
use std::{io::stdout, process::ExitCode};
use std::{error::Error, io::stdout};

/// Operations to wrangle ANSI escaped strings.
mod ansi;
Expand All @@ -43,16 +43,7 @@ mod tty;
/// Common utilities across all modules.
mod utils;

fn main() -> ExitCode {
if let Err(e) = run() {
eprintln!("{e}");
return ExitCode::FAILURE;
}

ExitCode::SUCCESS
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
fn main() -> Result<(), Box<dyn Error>> {
let ctx = Context::init()?;

if let Some(shell) = ctx.completions {
Expand Down
46 changes: 29 additions & 17 deletions src/render/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@ pub enum Coloring {
/// Turn on colorization always
Forced,
}

#[derive(Clone, Copy, Debug, clap::ValueEnum, PartialEq, Eq, Default)]
pub enum Glob {
// Disables glob based searching
#[default]
None,

/// Enables glob based searching
Sensitive,

/// Enables case-insensitive glob based searching
Insensitive,
}
/// Defines the CLI.
#[derive(Parser, Debug)]
#[command(name = "erdtree")]
Expand Down Expand Up @@ -114,12 +127,8 @@ pub struct Context {
pub pattern: Option<String>,

/// Enables glob based searching
#[arg(long, requires = "pattern")]
pub glob: bool,

/// Enables case-insensitive glob based searching
#[arg(long, requires = "pattern")]
pub iglob: bool,
#[arg(long, requires = "pattern", value_enum, default_value_t = Glob::default())]
pub glob: Glob,

/// Restrict regex or glob search to a particular file-type
#[arg(short = 't', long, requires = "pattern", value_enum)]
Expand Down Expand Up @@ -220,6 +229,15 @@ impl Context {
/// Initializes [Context], optionally reading in the configuration file to override defaults.
/// Arguments provided will take precedence over config.
pub fn init() -> Result<Self, Error> {
trait IntoVecOfStr {
KP64 marked this conversation as resolved.
Show resolved Hide resolved
fn as_vec_of_str(&self) -> Vec<&str>;
}
impl IntoVecOfStr for ArgMatches {
fn as_vec_of_str(&self) -> Vec<&str> {
self.ids().map(Id::as_str).collect()
}
}

let user_args = Self::command().args_override_self(true).get_matches();

let no_config = user_args
Expand All @@ -244,16 +262,13 @@ impl Context {
// user arguments.
let mut args = vec![OsString::from("--")];

let mut ids = user_args.ids().map(Id::as_str).collect::<Vec<&str>>();
let mut ids = user_args.as_vec_of_str();

ids.extend(config_args.ids().map(Id::as_str).collect::<Vec<&str>>());
ids.extend(config_args.as_vec_of_str());

ids = crate::utils::uniq(ids);

for id in ids {
if id == "Context" {
continue;
}
for id in ids.into_iter().filter(|&id| id != "Context") {
if id == "dir" {
if let Ok(Some(raw)) = user_args.try_get_raw(id) {
let raw_args = raw.map(OsStr::to_owned).collect::<Vec<OsString>>();
Expand Down Expand Up @@ -394,11 +409,8 @@ impl Context {

let mut negated_glob = false;

let overrides = if !self.glob && !self.iglob {
// Shouldn't really ever be hit but placing here as a safeguard.
return Err(Error::EmptyGlob);
} else {
if self.iglob {
let overrides = {
if self.glob == Glob::Insensitive {
builder.case_insensitive(true)?;
}

Expand Down
6 changes: 4 additions & 2 deletions src/render/tree/display/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ use crate::render::{
tree::Node,
};

type Theme = Box<dyn FnMut(&Node) -> &'static ThemesMap>;

/// Returns a closure that retrieves the regular theme.
pub fn regular_theme_getter() -> Box<dyn FnMut(&Node) -> &'static ThemesMap> {
pub fn regular_theme_getter() -> Theme {
Box::new(|_node: &Node| styles::get_tree_theme().unwrap())
}

/// Returns a closure that can smartly determine when a symlink is being followed and when it is
/// not being followed. When a symlink is being followed, all of its descendents should have tree
/// branches that are colored differently.
pub fn link_theme_getter() -> Box<dyn FnMut(&Node) -> &'static ThemesMap> {
pub fn link_theme_getter() -> Theme {
let mut link_depth = None;

Box::new(move |node: &Node| {
Expand Down
46 changes: 20 additions & 26 deletions src/render/tree/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
fs::inode::Inode,
render::{
context::{file, output::ColumnProperties, Context},
context::{self, file, output::ColumnProperties, Context},
disk_usage::file_size::FileSize,
styles,
},
Expand Down Expand Up @@ -282,19 +282,14 @@ where

/// Function to remove empty directories.
fn prune_directories(root_id_id: NodeId, tree: &mut Arena<Node>) {
let mut to_prune = vec![];

for node_id in root_id_id.descendants(tree).skip(1) {
let node = tree[node_id].get();

if !node.is_dir() {
continue;
}

if node_id.children(tree).count() == 0 {
to_prune.push(node_id);
}
}
let to_prune = root_id_id
.descendants(tree)
.skip(1)
.map(|node_id| (node_id, tree[node_id].get()))
.filter(|(_, node)| node.is_dir())
.map(|(node_id, _)| node_id)
.filter(|node_id| node_id.children(tree).count() == 0)
.collect::<Vec<_>>();

if to_prune.is_empty() {
return;
Expand All @@ -309,13 +304,11 @@ where

/// Filter for only directories.
fn filter_directories(root_id: NodeId, tree: &mut Arena<Node>) {
let mut to_detach = vec![];

for descendant_id in root_id.descendants(tree).skip(1) {
if !tree[descendant_id].get().is_dir() {
to_detach.push(descendant_id);
}
}
let to_detach = root_id
.descendants(tree)
.skip(1)
.filter(|&descendant_id| !tree[descendant_id].get().is_dir())
.collect::<Vec<_>>();

for descendant_id in to_detach {
descendant_id.detach(tree);
Expand Down Expand Up @@ -405,11 +398,12 @@ impl TryFrom<&Context> for WalkParallel {
.threads(ctx.threads);

if ctx.pattern.is_some() {
if ctx.glob || ctx.iglob {
builder.filter_entry(ctx.glob_predicate()?);
} else {
builder.filter_entry(ctx.regex_predicate()?);
}
match ctx.glob {
context::Glob::None => builder.filter_entry(ctx.regex_predicate()?),
context::Glob::Sensitive | context::Glob::Insensitive => {
builder.filter_entry(ctx.glob_predicate()?)
}
};
}

Ok(builder.build_parallel())
Expand Down
16 changes: 12 additions & 4 deletions src/render/tree/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,21 @@ impl Node {
}

/// Returns the underlying `ino` of the [`DirEntry`].
pub fn ino(&self) -> Option<u64> {
self.inode.map(|inode| inode.ino)
pub const fn ino(&self) -> Option<u64> {
if let Some(inode) = self.inode {
Some(inode.ino)
} else {
None
}
}

/// Returns the underlying `nlink` of the [`DirEntry`].
pub fn nlink(&self) -> Option<u64> {
self.inode.map(|inode| inode.nlink)
pub const fn nlink(&self) -> Option<u64> {
if let Some(inode) = self.inode {
Some(inode.nlink)
} else {
None
}
}

/// Returns `true` if node is a directory.
Expand Down
5 changes: 2 additions & 3 deletions src/tty/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ pub(super) unsafe fn win_width() -> Option<usize> {
};

(GetConsoleScreenBufferInfo(stdout_handle, &mut console_data) != 0)
.then(|| console_data.srWindow.Right - console_data.srWindow.Left + 1)
.then_some(console_data.srWindow.Right - console_data.srWindow.Left + 1)
.map(usize::try_from)
.map(Result::ok)
.flatten()
.and_then(Result::ok)
}
11 changes: 7 additions & 4 deletions tests/glob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod utils;
#[test]
fn glob() {
assert_eq!(
utils::run_cmd(&["--glob", "--pattern", "*.txt", "tests/data"]),
utils::run_cmd(&["--glob", "sensitive", "--pattern", "*.txt", "tests/data"]),
indoc!(
"100 B ┌─ nylarlathotep.txt
161 B ├─ nemesis.txt
Expand All @@ -24,7 +24,7 @@ fn glob() {
#[test]
fn glob_negative() {
assert_eq!(
utils::run_cmd(&["--glob", "--pattern", "!*.txt", "tests/data"]),
utils::run_cmd(&["--glob", "sensitive", "--pattern", "!*.txt", "tests/data"]),
indoc!(
"143 B ┌─ cassildas_song.md
143 B ┌─ the_yellow_king
Expand All @@ -38,7 +38,7 @@ fn glob_negative() {
#[test]
fn glob_case_insensitive() {
assert_eq!(
utils::run_cmd(&["--iglob", "--pattern", "*.TXT", "tests/data"]),
utils::run_cmd(&["--glob", "insensitive", "--pattern", "*.TXT", "tests/data"]),
indoc!(
"100 B ┌─ nylarlathotep.txt
161 B ├─ nemesis.txt
Expand All @@ -59,6 +59,7 @@ fn glob_with_filetype() {
assert_eq!(
utils::run_cmd(&[
"--glob",
"sensitive",
"--pattern",
"dream*",
"--file-type",
Expand All @@ -80,6 +81,7 @@ fn negated_glob_with_filetype() {
assert_eq!(
utils::run_cmd(&[
"--glob",
"sensitive",
"--pattern",
"!dream*",
"--file-type",
Expand All @@ -106,6 +108,7 @@ fn negated_glob_with_filetype() {
fn glob_empty_set_dir() {
utils::run_cmd(&[
"--glob",
"sensitive",
"--pattern",
"*.txt",
"--file-type",
Expand All @@ -117,5 +120,5 @@ fn glob_empty_set_dir() {
#[test]
#[should_panic]
fn glob_empty_set_file() {
utils::run_cmd(&["--glob", "--pattern", "*weewoo*", "tests/data"]);
utils::run_cmd(&["--glob", "sensitive", "--pattern", "*weewoo*", "tests/data"]);
}
9 changes: 8 additions & 1 deletion tests/prune.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ mod utils;
#[test]
fn prune() {
assert_eq!(
utils::run_cmd(&["--glob", "--pattern", "*.txt", "--prune", "tests/data"]),
utils::run_cmd(&[
"--glob",
"sensitive",
"--pattern",
"*.txt",
"--prune",
"tests/data"
]),
indoc!(
"100 B ┌─ nylarlathotep.txt
161 B ├─ nemesis.txt
Expand Down