Parse dircolors files, closes #20
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by sharkdp · committed by sharkdp · parent 33ddee7 · Browse files · 1 file·+50 added−7 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+50 added−7 removed
- other:+50 added−7 removed
Provenance
- Commit
eb02069- Tree
2999d92- Author
sharkdp <davidpeter@web.de>- Committer
sharkdp <davidpeter@web.de>- Parent
33ddee7
1 file changed+50 added−7 removed
modified:src/main.rs+50 added-7 removed
2 unmodified lines3 extern crate isatty;4 extern crate regex;5 extern crate walkdir;6 7+use std::collections::HashMap;8 use std::env;9 use std::error::Error;10 use std::ffi::OsStr;10-use std::io::Write;11+use std::fs::File;12+use std::io::{Write, BufReader,BufRead};13 use std::path::{Path, Component};14 use std::process;15 16 use ansi_term::Colour;1 unmodified line18 use isatty::stdout_isatty;19 use regex::{Regex, RegexBuilder};20 use walkdir::{WalkDir, DirEntry, WalkDirIterator};21 22+/// Maps file extensions to ANSI colors / styles.23+type ExtensionStyles = HashMap<String, ansi_term::Style>;24+25 /// Configuration options for *fd*.26 struct FdOptions {27 case_sensitive: bool,28 search_full_path: bool,29 search_hidden: bool,30 follow_links: bool,31 colored: bool,27- max_depth: usize32+ max_depth: usize,33+ extension_styles: Option<ExtensionStyles>34 }35 36 /// The default maximum recursion depth.37 const MAX_DEPTH_DEFAULT : usize = 25;24 unmodified lines62 let style =63 if component_path.symlink_metadata()64 .map(|md| md.file_type().is_symlink())65 .unwrap_or(false) {60- Colour::Purple66+ Colour::Cyan.normal()67 } else if component_path.is_dir() {62- Colour::Cyan68+ Colour::Blue.bold()69 } else {70+ // Loop up file extension71+ if let Some(ref ext_styles) = config.extension_styles {72+ component_path.extension()73+ .and_then(|e| e.to_str())74+ .and_then(|e| ext_styles.get(e))75+ .map(|r| r.clone())76+ .unwrap_or(Colour::White.normal())77+ }78+ else {64- Colour::White79+ Colour::White.normal()80+ }81 };82 83 print!("{}", style.paint(comp_str.to_str().unwrap()));84 1 unmodified line86 let sep = std::path::MAIN_SEPARATOR.to_string();87 print!("{}", style.paint(sep));88 }89 }74- print!("\n");90+ println!();91 }92 }93 94 /// Check if filename of entry starts with a dot.42 unmodified lines137 .expect("Failed writing to stderr");138 process::exit(1);139 }140 141+/// Parse `dircolors` file.142+fn parse_dircolors(path: &Path) -> std::io::Result<ExtensionStyles> {143+ let file = File::open(path)?;144+ let mut ext_styles = HashMap::new();145+146+ let pattern =147+ Regex::new(r"^\.([A-Za-z0-9]+)\s*38;5;([0-9]+)\b").unwrap();148+149+ for line in BufReader::new(file).lines() {150+ if let Some(caps) = pattern.captures(line.unwrap().as_str()) {151+ if let Some(ext) = caps.get(1).map(|m| m.as_str()) {152+ let fg = caps.get(2)153+ .map(|m| m.as_str())154+ .and_then(|n| u8::from_str_radix(n, 10).ok())155+ .unwrap_or(7); // white156+ ext_styles.insert(String::from(ext),157+ Colour::Fixed(fg).normal());158+ }159+ }160+ }161+ Ok(ext_styles)162+}163+164 fn main() {165 let args: Vec<String> = env::args().collect();166 167 let mut opts = Options::new();30 unmodified lines198 Err(_) => error("Could not get current directory!")199 };200 let current_dir = current_dir_buf.as_path();201 202+ let ext_styles = env::home_dir()203+ .map(|h| h.join(".dir_colors"))204+ .and_then(|path| parse_dircolors(&path).ok());205 206 let config = FdOptions {207 // The search will be case-sensitive if the command line flag is set or208 // if the pattern has an uppercase character (smart case).6 unmodified lines215 follow_links: matches.opt_present("follow"),216 max_depth:217 matches.opt_str("max-depth")218 .and_then(|ds| usize::from_str_radix(&ds, 10).ok())177- .unwrap_or(MAX_DEPTH_DEFAULT)219+ .unwrap_or(MAX_DEPTH_DEFAULT),220+ extension_styles: ext_styles221 };222 223 match RegexBuilder::new(pattern)224 .case_insensitive(!config.case_sensitive)5 unmodified lines