Colorize each path component, closes #19
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by sharkdp · committed by sharkdp · parent 5bde351 · Browse files · 1 file·+38 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+38 added−12 removed
- other:+38 added−12 removed
Provenance
- Commit
33ddee7- Tree
30006aa- Author
sharkdp <davidpeter@web.de>- Committer
sharkdp <davidpeter@web.de>- Parent
5bde351
1 file changed+38 added−12 removed
modified:src/main.rs+38 added-12 removed
6 unmodified lines7 use std::env;8 use std::error::Error;9 use std::ffi::OsStr;10 use std::io::Write;11-use std::path::Path;11+use std::path::{Path, Component};12 use std::process;13 14 use ansi_term::Colour;15 use getopts::Options;14 unmodified lines30 /// The default maximum recursion depth.31 const MAX_DEPTH_DEFAULT : usize = 25;32 33 /// Print a search result to the console.34-fn print_entry(entry: &DirEntry, path_rel: &Path, config: &FdOptions) {35- let path_str = match path_rel.to_str() {34+fn print_entry(path_root: &Path, path_entry: &Path, config: &FdOptions) {35+ let path_full = path_root.join(path_entry);36+37+ let path_str = match path_entry.to_str() {38 Some(p) => p,39 None => return40 };41 40- if config.colored {41- let style = match entry {42- e if e.path_is_symbolic_link() => Colour::Purple,43- e if e.path().is_dir() => Colour::Cyan,44- _ => Colour::White45- };46- println!("{}", style.paint(path_str));47- } else {42+ if !config.colored {43 println!("{}", path_str);44+ } else {45+ let mut component_path = path_root.to_path_buf();46+47+ // Traverse the path and colorize each component48+ for component in path_entry.components() {49+ let comp_str = match component {50+ Component::Normal(p) => p,51+ _ => error("Unexpected path component")52+ };53+54+ component_path.push(Path::new(comp_str));55+56+ let style =57+ if component_path.symlink_metadata()58+ .map(|md| md.file_type().is_symlink())59+ .unwrap_or(false) {60+ Colour::Purple61+ } else if component_path.is_dir() {62+ Colour::Cyan63+ } else {64+ Colour::White65+ };66+67+ print!("{}", style.paint(comp_str.to_str().unwrap()));68+69+ if component_path.is_dir() && component_path != path_full {70+ let sep = std::path::MAIN_SEPARATOR.to_string();71+ print!("{}", style.paint(sep));72+ }73+ }74+ print!("\n");75 }76 }77 78 /// Check if filename of entry starts with a dot.31 unmodified lines110 .and_then(OsStr::to_str)111 };112 113 search_str.and_then(|s| pattern.find(s))88- .map(|_| print_entry(&entry, path_rel, &config));114+ .map(|_| print_entry(&root, path_rel, &config));115 }116 }117 118 /// Print error message to stderr and exit with status `1`.68 unmodified lines