Skip to content

Commit

Permalink
configs
Browse files Browse the repository at this point in the history
  • Loading branch information
solidiquis committed May 5, 2024
1 parent d915132 commit 5e4da13
Show file tree
Hide file tree
Showing 13 changed files with 334 additions and 154 deletions.
29 changes: 4 additions & 25 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ keywords = ["tree", "find", "ls", "du", "commandline"]
exclude = ["assets/*", "scripts/*", "example/*"]
readme = "README.md"
license = "MIT"
rust-version = "1.76.0"
rust-version = "1.78.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand All @@ -36,7 +36,7 @@ anyhow = "1.0.75"
chrono = { version = "0.4.24", default-features = false, features = ["clock", "std"] }
clap = { version = "4.4.10", features = ["derive"] }
clap_complete = "4.1.1"
config = { version = "0.13.3", default-features = false, features = ["toml"] }
config = { version = "0.14.0", default-features = false, features = ["toml"] }
crossterm = "0.26.1"
ctrlc = "3.4.0"
dirs = "5.0"
Expand Down
17 changes: 10 additions & 7 deletions src/file/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ impl File {

#[cfg(unix)]
let unix_attrs = long
.long
.then(|| unix::Attrs::from((&metadata, &data)))
.unwrap_or_else(unix::Attrs::default);

Expand Down Expand Up @@ -173,20 +174,22 @@ impl File {
pub fn timestamp_from_ctx(&self, ctx: &Context) -> Option<String> {
use chrono::{DateTime, Local};

let system_time = match ctx.time {
let system_time = match ctx.long.time.unwrap_or_default() {
TimeStamp::Mod => self.metadata().accessed().ok(),
TimeStamp::Create => self.metadata().created().ok(),
TimeStamp::Access => self.metadata().accessed().ok(),
};

system_time
.map(DateTime::<Local>::from)
.map(|local_time| match ctx.time_format {
TimeFormat::Default => local_time.format("%d %h %H:%M %g"),
TimeFormat::Iso => local_time.format("%Y-%m-%d %H:%M:%S"),
TimeFormat::IsoStrict => local_time.format("%Y-%m-%dT%H:%M:%S%Z"),
TimeFormat::Short => local_time.format("%Y-%m-%d"),
})
.map(
|local_time| match ctx.long.time_format.unwrap_or_default() {
TimeFormat::Default => local_time.format("%d %h %H:%M %g"),
TimeFormat::Iso => local_time.format("%Y-%m-%d %H:%M:%S"),
TimeFormat::IsoStrict => local_time.format("%Y-%m-%dT%H:%M:%S%Z"),
TimeFormat::Short => local_time.format("%Y-%m-%d"),
},
)
.map(|dt| format!("{dt}"))
}

Expand Down
13 changes: 7 additions & 6 deletions src/file/tree/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
file::{tree::Tree, File},
user::{
args::{FileType, Layout},
Context, Globbing,
Context, Search,
},
};
use ahash::HashSet;
Expand Down Expand Up @@ -31,8 +31,8 @@ impl Tree {
self.filter_file_type(ctx);
}

if ctx.pattern.is_some() {
let Globbing { glob, iglob } = ctx.globbing;
if ctx.search.pattern.is_some() {
let Search { glob, iglob, .. } = ctx.search;

if glob || iglob {
self.filter_glob(ctx)?;
Expand Down Expand Up @@ -123,7 +123,9 @@ impl Tree {
pub fn filter_regex(
&mut self,
Context {
pattern, layout, ..
search: Search { pattern, .. },
layout,
..
}: &Context,
) -> Result<()> {
let re_pattern = pattern
Expand Down Expand Up @@ -174,8 +176,7 @@ impl Tree {
/// Filtering via globbing
fn filter_glob(&mut self, ctx: &Context) -> Result<()> {
let Context {
globbing: Globbing { iglob, .. },
pattern,
search: Search { pattern, iglob, .. },
layout,
..
} = ctx;
Expand Down
8 changes: 0 additions & 8 deletions src/file/unix/ug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,6 @@ impl UserGroupInfo for Metadata {}

/// Trait that allows for files to query their owner and group.
pub trait UserGroupInfo: MetadataExt {
/// Attemps to query the owner of the implementor.
fn try_get_owner(&self) -> Result<String, Error> {
unsafe {
let uid = self.uid();
try_get_user(uid)
}
}

/// Attempts to query both the owner and group of the implementor.
fn try_get_owner_and_group(&self) -> Result<(Owner, Group), Error> {
unsafe {
Expand Down
12 changes: 8 additions & 4 deletions src/render/row/long.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,14 @@ impl From<INodeError> for fmt::Error {
impl Display for Format<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Context {
group: enable_group,
ino: enable_ino,
nlink: enable_nlink,
octal: enable_octal,
long:
crate::user::Long {
group: enable_group,
ino: enable_ino,
nlink: enable_nlink,
octal: enable_octal,
..
},
column_metadata,
..
} = self.ctx;
Expand Down
4 changes: 2 additions & 2 deletions src/render/row/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub fn formatter<'a>(buf: &'a mut String, ctx: &'a Context) -> Result<RowFormatt
Layout::Flat => {
let root = ctx.dir_canonical()?;

match (ctx.long, ctx.suppress_size) {
match (ctx.long.long, ctx.suppress_size) {
(false, false) => Ok(Box::new(move |file, prefix| {
let size = format!("{}", file.size());
let base = root.ancestors().nth(1);
Expand Down Expand Up @@ -75,7 +75,7 @@ pub fn formatter<'a>(buf: &'a mut String, ctx: &'a Context) -> Result<RowFormatt
})),
}
},
_ => match (ctx.long, ctx.suppress_size) {
_ => match (ctx.long.long, ctx.suppress_size) {
(false, false) => Ok(Box::new(|file, prefix| {
let size = format!("{}", file.size());
let name = file.display_name();
Expand Down
4 changes: 1 addition & 3 deletions src/user/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
const ERDTREE_CONFIG_TOML: &str = ".erdtree.toml";
const ERDTREE_CONFIG_FILE: &str = ".erdtree";
const ERDTREE_TOML_PATH: &str = "ERDTREE_TOML_PATH";

const ERDTREE_CONFIG_NAME: &str = ".erdtreerc";
const ERDTREE_CONFIG_PATH: &str = "ERDTREE_CONFIG_PATH";

const ERDTREE_DIR: &str = "erdtree";

#[cfg(unix)]
Expand Down
53 changes: 22 additions & 31 deletions src/user/config/parse.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
use crate::user;
use ahash::HashMap;
use clap::{
ArgMatches,
Command,
CommandFactory,
error::Error as ClapError,
FromArgMatches,
Parser
};
use clap::{error::Error as ClapError, ArgMatches, CommandFactory};
use config::{Config, ConfigError};
use toml::Value;

Expand All @@ -20,7 +12,7 @@ pub enum Error {
TableNotFound(String),

#[error("Error while parsing config arguments: {0}")]
Parse(#[from] ClapError)
Parse(#[from] ClapError),
}

type Result<T> = std::result::Result<T, Error>;
Expand All @@ -31,7 +23,7 @@ pub fn args(conf: Config, table_name: Option<&str>) -> Result<Option<ArgMatches>
let maybe_config = conf.try_deserialize::<toml::Table>().map(|raw_config| {
deep_transform_keys(raw_config, |mut key| {
key.make_ascii_lowercase();
format!("--{}", key.replace("_", "-"))
format!("--{}", key.replace('_', "-"))
})
})?;

Expand All @@ -43,10 +35,10 @@ pub fn args(conf: Config, table_name: Option<&str>) -> Result<Option<ArgMatches>
Some(name) => match config.remove(&format!("--{name}")) {
Some(Value::Table(sub_table)) => {
config = sub_table;
}
},
_ => return Err(Error::TableNotFound(name.to_string())),
}
None => remove_sub_tables(&mut config)
},
None => remove_sub_tables(&mut config),
}

let arg_matches = into_args(config)?;
Expand All @@ -66,33 +58,32 @@ fn into_args(conf: TomlConfig) -> Result<ArgMatches> {
args.push(farg)
}
}
}
},
Value::Boolean(arg) if arg => {
args.push(arg_name.clone());
}
},
_ => {
if let Some(farg) = fmt_arg(param) {
args.push(arg_name.clone());
args.push(farg)
}
}
},
}
}

let cmd = crate::user::Context::command()
.try_get_matches_from(args)?;
let cmd = crate::user::Context::command().try_get_matches_from(args)?;

Ok(cmd)
}

/// Formats basic primitive types into OS args. Will ignore table and array types.
fn fmt_arg(val: Value) -> Option<String> {
match val {
Value::Float(p) => Some(format!("{p}")),
Value::String(p) => Some(format!("{p}")),
Value::Datetime(p) => Some(format!("{p}")),
Value::Integer(p) => Some(format!("{p}")),
_ => None
Value::Float(p) => Some(p.to_string()),
Value::String(p) => Some(p.to_string()),
Value::Datetime(p) => Some(p.to_string()),
Value::Integer(p) => Some(p.to_string()),
_ => None,
}
}

Expand All @@ -115,7 +106,7 @@ fn deep_transform_keys(toml: TomlConfig, transformer: KeyTransformer) -> Option<
let mut dfs_stack_src = vec![Value::Table(toml)];
let mut dfs_stack_dst = vec![("".to_string(), toml::map::Map::default())];

let mut key_iters = HashMap::default();
let mut key_iters = HashMap::default();

'outer: while !dfs_stack_src.is_empty() {
let Some(Value::Table(current_node)) = dfs_stack_src.last_mut() else {
Expand All @@ -126,9 +117,9 @@ fn deep_transform_keys(toml: TomlConfig, transformer: KeyTransformer) -> Option<
continue;
};

let keys = key_iters.entry(dst_key.clone()).or_insert_with(|| {
current_node.keys().cloned().collect::<Vec<_>>().into_iter()
});
let keys = key_iters
.entry(dst_key.clone())
.or_insert_with(|| current_node.keys().cloned().collect::<Vec<_>>().into_iter());

for key in keys {
match current_node.remove(&key) {
Expand All @@ -138,12 +129,12 @@ fn deep_transform_keys(toml: TomlConfig, transformer: KeyTransformer) -> Option<
dfs_stack_dst.push((transformed_key, toml::map::Map::default()));
dfs_stack_src.push(value);
continue 'outer;
}
},
_ => {
let transformed_key = transformer(key);
copy_dst.insert(transformed_key, value);
}
}
},
},
None => continue,
}
}
Expand Down
9 changes: 4 additions & 5 deletions src/user/config/test.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use crate::user::args::{Layout, Metric};
use super::parse;
use std::env::current_dir;
use crate::user::args::{Layout, Metric};
use config::{Config, File};

#[test]
fn test_toml_parse_top_level_table() {
let config = load_example();

let arg_matches = parse::args(config, None)
let arg_matches = parse::args(config, None)
.expect("Failed to parse example config.")
.expect("Expected top level table to be found.");

Expand All @@ -19,7 +18,7 @@ fn test_toml_parse_top_level_table() {
fn test_toml_parse_sub_table() {
let config = load_example();

let arg_matches = parse::args(config, Some("du"))
let arg_matches = parse::args(config, Some("du"))
.expect("Failed to parse example config.")
.expect("Expected sub table to be found.");

Expand All @@ -34,7 +33,7 @@ fn test_toml_parse_sub_table() {
}

fn load_example() -> Config {
let example_config = current_dir()
let example_config = std::env::current_dir()
.ok()
.map(|p| p.join("example").join(super::ERDTREE_CONFIG_TOML))
.and_then(|p| p.as_path().to_str().map(File::with_name))
Expand Down
Loading

0 comments on commit 5e4da13

Please sign in to comment.