Skip to content

Commit

Permalink
Avoid passing pls everywhere by using LazyLock
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvkb committed Sep 11, 2024
1 parent ca1bcdb commit 5e769f1
Show file tree
Hide file tree
Showing 12 changed files with 81 additions and 88 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ keywords = ["cli", "terminal", "posix", "ls"]
categories = ["command-line-utilities"]

edition = "2021"
rust-version = "1.70.0"
rust-version = "1.80.0"

[[bin]]
name = "pls"
Expand Down
31 changes: 15 additions & 16 deletions src/args/dir_group.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::args::input::Input;
use crate::enums::DetailField;
use crate::exc::Exc;
use crate::models::{Node, OwnerMan, Pls};
use crate::models::{Node, OwnerMan};
use crate::traits::Imp;
use crate::PLS;
use log::debug;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
Expand Down Expand Up @@ -43,13 +44,12 @@ impl DirGroup {
pub fn entries(
&self,
owner_man: &mut OwnerMan,
pls: &Pls,
) -> Result<Vec<HashMap<DetailField, String>>, Exc> {
let mut nodes = self.nodes(pls)?;
if pls.args.collapse {
let mut nodes = self.nodes()?;
if PLS.args.collapse {
nodes = Self::make_tree(nodes);
}
Self::re_sort(&mut nodes, owner_man, pls);
Self::re_sort(&mut nodes, owner_man);

let entries = nodes
.iter()
Expand All @@ -59,7 +59,6 @@ impl DirGroup {
&self.input.conf,
&self.input.conf.app_const,
&self.input.conf.entry_const,
pls,
&[],
None,
)
Expand All @@ -84,12 +83,12 @@ impl DirGroup {
///
/// If any criteria is not met, the node is not to be rendered and `None` is
/// returned.
fn node(&self, entry: DirEntry, pls: &Pls) -> Option<Node> {
fn node(&self, entry: DirEntry) -> Option<Node> {
let name = entry.file_name();
debug!("Checking visibility of name {name:?}.");
let haystack = name.as_bytes();

let include = pls
let include = PLS
.args
.only
.as_ref()
Expand All @@ -99,7 +98,7 @@ impl DirGroup {
return None;
}

let exclude = pls
let exclude = PLS
.args
.exclude
.as_ref()
Expand All @@ -112,13 +111,13 @@ impl DirGroup {
let mut node = Node::new(&entry.path());

debug!("Checking visibility of typ {:?}.", node.typ);
if !pls.args.typs.contains(&node.typ) {
if !PLS.args.typs.contains(&node.typ) {
return None;
}

node.match_specs(&self.input.conf.specs);

if !node.is_visible(&self.input.conf, pls) {
if !node.is_visible(&self.input.conf) {
return None;
}

Expand All @@ -129,11 +128,11 @@ impl DirGroup {
///
/// Unlike [`FilesGroup`](crate::args::files_group::FilesGroup), this
/// function filters out nodes based on visibility.
fn nodes(&self, pls: &Pls) -> Result<Vec<Node>, Exc> {
fn nodes(&self) -> Result<Vec<Node>, Exc> {
let entries = self.input.path.read_dir().map_err(Exc::Io)?;

let entries = entries
.filter_map(|entry| entry.ok().and_then(|entry| self.node(entry, pls)))
.filter_map(|entry| entry.ok().and_then(|entry| self.node(entry)))
.collect();
Ok(entries)
}
Expand All @@ -147,15 +146,15 @@ impl DirGroup {
/// This function iterates over all the sort bases and sorts the given list
/// of nodes. It is invoked both from the top-level and from each parent
/// node to sort its children.
fn re_sort(nodes: &mut [Node], owner_man: &mut OwnerMan, pls: &Pls) {
fn re_sort(nodes: &mut [Node], owner_man: &mut OwnerMan) {
if nodes.len() <= 1 {
return;
}
pls.args.sort_bases.iter().rev().for_each(|field| {
PLS.args.sort_bases.iter().rev().for_each(|field| {
nodes.sort_by(|a, b| field.compare(a, b, owner_man));
});
for node in nodes {
Self::re_sort(&mut node.children, owner_man, pls);
Self::re_sort(&mut node.children, owner_man);
}
}

Expand Down
9 changes: 2 additions & 7 deletions src/args/files_group.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::args::input::Input;
use crate::config::{Conf, ConfMan};
use crate::enums::DetailField;
use crate::models::{Node, OwnerMan, Pls};
use crate::models::{Node, OwnerMan};
use crate::utils::paths::common_ancestor;
use log::debug;
use std::collections::HashMap;
Expand Down Expand Up @@ -54,11 +54,7 @@ impl FilesGroup {
/// Since individual nodes are not nested, the function uses each node's
/// [`Node::row`] instead of the flattened output of each node's
/// [`Node::entries`].
pub fn entries(
&self,
owner_man: &mut OwnerMan,
pls: &Pls,
) -> Vec<HashMap<DetailField, String>> {
pub fn entries(&self, owner_man: &mut OwnerMan) -> Vec<HashMap<DetailField, String>> {
self.nodes()
.iter()
.map(|(node, conf)| {
Expand All @@ -67,7 +63,6 @@ impl FilesGroup {
conf,
&self.parent_conf.app_const,
&conf.entry_const,
pls,
&[],
)
})
Expand Down
17 changes: 8 additions & 9 deletions src/args/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use crate::enums::{DetailField, Typ};
use crate::exc::Exc;
use crate::fmt::render;
use crate::models::OwnerMan;
use crate::models::Pls;
use crate::output::{Grid, Table};
use crate::PLS;
use std::collections::HashMap;

// ======
Expand Down Expand Up @@ -53,7 +53,7 @@ impl Group {
groups
}

pub fn render(&self, show_title: bool, owner_man: &mut OwnerMan, pls: &Pls) -> Result<(), Exc> {
pub fn render(&self, show_title: bool, owner_man: &mut OwnerMan) -> Result<(), Exc> {
if show_title {
if let Self::Dir(group) = self {
println!(
Expand All @@ -63,14 +63,14 @@ impl Group {
}
}

let entries = self.entries(owner_man, pls)?;
let entries = self.entries(owner_man)?;

if pls.args.grid {
if PLS.args.grid {
let grid = Grid::new(entries);
grid.render(&self.conf().app_const, pls);
grid.render(&self.conf().app_const);
} else {
let table = Table::new(entries, matches!(self, Self::Files(_)));
table.render(&self.conf().app_const, pls);
table.render(&self.conf().app_const);
}

Ok(())
Expand All @@ -93,11 +93,10 @@ impl Group {
pub fn entries(
&self,
owner_man: &mut OwnerMan,
pls: &Pls,
) -> Result<Vec<HashMap<DetailField, String>>, Exc> {
match self {
Self::Dir(group) => group.entries(owner_man, pls),
Self::Files(group) => Ok(group.entries(owner_man, pls)),
Self::Dir(group) => group.entries(owner_man),
Self::Files(group) => Ok(group.entries(owner_man)),
}
}
}
6 changes: 3 additions & 3 deletions src/enums/sym.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::config::Conf;
use crate::exc::Exc;
use crate::models::{Node, Pls};
use crate::models::Node;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

Expand Down Expand Up @@ -44,7 +44,7 @@ pub enum SymTarget<'node> {

impl<'node> SymTarget<'node> {
/// Print the symlink target.
pub fn print(&self, conf: &Conf, pls: &Pls) -> String {
pub fn print(&self, conf: &Conf) -> String {
let state = self.into();
let sym_conf = conf.entry_const.symlink.get(&state).unwrap();
let directives = &sym_conf.style;
Expand All @@ -53,7 +53,7 @@ impl<'node> SymTarget<'node> {

match self {
SymTarget::Ok(node) => {
let path = node.display_name(conf, &conf.app_const, &conf.entry_const, pls, &[]);
let path = node.display_name(conf, &conf.app_const, &conf.entry_const, &[]);
format!(" <{directives}>{sep}</> <{ref_directives}>{path}</>")
}
SymTarget::Broken(path) | SymTarget::Cyclic(path) => {
Expand Down
8 changes: 5 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ mod output;
mod traits;
mod utils;

use crate::models::Pls;

use log::debug;
use std::sync::LazyLock;

use crate::models::Pls;
static PLS: LazyLock<Pls> = LazyLock::new(Pls::default);

/// Create a `Pls` instance and immediately delegate to it.
///
Expand All @@ -21,8 +24,7 @@ fn main() {
env_logger::init();
debug!("Hello!");

let mut pls = Pls::default();
pls.run();
PLS.run();

debug!("Bye!");
}
36 changes: 16 additions & 20 deletions src/models/node.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::config::{AppConst, Conf, EntryConst};
use crate::enums::{Appearance, Collapse, DetailField, Typ};
use crate::models::{OwnerMan, Pls, Spec};
use crate::models::{OwnerMan, Spec};
use crate::traits::{Detail, Imp, Name, Sym};
use crate::PLS;
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use std::fmt::{Display, Formatter, Result as FmtResult};
Expand Down Expand Up @@ -153,11 +154,11 @@ impl<'pls> Node<'pls> {
///
/// * the node's type
/// * specs associated with the node
fn directives(&self, app_const: &AppConst, entry_const: &EntryConst, pls: &Pls) -> String {
fn directives(&self, app_const: &AppConst, entry_const: &EntryConst) -> String {
let mut directives = String::from(self.typ.directives(entry_const));

if !self.appearances.contains(&Appearance::Symlink) {
let imp_dir = Imp::directives(self, app_const, pls);
let imp_dir = Imp::directives(self, app_const);
if let Some(directive) = imp_dir {
directives.push(' ');
directives.push_str(&directive);
Expand Down Expand Up @@ -215,25 +216,24 @@ impl<'pls> Node<'pls> {
conf: &Conf,
app_const: &AppConst,
entry_const: &EntryConst,
pls: &Pls,
tree_shapes: &[&str],
) -> String {
let text_directives = self.directives(app_const, entry_const, pls);
let text_directives = self.directives(app_const, entry_const);
let icon_directives = text_directives.replace("underline", "");

let mut parts = String::default();

// Tree shape
if self.appearances.contains(&Appearance::TreeChild) {
let offset = " ".repeat(if pls.args.align { 3 } else { 2 });
let offset = " ".repeat(if PLS.args.align { 3 } else { 2 });
parts.push_str(&tree_shapes.iter().fold(String::new(), |mut acc, shape| {
let _ = write!(acc, "{offset}{shape}"); // `write!`-ing into a `String` can never fail.
acc
}));
}

// Icon
if pls.args.icon && !self.appearances.contains(&Appearance::Symlink) {
if PLS.args.icon && !self.appearances.contains(&Appearance::Symlink) {
parts.push_str(&format!(
"<{icon_directives}>{:<1}</> ",
self.icon(conf, entry_const),
Expand All @@ -242,23 +242,23 @@ impl<'pls> Node<'pls> {

// Name and suffix
parts.push_str(&format!("<{text_directives}>"));
if !&pls.args.align
if !PLS.args.align
|| self.appearances.contains(&Appearance::Symlink)
|| self.appearances.contains(&Appearance::SoloFile)
{
parts.push_str(&self.display_name)
} else {
parts.push_str(&self.aligned_name())
}
if pls.args.suffix && !self.appearances.contains(&Appearance::Symlink) {
if PLS.args.suffix && !self.appearances.contains(&Appearance::Symlink) {
// Symlink should not have suffix because it should show the path reference without modifications
parts.push_str(self.typ.suffix(entry_const))
};
parts.push_str("</>");

if pls.args.sym {
if PLS.args.sym {
if let Some(target) = self.target() {
parts.push_str(&target.print(conf, pls));
parts.push_str(&target.print(conf));
}
}

Expand All @@ -274,7 +274,6 @@ impl<'pls> Node<'pls> {
detail: DetailField,
owner_man: &mut OwnerMan,
entry_const: &EntryConst,
pls: &Pls,
) -> String {
let val = match detail {
// `Detail` trait
Expand All @@ -291,7 +290,7 @@ impl<'pls> Node<'pls> {
DetailField::Mtime => self.time(detail, entry_const),
DetailField::Ctime => self.time(detail, entry_const),
DetailField::Atime => self.time(detail, entry_const),
DetailField::Size => self.size(entry_const, pls),
DetailField::Size => self.size(entry_const),
DetailField::Blocks => self.blocks(entry_const),
// `Typ` enum
DetailField::Typ => Some(self.typ.ch(entry_const)),
Expand All @@ -309,20 +308,19 @@ impl<'pls> Node<'pls> {
conf: &Conf,
app_const: &AppConst,
entry_const: &EntryConst,
pls: &Pls,
tree_shape: &[&str],
) -> HashMap<DetailField, String> {
pls.args
PLS.args
.details
.iter()
.map(|&detail| {
if detail == DetailField::Name {
(
detail,
self.display_name(conf, app_const, entry_const, pls, tree_shape),
self.display_name(conf, app_const, entry_const, tree_shape),
)
} else {
(detail, self.get_value(detail, owner_man, entry_const, pls))
(detail, self.get_value(detail, owner_man, entry_const))
}
})
.collect()
Expand All @@ -339,7 +337,6 @@ impl<'pls> Node<'pls> {
conf: &Conf,
app_const: &AppConst,
entry_const: &EntryConst,
pls: &Pls,
parent_shapes: &[&str], // list of shapes inherited from the parent
own_shape: Option<&str>, // shape to show just before the current node
) -> Vec<HashMap<DetailField, String>> {
Expand All @@ -362,7 +359,7 @@ impl<'pls> Node<'pls> {
all_shapes.push(more_shape);
}

once(self.row(owner_man, conf, app_const, entry_const, pls, &all_shapes))
once(self.row(owner_man, conf, app_const, entry_const, &all_shapes))
.chain(self.children.iter().enumerate().flat_map(|(idx, child)| {
let child_own_shape = if idx == self.children.len() - 1 {
&app_const.tree.bend_dash
Expand All @@ -375,7 +372,6 @@ impl<'pls> Node<'pls> {
conf,
app_const,
entry_const,
pls,
&child_parent_shapes,
Some(child_own_shape),
)
Expand Down
Loading

0 comments on commit 5e769f1

Please sign in to comment.