diff --git a/Cargo.lock b/Cargo.lock index 505a9649..a9e7e426 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -44,15 +44,16 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.4" +version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab91ebe16eb252986481c5b62f6098f3b698a45e34b5b98200cf20dd2484a44" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", + "is_terminal_polyfill", "utf8parse", ] @@ -114,6 +115,12 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +[[package]] +name = "bitflags" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" + [[package]] name = "bstr" version = "1.3.0" @@ -156,9 +163,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.10" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fffed7514f420abec6d183b1d3acfd9099c79c3a10a06ade4f8203f1411272" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" dependencies = [ "clap_builder", "clap_derive", @@ -166,9 +173,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.9" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63361bae7eef3771745f02d8d892bec2fee5f6e34af316ba556e7f97a7069ff1" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" dependencies = [ "anstream", "anstyle", @@ -187,9 +194,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.4.7" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" dependencies = [ "heck", "proc-macro2", @@ -199,9 +206,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "colorchoice" @@ -230,11 +237,11 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "crossterm" -version = "0.26.1" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a84cda67535339806297f1b331d6dd6320470d2a0fe65381e79ee9e156dd3d13" +checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" dependencies = [ - "bitflags", + "bitflags 2.5.0", "crossterm_winapi", "libc", "mio", @@ -246,9 +253,9 @@ dependencies = [ [[package]] name = "crossterm_winapi" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" dependencies = [ "winapi", ] @@ -309,7 +316,6 @@ dependencies = [ "indextree", "indoc", "libc", - "log", "lscolors", "once_cell", "regex", @@ -409,9 +415,9 @@ checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" [[package]] name = "heck" -version = "0.4.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" @@ -501,6 +507,12 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" + [[package]] name = "js-sys" version = "0.3.64" @@ -590,7 +602,7 @@ version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfdda3d196821d6af13126e40375cdf7da646a96114af134d5f417a9a1dc8e1a" dependencies = [ - "bitflags", + "bitflags 1.3.2", "cfg-if", "libc", "static_assertions", @@ -637,9 +649,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.17.1" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "overload" @@ -700,7 +712,7 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] @@ -737,7 +749,7 @@ version = "0.36.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd5c6ff11fecd55b40746d1995a02f2eb375bf8c00d192d521ee09f42bef37bc" dependencies = [ - "bitflags", + "bitflags 1.3.2", "errno 0.2.8", "io-lifetimes", "libc", @@ -751,7 +763,7 @@ version = "0.37.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2aae838e49b3d63e9274e1c01833cc8139d3fec468c3b84688c628f44b1ae11d" dependencies = [ - "bitflags", + "bitflags 1.3.2", "errno 0.3.1", "io-lifetimes", "libc", @@ -805,9 +817,9 @@ dependencies = [ [[package]] name = "signal-hook" -version = "0.3.15" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9" +checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", "signal-hook-registry", @@ -856,9 +868,9 @@ dependencies = [ [[package]] name = "strsim" -version = "0.10.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" diff --git a/Cargo.toml b/Cargo.toml index 78c96036..49cf6832 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,19 +34,18 @@ ahash = "0.8.6" ansi_term = "0.12.1" anyhow = "1.0.75" chrono = { version = "0.4.24", default-features = false, features = ["clock", "std"] } -clap = { version = "4.4.10", features = ["derive"] } +clap = { version = "4.5.4", features = ["derive"] } clap_complete = "4.1.1" config = { version = "0.14.0", default-features = false, features = ["toml"] } -crossterm = "0.26.1" +crossterm = "0.27.0" ctrlc = "3.4.0" dirs = "5.0" errno = "0.3.1" filesize = "0.2.0" ignore = "0.4.2" indextree = "4.6.0" -log = { version = "0.4.20", features = ["std"] } lscolors = { version = "0.13.0", features = ["ansi_term"] } -once_cell = "1.17.0" +once_cell = "1.19.0" regex = "1.7.3" terminal_size = "0.2.6" thiserror = "1.0.40" diff --git a/rustfmt.toml b/rustfmt.toml deleted file mode 100644 index 8c795ae5..00000000 --- a/rustfmt.toml +++ /dev/null @@ -1 +0,0 @@ -match_block_trailing_comma = true diff --git a/src/disk/mod.rs b/src/disk/mod.rs index 044407f1..80d86e94 100644 --- a/src/disk/mod.rs +++ b/src/disk/mod.rs @@ -119,10 +119,7 @@ impl Usage { std::fs::read_to_string(data.path()).map(|data| data.split_whitespace().count())?; let word_count = u64::try_from(word_count).map_or_else( - |e| { - log::warn!("Usage::init_word_count {e}"); - Self::WordCount(word_count as u64) - }, + |_| Self::WordCount(word_count as u64), Self::WordCount, ); @@ -144,10 +141,7 @@ impl Usage { let line_count = fs::read_to_string(data.path()).map(|data| data.lines().count())?; let line_count = u64::try_from(line_count).map_or_else( - |e| { - log::warn!("Usage::init_line_count {e}"); - Self::WordCount(line_count as u64) - }, + |_| Self::WordCount(line_count as u64), Self::LineCount, ); diff --git a/src/file/mod.rs b/src/file/mod.rs index 473bbfdb..75650128 100644 --- a/src/file/mod.rs +++ b/src/file/mod.rs @@ -46,6 +46,14 @@ pub struct File { unix_attrs: unix::Attrs, } +// For keeping track of the count of file-types while loading from disk. +#[derive(Default)] +pub struct Accumulator { + num_file: usize, + num_dir: usize, + num_link: usize, +} + /// [`Display`] implementation concerned with human-readable presentation of the file-name. pub struct DisplayName<'a> { file: &'a File, @@ -246,6 +254,26 @@ impl Deref for File { } } +impl Accumulator { + pub fn total(&self) -> usize { + self.num_dir + self.num_file + self.num_link + } + + pub fn increment(&mut self, ft: Option) { + let Some(file_type) = ft else { + return + }; + + if file_type.is_file() { + self.num_file += 1; + } else if file_type.is_dir() { + self.num_dir += 1; + } else if file_type.is_symlink() { + self.num_link += 1; + } + } +} + impl Display for DisplayName<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let file_name = self.file.file_name().to_string_lossy(); diff --git a/src/file/tree/mod.rs b/src/file/tree/mod.rs index afaa8c22..034adce8 100644 --- a/src/file/tree/mod.rs +++ b/src/file/tree/mod.rs @@ -2,6 +2,7 @@ use super::order; use crate::{ error::prelude::*, file::File, + progress, user::{ args::{Layout, Sort, SortType}, column, Context, @@ -41,13 +42,13 @@ pub enum TreeError { impl Tree { /// Like [`Tree::init`] but leverages parallelism for disk-reads and [`File`] initialization. - pub fn init(ctx: &Context) -> Result<(Self, column::Metadata)> { - let TransitionState { + pub fn init(ctx: &Context) -> Result<(Self, super::Accumulator, column::Metadata)> { + let (TransitionState { mut arena, mut branches, mut column_metadata, root_id, - } = Self::load(ctx)?; + }, accumulator)= Self::load(ctx)?; let mut dir_stack = vec![root_id]; let mut inode_set = HashSet::default(); @@ -83,23 +84,15 @@ impl Tree { continue 'outer; } - match dirent_node.inode() { - Ok(inode) => { - #[cfg(unix)] - column_metadata.update_inode_attr_widths(&inode); - - *current_dirsize += inode_set - .insert(inode) - .then(|| dirent_node.size().value()) - .unwrap_or(0); - }, - Err(err) => { - log::warn!( - "Failed to query inode of {} which may affect disk usage report: {err}", - dirent_node.path().display(), - ); - }, - }; + if let Ok(inode) = dirent_node.inode() { + #[cfg(unix)] + column_metadata.update_inode_attr_widths(&inode); + + *current_dirsize += inode_set + .insert(inode) + .then(|| dirent_node.size().value()) + .unwrap_or(0); + } } dir_stack.pop(); @@ -175,16 +168,16 @@ impl Tree { let tree = Self { root_id, arena }; - Ok((tree, column_metadata)) + Ok((tree, accumulator, column_metadata)) } - pub fn init_without_disk_usage(ctx: &Context) -> Result<(Self, column::Metadata)> { - let TransitionState { + pub fn init_without_disk_usage(ctx: &Context) -> Result<(Self, super::Accumulator, column::Metadata)> { + let (TransitionState { mut arena, mut branches, mut column_metadata, root_id, - } = Self::load(ctx)?; + }, accumulator)= Self::load(ctx)?; #[cfg(unix)] macro_rules! update_metadata { @@ -256,16 +249,20 @@ impl Tree { let tree = Self { root_id, arena }; - Ok((tree, column_metadata)) + Ok((tree, accumulator, column_metadata)) } /// Reads data from disk and aggregates data along with metadata into a [`TransitionState`] /// which callers would then consume to construct a [`Tree`]. - fn load(ctx: &Context) -> Result { + fn load(ctx: &Context) -> Result<(TransitionState, super::Accumulator)> { let mut arena = Arena::new(); let mut branches = HashMap::>::default(); let mut column_metadata = column::Metadata::default(); let mut maybe_root_id = None; + let mut accumulator = super::Accumulator::default(); + + // To notify the progress indicator + let notifier = progress::Indicator::use_notifier(); traverse::run(ctx, |file| { #[cfg(unix)] @@ -275,6 +272,9 @@ impl Tree { let file = arena[node_id].get(); let file_path = file.path(); + accumulator.increment(file.file_type()); + progress::Indicator::notify(¬ifier, accumulator.total()); + maybe_root_id = (file.depth() == 0).then_some(node_id).or(maybe_root_id); if let Some(parent) = file_path.parent() { @@ -287,17 +287,21 @@ impl Tree { Ok(()) })?; + progress::Indicator::finish(¬ifier); + let root_id = maybe_root_id .ok_or(TreeError::RootDir) .into_report(ErrorCategory::Internal) .context(error_source!())?; - Ok(TransitionState { + let ts = TransitionState { arena, branches, column_metadata, root_id, - }) + }; + + Ok((ts, accumulator)) } pub fn root_id(&self) -> NodeId { diff --git a/src/file/tree/traverse.rs b/src/file/tree/traverse.rs index 3ebbd54c..dd725fd1 100644 --- a/src/file/tree/traverse.rs +++ b/src/file/tree/traverse.rs @@ -24,9 +24,9 @@ where loop { match rx.recv().into_report(ErrorCategory::Internal) { Ok(TraversalState::Ongoing(file)) => op(file)?, - Ok(TraversalState::Error(e)) => log::warn!("{e}"), Ok(TraversalState::Done) => break, Err(e) => return Err(e), + _ => (), } } Ok(()) diff --git a/src/logging.rs b/src/logging.rs deleted file mode 100644 index b8944e85..00000000 --- a/src/logging.rs +++ /dev/null @@ -1,44 +0,0 @@ -use crate::error::prelude::*; -use chrono::Utc; -use log::{LevelFilter, Log, Metadata, Record}; -use std::fmt::Write; - -pub static mut BUFFER: String = String::new(); - -pub struct LoggityLog; - -impl LoggityLog { - pub fn new() -> Self { - LoggityLog {} - } - - pub fn init() -> Result<&'static LoggityLog> { - let logger = Box::new(LoggityLog::new()); - let leak: &'static LoggityLog = Box::leak(logger); - log::set_logger(leak).into_report(ErrorCategory::Internal)?; - log::set_max_level(LevelFilter::Info); - Ok(leak) - } -} - -impl Log for LoggityLog { - fn enabled(&self, _metadata: &Metadata<'_>) -> bool { - true - } - - fn log(&self, record: &Record<'_>) { - unsafe { - let _ = writeln!( - BUFFER, - "[{}] {} {}", - Utc::now().to_rfc3339(), - record.level(), - record.args() - ); - } - } - - fn flush(&self) { - unsafe { println!("{BUFFER}") } - } -} diff --git a/src/main.rs b/src/main.rs index 915192c5..42edb582 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,10 @@ #![cfg_attr(windows, feature(windows_by_handle))] use clap::CommandFactory; -use log::Log; use std::{ - io::{stdout, Write}, + io::stdout, process::ExitCode, }; -/// Defines the command-line interface and the context used throughout Erdtree. -mod user; -use user::Context; - /// Concerned with disk usage calculation and presentation. mod disk; @@ -23,11 +18,22 @@ mod file; /// Concerned with file icons. mod icon; -/// Concerned with logging throughout the application. -mod logging; +/// Progress indicator. +mod progress; + +/// Defines the command-line interface and the context used throughout Erdtree. +mod user; +use user::Context; + + +/// For basic performance measurements when compiling for debug. +#[cfg(debug_assertions)] +#[macro_use] +mod perf; /// Concerned with rendering the program output. mod render; +use render::Renderer; const BIN_NAME: &str = "erd"; @@ -40,39 +46,55 @@ fn main() -> ExitCode { } fn run() -> Result<()> { + #[cfg(debug_assertions)] + { + perf::init_global(); + perf::begin_recording("crate::main"); + } + + #[cfg(debug_assertions)] + crate::perf::begin_recording("crate::user::Context::init"); + let mut ctx = user::Context::init()?; + #[cfg(debug_assertions)] + crate::perf::finish_recording("crate::user::Context::init"); + if let Some(shell) = ctx.completions { clap_complete::generate(shell, &mut Context::command(), BIN_NAME, &mut stdout()); return Ok(()); } - let logger = ctx - .verbose - .then_some(logging::LoggityLog::init()) - .transpose()?; - - let mut file_tree = if ctx.suppress_size { - file::Tree::init_without_disk_usage(&ctx).map(|(tree, column_metadata)| { - ctx.update_column_metadata(column_metadata); - tree - })? + // TODO: Use accumulator + let (mut file_tree, _accumulator, column_metadata) = if ctx.no_progress { + if ctx.suppress_size { + file::Tree::init_without_disk_usage(&ctx) + } else { + file::Tree::init(&ctx) + } } else { - file::Tree::init(&ctx).map(|(tree, column_metadata)| { - ctx.update_column_metadata(column_metadata); - tree - })? - }; + progress::Indicator::init().show_progress(|| { + if ctx.suppress_size { + file::Tree::init_without_disk_usage(&ctx) + } else { + file::Tree::init(&ctx) + } + }) + }?; + + ctx.update_column_metadata(column_metadata); file_tree.filter_nodes(&ctx)?; - let output = render::output(&file_tree, &ctx)?; + Renderer::new(&ctx, &file_tree).render()?; - let mut stdout = stdout().lock(); - writeln!(stdout, "{output}").into_report(ErrorCategory::Warning)?; + #[cfg(debug_assertions)] + { + perf::finish_recording("crate::main"); - if let Some(logger) = logger { - logger.flush(); + if ctx.debug { + perf::output(std::io::stdout()); + } } Ok(()) diff --git a/src/perf.rs b/src/perf.rs new file mode 100644 index 00000000..4afe22d3 --- /dev/null +++ b/src/perf.rs @@ -0,0 +1,132 @@ +use ahash::HashMap; +use once_cell::sync::Lazy; +use std::{ + io, + fmt, + sync::{ + mpsc::{self, Sender}, + OnceLock, + }, + time::{Duration, Instant}, + thread::{self, JoinHandle}, +}; + +static mut GLOBAL_PERF_METRICS: OnceLock = OnceLock::new(); +static OUTPUT_NOTIFIER: OnceLock> = OnceLock::new(); +static mut ONGOING_RECORDINGS: Lazy> = Lazy::new(HashMap::default); + +#[derive(Debug)] +pub struct Recording { + name: String, + start: Instant, + duration: Option, +} + +#[derive(Debug)] +pub struct PerfMetrics(Option>>); + +enum Message { + Recording(Recording), + Terminate, +} + +pub fn init_global() { + let (tx, rx) = mpsc::channel(); + + OUTPUT_NOTIFIER.set(tx).unwrap(); + + let handle = thread::spawn(move || { + let mut recordings = Vec::new(); + + while let Ok(Message::Recording(recording)) = rx.recv() { + recordings.push(recording); + } + + recordings + }); + + unsafe { + GLOBAL_PERF_METRICS.set(PerfMetrics(Some(handle))).unwrap(); + } +} + +pub fn begin_recording(name: &str) { + let recording = Recording { + name: name.to_string(), + start: Instant::now(), + duration: None, + }; + + unsafe { + if let Some(old_value) = ONGOING_RECORDINGS.insert(name.to_string(), recording) { + panic!("Can't have two ongoing recordings with the same name: {old_value}"); + } + } +} + +pub fn finish_recording(name: &str) { + let mut recording = unsafe { + ONGOING_RECORDINGS + .remove(name) + .unwrap_or_else(|| panic!("No ongoing recording with name '{name}'")) + }; + + recording.duration = Some(recording.start.elapsed()); + + OUTPUT_NOTIFIER + .get() + .cloned() + .and_then(|tx| { + tx.send(Message::Recording(recording)).ok() + }); +} + +pub fn output(mut w: T) { + OUTPUT_NOTIFIER.get().cloned().and_then(|tx| { + tx.send(Message::Terminate).ok() + }); + + let mut recordings = unsafe { + GLOBAL_PERF_METRICS + .get_mut() + .and_then(|PerfMetrics(join)| { + join.take() + .and_then(|h| h.join().ok()) + }) + .unwrap() + }; + + recordings.sort_by_cached_key(|a| a.duration.unwrap().as_nanos()); + + let out = recordings + .into_iter() + .rev() + .map(|r| format!("{r}")) + .collect::>() + .join("\n"); + + writeln!(w, "Performance metrics:\n{out}").unwrap(); + + unsafe { + if !ONGOING_RECORDINGS.is_empty() { + let still_ongoing = ONGOING_RECORDINGS + .keys() + .map(|k| format!("- {k}")) + .collect::>() + .join("\n"); + writeln!(w, "The following recordings are finished:\n{still_ongoing}").unwrap(); + } + } +} + +impl fmt::Display for Recording { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + " {}:\n\t{}ms | {}ns", + self.name, + self.duration.unwrap().as_millis(), + self.duration.unwrap().as_nanos(), + ) + } +} diff --git a/src/progress.rs b/src/progress.rs new file mode 100644 index 00000000..be0059a3 --- /dev/null +++ b/src/progress.rs @@ -0,0 +1,129 @@ +use crossterm::{ + cursor, + ExecutableCommand, + terminal::{self, ClearType}, +}; +use std::{ + io::{self, Write}, + fmt, + sync::{ + mpsc::{self, Receiver, Sender}, + OnceLock, + }, + thread, +}; + +/// For progress indicator to throttle printin. +pub const RENDER_INTERVAL_MS: u64 = 33; + +/// To notify the progress indicator +static NOTIFIER: OnceLock> = OnceLock::new(); + +pub struct Indicator { + counter: usize, + state: IndicatorState, + mailbox: Receiver, +} + +pub enum Message { + Indexing(usize), + DoneIndexing, +} + +#[derive(Default)] +enum IndicatorState { + #[default] + Indexing, + PreparingOutput, +} + +#[derive(Default)] +pub struct FileCounter { + num_file: usize, + num_dir: usize, + num_link: usize, +} + +impl Indicator { + pub fn init() -> Self { + let (tx, rx) = mpsc::channel(); + + NOTIFIER.set(tx).unwrap(); + + Self { + counter: 0, + state: IndicatorState::default(), + mailbox: rx, + } + } + + pub fn use_notifier() -> Option> { + NOTIFIER.get().cloned() + } + + fn update_state(&mut self, new_state: IndicatorState) { + self.state = new_state; + } + + pub fn notify(notifier: &Option>, count: usize) { + if let Some(n) = notifier.as_ref() { + let _ = n.send(Message::Indexing(count)); + } + } + + pub fn finish(notifier: &Option>) { + if let Some(n) = notifier.as_ref() { + let _ = n.send(Message::DoneIndexing); + } + } + + pub fn show_progress(mut self, op: F) -> T + where F: FnOnce() -> T + { + let _ = io::stdout().execute(cursor::Hide); + + let comp_result = thread::scope(move |s| { + let handle = s.spawn(move || { + let threshold = std::time::Duration::from_millis(RENDER_INTERVAL_MS); + let mut time_last_print = std::time::Instant::now(); + let mut stdout = io::stdout(); + let _ = stdout.execute(cursor::SavePosition); + + while let Ok(Message::Indexing(count)) = self.mailbox.recv() { + self.counter = count; + + if time_last_print.elapsed() < threshold { + continue; + } + let _ = stdout.execute(terminal::Clear(ClearType::CurrentLine)); + let _ = write!(stdout, "{self}"); + let _ = stdout.execute(cursor::RestorePosition); + time_last_print = std::time::Instant::now(); + } + self.update_state(IndicatorState::PreparingOutput); + let _ = stdout.execute(terminal::Clear(ClearType::CurrentLine)); + let _ = write!(stdout, "{self}"); + }); + + let out = op(); + handle.join().unwrap(); + + out + }); + + let _ = io::stdout().execute(cursor::Show); + + comp_result + } +} + +impl fmt::Display for Indicator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.state { + IndicatorState::Indexing => { + write!(f, "Indexing {} files...", self.counter) + } + IndicatorState::PreparingOutput => write!(f, "Preparing output..."), + } + } +} diff --git a/src/render/mod.rs b/src/render/mod.rs index 66d2c1fb..a32364bc 100644 --- a/src/render/mod.rs +++ b/src/render/mod.rs @@ -4,6 +4,7 @@ use crate::{ user::{args::Layout, Context}, }; use indextree::{NodeEdge, NodeId}; +use std::io::{self, Write}; /// Used for padding between tree branches. pub const SEP: &str = " "; @@ -24,188 +25,199 @@ pub const ROTATED_T: &str = "\u{251C}\u{2500} "; /// row in the program output. mod row; -pub fn output(file_tree: &file::Tree, ctx: &Context) -> Result { - match ctx.layout { - Layout::Tree => tree(file_tree, ctx), - Layout::InvertedTree => inverted_tree(file_tree, ctx), - Layout::Flat => flat(file_tree, ctx), - } +pub struct Renderer<'a> { + ctx: &'a Context, + file_tree: &'a file::Tree, } -fn inverted_tree(file_tree: &file::Tree, ctx: &Context) -> Result { - let arena = file_tree.arena(); - let root = file_tree.root_id(); - let max_depth = ctx.level(); +impl<'a> Renderer<'a> { + pub fn new(ctx: &'a Context, file_tree: &'a file::Tree) -> Self { + Self { ctx, file_tree } + } - let mut buf = String::new(); + pub fn render(self) -> Result<()> { + let out = match self.ctx.layout { + Layout::Tree => self.tree(), + Layout::InvertedTree => self.inverted_tree(), + Layout::Flat => self.flat(), + }?; - let is_first_sibling = |node_id: NodeId, depth: usize| { - (depth > 0) - .then(|| node_id.following_siblings(arena).nth(1).is_none()) - .unwrap_or(false) - }; + writeln!(io::stdout(), "{out}").into_report(ErrorCategory::Warning)?; - let mut inherited_prefix_components = vec![""]; + Ok(()) + } - let mut formatter = row::formatter(&mut buf, ctx)?; + fn inverted_tree(&self) -> Result { + let arena = self.file_tree.arena(); + let root = self.file_tree.root_id(); + let max_depth = self.ctx.level(); - let mut reverse_traverse = root.reverse_traverse(arena); - reverse_traverse.next(); + let mut buf = String::new(); - for node_edge in reverse_traverse { - let (node, node_id, depth) = match node_edge { - NodeEdge::Start(node_id) => { - let node = arena[node_id].get(); - let depth = node.depth(); + let is_first_sibling = |node_id: NodeId, depth: usize| { + (depth > 0) + .then(|| node_id.following_siblings(arena).nth(1).is_none()) + .unwrap_or(false) + }; - if node.is_dir() { - inherited_prefix_components.pop(); - } + let mut inherited_prefix_components = vec![""]; - if depth > max_depth { - continue; - } + let mut formatter = row::formatter(&mut buf, self.ctx)?; + + let mut reverse_traverse = root.reverse_traverse(arena); + reverse_traverse.next(); - (node, node_id, depth) - }, - NodeEdge::End(node_id) => { - let node = arena[node_id].get(); - let depth = node.depth(); - - if node.is_dir() { - if is_first_sibling(node_id, depth) { - inherited_prefix_components.push(SEP); - } else { - inherited_prefix_components.push(VLINE); + for node_edge in reverse_traverse { + let (node, node_id, depth) = match node_edge { + NodeEdge::Start(node_id) => { + let node = arena[node_id].get(); + let depth = node.depth(); + + if node.is_dir() { + inherited_prefix_components.pop(); } - } - continue; - }, - }; - let prefix = format!( - "{}{}", - inherited_prefix_components.join(""), - (depth > 0) - .then(|| { - is_first_sibling(node_id, depth) - .then_some(UL_CORNER) - .unwrap_or(ROTATED_T) - }) - .unwrap_or("") - ); - - if let Err(e) = formatter(node, prefix) { - log::warn!("{e}"); + if depth > max_depth { + continue; + } + + (node, node_id, depth) + }, + NodeEdge::End(node_id) => { + let node = arena[node_id].get(); + let depth = node.depth(); + + if node.is_dir() { + if is_first_sibling(node_id, depth) { + inherited_prefix_components.push(SEP); + } else { + inherited_prefix_components.push(VLINE); + } + } + continue; + }, + }; + + let prefix = format!( + "{}{}", + inherited_prefix_components.join(""), + (depth > 0) + .then(|| { + is_first_sibling(node_id, depth) + .then_some(UL_CORNER) + .unwrap_or(ROTATED_T) + }) + .unwrap_or("") + ); + + let _ = formatter(node, prefix); } - } - drop(formatter); + drop(formatter); - Ok(buf) -} + Ok(buf) + } -pub fn tree(file_tree: &file::Tree, ctx: &Context) -> Result { - let arena = file_tree.arena(); - let root = file_tree.root_id(); - let max_depth = ctx.level(); + pub fn tree(&self) -> Result { + let arena = self.file_tree.arena(); + let root = self.file_tree.root_id(); + let max_depth = self.ctx.level(); - let mut buf = String::new(); + let mut buf = String::new(); - let is_last_sibling = |node_id: NodeId, depth: usize| { - (depth > 0) - .then(|| node_id.following_siblings(arena).nth(1).is_none()) - .unwrap_or(false) - }; + let is_last_sibling = |node_id: NodeId, depth: usize| { + (depth > 0) + .then(|| node_id.following_siblings(arena).nth(1).is_none()) + .unwrap_or(false) + }; - let mut inherited_prefix_components = vec![""]; + let mut inherited_prefix_components = vec![""]; - let mut formatter = row::formatter(&mut buf, ctx)?; + let mut formatter = row::formatter(&mut buf, self.ctx)?; - let mut traverse = root.traverse(arena); - traverse.next(); + let mut traverse = root.traverse(arena); + traverse.next(); - formatter(arena[root].get(), "".to_string()) - .into_report(ErrorCategory::Internal) - .context(error_source!())?; + formatter(arena[root].get(), "".to_string()) + .into_report(ErrorCategory::Internal) + .context(error_source!())?; - for node_edge in traverse { - let (node, node_id, depth) = match node_edge { - NodeEdge::Start(node_id) => { - let node = arena[node_id].get(); - let depth = node.depth(); + for node_edge in traverse { + let (node, node_id, depth) = match node_edge { + NodeEdge::Start(node_id) => { + let node = arena[node_id].get(); + let depth = node.depth(); - if depth > max_depth { - continue; - } + if depth > max_depth { + continue; + } - (node, node_id, depth) - }, - NodeEdge::End(node_id) => { - let node = arena[node_id].get(); - let depth = node.depth(); + (node, node_id, depth) + }, + NodeEdge::End(node_id) => { + let node = arena[node_id].get(); + let depth = node.depth(); - if node.is_dir() && depth < max_depth { - inherited_prefix_components.pop(); + if node.is_dir() && depth < max_depth { + inherited_prefix_components.pop(); + } + continue; + }, + }; + + let prefix = format!( + "{}{}", + inherited_prefix_components.join(""), + (depth > 0) + .then(|| { + is_last_sibling(node_id, depth) + .then_some(BL_CORNER) + .unwrap_or(ROTATED_T) + }) + .unwrap_or("") + ); + + let _ = formatter(node, prefix); + + if node.is_dir() && depth < max_depth { + if is_last_sibling(node_id, depth) { + inherited_prefix_components.push(SEP); + } else { + inherited_prefix_components.push(VLINE); } - continue; - }, - }; - - let prefix = format!( - "{}{}", - inherited_prefix_components.join(""), - (depth > 0) - .then(|| { - is_last_sibling(node_id, depth) - .then_some(BL_CORNER) - .unwrap_or(ROTATED_T) - }) - .unwrap_or("") - ); - - if let Err(e) = formatter(node, prefix) { - log::warn!("{e}"); - } - - if node.is_dir() && depth < max_depth { - if is_last_sibling(node_id, depth) { - inherited_prefix_components.push(SEP); - } else { - inherited_prefix_components.push(VLINE); } } - } - drop(formatter); + drop(formatter); - Ok(buf) -} + Ok(buf) + } -fn flat(file_tree: &file::Tree, ctx: &Context) -> Result { - let arena = file_tree.arena(); - let root = file_tree.root_id(); - let max_depth = ctx.level(); - let mut buf = String::new(); + fn flat(&self) -> Result { + let arena = self.file_tree.arena(); + let root = self.file_tree.root_id(); + let max_depth = self.ctx.level(); + let mut buf = String::new(); - let mut formatter = row::formatter(&mut buf, ctx)?; + let mut formatter = row::formatter(&mut buf, self.ctx)?; - for node_edge in root.traverse(arena) { - let node_id = match node_edge { - NodeEdge::Start(_) => continue, - NodeEdge::End(id) if id.is_removed(arena) => continue, - NodeEdge::End(id) => id, - }; + for node_edge in root.traverse(arena) { + let node_id = match node_edge { + NodeEdge::Start(_) => continue, + NodeEdge::End(id) if id.is_removed(arena) => continue, + NodeEdge::End(id) => id, + }; - let node = arena[node_id].get(); + let node = arena[node_id].get(); - if node.depth() > max_depth { - continue; + if node.depth() > max_depth { + continue; + } + + formatter(node, "".to_string()).into_report(ErrorCategory::Warning)?; } + drop(formatter); - formatter(node, "".to_string()).into_report(ErrorCategory::Warning)?; + Ok(buf) } - drop(formatter); - - Ok(buf) } diff --git a/src/user/mod.rs b/src/user/mod.rs index c6ae0717..d772f857 100644 --- a/src/user/mod.rs +++ b/src/user/mod.rs @@ -1,7 +1,11 @@ use crate::error::prelude::*; use ahash::HashMap; use clap::{parser::ValueSource, ArgMatches, Args, CommandFactory, FromArgMatches, Parser}; -use std::{env, fs, path::PathBuf}; +use std::{ + env, + fs, + path::PathBuf, +}; /// Enum definitions for enumerated command-line arguments. pub mod args; @@ -85,6 +89,10 @@ pub struct Context { #[arg(short, long)] pub no_config: bool, + /// Hide the progress indicator + #[arg(long)] + pub no_progress: bool, + #[command(flatten)] pub search: Search, @@ -116,10 +124,6 @@ pub struct Context { #[arg(short = 'x', long = "one-file-system")] pub same_fs: bool, - /// Prints logs at the end of the output - #[arg(short = 'v', long = "verbose")] - pub verbose: bool, - #[arg(long)] /// Print completions for a given shell to stdout pub completions: Option, @@ -129,6 +133,11 @@ pub struct Context { ////////////////////////// #[clap(skip = column::Metadata::default())] pub column_metadata: column::Metadata, + + #[cfg(debug_assertions)] + #[arg(long)] + // Output debug information at the end of the output + pub debug: bool, } #[derive(Args, Debug)] @@ -193,7 +202,9 @@ impl Context { Self::from_arg_matches(&clargs).into_report(ErrorCategory::User)? }; - if ctx.dir.is_none() { + if let Some(dir_arg) = clargs.get_one::("dir").cloned() { + ctx.dir = Some(dir_arg) + } else { let current_dir = Self::get_current_dir()?; ctx.dir = Some(current_dir); }