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

refactor: ♻️ more functional Programming #183

Merged
merged 3 commits into from
May 28, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 3 additions & 12 deletions src/ansi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,12 @@ pub trait Escaped: AsRef<str> {
'outer: while let Some(ch) = chars.next() {
resultant.push(ch);

if ch == '\u{1b}' && !open_sequence {
if ch == '\u{1b}'{
for code in chars.by_ref() {
resultant.push(code);

if code == 'm' {
open_sequence = true;
continue 'outer;
}
}
} else if ch == '\u{1b}' && open_sequence {
for code in chars.by_ref() {
resultant.push(code);

if code == 'm' {
open_sequence = false;
open_sequence = !open_sequence;
continue 'outer;
}
}
Expand All @@ -66,7 +57,7 @@ fn truncate() {
use ansi_term::Color::Red;

let control = Red.bold().paint("Hello").to_string();
let base = format!("{}{}", Red.bold().paint("Hello World"), "!!!");
let base = format!("{}!!!", Red.bold().paint("Hello World"));
let trunc = <str as Escaped>::truncate(&base, 5);

assert_eq!(control, trunc);
Expand Down
25 changes: 12 additions & 13 deletions src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub struct Context {
dir: Option<PathBuf>,

/// Mode of coloring output
#[arg(short = 'C', long, value_enum, default_value_t = Coloring::default())]
#[arg(short = 'C', long, value_enum, default_value_t)]
pub color: Coloring,

/// Print physical or logical file size
Expand Down Expand Up @@ -145,19 +145,19 @@ pub struct Context {
pub sort: sort::Type,

/// Sort directories before or after all other file types
#[arg(long, value_enum, default_value_t = dir::Order::default())]
#[arg(long, value_enum, default_value_t)]
pub dir_order: dir::Order,

/// Number of threads to use
#[arg(short = 'T', long, default_value_t = 3)]
pub threads: usize,

/// Report disk usage in binary or SI units
#[arg(short, long, value_enum, default_value_t = PrefixKind::default())]
#[arg(short, long, value_enum, default_value_t)]
pub unit: PrefixKind,

/// Which kind of layout to use when rendering the output
#[arg(short = 'y', long, value_enum, default_value_t = layout::Type::default())]
#[arg(short = 'y', long, value_enum, default_value_t)]
pub layout: layout::Type,

/// Show hidden files
Expand Down Expand Up @@ -374,7 +374,7 @@ impl Context {
.filter(|pair| pair[1] != "false")
.flatten()
.filter(|s| s != "true")
.collect::<Vec<OsString>>();
.collect::<Vec<_>>();

args.extend(raw_args);
}
Expand All @@ -395,7 +395,7 @@ impl Context {
let file_type = self.file_type();

Ok(match file_type {
file::Type::Dir => Box::new(move |dir_entry: &DirEntry| {
file::Type::Dir => Box::new(move |dir_entry| {
let is_dir = dir_entry.file_type().map_or(false, |ft| ft.is_dir());
if is_dir {
return Self::ancestor_regex_match(dir_entry.path(), &re, 0);
Expand All @@ -404,7 +404,7 @@ impl Context {
Self::ancestor_regex_match(dir_entry.path(), &re, 1)
}),

_ => Box::new(move |dir_entry: &DirEntry| {
_ => Box::new(move |dir_entry| {
let entry_type = dir_entry.file_type();
let is_dir = entry_type.map_or(false, |ft| ft.is_dir());

Expand All @@ -419,7 +419,7 @@ impl Context {
file::Type::Link if entry_type.map_or(true, |ft| !ft.is_symlink()) => {
return false
}
_ => (),
_ => {}
}
let file_name = dir_entry.file_name().to_string_lossy();
re.is_match(&file_name)
Expand Down Expand Up @@ -455,7 +455,7 @@ impl Context {
let file_type = self.file_type();

match file_type {
file::Type::Dir => Ok(Box::new(move |dir_entry: &DirEntry| {
file::Type::Dir => Ok(Box::new(move |dir_entry| {
let is_dir = dir_entry.file_type().map_or(false, |ft| ft.is_dir());

if is_dir {
Expand All @@ -473,7 +473,7 @@ impl Context {
}
})),

_ => Ok(Box::new(move |dir_entry: &DirEntry| {
_ => Ok(Box::new(move |dir_entry| {
let entry_type = dir_entry.file_type();
let is_dir = entry_type.map_or(false, |ft| ft.is_dir());

Expand All @@ -488,7 +488,7 @@ impl Context {
file::Type::Link if entry_type.map_or(true, |ft| !ft.is_symlink()) => {
return false
}
_ => (),
_ => {},
}

let matched = overrides.matched(dir_entry.path(), false);
Expand Down Expand Up @@ -536,8 +536,7 @@ impl Context {

/// Answers whether disk usage is asked to be reported in bytes.
pub const fn byte_metric(&self) -> bool {
matches!(self.disk_usage, DiskUsage::Logical)
|| matches!(self.disk_usage, DiskUsage::Physical)
matches!(self.disk_usage, DiskUsage::Logical | DiskUsage::Physical)
}

/// Do any of the components of a path match the provided glob? This is used for ensuring that
Expand Down
18 changes: 9 additions & 9 deletions src/disk_usage/file_size/byte.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl Display for Metric {
if self.human_readable {
let unit = SiPrefix::from(self.value);

if matches!(unit, SiPrefix::Base) {
if unit == SiPrefix::Base {
format!("{} {unit}", self.value)
} else {
let base_value = unit.base_value();
Expand All @@ -128,7 +128,7 @@ impl Display for Metric {
if self.human_readable {
let unit = BinPrefix::from(self.value);

if matches!(unit, BinPrefix::Base) {
if unit == BinPrefix::Base {
format!("{} {unit}", self.value)
} else {
let base_value = unit.base_value();
Expand Down Expand Up @@ -158,7 +158,7 @@ fn test_metric() {
prefix_kind: PrefixKind::Bin,
cached_display: RefCell::<String>::default(),
};
assert_eq!(format!("{}", metric), "100 B");
assert_eq!(format!("{metric}"), "100 B");

let metric = Metric {
value: 1000,
Expand All @@ -167,7 +167,7 @@ fn test_metric() {
prefix_kind: PrefixKind::Si,
cached_display: RefCell::<String>::default(),
};
assert_eq!(format!("{}", metric), "1.0 KB");
assert_eq!(format!("{metric}"), "1.0 KB");

let metric = Metric {
value: 1000,
Expand All @@ -176,7 +176,7 @@ fn test_metric() {
prefix_kind: PrefixKind::Bin,
cached_display: RefCell::<String>::default(),
};
assert_eq!(format!("{}", metric), "1000 B");
assert_eq!(format!("{metric}"), "1000 B");

let metric = Metric {
value: 1024,
Expand All @@ -185,7 +185,7 @@ fn test_metric() {
prefix_kind: PrefixKind::Bin,
cached_display: RefCell::<String>::default(),
};
assert_eq!(format!("{}", metric), "1.0 KiB");
assert_eq!(format!("{metric}"), "1.0 KiB");

let metric = Metric {
value: 2_u64.pow(20),
Expand All @@ -194,14 +194,14 @@ fn test_metric() {
prefix_kind: PrefixKind::Bin,
cached_display: RefCell::<String>::default(),
};
assert_eq!(format!("{}", metric), "1.0 MiB");
assert_eq!(format!("{metric}"), "1.0 MiB");

let metric = Metric {
value: 123454,
value: 123_454,
kind: MetricKind::Logical,
human_readable: false,
prefix_kind: PrefixKind::Bin,
cached_display: RefCell::<String>::default(),
};
assert_eq!(format!("{}", metric), "123454 B");
assert_eq!(format!("{metric}"), "123454 B");
}
2 changes: 1 addition & 1 deletion src/disk_usage/file_size/line_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ impl Metric {
/// Reads in contents of a file given by `path` and attempts to compute the total number of
/// lines in that file. If a file is not UTF-8 encoded as in the case of a binary jpeg file
/// then `None` will be returned.
pub fn init<P: AsRef<Path>>(path: P) -> Option<Self> {
pub fn init(path: impl AsRef<Path>) -> Option<Self> {
let data = fs::read_to_string(path.as_ref()).ok()?;

let lines = data.lines().count();
Expand Down
2 changes: 1 addition & 1 deletion src/disk_usage/file_size/word_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl Metric {
/// then `None` will be returned.
///
/// Words are UTF-8 encoded byte sequences delimited by Unicode Derived Core Property `White_Space`.
pub fn init<P: AsRef<Path>>(path: P) -> Option<Self> {
pub fn init(path: impl AsRef<Path>) -> Option<Self> {
let data = fs::read_to_string(path.as_ref()).ok()?;

let words = data.split_whitespace().count();
Expand Down
4 changes: 2 additions & 2 deletions src/disk_usage/units.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub enum PrefixKind {
}

/// Binary prefixes.
#[derive(Debug)]
#[derive(Debug, PartialEq, Eq)]
pub enum BinPrefix {
Base,
Kibi,
Expand All @@ -26,7 +26,7 @@ pub enum BinPrefix {
}

/// SI prefixes.
#[derive(Debug)]
#[derive(Debug, PartialEq, Eq)]
pub enum SiPrefix {
Base,
Kilo,
Expand Down
16 changes: 7 additions & 9 deletions src/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub struct IndicatorHandle {
}

/// The different messages that could be sent to the thread that owns the [`Indicator`].
#[derive(Debug)]
#[derive(Debug, PartialEq, Eq)]
pub enum Message {
/// Message that indicates that we are currently reading from disk and that a file was indexed.
Index,
Expand All @@ -41,7 +41,7 @@ pub enum Message {
}

/// All of the different states the [`Indicator`] can be in during its life cycle.
#[derive(Default)]
#[derive(Default, PartialEq)]
enum IndicatorState {
/// We are currently reading from disk.
#[default]
Expand Down Expand Up @@ -93,28 +93,26 @@ impl Indicator {
/// through its internal states. An [`IndicatorHandle`] is returned as a mechanism to allow the
/// outside world to send messages to the worker thread and ultimately to the [`Indicator`].
pub fn measure() -> IndicatorHandle {
let (tx, rx) = mpsc::channel::<Message>();
let (tx, rx) = mpsc::channel();

let join_handle = thread::spawn(move || -> Result<(), Error> {
let join_handle = thread::spawn(move || {
let mut indicator = Self::default();

indicator.stdout.execute(cursor::SavePosition)?;
indicator.stdout.execute(cursor::Hide)?;

while let Ok(msg) = rx.recv() {
if matches!(indicator.state, IndicatorState::Indexing) {
if indicator.state == IndicatorState::Indexing {
match msg {
Message::Index => indicator.index()?,
Message::DoneIndexing => {
indicator.update_state(IndicatorState::Rendering)?;
}
Message::RenderReady => (),
Message::RenderReady => {}
}
}

if matches!(indicator.state, IndicatorState::Rendering)
&& matches!(msg, Message::RenderReady)
{
if indicator.state == IndicatorState::Rendering && msg == Message::RenderReady {
indicator.update_state(IndicatorState::Done)?;
break;
}
Expand Down
32 changes: 15 additions & 17 deletions src/render/grid/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::{
path::Path,
};


#[cfg(unix)]
use chrono::{DateTime, Local};

Expand Down Expand Up @@ -71,7 +70,7 @@ impl<'a> Cell<'a> {

match self.kind {
Kind::FileName { prefix } => {
let pre = prefix.unwrap_or("");
let pre = prefix.unwrap_or_default();
let name = theme::stylize_file_name(node);

if !ctx.icons {
Expand Down Expand Up @@ -103,11 +102,10 @@ impl<'a> Cell<'a> {
.display()
};

let formatted_path = if let Some(style) = node.style() {
format!("{}", style.paint(path.to_string()))
} else {
path.to_string()
};
let formatted_path = node.style().map_or_else(
|| path.to_string(),
|style| format!("{}", style.paint(path.to_string())),
);

if !ctx.icons {
return write!(f, "{formatted_path}");
Expand Down Expand Up @@ -147,10 +145,10 @@ impl<'a> Cell<'a> {

let max_width = ctx.max_nlink_width;

let out = node
.nlink()
.map(|num| format!("{num:>max_width$}"))
.unwrap_or(format!("{PLACEHOLDER:>max_width$}"));
let out = node.nlink().map_or_else(
|| format!("{PLACEHOLDER:>max_width$}"),
|num| format!("{num:>max_width$}"),
);

let formatted_nlink = if let Ok(style) = styles::get_nlink_style() {
style.paint(out).to_string()
Expand All @@ -170,10 +168,10 @@ impl<'a> Cell<'a> {

let max_width = ctx.max_ino_width;

let out = node
.ino()
.map(|num| format!("{num:>max_width$}"))
.unwrap_or(format!("{PLACEHOLDER:>max_width$}"));
let out = node.ino().map_or_else(
|| format!("{PLACEHOLDER:>max_width$}"),
|num| format!("{num:>max_width$}"),
);

let formatted_ino = if let Ok(style) = styles::get_ino_style() {
style.paint(out).to_string()
Expand All @@ -190,7 +188,7 @@ impl<'a> Cell<'a> {
fn fmt_owner(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let max_owner_width = self.ctx.max_owner_width;

let owner = self.node.owner().map_or(styles::PLACEHOLDER, |o| o);
let owner = self.node.owner().unwrap_or(styles::PLACEHOLDER);

if let Ok(style) = styles::get_owner_style() {
let formatted_owner = format!("{owner:>max_owner_width$}");
Expand All @@ -206,7 +204,7 @@ impl<'a> Cell<'a> {
fn fmt_group(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let max_group_width = self.ctx.max_group_width;

let group = self.node.group().map_or(styles::PLACEHOLDER, |o| o);
let group = self.node.group().unwrap_or(styles::PLACEHOLDER);

if let Ok(style) = styles::get_group_style() {
let formatted_group = format!("{group:>max_group_width$}");
Expand Down
Loading