Skip to content
Myr

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

1 file+50 added−7 removed

modified:src/main.rs+50 added-7 removed
2 unmodified lines
3extern crate isatty;4extern crate regex;5extern crate walkdir;67use std::collections::HashMap;8use std::env;9use std::error::Error;10use std::ffi::OsStr;10use std::io::Write;11use std::fs::File;12use std::io::{Write, BufReader,BufRead};13use std::path::{Path, Component};14use std::process;1516use ansi_term::Colour;
1 unmodified line
18use isatty::stdout_isatty;19use regex::{Regex, RegexBuilder};20use walkdir::{WalkDir, DirEntry, WalkDirIterator};2122/// Maps file extensions to ANSI colors / styles.23type ExtensionStyles = HashMap<String, ansi_term::Style>;2425/// Configuration options for *fd*.26struct 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}3536/// The default maximum recursion depth.37const MAX_DEPTH_DEFAULT : usize = 25;
24 unmodified lines
62 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 };8283 print!("{}", style.paint(comp_str.to_str().unwrap()));84
1 unmodified line
86 let sep = std::path::MAIN_SEPARATOR.to_string();87 print!("{}", style.paint(sep));88 }89 }74 print!("\n");90 println!();91 }92}9394/// Check if filename of entry starts with a dot.
42 unmodified lines
137 .expect("Failed writing to stderr");138 process::exit(1);139}140141/// Parse `dircolors` file.142fn parse_dircolors(path: &Path) -> std::io::Result<ExtensionStyles> {143 let file = File::open(path)?;144 let mut ext_styles = HashMap::new();145146 let pattern =147 Regex::new(r"^\.([A-Za-z0-9]+)\s*38;5;([0-9]+)\b").unwrap();148149 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}163164fn main() {165 let args: Vec<String> = env::args().collect();166167 let mut opts = Options::new();
30 unmodified lines
198 Err(_) => error("Could not get current directory!")199 };200 let current_dir = current_dir_buf.as_path();201202 let ext_styles = env::home_dir()203 .map(|h| h.join(".dir_colors"))204 .and_then(|path| parse_dircolors(&path).ok());205206 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 lines
215 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 };222223 match RegexBuilder::new(pattern)224 .case_insensitive(!config.case_sensitive)
5 unmodified lines