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
Provenance
- Commit
4b5efa3- Tree
8867deb- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
afcdaf2
5 files changed+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.8-9-use ansi_term::{Colour, Style};10-/// A parser for the `LS_COLORS` environment variable.11-use std::collections::HashMap;12-13-/// Maps file extensions to ANSI colors / styles.14-pub type ExtensionStyles = HashMap<String, Style>;15-16-/// Maps filenames to ANSI colors / styles.17-pub type FilenameStyles = HashMap<String, Style>;18-19-const 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-];24-25-/// Defines how different file system entries should be colorized / styled.26-#[derive(Debug, PartialEq)]27-pub struct LsColors {28- /// ANSI Style for directories.29- pub directory: Style,30-31- /// ANSI style for symbolic links.32- pub symlink: Style,33-34- /// ANSI style for executable files.35- pub executable: Style,36-37- /// A map that defines ANSI styles for different file extensions.38- pub extensions: ExtensionStyles,39-40- /// A map that defines ANSI styles for different specific filenames.41- pub filenames: FilenameStyles,42-}43-44-impl 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-}56-57-impl 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- }68-69- /// Parse ANSI escape sequences like `38;5;10;1`.70- fn parse_style(code: &str) -> Option<Style> {71- let mut split = code.split(';');72-73- 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);76-77- 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();84-85- 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- };92-93- 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- };108-109- if decoration.is_none() {110- // Try to find a decoration somewhere in the sequence111- decoration = code.split(';').flat_map(LsColors::parse_decoration).next();112- }113-114- let ansi_style = decoration.unwrap_or(Colour::normal)(color);115-116- Some(ansi_style)117- } else {118- None119- }120- }121-122- /// 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- }131-132- 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);135-136- 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- }157-158- /// Generate a `LsColors` structure from a string.159- pub fn from_string(input: &str) -> LsColors {160- let mut lscolors = LsColors::default();161-162- for s in input.split(':') {163- lscolors.add_entry(s);164- }165-166- lscolors167- }168-}169-170-#[cfg(test)]171-mod test {172- use super::*;173-174- #[test]175- fn test_parse_simple() {176- assert_eq!(Some(Colour::Red.normal()), LsColors::parse_style("31"));177- }178-179- #[test]180- fn test_parse_decoration() {181- assert_eq!(Some(Colour::Red.normal()), LsColors::parse_style("00;31"));182-183- assert_eq!(Some(Colour::Blue.italic()), LsColors::parse_style("03;34"));184-185- assert_eq!(Some(Colour::Cyan.bold()), LsColors::parse_style("01;36"));186- }187-188- #[test]189- fn test_parse_decoration_backwards() {190- assert_eq!(Some(Colour::Blue.italic()), LsColors::parse_style("34;03"));191-192- assert_eq!(Some(Colour::Cyan.bold()), LsColors::parse_style("36;01"));193-194- assert_eq!(Some(Colour::Red.normal()), LsColors::parse_style("31;00"));195- }196-197- #[test]198- fn test_parse_256() {199- assert_eq!(200- Some(Colour::Fixed(115).normal()),201- LsColors::parse_style("38;5;115")202- );203-204- assert_eq!(205- Some(Colour::Fixed(115).normal()),206- LsColors::parse_style("00;38;5;115")207- );208-209- assert_eq!(210- Some(Colour::Fixed(119).bold()),211- LsColors::parse_style("01;38;5;119")212- );213-214- assert_eq!(215- Some(Colour::Fixed(119).bold()),216- LsColors::parse_style("38;5;119;01")217- );218- }219-220- #[test]221- fn test_from_string() {222- assert_eq!(LsColors::default(), LsColors::from_string(&String::new()));223-224- let result = LsColors::from_string(&String::from(225- "rs=0:di=03;34:ln=01;36:*.foo=01;35:*README=33",226- ));227-228- 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 lines15 extern crate lazy_static;16 extern crate humantime;17 #[cfg(all(unix, not(target_os = "redox")))]18 extern crate libc;19+extern crate lscolors;20 extern crate num_cpus;21 extern crate regex;22 extern crate regex_syntax;23 3 unmodified lines27 mod app;28 mod exec;29 mod exit_codes;30 pub mod fshelper;30-pub mod lscolors;31 mod output;32 mod walk;33 34 use std::env;2 unmodified lines37 use std::sync::Arc;38 use std::time;39 40 use atty::Stream;41+use lscolors::LsColors;42 use regex::{RegexBuilder, RegexSetBuilder};43 44 use exec::CommandTemplate;45 use internal::{46 filter::{SizeFilter, TimeFilter},47 opts::FdOptions,48 pattern_has_uppercase_char, transform_args_with_exec, FileTypes,49 };49-use lscolors::LsColors;50 51 fn 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 lines131 #[cfg(windows)]132 let colored_output = colored_output && ansi_term::enable_ansi_support().is_ok();133 134 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 linesmodified:src/output.rs+5 added-35 removed
5 unmodified lines6 // notice may not be copied, modified, or distributed except7 // according to those terms.8 9 use exit_codes::ExitCode;10-use fshelper::is_executable;10 use internal::opts::FdOptions;12-use lscolors::LsColors;11+use lscolors::{LsColors, Style};12 13 use std::io::{self, Write};14 use std::ops::Deref;15 use std::path::{self, Component, Path, PathBuf};53 unmodified lines69 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()));72 74- 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);77 78 write!(handle, "{}{}", separator, style.paint(comp_str))?;79 80 // Determine separator to print before next component.24 unmodified lines105 106 let path_str = path.to_string_lossy();107 write!(&mut io::stdout(), "{}{}", path_str, separator)108 }107-108-fn 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- }116-117- let metadata = path.metadata();118-119- 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 lines86 "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 lines191 "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",192 ]193 194 [[package]]195+name = "lscolors"196+version = "0.1.0"197+source = "registry+https://github.com/rust-lang/crates.io-index"198+dependencies = [199+ "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",200+]201+202+[[package]]203 name = "memchr"204 version = "2.0.1"205 source = "registry+https://github.com/rust-lang/crates.io-index"206 dependencies = [224 unmodified lines431 "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 linesmodified:Cargo.toml+1 added
39 unmodified lines40414243444546474812 unmodified lines39 unmodified linesregex = "1.0.0"regex-syntax = "0.6"ctrlc = "3.1"humantime = "1.1.1"lscolors = "0.1"
[dependencies.clap]version = "2.31.2"features = ["suggestions", "color", "wrap_help"]12 unmodified lines