send DirEntries to output instead of just path
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jonathan Goren · committed by Jonathan Goren · parent 81669f4 · Browse files · 7 files·+88 added−80 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+88 added−80 removed
- other:+88 added−80 removed
Provenance
- Commit
813a802- Tree
8941769- Author
Jonathan Goren <jonagn@gmail.com>- Committer
Jonathan Goren <jonagn@gmail.com>- Parent
81669f4
7 files changed+88 added−80 removed
modified:src/exec/job.rs+5 added-5 removed
1-use std::path::PathBuf;1 use std::sync::{Arc, Mutex};2 3 use crossbeam_channel::Receiver;4 5+use crate::entry::DirEntry;6 use crate::error::print_error;7 use crate::exit_codes::{merge_exitcodes, ExitCode};8 use crate::walk::WorkerResult;9 15 unmodified lines25 let lock = rx.lock().unwrap();26 27 // Obtain the next result from the receiver, else if the channel28 // has closed, exit from the loop29- let value: PathBuf = match lock.recv() {30- Ok(WorkerResult::Entry(path)) => path,29+ let value: DirEntry = match lock.recv() {30+ Ok(WorkerResult::Entry(val)) => val,31 Ok(WorkerResult::Error(err)) => {32 if show_filesystem_errors {33 print_error(err.to_string());34 }4 unmodified lines39 40 // Drop the lock so that other threads can read from the receiver.41 drop(lock);42 // Generate a command, execute it and store its exit code.43- results.push(cmd.generate_and_execute(&value, Arc::clone(&out_perm), buffer_output))43+ results.push(cmd.generate_and_execute(value.path(), Arc::clone(&out_perm), buffer_output))44 }45 // Returns error in case of any error.46 merge_exitcodes(results)47 }5 unmodified lines53 buffer_output: bool,54 limit: usize,55 ) -> ExitCode {56 let paths = rx.iter().filter_map(|value| match value {57- WorkerResult::Entry(path) => Some(path),57+ WorkerResult::Entry(val) => Some(val.path().to_owned()),58 WorkerResult::Error(err) => {59 if show_filesystem_errors {60 print_error(err.to_string());61 }17 unmodified linesadded:src/entry.rs+62 added
1+use std::{2+ fs::{FileType, Metadata},3+ path::{Path, PathBuf},4+};5+6+use once_cell::unsync::OnceCell;7+8+enum DirEntryInner {9+ Normal(ignore::DirEntry),10+ BrokenSymlink(PathBuf),11+}12+13+pub struct DirEntry {14+ inner: DirEntryInner,15+ metadata: OnceCell<Option<Metadata>>,16+}17+18+impl DirEntry {19+ pub fn normal(e: ignore::DirEntry) -> Self {20+ Self {21+ inner: DirEntryInner::Normal(e),22+ metadata: OnceCell::new(),23+ }24+ }25+26+ pub fn broken_symlink(path: PathBuf) -> Self {27+ Self {28+ inner: DirEntryInner::BrokenSymlink(path),29+ metadata: OnceCell::new(),30+ }31+ }32+33+ pub fn path(&self) -> &Path {34+ match &self.inner {35+ DirEntryInner::Normal(e) => e.path(),36+ DirEntryInner::BrokenSymlink(pathbuf) => pathbuf.as_path(),37+ }38+ }39+40+ pub fn file_type(&self) -> Option<FileType> {41+ match &self.inner {42+ DirEntryInner::Normal(e) => e.file_type(),43+ DirEntryInner::BrokenSymlink(_) => self.metadata().map(|m| m.file_type()),44+ }45+ }46+47+ pub fn metadata(&self) -> Option<&Metadata> {48+ self.metadata49+ .get_or_init(|| match &self.inner {50+ DirEntryInner::Normal(e) => e.metadata().ok(),51+ DirEntryInner::BrokenSymlink(path) => path.symlink_metadata().ok(),52+ })53+ .as_ref()54+ }55+56+ pub fn depth(&self) -> Option<usize> {57+ match &self.inner {58+ DirEntryInner::Normal(e) => Some(e.depth()),59+ DirEntryInner::BrokenSymlink(_) => None,60+ }61+ }62+}modified:src/filesystem.rs+2 added-2 removed
7 unmodified lines8 use std::path::{Path, PathBuf};9 10 use normpath::PathExt;11 12-use crate::walk;12+use crate::entry;13 14 pub fn path_absolute_form(path: &Path) -> io::Result<PathBuf> {15 if path.is_absolute() {16 return Ok(path.to_path_buf());33 unmodified lines50 pub fn is_executable(_: &fs::Metadata) -> bool {51 false52 }53 54-pub fn is_empty(entry: &walk::DirEntry) -> bool {54+pub fn is_empty(entry: &entry::DirEntry) -> bool {55 if let Some(file_type) = entry.file_type() {56 if file_type.is_dir() {57 if let Ok(mut entries) = fs::read_dir(entry.path()) {58 entries.next().is_none()90 unmodified linesmodified:src/filetypes.rs+2 added-2 removed
1+use crate::entry;2 use crate::filesystem;2-use crate::walk;3 4 /// Whether or not to show5 #[derive(Default)]6 pub struct FileTypes {6 unmodified lines13 pub empty_only: bool,14 }15 16 impl FileTypes {17- pub fn should_ignore(&self, entry: &walk::DirEntry) -> bool {17+ pub fn should_ignore(&self, entry: &entry::DirEntry) -> bool {18 if let Some(ref entry_type) = entry.file_type() {19 (!self.files && entry_type.is_file())20 || (!self.directories && entry_type.is_dir())21 || (!self.symlinks && entry_type.is_symlink())18 unmodified linesmodified:src/main.rs+1 added
1 mod app;2 mod config;3+mod entry;4 mod error;5 mod exec;6 mod exit_codes;7 mod filesystem;563 unmodified linesmodified:src/output.rs+5 added-3 removed
3 unmodified lines4 5 use lscolors::{Indicator, LsColors, Style};6 7 use crate::config::Config;8+use crate::entry::DirEntry;9 use crate::error::print_error;10 use crate::exit_codes::ExitCode;11 use crate::filesystem::strip_current_dir;12 1 unmodified line14 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)15 }16 17 // TODO: this function is performance critical and can probably be optimized17-pub fn print_entry<W: Write>(stdout: &mut W, entry: &Path, config: &Config) {18+pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) {19+ let path = entry.path();20 let path = if config.strip_cwd_prefix {19- strip_current_dir(entry)21+ strip_current_dir(path)22 } else {21- entry23+ path24 };25 26 let r = if let Some(ref ls_colors) = config.ls_colors {27 print_entry_colorized(stdout, path, config, ls_colors)107 unmodified linesmodified:src/walk.rs+11 added-68 removed
1 use std::ffi::OsStr;2-use std::fs::{FileType, Metadata};2 use std::io;3 use std::mem;5-use std::path::{Path, PathBuf};4+use std::path::PathBuf;5 use std::sync::atomic::{AtomicBool, Ordering};6 use std::sync::{Arc, Mutex};7 use std::thread;8 use std::time::{Duration, Instant};2 unmodified lines11 use anyhow::{anyhow, Result};12 use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender};13 use ignore::overrides::OverrideBuilder;14 use ignore::{self, WalkBuilder};16-use once_cell::unsync::OnceCell;15 use regex::bytes::Regex;16 17 use crate::config::Config;18+use crate::entry::DirEntry;19 use crate::error::print_error;20 use crate::exec;21 use crate::exit_codes::{merge_exitcodes, ExitCode};22 use crate::filesystem;11 unmodified lines34 }35 36 /// The Worker threads can result in a valid entry having PathBuf or an error.37 pub enum WorkerResult {39- Entry(PathBuf),38+ Entry(DirEntry),39 Error(ignore::Error),40 }41 42 /// Maximum size of the output buffer before flushing results to the console142 unmodified lines185 mode: ReceiverMode,186 /// The deadline to switch to streaming mode.187 deadline: Instant,188 /// The buffer of quickly received paths.190- buffer: Vec<PathBuf>,189+ buffer: Vec<DirEntry>,190 /// Result count.191 num_results: usize,192 }193 48 unmodified lines242 243 /// Wait for a result or state change.244 fn poll(&mut self) -> Result<(), ExitCode> {245 match self.recv() {247- Ok(WorkerResult::Entry(path)) => {246+ Ok(WorkerResult::Entry(dir_entry)) => {247 if self.config.quiet {248 return Err(ExitCode::HasResults(true));249 }250 251 match self.mode {252 ReceiverMode::Buffering => {254- self.buffer.push(path);253+ self.buffer.push(dir_entry);254 if self.buffer.len() > MAX_BUFFER_LENGTH {255 self.stream()?;256 }257 }258 ReceiverMode::Streaming => {260- self.print(&path)?;259+ self.print(&dir_entry)?;260 self.flush()?;261 }262 }263 20 unmodified lines284 Ok(())285 }286 287 /// Output a path.289- fn print(&mut self, path: &Path) -> Result<(), ExitCode> {290- output::print_entry(&mut self.stdout, path, &self.config);288+ fn print(&mut self, entry: &DirEntry) -> Result<(), ExitCode> {289+ output::print_entry(&mut self.stdout, entry, &self.config);290 291 if self.interrupt_flag.load(Ordering::Relaxed) {292 // Ignore any errors on flush, because we're about to exit anyway293 let _ = self.flush();17 unmodified lines311 312 /// Stop looping.313 fn stop(&mut self) -> Result<(), ExitCode> {314 if self.mode == ReceiverMode::Buffering {316- self.buffer.sort();315+ self.buffer.sort_by(|e1, e2| e1.path().cmp(e2.path()));316 self.stream()?;317 }318 319 if self.config.quiet {82 unmodified lines402 }403 })404 }405 407-enum DirEntryInner {408- Normal(ignore::DirEntry),409- BrokenSymlink(PathBuf),410-}411-412-pub struct DirEntry {413- inner: DirEntryInner,414- metadata: OnceCell<Option<Metadata>>,415-}416-417-impl DirEntry {418- fn normal(e: ignore::DirEntry) -> Self {419- Self {420- inner: DirEntryInner::Normal(e),421- metadata: OnceCell::new(),422- }423- }424-425- fn broken_symlink(path: PathBuf) -> Self {426- Self {427- inner: DirEntryInner::BrokenSymlink(path),428- metadata: OnceCell::new(),429- }430- }431-432- pub fn path(&self) -> &Path {433- match &self.inner {434- DirEntryInner::Normal(e) => e.path(),435- DirEntryInner::BrokenSymlink(pathbuf) => pathbuf.as_path(),436- }437- }438-439- pub fn file_type(&self) -> Option<FileType> {440- match &self.inner {441- DirEntryInner::Normal(e) => e.file_type(),442- DirEntryInner::BrokenSymlink(_) => self.metadata().map(|m| m.file_type()),443- }444- }445-446- pub fn metadata(&self) -> Option<&Metadata> {447- self.metadata448- .get_or_init(|| match &self.inner {449- DirEntryInner::Normal(e) => e.metadata().ok(),450- DirEntryInner::BrokenSymlink(path) => path.symlink_metadata().ok(),451- })452- .as_ref()453- }454-455- pub fn depth(&self) -> Option<usize> {456- match &self.inner {457- DirEntryInner::Normal(e) => Some(e.depth()),458- DirEntryInner::BrokenSymlink(_) => None,459- }460- }461-}462-406 fn spawn_senders(407 config: &Arc<Config>,408 quit_flag: &Arc<AtomicBool>,409 pattern: Arc<Regex>,142 unmodified lines552 return ignore::WalkState::Continue;553 }554 }555 613- let send_result = tx_thread.send(WorkerResult::Entry(entry_path.to_owned()));556+ let send_result = tx_thread.send(WorkerResult::Entry(entry));557 558 if send_result.is_err() {559 return ignore::WalkState::Quit;560 }10 unmodified lines