Skip to content
Myr

Use lscolors crate

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Use my new [lscolors](https://github.com/sharkdp/lscolors) crate instead of the internal `lscolors` module - Speeds up `LS_COLORS` querying, leading to a nice 25% performance improvement when - Adds support for 24-bit colors and background colors closes #368 closes #363

authored by sharkdp · committed by David Peter · parent afcdaf2 · Browse files · 5 files+19 added−279 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+19 added−279 removed

  • other:+19 added−279 removed

5 files+19 added−279 removed

deleted:src/lscolors/mod.rs-236 removed
1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89use ansi_term::{Colour, Style};10/// A parser for the `LS_COLORS` environment variable.11use std::collections::HashMap;1213/// Maps file extensions to ANSI colors / styles.14pub type ExtensionStyles = HashMap<String, Style>;1516/// Maps filenames to ANSI colors / styles.17pub type FilenameStyles = HashMap<String, Style>;1819const LS_CODES: &[&str] = &[20 "no", "no", "fi", "rs", "di", "ln", "ln", "ln", "or", "mi", "pi", "pi", "so", "bd", "bd", "cd",21 "cd", "do", "ex", "lc", "lc", "rc", "rc", "ec", "ec", "su", "su", "sg", "sg", "st", "ow", "ow",22 "tw", "tw", "ca", "mh", "cl",23];2425/// Defines how different file system entries should be colorized / styled.26#[derive(Debug, PartialEq)]27pub struct LsColors {28 /// ANSI Style for directories.29 pub directory: Style,3031 /// ANSI style for symbolic links.32 pub symlink: Style,3334 /// ANSI style for executable files.35 pub executable: Style,3637 /// A map that defines ANSI styles for different file extensions.38 pub extensions: ExtensionStyles,3940 /// A map that defines ANSI styles for different specific filenames.41 pub filenames: FilenameStyles,42}4344impl Default for LsColors {45 /// Get a default LsColors structure.46 fn default() -> LsColors {47 LsColors {48 directory: Colour::Blue.bold(),49 symlink: Colour::Cyan.normal(),50 executable: Colour::Red.bold(),51 extensions: HashMap::new(),52 filenames: HashMap::new(),53 }54 }55}5657impl LsColors {58 /// Parse a single text-decoration code (normal, bold, italic, ...).59 fn parse_decoration(code: &str) -> Option<fn(Colour) -> Style> {60 match code {61 "0" | "00" => Some(Colour::normal),62 "1" | "01" => Some(Colour::bold),63 "3" | "03" => Some(Colour::italic),64 "4" | "04" => Some(Colour::underline),65 _ => None,66 }67 }6869 /// Parse ANSI escape sequences like `38;5;10;1`.70 fn parse_style(code: &str) -> Option<Style> {71 let mut split = code.split(';');7273 if let Some(first) = split.next() {74 // Try to match the first part as a text-decoration argument75 let mut decoration = LsColors::parse_decoration(first);7677 let c1 = if decoration.is_none() {78 Some(first)79 } else {80 split.next()81 };82 let c2 = split.next();83 let c3 = split.next();8485 let color = if c1 == Some("38") && c2 == Some("5") {86 let n_white = 7;87 let n = if let Some(num) = c3 {88 u8::from_str_radix(num, 10).unwrap_or(n_white)89 } else {90 n_white91 };9293 Colour::Fixed(n)94 } else if let Some(color_s) = c1 {95 match color_s {96 "30" => Colour::Black,97 "31" => Colour::Red,98 "32" => Colour::Green,99 "33" => Colour::Yellow,100 "34" => Colour::Blue,101 "35" => Colour::Purple,102 "36" => Colour::Cyan,103 _ => Colour::White,104 }105 } else {106 Colour::White107 };108109 if decoration.is_none() {110 // Try to find a decoration somewhere in the sequence111 decoration = code.split(';').flat_map(LsColors::parse_decoration).next();112 }113114 let ansi_style = decoration.unwrap_or(Colour::normal)(color);115116 Some(ansi_style)117 } else {118 None119 }120 }121122 /// Add a new `LS_COLORS` entry.123 fn add_entry(&mut self, input: &str) {124 let mut parts = input.trim().split('=');125 if let Some(pattern) = parts.next() {126 if let Some(style_code) = parts.next() {127 // Ensure that the input was split into exactly two parts:128 if !parts.next().is_none() {129 return;130 }131132 if let Some(style) = LsColors::parse_style(style_code) {133 // Try to match against one of the known codes134 let res = LS_CODES.iter().find(|&&c| c == pattern);135136 if let Some(code) = res {137 match code.as_ref() {138 "di" => self.directory = style,139 "ln" => self.symlink = style,140 "ex" => self.executable = style,141 _ => return,142 }143 } else if pattern.starts_with("*.") {144 let extension = String::from(pattern).split_off(2);145 self.extensions.insert(extension, style);146 } else if pattern.starts_with('*') {147 let filename = String::from(pattern).split_off(1);148 self.filenames.insert(filename, style);149 } else {150 // Unknown/corrupt pattern151 return;152 }153 }154 }155 }156 }157158 /// Generate a `LsColors` structure from a string.159 pub fn from_string(input: &str) -> LsColors {160 let mut lscolors = LsColors::default();161162 for s in input.split(':') {163 lscolors.add_entry(s);164 }165166 lscolors167 }168}169170#[cfg(test)]171mod test {172 use super::*;173174 #[test]175 fn test_parse_simple() {176 assert_eq!(Some(Colour::Red.normal()), LsColors::parse_style("31"));177 }178179 #[test]180 fn test_parse_decoration() {181 assert_eq!(Some(Colour::Red.normal()), LsColors::parse_style("00;31"));182183 assert_eq!(Some(Colour::Blue.italic()), LsColors::parse_style("03;34"));184185 assert_eq!(Some(Colour::Cyan.bold()), LsColors::parse_style("01;36"));186 }187188 #[test]189 fn test_parse_decoration_backwards() {190 assert_eq!(Some(Colour::Blue.italic()), LsColors::parse_style("34;03"));191192 assert_eq!(Some(Colour::Cyan.bold()), LsColors::parse_style("36;01"));193194 assert_eq!(Some(Colour::Red.normal()), LsColors::parse_style("31;00"));195 }196197 #[test]198 fn test_parse_256() {199 assert_eq!(200 Some(Colour::Fixed(115).normal()),201 LsColors::parse_style("38;5;115")202 );203204 assert_eq!(205 Some(Colour::Fixed(115).normal()),206 LsColors::parse_style("00;38;5;115")207 );208209 assert_eq!(210 Some(Colour::Fixed(119).bold()),211 LsColors::parse_style("01;38;5;119")212 );213214 assert_eq!(215 Some(Colour::Fixed(119).bold()),216 LsColors::parse_style("38;5;119;01")217 );218 }219220 #[test]221 fn test_from_string() {222 assert_eq!(LsColors::default(), LsColors::from_string(&String::new()));223224 let result = LsColors::from_string(&String::from(225 "rs=0:di=03;34:ln=01;36:*.foo=01;35:*README=33",226 ));227228 assert_eq!(Colour::Blue.italic(), result.directory);229 assert_eq!(Colour::Cyan.bold(), result.symlink);230 assert_eq!(Some(&Colour::Purple.bold()), result.extensions.get("foo"));231 assert_eq!(232 Some(&Colour::Yellow.normal()),233 result.filenames.get("README")234 );235 }236}
modified:src/main.rs+3 added-8 removed
14 unmodified lines
15extern crate lazy_static;16extern crate humantime;17#[cfg(all(unix, not(target_os = "redox")))]18extern crate libc;19extern crate lscolors;20extern crate num_cpus;21extern crate regex;22extern crate regex_syntax;23
3 unmodified lines
27mod app;28mod exec;29mod exit_codes;30pub mod fshelper;30pub mod lscolors;31mod output;32mod walk;3334use std::env;
2 unmodified lines
37use std::sync::Arc;38use std::time;3940use atty::Stream;41use lscolors::LsColors;42use regex::{RegexBuilder, RegexSetBuilder};4344use exec::CommandTemplate;45use internal::{46 filter::{SizeFilter, TimeFilter},47 opts::FdOptions,48 pattern_has_uppercase_char, transform_args_with_exec, FileTypes,49};49use lscolors::LsColors;5051fn main() {52 let checked_args = transform_args_with_exec(env::args_os());53 let matches = app::build_app().get_matches_from(checked_args);
77 unmodified lines
131 #[cfg(windows)]132 let colored_output = colored_output && ansi_term::enable_ansi_support().is_ok();133134 let ls_colors = if colored_output {135 Some(136 env::var("LS_COLORS")137 .ok()138 .map(|val| LsColors::from_string(&val))139 .unwrap_or_default(),140 )135 Some(LsColors::from_env().unwrap_or_default())136 } else {137 None138 };139
138 unmodified lines
modified:src/output.rs+5 added-35 removed
5 unmodified lines
6// notice may not be copied, modified, or distributed except7// according to those terms.89use exit_codes::ExitCode;10use fshelper::is_executable;10use internal::opts::FdOptions;12use lscolors::LsColors;11use lscolors::{LsColors, Style};1213use std::io::{self, Write};14use std::ops::Deref;15use std::path::{self, Component, Path, PathBuf};
53 unmodified lines
69 for component in path.components() {70 let comp_str = component.as_os_str().to_string_lossy();71 component_path.push(Path::new(comp_str.deref()));7274 let style = get_path_style(&component_path, ls_colors).unwrap_or(&default_style);73 let style = ls_colors.style_for_path(&component_path);74 let style = style75 .map(Style::to_ansi_term_style)76 .unwrap_or(default_style);7778 write!(handle, "{}{}", separator, style.paint(comp_str))?;7980 // Determine separator to print before next component.
24 unmodified lines
105106 let path_str = path.to_string_lossy();107 write!(&mut io::stdout(), "{}{}", path_str, separator)108}107108fn get_path_style<'a>(path: &Path, ls_colors: &'a LsColors) -> Option<&'a ansi_term::Style> {109 if path110 .symlink_metadata()111 .map(|md| md.file_type().is_symlink())112 .unwrap_or(false)113 {114 return Some(&ls_colors.symlink);115 }116117 let metadata = path.metadata();118119 if metadata.as_ref().map(|md| md.is_dir()).unwrap_or(false) {120 Some(&ls_colors.directory)121 } else if metadata.map(|md| is_executable(&md)).unwrap_or(false) {122 Some(&ls_colors.executable)123 } else if let Some(filename_style) = path124 .file_name()125 .and_then(|n| n.to_str())126 .and_then(|n| ls_colors.filenames.get(n))127 {128 Some(filename_style)129 } else if let Some(extension_style) = path130 .extension()131 .and_then(|e| e.to_str())132 .and_then(|e| ls_colors.extensions.get(e))133 {134 Some(extension_style)135 } else {136 None137 }138}
modified:Cargo.lock+10 added
85 unmodified lines
86 "humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)",87 "ignore 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",88 "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",89 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",90 "lscolors 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",91 "num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)",92 "regex 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",93 "regex-syntax 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)",94 "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
96 unmodified lines
191 "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",192]193194[[package]]195name = "lscolors"196version = "0.1.0"197source = "registry+https://github.com/rust-lang/crates.io-index"198dependencies = [199 "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",200]201202[[package]]203name = "memchr"204version = "2.0.1"205source = "registry+https://github.com/rust-lang/crates.io-index"206dependencies = [
224 unmodified lines
431"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"432"checksum lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ca488b89a5657b0a2ecd45b95609b3e848cf1755da332a0da46e2b2b1cb371a7"433"checksum libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)" = "76e3a3ef172f1a0b9a9ff0dd1491ae5e6c948b94479a3021819ba7d860c8645d"434"checksum log 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "cba860f648db8e6f269df990180c2217f333472b4a6e901e97446858487971e2"435"checksum lscolors 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3eea90e242149c448a1dac8ddb3ed75f49cba948a63482348b23a1b11ee0ac87"436"checksum memchr 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "796fba70e76612589ed2ce7f45282f5af869e0fdd7cc6199fa1aa1f1d591ba9d"437"checksum nix 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d37e713a259ff641624b6cb20e3b12b2952313ba36b6823c0f16e6cfd9e5de17"438"checksum num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c51a3322e4bca9d212ad9a158a02abc6934d005490c054a2778df73a70aa0a30"439"checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0"
25 unmodified lines
modified:Cargo.toml+1 added