lscolors-0.20.0/.cargo_vcs_info.json0000644000000001360000000000100127530ustar { "git": { "sha1": "fd932f838d055990378e3d73fbd5d61185da495e" }, "path_in_vcs": "" }lscolors-0.20.0/.github/workflows/CICD.yml000064400000000000000000000323021046102023000163650ustar 00000000000000name: CICD env: CICD_INTERMEDIATES_DIR: "_cicd-intermediates" MSRV_FEATURES: "" on: workflow_dispatch: pull_request: push: branches: - master tags: - '*' jobs: crate_metadata: name: Extract crate metadata runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Extract crate information id: crate_metadata run: | cargo metadata --no-deps --format-version 1 | jq -r '"name=" + .packages[0].name' | tee -a $GITHUB_OUTPUT cargo metadata --no-deps --format-version 1 | jq -r '"version=" + .packages[0].version' | tee -a $GITHUB_OUTPUT cargo metadata --no-deps --format-version 1 | jq -r '"maintainer=" + .packages[0].authors[0]' | tee -a $GITHUB_OUTPUT cargo metadata --no-deps --format-version 1 | jq -r '"homepage=" + .packages[0].homepage' | tee -a $GITHUB_OUTPUT cargo metadata --no-deps --format-version 1 | jq -r '"msrv=" + .packages[0].rust_version' | tee -a $GITHUB_OUTPUT outputs: name: ${{ steps.crate_metadata.outputs.name }} version: ${{ steps.crate_metadata.outputs.version }} maintainer: ${{ steps.crate_metadata.outputs.maintainer }} homepage: ${{ steps.crate_metadata.outputs.homepage }} msrv: ${{ steps.crate_metadata.outputs.msrv }} ensure_cargo_fmt: name: Ensure 'cargo fmt' has been run runs-on: ubuntu-20.04 steps: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - uses: actions/checkout@v4 - run: cargo fmt -- --check min_version: name: Minimum supported rust version runs-on: ubuntu-20.04 needs: crate_metadata steps: - name: Checkout source code uses: actions/checkout@v4 - name: Install rust toolchain (v${{ needs.crate_metadata.outputs.msrv }}) uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.crate_metadata.outputs.msrv }} components: clippy - name: Run clippy (on minimum supported rust version to prevent warnings we can't fix) run: | cargo clippy --all-targets --features=gnu_legacy cargo clippy --all-targets --features=crossterm,ansi_term,nu-ansi-term - name: Run tests run: | cargo test --features=gnu_legacy cargo test --features=crossterm,ansi_term,nu-ansi-term documentation: name: Documentation runs-on: ubuntu-20.04 steps: - name: Git checkout uses: actions/checkout@v2 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@master with: toolchain: stable - name: Check documentation env: RUSTDOCFLAGS: -D warnings run: | cargo doc --no-deps --document-private-items --features=gnu_legacy cargo doc --no-deps --document-private-items --features=crossterm,ansi_term,nu-ansi-term build: name: ${{ matrix.job.target }} (${{ matrix.job.os }} with ${{ matrix.terminal }}) runs-on: ${{ matrix.job.os }} needs: crate_metadata strategy: fail-fast: false matrix: job: - { target: aarch64-unknown-linux-gnu , os: ubuntu-20.04, use-cross: true } - { target: arm-unknown-linux-gnueabihf , os: ubuntu-20.04, use-cross: true } - { target: arm-unknown-linux-musleabihf, os: ubuntu-20.04, use-cross: true } - { target: i686-pc-windows-msvc , os: windows-2019 } - { target: i686-unknown-linux-gnu , os: ubuntu-20.04, use-cross: true } - { target: i686-unknown-linux-musl , os: ubuntu-20.04, use-cross: true } - { target: x86_64-apple-darwin , os: macos-12 } - { target: x86_64-pc-windows-gnu , os: windows-2019 } - { target: x86_64-pc-windows-msvc , os: windows-2019 } - { target: x86_64-unknown-linux-gnu , os: ubuntu-20.04, use-cross: true } - { target: x86_64-unknown-linux-musl , os: ubuntu-20.04, use-cross: true } terminal: - ansi_term - crossterm - nu-ansi-term - gnu_legacy env: BUILD_CMD: cargo steps: - name: Checkout source code uses: actions/checkout@v4 - name: Install prerequisites shell: bash run: | case ${{ matrix.job.target }} in arm-unknown-linux-*) sudo apt-get -y update ; sudo apt-get -y install gcc-arm-linux-gnueabihf ;; aarch64-unknown-linux-gnu) sudo apt-get -y update ; sudo apt-get -y install gcc-aarch64-linux-gnu ;; esac - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable with: targets: ${{ matrix.job.target }} - name: Install cross if: matrix.job.use-cross uses: taiki-e/install-action@v2 with: tool: cross - name: Overwrite build command env variable if: matrix.job.use-cross shell: bash run: echo "BUILD_CMD=cross" >> $GITHUB_ENV - name: Show version information (Rust, cargo, GCC) shell: bash run: | gcc --version || true rustup -V rustup toolchain list rustup default cargo -V rustc -V - name: Build shell: bash run: $BUILD_CMD build --release --target=${{ matrix.job.target }} --features=${{ matrix.terminal }} - name: Set binary name & path id: bin shell: bash run: | # Figure out suffix of binary EXE_suffix="" case ${{ matrix.job.target }} in *-pc-windows-*) EXE_suffix=".exe" ;; esac; # Setup paths BIN_NAME="${{ needs.crate_metadata.outputs.name }}${EXE_suffix}" BIN_PATH="target/${{ matrix.job.target }}/release/${BIN_NAME}" # Let subsequent steps know where to find the binary echo "BIN_PATH=${BIN_PATH}" >> $GITHUB_OUTPUT echo "BIN_NAME=${BIN_NAME}" >> $GITHUB_OUTPUT - name: Run tests for all other targets shell: bash if: ${{ !startsWith(matrix.job.target, 'a') }} run: $BUILD_CMD test --target=${{ matrix.job.target }} --features=${{ matrix.terminal }} --lib --bin ${{ needs.crate_metadata.outputs.name }} - name: Run tests for arm and aarch64 shell: bash if: startsWith(matrix.job.target, 'a') run: $BUILD_CMD test --target=${{ matrix.job.target }} --features=${{ matrix.terminal }} --lib --bin ${{ needs.crate_metadata.outputs.name }} - name: Run lscolors shell: bash run: $BUILD_CMD run --target=${{ matrix.job.target }} --features ${{ matrix.terminal }} -- Cargo.toml Cargo.lock LICENSE-APACHE LICENSE-MIT README.md src/lib.rs - name: "Feature check: ${{ matrix.terminal }}" shell: bash run: $BUILD_CMD check --target=${{ matrix.job.target }} --verbose --lib --features ${{ matrix.terminal }} - name: Create tarball id: package shell: bash run: | PKG_suffix=".tar.gz" ; case ${{ matrix.job.target }} in *-pc-windows-*) PKG_suffix=".zip" ;; esac; PKG_BASENAME=${{ needs.crate_metadata.outputs.name }}-v${{ needs.crate_metadata.outputs.version }}-${{ matrix.job.target }} PKG_NAME=${PKG_BASENAME}${PKG_suffix} echo "PKG_NAME=${PKG_NAME}" >> $GITHUB_OUTPUT PKG_STAGING="${{ env.CICD_INTERMEDIATES_DIR }}/package" ARCHIVE_DIR="${PKG_STAGING}/${PKG_BASENAME}/" mkdir -p "${ARCHIVE_DIR}" # Binary cp "${{ steps.bin.outputs.BIN_PATH }}" "$ARCHIVE_DIR" # README, LICENSE files cp "README.md" "LICENSE-MIT" "LICENSE-APACHE" "$ARCHIVE_DIR" # base compressed package pushd "${PKG_STAGING}/" >/dev/null case ${{ matrix.job.target }} in *-pc-windows-*) 7z -y a "${PKG_NAME}" "${PKG_BASENAME}"/* | tail -2 ;; *) tar czf "${PKG_NAME}" "${PKG_BASENAME}"/* ;; esac; popd >/dev/null # Let subsequent steps know where to find the compressed package echo "PKG_PATH=${PKG_STAGING}/${PKG_NAME}" >> $GITHUB_OUTPUT - name: Create Debian package id: debian-package shell: bash if: startsWith(matrix.job.os, 'ubuntu') run: | COPYRIGHT_YEARS="2018 - "$(date "+%Y") DPKG_STAGING="${{ env.CICD_INTERMEDIATES_DIR }}/debian-package" DPKG_DIR="${DPKG_STAGING}/dpkg" mkdir -p "${DPKG_DIR}" DPKG_BASENAME=${{ needs.crate_metadata.outputs.name }} DPKG_CONFLICTS=${{ needs.crate_metadata.outputs.name }}-musl case ${{ matrix.job.target }} in *-musl*) DPKG_BASENAME=${{ needs.crate_metadata.outputs.name }}-musl ; DPKG_CONFLICTS=${{ needs.crate_metadata.outputs.name }} ;; esac; DPKG_VERSION=${{ needs.crate_metadata.outputs.version }} unset DPKG_ARCH case ${{ matrix.job.target }} in aarch64-*-linux-*) DPKG_ARCH=arm64 ;; arm-*-linux-*hf) DPKG_ARCH=armhf ;; i686-*-linux-*) DPKG_ARCH=i686 ;; x86_64-*-linux-*) DPKG_ARCH=amd64 ;; *) DPKG_ARCH=notset ;; esac; DPKG_NAME="${DPKG_BASENAME}_${DPKG_VERSION}_${DPKG_ARCH}.deb" echo "DPKG_NAME=${DPKG_NAME}" >> $GITHUB_OUTPUT # Binary install -Dm755 "${{ steps.bin.outputs.BIN_PATH }}" "${DPKG_DIR}/usr/bin/${{ steps.bin.outputs.BIN_NAME }}" # README and LICENSE install -Dm644 "README.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/README.md" install -Dm644 "LICENSE-MIT" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-MIT" install -Dm644 "LICENSE-APACHE" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-APACHE" cat > "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/copyright" < "${DPKG_DIR}/DEBIAN/control" <> $GITHUB_OUTPUT # build dpkg fakeroot dpkg-deb --build "${DPKG_DIR}" "${DPKG_PATH}" - name: "Artifact upload: tarball" uses: actions/upload-artifact@master if: matrix.terminal == 'ansi_term' with: name: ${{ steps.package.outputs.PKG_NAME }} path: ${{ steps.package.outputs.PKG_PATH }} - name: "Artifact upload: Debian package" uses: actions/upload-artifact@master if: steps.debian-package.outputs.DPKG_NAME && matrix.terminal == 'ansi_term' with: name: ${{ steps.debian-package.outputs.DPKG_NAME }} path: ${{ steps.debian-package.outputs.DPKG_PATH }} - name: Check for release id: is-release shell: bash run: | unset IS_RELEASE ; if [[ $GITHUB_REF =~ ^refs/tags/v[0-9].* ]]; then IS_RELEASE='true' ; fi echo "IS_RELEASE=${IS_RELEASE}" >> $GITHUB_OUTPUT - name: Publish archives and packages uses: softprops/action-gh-release@v1 if: steps.is-release.outputs.IS_RELEASE with: files: | ${{ steps.package.outputs.PKG_PATH }} ${{ steps.debian-package.outputs.DPKG_PATH }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} lscolors-0.20.0/.gitignore000064400000000000000000000000361046102023000135320ustar 00000000000000/target **/*.rs.bk Cargo.lock lscolors-0.20.0/Cargo.lock0000644000000243740000000000100107400ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "ansi_term" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" dependencies = [ "winapi", ] [[package]] name = "autocfg" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "bitflags" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "crossterm" version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" dependencies = [ "bitflags", "crossterm_winapi", "mio", "parking_lot", "rustix", "signal-hook", "signal-hook-mio", "winapi", ] [[package]] name = "crossterm_winapi" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" dependencies = [ "winapi", ] [[package]] name = "errno" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "fastrand" version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6" [[package]] name = "hermit-abi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "libc" version = "0.2.159" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5" [[package]] name = "linux-raw-sys" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "lock_api" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "lscolors" version = "0.20.0" dependencies = [ "aho-corasick", "ansi_term", "crossterm", "nu-ansi-term", "owo-colors", "tempfile", ] [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "mio" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" dependencies = [ "hermit-abi", "libc", "log", "wasi", "windows-sys 0.52.0", ] [[package]] name = "nu-ansi-term" version = "0.50.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4a28e057d01f97e61255210fcff094d74ed0466038633e95017f5beb68e4399" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "once_cell" version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82881c4be219ab5faaf2ad5e5e5ecdff8c66bd7402ca3160975c93b24961afd1" dependencies = [ "portable-atomic", ] [[package]] name = "owo-colors" version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb37767f6569cd834a413442455e0f066d0d522de8630436e2a1761d9726ba56" [[package]] name = "parking_lot" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", "windows-targets", ] [[package]] name = "portable-atomic" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" [[package]] name = "redox_syscall" version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" dependencies = [ "bitflags", ] [[package]] name = "rustix" version = "0.38.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys 0.52.0", ] [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "signal-hook" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", "signal-hook-registry", ] [[package]] name = "signal-hook-mio" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34db1a06d485c9142248b7a054f034b349b212551f3dfd19c94d45a754a217cd" dependencies = [ "libc", "mio", "signal-hook", ] [[package]] name = "signal-hook-registry" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" dependencies = [ "libc", ] [[package]] name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "tempfile" version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f2c9fc62d0beef6951ccffd757e241266a2c833136efbe35af6cd2567dca5b" dependencies = [ "cfg-if", "fastrand", "once_cell", "rustix", "windows-sys 0.59.0", ] [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" lscolors-0.20.0/Cargo.toml0000644000000026730000000000100107610ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.70.0" name = "lscolors" version = "0.20.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" [profile.release] lto = true codegen-units = 1 strip = true [[bin]] name = "lscolors" path = "src/bin.rs" [dependencies.aho-corasick] version = "1.1.3" [dependencies.ansi_term] version = "0.12" optional = true [dependencies.crossterm] version = "0.28" optional = true [dependencies.nu-ansi-term] version = "0.50" optional = true [dependencies.owo-colors] version = "4.0" optional = true [dev-dependencies.tempfile] version = "^3" [features] default = ["nu-ansi-term"] gnu_legacy = ["nu-ansi-term/gnu_legacy"] lscolors-0.20.0/Cargo.toml.orig000064400000000000000000000016641046102023000144410ustar 00000000000000[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.20.0" readme = "README.md" edition = "2021" authors = ["David Peter "] rust-version = "1.70.0" [features] default = ["nu-ansi-term"] gnu_legacy = ["nu-ansi-term/gnu_legacy"] [dependencies] ansi_term = { version = "0.12", optional = true } nu-ansi-term = { version = "0.50", optional = true } crossterm = { version = "0.28", optional = true } owo-colors = { version = "4.0", optional = true } aho-corasick = "1.1.3" [dev-dependencies] tempfile = "^3" [[bin]] name = "lscolors" path = "src/bin.rs" [profile.release] lto = true strip = true codegen-units = 1 lscolors-0.20.0/LICENSE-APACHE000064400000000000000000000261351046102023000134760ustar 00000000000000 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.20.0/LICENSE-MIT000064400000000000000000000017771046102023000132130ustar 00000000000000Permission 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.20.0/README.md000064400000000000000000000060021046102023000130200ustar 00000000000000# lscolors [![CICD](https://github.com/sharkdp/lscolors/actions/workflows/CICD.yml/badge.svg)](https://github.com/sharkdp/lscolors/actions/workflows/CICD.yml) [![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)); // If you want to use `nu-ansi-term` (fork of ansi_term) or `gnu_legacy`: let nu_ansi_style = style.map(Style::to_nu_ansi_term_style) .unwrap_or_default(); println!("{}", nu_ansi_style.paint(path)); // If you want to use `crossterm`: let crossterm_style = style.map(Style::to_crossterm_style) .unwrap_or_default(); println!("{}", crossterm_style.apply(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). If you want to build the application from source, you can run ```rs cargo build --release --features=nu-ansi-term --locked ``` ## Features ```rust // Cargo.toml [dependencies] // use ansi-term coloring lscolors = { version = "v0.14.0", features = ["ansi_term"] } // use crossterm coloring lscolors = { version = "v0.14.0", features = ["crossterm"] } // use nu-ansi-term coloring lscolors = { version = "v0.14.0", features = ["nu-ansi-term"] } // use nu-ansi-term coloring in gnu legacy mode with double digit styles lscolors = { version = "v0.14.0", features = ["gnu_legacy"] } ``` ## 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/2.6/src/color.c#L556) by [**@tavianator**](https://github.com/tavianator) * [The `DIR_COLORS(5)` man page](https://linux.die.net/man/5/dir_colors) lscolors-0.20.0/src/bin.rs000064400000000000000000000047121046102023000134540ustar 00000000000000use std::env; use std::io; use std::io::prelude::*; use std::path::Path; use lscolors::{LsColors, Style}; #[cfg(all( not(feature = "nu-ansi-term"), not(feature = "gnu_legacy"), not(feature = "ansi_term"), not(feature = "crossterm"), not(feature = "owo-colors") ))] compile_error!( "one feature must be enabled: ansi_term, nu-ansi-term, crossterm, gnu_legacy, owo-colors" ); 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)) { #[cfg(any(feature = "nu-ansi-term", feature = "gnu_legacy"))] { let ansi_style = style.map(Style::to_nu_ansi_term_style).unwrap_or_default(); write!(handle, "{}", ansi_style.paint(component.to_string_lossy()))?; } #[cfg(feature = "ansi_term")] { let ansi_style = style.map(Style::to_ansi_term_style).unwrap_or_default(); write!(handle, "{}", ansi_style.paint(component.to_string_lossy()))?; } #[cfg(feature = "crossterm")] { let ansi_style = style.map(Style::to_crossterm_style).unwrap_or_default(); write!(handle, "{}", ansi_style.apply(component.to_string_lossy()))?; } #[cfg(feature = "owo-colors")] { use owo_colors::OwoColorize; let ansi_style = style.map(Style::to_owo_colors_style).unwrap_or_default(); write!(handle, "{}", component.to_string_lossy().style(ansi_style))?; } } 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 Ok(size) = stdin.lock().read_until(b'\n', &mut buf) { if size == 0 { break; } let path_str = String::from_utf8_lossy(&buf[..(buf.len() - 1)]); #[cfg(windows)] let path_str = path_str.trim_end_matches('\r'); print_path(&mut stdout, &ls_colors, path_str.as_ref())?; buf.clear(); } } Ok(()) } fn main() { run().ok(); } lscolors-0.20.0/src/fs.rs000064400000000000000000000011631046102023000133110ustar 00000000000000use std::fs; #[cfg(any(unix, target_os = "redox"))] use std::os::unix::fs::MetadataExt; /// Get the UNIX-style mode bits from some metadata if available, otherwise 0. #[allow(unused_variables)] pub fn mode(md: &fs::Metadata) -> u32 { #[cfg(any(unix, target_os = "redox"))] return md.mode(); #[cfg(not(any(unix, target_os = "redox")))] return 0; } /// Get the number of hard links to a file, or 1 if unknown. #[allow(unused_variables)] pub fn nlink(md: &fs::Metadata) -> u64 { #[cfg(any(unix, target_os = "redox"))] return md.nlink(); #[cfg(not(any(unix, target_os = "redox")))] return 1; } lscolors-0.20.0/src/lib.rs000064400000000000000000001042751046102023000134570ustar 00000000000000//! 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 `nu_ansi_term`: //! # #[cfg(features = "nu-ansi-term")] //! # { //! let ansi_style = style.map(Style::to_nu_ansi_term_style).unwrap_or_default(); //! println!("{}", ansi_style.paint(path)); //! # } //! //! // If you want to use `ansi_term`: //! # #[cfg(features = "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; mod suffix; use std::collections::HashMap; use std::env; use std::ffi::OsString; use std::fs::{DirEntry, FileType, Metadata}; use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR}; use crate::suffix::{SuffixMap, SuffixMapBuilder}; 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, } } } /// 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 } } } /// A colorable file path. pub trait Colorable { /// Get the full path to this file. fn path(&self) -> PathBuf; /// Get the name of this file. fn file_name(&self) -> OsString; /// Try to get the type of this file. fn file_type(&self) -> Option; /// Try to get the metadata for this file. fn metadata(&self) -> Option; } impl Colorable for DirEntry { fn path(&self) -> PathBuf { self.path() } fn file_name(&self) -> OsString { self.file_name() } fn file_type(&self) -> Option { self.file_type().ok() } fn metadata(&self) -> Option { self.metadata().ok() } } /// Builder for [LsColors]. struct LsColorsBuilder { indicator_mapping: HashMap, /// Whether Indicator::RegularFile falls back to Indicator::Normal /// (see ) file_normal_fallback: bool, suffixes: SuffixMapBuilder, } impl LsColorsBuilder { fn empty() -> Self { Self { indicator_mapping: HashMap::new(), file_normal_fallback: true, suffixes: SuffixMapBuilder::default(), } } fn add_from_string(&mut self, input: &str) { for entry in input.split(':') { let parts: Vec<_> = entry.split('=').collect(); if let Some([entry, ansi_style]) = parts.get(0..2) { let style = Style::from_ansi_sequence(ansi_style); if let Some(suffix) = entry.strip_prefix('*') { self.suffixes.push(suffix, style); } else if let Some(indicator) = Indicator::from(entry) { if let Some(style) = style { self.indicator_mapping.insert(indicator, style); } else { self.indicator_mapping.remove(&indicator); if indicator == Indicator::RegularFile { self.file_normal_fallback = false; } } } } } } fn build(self) -> LsColors { LsColors { indicator_mapping: self.indicator_mapping, file_normal_fallback: self.file_normal_fallback, suffixes: self.suffixes.build(), } } } const LS_COLORS_DEFAULT: &str = "rs=0:lc=\x1b[:rc=m:cl=\x1b[K:ex=01;32:sg=30;43:su=37;41:di=01;34:st=37;44:ow=34;42:tw=30;42:ln=01;36:bd=01;33:cd=01;33:do=01;35:pi=33:so=01;35:"; impl Default for LsColorsBuilder { fn default() -> Self { let mut builder = Self::empty(); builder.add_from_string(LS_COLORS_DEFAULT); builder } } /// Holds information about how different file system entries should be colorized / styled. #[derive(Debug, Clone)] pub struct LsColors { indicator_mapping: HashMap, /// Whether Indicator::RegularFile falls back to Indicator::Normal /// (see ) file_normal_fallback: bool, suffixes: SuffixMap, } impl Default for LsColors { /// Constructs a default `LsColors` instance with some default styles. See `man dircolors` for /// information about the default styles and colors. fn default() -> Self { LsColorsBuilder::default().build() } } impl LsColors { /// Construct an empty [`LsColors`](struct.LsColors.html) instance with no pre-defined styles. pub fn empty() -> Self { LsColorsBuilder::empty().build() } /// Creates a new [`LsColors`](struct.LsColors.html) instance from the `LS_COLORS` environment /// variable. The basis for this is a default style as constructed via the `Default` /// implementation. 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 builder = LsColorsBuilder::default(); builder.add_from_string(input); builder.build() } /// 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()) } /// Check if an indicator has an associated color. fn has_color_for(&self, indicator: Indicator) -> bool { self.indicator_mapping.contains_key(&indicator) } /// Check if we need metadata to color a regular file. fn needs_file_metadata(&self) -> bool { self.has_color_for(Indicator::Setuid) || self.has_color_for(Indicator::Setgid) || self.has_color_for(Indicator::ExecutableFile) || self.has_color_for(Indicator::MultipleHardLinks) } /// Check if we need metadata to color a directory. fn needs_dir_metadata(&self) -> bool { self.has_color_for(Indicator::StickyAndOtherWritable) || self.has_color_for(Indicator::OtherWritable) || self.has_color_for(Indicator::Sticky) } /// Get the indicator type for a path with corresponding metadata. fn indicator_for(&self, file: &F) -> Indicator { let file_type = file.file_type(); if let Some(file_type) = file_type { if file_type.is_file() { if self.needs_file_metadata() { if let Some(metadata) = file.metadata() { let mode = crate::fs::mode(&metadata); let nlink = crate::fs::nlink(&metadata); if self.has_color_for(Indicator::Setuid) && mode & 0o4000 != 0 { return Indicator::Setuid; } else if self.has_color_for(Indicator::Setgid) && mode & 0o2000 != 0 { return Indicator::Setgid; } else if self.has_color_for(Indicator::ExecutableFile) && mode & 0o0111 != 0 { return Indicator::ExecutableFile; } else if self.has_color_for(Indicator::MultipleHardLinks) && nlink > 1 { return Indicator::MultipleHardLinks; } } } Indicator::RegularFile } else if file_type.is_dir() { if self.needs_dir_metadata() { if let Some(metadata) = file.metadata() { let mode = crate::fs::mode(&metadata); if self.has_color_for(Indicator::StickyAndOtherWritable) && mode & 0o1002 == 0o1002 { return Indicator::StickyAndOtherWritable; } else if self.has_color_for(Indicator::OtherWritable) && mode & 0o0002 != 0 { return Indicator::OtherWritable; } else if self.has_color_for(Indicator::Sticky) && mode & 0o1000 != 0 { return Indicator::Sticky; } } } Indicator::Directory } else if file_type.is_symlink() { // This works because `Path::exists` traverses symlinks. if self.has_color_for(Indicator::OrphanedSymbolicLink) && !file.path().exists() { return Indicator::OrphanedSymbolicLink; } Indicator::SymbolicLink } else { #[cfg(unix)] { use std::os::unix::fs::FileTypeExt; if file_type.is_fifo() { return Indicator::FIFO; } if file_type.is_socket() { return Indicator::Socket; } if file_type.is_block_device() { return Indicator::BlockDevice; } if file_type.is_char_device() { return Indicator::CharacterDevice; } } // Treat files of unknown type as errors Indicator::MissingFile } } else { // Default to a regular file, so we still try the suffix map when no metadata is available Indicator::RegularFile } } /// Get the ANSI style for a colorable path. pub fn style_for(&self, file: &F) -> Option<&Style> { let indicator = self.indicator_for(file); if indicator == Indicator::RegularFile { // Note: using '.to_str()' here means that filename // matching will not work with invalid-UTF-8 paths. let filename = file.file_name(); if let Some(style) = self.style_for_str(filename.to_str()?) { return Some(style); } } self.style_for_indicator(indicator) } /// Get the ANSI style for a string. This does not have to be a valid filepath. pub fn style_for_str(&self, file_str: &str) -> Option<&Style> { self.suffixes.get(file_str) } /// 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> { struct PathWithMetadata<'a> { path: &'a Path, metadata: Option<&'a Metadata>, } impl Colorable for PathWithMetadata<'_> { fn path(&self) -> PathBuf { self.path.to_owned() } fn file_name(&self) -> OsString { // Path::file_name() only works if the last component is Normal, but // we want it for all component types, so we open code it self.path .components() .last() .map(|c| c.as_os_str()) .unwrap_or_else(|| self.path.as_os_str()) .to_owned() } fn file_type(&self) -> Option { self.metadata.map(|m| m.file_type()) } fn metadata(&self) -> Option { self.metadata.cloned() } } let path = path.as_ref(); self.style_for(&PathWithMetadata { path, metadata }) } /// 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> { self.indicator_mapping .get(&indicator) .or_else(|| { self.indicator_mapping.get(&match indicator { Indicator::Setuid | Indicator::Setgid | Indicator::ExecutableFile | Indicator::MultipleHardLinks => Indicator::RegularFile, Indicator::StickyAndOtherWritable | Indicator::OtherWritable | Indicator::Sticky => Indicator::Directory, Indicator::OrphanedSymbolicLink => Indicator::SymbolicLink, Indicator::MissingFile => Indicator::OrphanedSymbolicLink, _ => indicator, }) }) .or_else(|| { if indicator == Indicator::RegularFile && !self.file_normal_fallback { None } else { self.indicator_mapping.get(&Indicator::Normal) } }) } } #[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::from_string("*.wav=00;36:"); let style_dir = lscolors.style_for_indicator(Indicator::Directory).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) .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"); // dummy.foo matches to *.foo without getting overriden. 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); // README.foo matches to *README.foo by overriding *.foo 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); let lscolors = LsColors::from_string("*README.foo=33;44:*.foo=01;35"); 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); // README.foo matches to *.foo because *.foo overrides *README.foo let style_readme = lscolors .style_for_path("some/other/folder/README.foo") .unwrap(); assert_eq!(FontStyle::bold(), style_readme.font_style); assert_eq!(Some(Color::Magenta), style_readme.foreground); assert_eq!(None, 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); } #[test] fn default_styles_should_be_preserved() { // Setting an unrelated style should not influence the default // style for "directory" (below) let lscolors = LsColors::from_string("ex=01:"); let style_dir = lscolors.style_for_indicator(Indicator::Directory).unwrap(); assert_eq!(FontStyle::bold(), style_dir.font_style); assert_eq!(Some(Color::Blue), style_dir.foreground); assert_eq!(None, style_dir.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