lscolors-0.6.0/.gitignore010064400017500001735000000000361340200757300135710ustar0000000000000000/target **/*.rs.bk Cargo.lock lscolors-0.6.0/.travis.yml010064400017500001735000000055401342167106000137160ustar0000000000000000language: rust cache: cargo matrix: include: # Stable channel. - os: linux rust: stable env: TARGET=x86_64-unknown-linux-gnu - os: linux rust: stable env: - TARGET=x86_64-unknown-linux-musl - CC_x86_64_unknown_linux_musl=/usr/bin/musl-gcc - os: osx rust: stable env: TARGET=x86_64-apple-darwin - os: windows rust: stable env: TARGET=x86_64-pc-windows-msvc # Minimum Rust supported channel. - os: linux rust: 1.31.0 env: TARGET=x86_64-unknown-linux-gnu addons: apt: packages: # needed to build deb packages - fakeroot env: global: # Default target on travis-ci. # Used as conditional check in the install stage - HOST=x86_64-unknown-linux-gnu # Used on the deployment script - PROJECT_NAME=lscolors install: # prevent target re-add error from rustup - if [[ $TRAVIS_OS_NAME = linux && $HOST != $TARGET ]]; then rustup target add $TARGET; fi script: # Incorporate TARGET env var to the build and test process - cargo build --target $TARGET --verbose - RUST_BACKTRACE=1 cargo test --target $TARGET --verbose - find . -maxdepth 3 | cargo run before_deploy: - bash ci/before_deploy.bash deploy: provider: releases # NOTE updating the `api_key.secure` # - go to: https://github.com/settings/tokens/new # - generate new token using `public_repo` scope # - encrypt it using: `travis encrypt API_KEY_HERE` # - paste the output below api_key: secure: "RtF/aUVRQYM9TgG4gxPhzsmffS3Mz9qEVBSEmuwaZZd/xh+kyt7QF/zgNxwP3Hc6tojngF7GtLDNm9Myu0a8dtsEadEWdA/ljbZlBPprPfVgXOo5N17NoGv3/eeHYQudKuJ3xy9WFU6Yf635NH2gkuZDaFQZ/iOdgJ6AGqDWvyUPfjUKBRB0JEKlNL3qOIWuaQ9RAEeIGHp4k3sXGIlCBaCmsy/QkC3yszMrqxBC6YY4fPUCKZpkUKJR42ZPavVoCFnZaWPm/SggjWlVXEma9WZJUv6JXt67TlNFrWjGHBcY/yoi8dZ74q+/dNK47cfhOwpdD6EtX8zyRJ+UhPnU/CCdom2DYBDVaQgdAIEi/kKukRuLF87+F0skx03CZTCG54TglKI8tdYwLqoVNA3ztUZB9HAVpGG8al+nLx4xUYR0sObRkJHcHyiwMP+xQ+M/btyl321Y0u4IbtCjtlBKjkSNFQNXwYJZR5H9E2X6Lo6MFzSjtG+wl0o9+mFFW/TiTIaSdsP+ABsTJqUBlVR2v9bIfcsCHXhWLi9JuoIkZQcpbqHSP6OWBFLBCu1+jixALwSnk+oDzHisgjaw84Rc+FkRTEav0wi6StyhDmpKxu61Q7RGdyyxgYYCwu19Z+EqmSF9RDsIHEPXiMn4R2XDi88NKIuKNJ1OYyLSrkXEM2E=" # for uploading multiple files file_glob: true # NOTE explanation on each env variable # - PROJECT_NAME: name of the project, set on the `env.global` above # - TRAVIS_TAG: tag name that the build is being deployed for, usually the version number # - TARGET: target triple of the build file: - $PROJECT_NAME-$TRAVIS_TAG-$TARGET.* - $PROJECT_NAME*.deb # don't delete artifacts from previous stage skip_cleanup: true on: # deploy only if we push a tag tags: true # deploy only on stable channel that has TARGET env variable sets condition: $TRAVIS_RUST_VERSION = stable && $TARGET != "x86_64-pc-windows-msvc" notifications: email: on_success: never lscolors-0.6.0/Cargo.toml.orig010064400017500001735000000012431353745424700145060ustar0000000000000000[package] name = "lscolors" description = "Colorize paths using the LS_COLORS environment variable" categories = ["command-line-interface"] homepage = "https://github.com/sharkdp/lscolors" repository = "https://github.com/sharkdp/lscolors" keywords = [ "cli", "linux", "terminal", "filesystem", "color" ] license = "MIT/Apache-2.0" version = "0.6.0" readme = "README.md" edition = "2018" authors = ["David Peter "] [dependencies] ansi_term = { version = "0.12", optional = true } [dev-dependencies] tempfile = "^3" [features] default = ["ansi_term"] [[bin]] name = "lscolors" path = "src/bin.rs" required-features = ["ansi_term"] lscolors-0.6.0/Cargo.toml0000644000000022310000000000000107320ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "lscolors" version = "0.6.0" authors = ["David Peter "] description = "Colorize paths using the LS_COLORS environment variable" homepage = "https://github.com/sharkdp/lscolors" readme = "README.md" keywords = ["cli", "linux", "terminal", "filesystem", "color"] categories = ["command-line-interface"] license = "MIT/Apache-2.0" repository = "https://github.com/sharkdp/lscolors" [[bin]] name = "lscolors" path = "src/bin.rs" required-features = ["ansi_term"] [dependencies.ansi_term] version = "0.12" optional = true [dev-dependencies.tempfile] version = "^3" [features] default = ["ansi_term"] lscolors-0.6.0/LICENSE-APACHE010064400017500001735000000261351336761635500135530ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. lscolors-0.6.0/LICENSE-MIT010064400017500001735000000017771336761636100132650ustar0000000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lscolors-0.6.0/README.md010064400017500001735000000040441347626711500130760ustar0000000000000000# lscolors [![Build Status](https://travis-ci.org/sharkdp/lscolors.svg?branch=master)](https://travis-ci.org/sharkdp/lscolors) [![Crates.io](https://img.shields.io/crates/v/lscolors.svg)](https://crates.io/crates/lscolors) [![Documentation](https://docs.rs/lscolors/badge.svg)](https://docs.rs/lscolors) A cross-platform library for colorizing paths according to the `LS_COLORS` environment variable (like `ls`). ## Usage ```rust use lscolors::{LsColors, Style}; let lscolors = LsColors::from_env().unwrap_or_default(); let path = "some/folder/test.tar.gz"; let style = lscolors.style_for_path(path); // If you want to use `ansi_term`: let ansi_style = style.map(Style::to_ansi_term_style) .unwrap_or_default(); println!("{}", ansi_style.paint(path)); ``` ## Command-line application This crate also comes with a small command-line program `lscolors` that can be used to colorize the output of other commands: ```bash > find . -maxdepth 2 | lscolors > rg foo -l | lscolors ``` You can install it by running `cargo install lscolors` or by downloading one of the prebuilt binaries from the [release page](https://github.com/sharkdp/lscolors/releases). ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## References Information about the `LS_COLORS` environment variable is sparse. Here is a short list of useful references: * [`LS_COLORS` implementation in the GNU coreutils version of `ls`](https://github.com/coreutils/coreutils/blob/17983b2cb3bccbb4fa69691178caddd99269bda9/src/ls.c#L2507-L2647) (the reference implementation) * [`LS_COLORS` implementation in `bfs`](https://github.com/tavianator/bfs/blob/2d3b03183c9f1cdb685977f349bf4bbc74a2038d/color.c#L308) by [**@tavianator**](https://github.com/tavianator) * [The `DIR_COLORS(5)` man page](https://linux.die.net/man/5/dir_colors) lscolors-0.6.0/ci/.gitattributes010064400017500001735000000000311340320204600150530ustar0000000000000000*.bash linguist-vendored lscolors-0.6.0/ci/before_deploy.bash010075500017500001735000000046151340317412700156640ustar0000000000000000#!/usr/bin/env bash # Building and packaging for release set -ex build() { cargo build --target "$TARGET" --release --verbose } pack() { local tempdir local out_dir local package_name tempdir=$(mktemp -d 2>/dev/null || mktemp -d -t tmp) out_dir=$(pwd) package_name="$PROJECT_NAME-$TRAVIS_TAG-$TARGET" # create a "staging" directory mkdir "$tempdir/$package_name" # copying the main binary cp "target/$TARGET/release/$PROJECT_NAME" "$tempdir/$package_name/" strip "$tempdir/$package_name/$PROJECT_NAME" # readme and license cp README.md "$tempdir/$package_name" cp LICENSE-MIT "$tempdir/$package_name" cp LICENSE-APACHE "$tempdir/$package_name" # archiving pushd "$tempdir" tar czf "$out_dir/$package_name.tar.gz" "$package_name"/* popd rm -r "$tempdir" } make_deb() { local tempdir local architecture local version local dpkgname local conflictname case $TARGET in x86_64*) architecture=amd64 ;; i686*) architecture=i386 ;; *) echo "ERROR: unknown target" >&2 return 1 ;; esac version=${TRAVIS_TAG#v} if [[ $TARGET = *musl* ]]; then dpkgname=$PROJECT_NAME-musl conflictname=$PROJECT_NAME else dpkgname=$PROJECT_NAME conflictname=$PROJECT_NAME-musl fi tempdir=$(mktemp -d 2>/dev/null || mktemp -d -t tmp) # copy the main binary install -Dm755 "target/$TARGET/release/$PROJECT_NAME" "$tempdir/usr/bin/$PROJECT_NAME" strip "$tempdir/usr/bin/$PROJECT_NAME" # readme and license install -Dm644 README.md "$tempdir/usr/share/doc/$PROJECT_NAME/README.md" install -Dm644 LICENSE-MIT "$tempdir/usr/share/doc/$PROJECT_NAME/LICENSE-MIT" install -Dm644 LICENSE-APACHE "$tempdir/usr/share/doc/$PROJECT_NAME/LICENSE-APACHE" # Control file mkdir "$tempdir/DEBIAN" cat > "$tempdir/DEBIAN/control" < Architecture: $architecture Provides: $PROJECT_NAME Conflicts: $conflictname Description: Colorizes paths from STDIN just like 'ls'. EOF fakeroot dpkg-deb --build "$tempdir" "${dpkgname}_${version}_${architecture}.deb" } main() { build pack if [[ $TARGET = *linux* ]]; then make_deb fi } main lscolors-0.6.0/src/bin.rs010064400017500001735000000024311342167101600135070ustar0000000000000000use std::env; use std::io; use std::io::prelude::*; use std::path::Path; use lscolors::{LsColors, Style}; fn print_path(handle: &mut dyn Write, ls_colors: &LsColors, path: &str) -> io::Result<()> { for (component, style) in ls_colors.style_for_path_components(Path::new(path)) { let ansi_style = style.map(Style::to_ansi_term_style).unwrap_or_default(); write!(handle, "{}", ansi_style.paint(component.to_string_lossy()))?; } writeln!(handle)?; Ok(()) } fn run() -> io::Result<()> { let ls_colors = LsColors::from_env().unwrap_or_default(); let stdout = io::stdout(); let mut stdout = stdout.lock(); let mut args = env::args(); if args.len() >= 2 { // Skip program name args.next(); for arg in args { print_path(&mut stdout, &ls_colors, &arg)?; } } else { let stdin = io::stdin(); let mut buf = vec![]; while let Some(size) = stdin.lock().read_until(b'\n', &mut buf).ok() { if size == 0 { break; } let path_str = String::from_utf8_lossy(&buf[..(buf.len() - 1)]); print_path(&mut stdout, &ls_colors, path_str.as_ref())?; buf.clear(); } } Ok(()) } fn main() { run().ok(); } lscolors-0.6.0/src/fs.rs010064400017500001735000000004571342110015500133440ustar0000000000000000use std::fs; #[cfg(any(unix, target_os = "redox"))] use std::os::unix::fs::PermissionsExt; #[cfg(any(unix, target_os = "redox"))] pub fn is_executable(md: &fs::Metadata) -> bool { md.permissions().mode() & 0o111 != 0 } #[cfg(windows)] pub fn is_executable(_: &fs::Metadata) -> bool { false } lscolors-0.6.0/src/lib.rs010064400017500001735000000461521347626711500135300ustar0000000000000000//! A library for colorizing paths according to the `LS_COLORS` environment variable. //! //! # Example //! ``` //! use lscolors::{LsColors, Style}; //! //! let lscolors = LsColors::from_env().unwrap_or_default(); //! //! let path = "some/folder/archive.zip"; //! let style = lscolors.style_for_path(path); //! //! // If you want to use `ansi_term`: //! let ansi_style = style.map(Style::to_ansi_term_style).unwrap_or_default(); //! println!("{}", ansi_style.paint(path)); //! ``` mod fs; pub mod style; use std::collections::HashMap; use std::env; use std::ffi::OsString; use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR}; pub use crate::style::{Color, FontStyle, Style}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Indicator { /// `no`: Normal (non-filename) text Normal, /// `fi`: Regular file RegularFile, /// `di`: Directory Directory, /// `ln`: Symbolic link SymbolicLink, /// `pi`: Named pipe or FIFO FIFO, /// `so`: Socket Socket, /// `do`: Door (IPC connection to another program) Door, /// `bd`: Block-oriented device BlockDevice, /// `cd`: Character-oriented device CharacterDevice, /// `or`: A broken symbolic link OrphanedSymbolicLink, /// `su`: A file that is setuid (`u+s`) Setuid, /// `sg`: A file that is setgid (`g+s`) Setgid, /// `st`: A directory that is sticky and other-writable (`+t`, `o+w`) Sticky, /// `ow`: A directory that is not sticky and other-writeable (`o+w`) OtherWritable, /// `tw`: A directory that is sticky and other-writable (`+t`, `o+w`) StickyAndOtherWritable, /// `ex`: Executable file ExecutableFile, /// `mi`: Missing file MissingFile, /// `ca`: File with capabilities set Capabilities, /// `mh`: File with multiple hard links MultipleHardLinks, /// `lc`: Code that is printed before the color sequence LeftCode, /// `rc`: Code that is printed after the color sequence RightCode, /// `ec`: End code EndCode, /// `rs`: Code to reset to ordinary colors Reset, /// `cl`: Code to clear to the end of the line ClearLine, } impl Indicator { pub fn from(indicator: &str) -> Option { match indicator { "no" => Some(Indicator::Normal), "fi" => Some(Indicator::RegularFile), "di" => Some(Indicator::Directory), "ln" => Some(Indicator::SymbolicLink), "pi" => Some(Indicator::FIFO), "so" => Some(Indicator::Socket), "do" => Some(Indicator::Door), "bd" => Some(Indicator::BlockDevice), "cd" => Some(Indicator::CharacterDevice), "or" => Some(Indicator::OrphanedSymbolicLink), "su" => Some(Indicator::Setuid), "sg" => Some(Indicator::Setgid), "st" => Some(Indicator::Sticky), "ow" => Some(Indicator::OtherWritable), "tw" => Some(Indicator::StickyAndOtherWritable), "ex" => Some(Indicator::ExecutableFile), "mi" => Some(Indicator::MissingFile), "ca" => Some(Indicator::Capabilities), "mh" => Some(Indicator::MultipleHardLinks), "lc" => Some(Indicator::LeftCode), "rc" => Some(Indicator::RightCode), "ec" => Some(Indicator::EndCode), "rs" => Some(Indicator::Reset), "cl" => Some(Indicator::ClearLine), _ => None, } } } type FileNameSuffix = String; /// Iterator over the path components with their respective style. pub struct StyledComponents<'a> { /// Reference to the underlying LsColors object lscolors: &'a LsColors, /// Full path to the current component component_path: PathBuf, /// Underlying iterator over the path components components: std::iter::Peekable>, } impl<'a> Iterator for StyledComponents<'a> { type Item = (OsString, Option<&'a Style>); fn next(&mut self) -> Option { if let Some(component) = self.components.next() { let mut component_str = component.as_os_str().to_os_string(); self.component_path.push(&component_str); let style = self.lscolors.style_for_path(&self.component_path); if self.components.peek().is_some() { match component { // Prefix needs no separator, as it is always followed by RootDir. // RootDir is already a separator. Component::Prefix(_) | Component::RootDir => {} // Everything else uses a separator that is painted the same way as the component. Component::CurDir | Component::ParentDir | Component::Normal(_) => { component_str.push(MAIN_SEPARATOR.to_string()); } } } Some((component_str, style)) } else { None } } } const LS_COLORS_DEFAULT: &str = "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:"; /// Holds information about how different file system entries should be colorized / styled. #[derive(Debug, Clone)] pub struct LsColors { indicator_mapping: HashMap, // Note: you might expect to see a `HashMap` for `suffix_mapping` as well, but we need to // preserve the exact order of the mapping in order to be consistent with `ls`. suffix_mapping: Vec<(FileNameSuffix, Style)>, } impl Default for LsColors { /// Constructs a default `LsColors` instance with some /// default styles. fn default() -> Self { LsColors::from_string(LS_COLORS_DEFAULT) } } impl LsColors { /// Construct an empty [`LsColors`](struct.LsColors.html) instance with no pre-defined styles. pub fn empty() -> Self { LsColors { indicator_mapping: HashMap::new(), suffix_mapping: vec![], } } /// Creates a new [`LsColors`](struct.LsColors.html) instance from the `LS_COLORS` environment variable. pub fn from_env() -> Option { env::var("LS_COLORS") .ok() .as_ref() .map(|s| Self::from_string(s)) } /// Creates a new [`LsColors`](struct.LsColors.html) instance from the given string. pub fn from_string(input: &str) -> Self { let mut lscolors = LsColors::empty(); for entry in input.split(':') { let parts: Vec<_> = entry.split('=').collect(); if let Some([entry, ansi_style]) = parts.get(0..2) { if let Some(style) = Style::from_ansi_sequence(ansi_style) { if entry.starts_with('*') { lscolors .suffix_mapping .push((entry[1..].to_string().to_ascii_lowercase(), style)); } else if let Some(indicator) = Indicator::from(entry) { lscolors.indicator_mapping.insert(indicator, style); } } } } lscolors } /// Get the ANSI style for a given path. /// /// *Note:* this function calls `Path::symlink_metadata` internally. If you already happen to /// have the `Metadata` available, use [`style_for_path_with_metadata`](#method.style_for_path_with_metadata). pub fn style_for_path>(&self, path: P) -> Option<&Style> { let metadata = path.as_ref().symlink_metadata().ok(); self.style_for_path_with_metadata(path, metadata.as_ref()) } /// Get the ANSI style for a path, given the corresponding `Metadata` struct. /// /// *Note:* The `Metadata` struct must have been acquired via `Path::symlink_metadata` in /// order to colorize symbolic links correctly. pub fn style_for_path_with_metadata>( &self, path: P, metadata: Option<&std::fs::Metadata>, ) -> Option<&Style> { if let Some(metadata) = metadata { if metadata.is_dir() { return self.style_for_indicator(Indicator::Directory); } if metadata.file_type().is_symlink() { // This works because `Path::exists` traverses symlinks. if path.as_ref().exists() { return self.style_for_indicator(Indicator::SymbolicLink); } else { return self.style_for_indicator(Indicator::OrphanedSymbolicLink); } } #[cfg(unix)] { use std::os::unix::fs::FileTypeExt; let filetype = metadata.file_type(); if filetype.is_fifo() { return self.style_for_indicator(Indicator::FIFO); } if filetype.is_socket() { return self.style_for_indicator(Indicator::Socket); } if filetype.is_block_device() { return self.style_for_indicator(Indicator::BlockDevice); } if filetype.is_char_device() { return self.style_for_indicator(Indicator::CharacterDevice); } } if crate::fs::is_executable(&metadata) { return self.style_for_indicator(Indicator::ExecutableFile); } } // Note: using '.to_str()' here means that filename // matching will not work with invalid-UTF-8 paths. let filename = path.as_ref().file_name()?.to_str()?.to_ascii_lowercase(); // We need to traverse LS_COLORS from back to front // to be consistent with `ls`: for (suffix, style) in self.suffix_mapping.iter().rev() { // Note: For some reason, 'ends_with' is much // slower if we omit `.as_str()` here: if filename.ends_with(suffix.as_str()) { return Some(style); } } None } /// Get ANSI styles for each component of a given path. Components already include the path /// separator symbol, if required. For a path like `foo/bar/test.md`, this would return an /// iterator over three pairs for the three path components `foo/`, `bar/` and `test.md` /// together with their respective styles. pub fn style_for_path_components<'a>(&'a self, path: &'a Path) -> StyledComponents<'a> { StyledComponents { lscolors: &self, component_path: PathBuf::new(), components: path.components().peekable(), } } /// Get the ANSI style for a certain `Indicator` (regular file, directory, symlink, ...). Note /// that this function implements a fallback logic for some of the indicators (just like `ls`). /// For example, the style for `mi` (missing file) falls back to `or` (orphaned symbolic link) /// if it has not been specified explicitly. pub fn style_for_indicator(&self, indicator: Indicator) -> Option<&Style> { match indicator { Indicator::MissingFile => self .indicator_mapping .get(&Indicator::MissingFile) .or_else(|| self.indicator_mapping.get(&Indicator::OrphanedSymbolicLink)), _ => self.indicator_mapping.get(&indicator), } } } #[cfg(test)] mod tests { use crate::style::{Color, FontStyle, Style}; use crate::{Indicator, LsColors}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; #[test] fn basic_usage() { let lscolors = LsColors::default(); let style_dir = lscolors .style_for_indicator(Indicator::Directory) .clone() .unwrap(); assert_eq!(FontStyle::bold(), style_dir.font_style); assert_eq!(Some(Color::Blue), style_dir.foreground); assert_eq!(None, style_dir.background); let style_symlink = lscolors .style_for_indicator(Indicator::SymbolicLink) .clone() .unwrap(); assert_eq!(FontStyle::bold(), style_symlink.font_style); assert_eq!(Some(Color::Cyan), style_symlink.foreground); assert_eq!(None, style_symlink.background); let style_rs = lscolors.style_for_path("test.wav").unwrap(); assert_eq!(FontStyle::default(), style_rs.font_style); assert_eq!(Some(Color::Cyan), style_rs.foreground); assert_eq!(None, style_rs.background); } #[test] fn style_for_path_uses_correct_ordering() { let lscolors = LsColors::from_string("*.foo=01;35:*README.foo=33;44"); let style_foo = lscolors.style_for_path("some/folder/dummy.foo").unwrap(); assert_eq!(FontStyle::bold(), style_foo.font_style); assert_eq!(Some(Color::Magenta), style_foo.foreground); assert_eq!(None, style_foo.background); let style_readme = lscolors .style_for_path("some/other/folder/README.foo") .unwrap(); assert_eq!(FontStyle::default(), style_readme.font_style); assert_eq!(Some(Color::Yellow), style_readme.foreground); assert_eq!(Some(Color::Blue), style_readme.background); } #[test] fn style_for_path_uses_lowercase_matching() { let lscolors = LsColors::from_string("*.O=01;35"); let style_artifact = lscolors.style_for_path("artifact.o").unwrap(); assert_eq!(FontStyle::bold(), style_artifact.font_style); assert_eq!(Some(Color::Magenta), style_artifact.foreground); assert_eq!(None, style_artifact.background); } fn temp_dir() -> tempfile::TempDir { tempfile::tempdir().expect("temporary directory") } fn create_file>(path: P) -> PathBuf { File::create(&path).expect("temporary file"); path.as_ref().to_path_buf() } fn create_dir>(path: P) -> PathBuf { fs::create_dir(&path).expect("temporary directory"); path.as_ref().to_path_buf() } fn get_default_style>(path: P) -> Option