which-8.0.0/.cargo_vcs_info.json0000644000000001360000000000100121430ustar { "git": { "sha1": "adac2cdae7eaef4d5ce4cb2984ba43a0559adf06" }, "path_in_vcs": "" }which-8.0.0/.github/workflows/rust.yml000064400000000000000000000057361046102023000160630ustar 00000000000000name: Main workflow on: push: pull_request: jobs: # Run the `rustfmt` code formatter rustfmt: name: Rustfmt [Formatter] runs-on: ubuntu-latest steps: - name: Setup | Checkout uses: actions/checkout@v4 - name: Setup | Rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: stable components: rustfmt - name: Build | Format run: cargo fmt --all -- --check # Run the `clippy` linting tool clippy: name: Clippy [Linter] strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - name: Setup | Checkout uses: actions/checkout@v4 - name: Setup | Rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: stable components: clippy - name: Build | Lint run: cargo clippy --workspace --all-targets --all-features -- -Dwarnings - name: Build | Lint (no features) run: cargo clippy --workspace --all-targets -- -Dwarnings # Ensure that the project could be successfully compiled cargo_check: name: Compile strategy: matrix: target: [x86_64-unknown-linux-musl, wasm32-wasip1, wasm32-unknown-unknown] runs-on: ubuntu-latest steps: - name: Setup | Checkout uses: actions/checkout@v4 - name: Setup | Rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: stable target: ${{ matrix.target }} - name: Build | Check if: ${{ matrix.target != 'wasm32-unknown-unknown' }} run: | cargo check --workspace --target ${{ matrix.target }} cargo check --workspace --target ${{ matrix.target }} --features regex - name: Build | Check (no default features) run: | cargo check --workspace --target ${{ matrix.target }} --no-default-features cargo check --workspace --target ${{ matrix.target }} --no-default-features --features regex # Run tests on Linux, macOS, and Windows # On both Rust stable and Rust nightly test: name: Test Suite runs-on: ${{ matrix.os }} needs: cargo_check # First check then run expansive tests strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] rust: ['1.70', stable, nightly] steps: - name: Setup | Checkout uses: actions/checkout@v4 - name: Setup | Rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: ${{ matrix.rust }} # Run the ignored tests that expect the above setup - name: Build | Test run: cargo test --workspace --all-features -- --include-ignored - name: Build | Test (no default features) run: cargo test --workspace --no-default-features cargo-deny: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - uses: EmbarkStudios/cargo-deny-action@v1 which-8.0.0/.gitignore000064400000000000000000000000331046102023000127170ustar 00000000000000target Cargo.lock .vscode/ which-8.0.0/CHANGELOG.md000064400000000000000000000042021046102023000125420ustar 00000000000000# CHANGELOG ## 8.0.0 - Add new `Sys` trait to allow abstracting over the underlying filesystem. Particularly useful for `wasm32-unknown-unknown` targets. Thanks [@dsherret](https://github.com/dsherret) for this contribution to which! - Add more debug level tracing for otherwise silent I/O errors. - Call the `NonFatalHandler` in more places to catch previously ignored I/O errors. - Remove use of the `either` dependency. ## 7.0.3 - Update rustix to version 1.0. Congrats to rustix on this milestone, and thanks [@mhils](https://github.com/mhils) for this contribution to which! ## 7.0.2 - Don't return paths containing the single dot `.` reference to the current directory, even if the original request was given in terms of the current directory. Thanks [@jakobhellermann](https://github.com/jakobhellermann) for this contribution! ## 7.0.1 - Get user home directory from `env_home` instead of `home`. Thanks [@micolous](https://github.com/micolous) for this contribution! - If home directory is unavailable, do not expand the tilde to an empty string. Leave it as is. ## 7.0.0 - Add support to `WhichConfig` for a user provided closure that will be called whenever a nonfatal error occurs. This technically breaks a few APIs due to the need to add more generics and lifetimes. Most code will compile without changes. ## 6.0.3 - Enhance `tracing` feature with some `debug` level logs for higher level logic. ## 6.0.2 - Add `tracing` feature which outputs debugging information to the [`tracing`](https://crates.io/crates/tracing) ecosystem. ## 6.0.1 - Remove dependency on `once_cell` for Windows users, replace with `std::sync::OnceLock`. ## 6.0.0 - MSRV is now 1.70 - Upgraded all dependencies to latest version ## 5.0.0 - Remove several unused error messages - Windows executables can now be found even if they don't have a '.exe' extension. - Add new error message, `Error::CannotGetCurrentDirAndPathListEmpty` ## 4.4.2 - Remove dependency on `dirs` crate due to MPL licensing in its tree. Use `home` crate instead. (@Xaeroxe) ## 4.4.1 - Add tilde expansion for home directory (@Xaeroxe) - Swap out libc for rustix, forbid unsafe (@notgull) which-8.0.0/Cargo.lock0000644000000166020000000000100101230ustar # 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 = "bitflags" version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "env_home" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" [[package]] name = "errno" version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "getrandom" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", "r-efi", "wasi", ] [[package]] name = "libc" version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "linux-raw-sys" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "pin-project-lite" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "r-efi" version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" [[package]] name = "regex" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "rustix" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "tempfile" version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys", ] [[package]] name = "tracing" version = "0.1.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" dependencies = [ "pin-project-lite", "tracing-core", ] [[package]] name = "tracing-core" version = "0.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" [[package]] name = "wasi" version = "0.14.2+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "which" version = "8.0.0" dependencies = [ "env_home", "regex", "rustix", "tempfile", "tracing", "winsafe", ] [[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" [[package]] name = "winsafe" version = "0.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" [[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags", ] which-8.0.0/Cargo.toml0000644000000036720000000000100101510ustar # 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" name = "which" version = "8.0.0" authors = ["Harry Fei , Jacob Kiesel "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = 'A Rust equivalent of Unix command "which". Locate installed executable in cross platforms.' documentation = "https://docs.rs/which/" readme = "README.md" keywords = [ "which", "which-rs", "unix", "command", ] categories = [ "os", "filesystem", ] license = "MIT" repository = "https://github.com/harryfei/which-rs.git" [package.metadata.docs.rs] all-features = true [features] default = ["real-sys"] real-sys = [ "dep:env_home", "dep:rustix", "dep:winsafe", ] regex = ["dep:regex"] tracing = ["dep:tracing"] [lib] name = "which" path = "src/lib.rs" [[test]] name = "basic" path = "tests/basic.rs" [dependencies.regex] version = "1.10.2" optional = true [dependencies.tracing] version = "0.1.40" optional = true default-features = false [dev-dependencies.tempfile] version = "3.9.0" [target.'cfg(any(unix, target_os = "wasi", target_os = "redox"))'.dependencies.rustix] version = "1.0.5" features = [ "fs", "std", ] optional = true default-features = false [target.'cfg(any(windows, unix, target_os = "redox"))'.dependencies.env_home] version = "0.1.0" optional = true [target."cfg(windows)".dependencies.winsafe] version = "0.0.19" features = ["kernel"] optional = true which-8.0.0/Cargo.toml.orig000064400000000000000000000023731046102023000136270ustar 00000000000000[package] name = "which" version = "8.0.0" edition = "2021" rust-version = "1.70" authors = ["Harry Fei , Jacob Kiesel "] repository = "https://github.com/harryfei/which-rs.git" documentation = "https://docs.rs/which/" license = "MIT" description = "A Rust equivalent of Unix command \"which\". Locate installed executable in cross platforms." readme = "README.md" categories = ["os", "filesystem"] keywords = ["which", "which-rs", "unix", "command"] [features] default = ["real-sys"] regex = ["dep:regex"] tracing = ["dep:tracing"] real-sys = ["dep:env_home", "dep:rustix", "dep:winsafe"] [dependencies] regex = { version = "1.10.2", optional = true } tracing = { version = "0.1.40", default-features = false, optional = true } [target.'cfg(any(windows, unix, target_os = "redox"))'.dependencies] env_home = { version = "0.1.0", optional = true } [target.'cfg(any(unix, target_os = "wasi", target_os = "redox"))'.dependencies] rustix = { version = "1.0.5", default-features = false, features = ["fs", "std"], optional = true } [target.'cfg(windows)'.dependencies] winsafe = { version = "0.0.19", features = ["kernel"], optional = true } [dev-dependencies] tempfile = "3.9.0" [package.metadata.docs.rs] all-features = true which-8.0.0/LICENSE.txt000064400000000000000000000020401046102023000125520ustar 00000000000000Copyright (c) 2015 fangyuanziti Permission 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. which-8.0.0/README.md000064400000000000000000000045461046102023000122230ustar 00000000000000[![Build Status](https://github.com/harryfei/which-rs/actions/workflows/rust.yml/badge.svg)](https://github.com/harryfei/which-rs/actions/workflows/rust.yml) [![Actively Maintained](https://img.shields.io/badge/Maintenance%20Level-Actively%20Maintained-green.svg)](https://gist.github.com/cheerfulstoic/d107229326a01ff0f333a1d3476e068d) # which A Rust equivalent of Unix command "which". Locate installed executable in cross platforms. ## Support platforms * Linux * Windows * macOS * wasm32-wasi* ### A note on WebAssembly This project aims to support WebAssembly with the [WASI](https://wasi.dev/) extension. All `wasm32-wasi*` targets are officially supported. If you need to add a conditional dependency on `which` please refer to [the relevant cargo documentation for platform specific dependencies.](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies) Here's an example of how to conditionally add `which`. You should tweak this to your needs. ```toml [target.'cfg(not(all(target_family = "wasm", target_os = "unknown")))'.dependencies] which = "7.0.0" ``` Note that non-WASI environments have no access to the system. Using this in that situation requires disabling the default features of this crate and providing a custom `which::sys::Sys` implementation to `which::WhichConfig`. ## Examples 1) To find which rustc executable binary is using. ``` rust use which::which; let result = which("rustc").unwrap(); assert_eq!(result, PathBuf::from("/usr/bin/rustc")); ``` 2. After enabling the `regex` feature, find all cargo subcommand executables on the path: ``` rust use which::which_re; which_re(Regex::new("^cargo-.*").unwrap()).unwrap() .for_each(|pth| println!("{}", pth.to_string_lossy())); ``` ## MSRV This crate currently has an MSRV of Rust 1.70. Increasing the MSRV is considered a breaking change and thus requires a major version bump. We cannot make any guarantees about the MSRV of our dependencies. You may be required to pin one of our dependencies to a lower version in your own Cargo.toml in order to compile with the minimum supported Rust version. Eventually Cargo will handle this automatically. See [rust-lang/cargo#9930](https://github.com/rust-lang/cargo/issues/9930) for more. ## Documentation The documentation is [available online](https://docs.rs/which/). which-8.0.0/clippy.toml000064400000000000000000000111111046102023000131230ustar 00000000000000disallowed-methods = [ { path = "std::env::current_dir", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::canonicalize", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::is_dir", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::is_file", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::is_symlink", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::metadata", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::read_dir", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::read_link", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::symlink_metadata", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::try_exists", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::exists", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::canonicalize", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::is_dir", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::is_file", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::is_symlink", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::metadata", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::read_dir", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::read_link", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::symlink_metadata", reason = "System operations should be done using Sys trait" }, { path = "std::path::PathBuf::try_exists", reason = "System operations should be done using Sys trait" }, { path = "std::env::set_current_dir", reason = "System operations should be done using Sys trait" }, { path = "std::env::split_paths", reason = "System operations should be done using Sys trait" }, { path = "std::env::temp_dir", reason = "System operations should be done using Sys trait" }, { path = "std::env::var", reason = "System operations should be done using Sys trait" }, { path = "std::env::var_os", reason = "System operations should be done using Sys trait" }, { path = "std::fs::canonicalize", reason = "System operations should be done using Sys trait" }, { path = "std::fs::copy", reason = "System operations should be done using Sys trait" }, { path = "std::fs::create_dir_all", reason = "System operations should be done using Sys trait" }, { path = "std::fs::create_dir", reason = "System operations should be done using Sys trait" }, { path = "std::fs::DirBuilder::new", reason = "System operations should be done using Sys trait" }, { path = "std::fs::hard_link", reason = "System operations should be done using Sys trait" }, { path = "std::fs::metadata", reason = "System operations should be done using Sys trait" }, { path = "std::fs::OpenOptions::new", reason = "System operations should be done using Sys trait" }, { path = "std::fs::read_dir", reason = "System operations should be done using Sys trait" }, { path = "std::fs::read_link", reason = "System operations should be done using Sys trait" }, { path = "std::fs::read_to_string", reason = "System operations should be done using Sys trait" }, { path = "std::fs::read", reason = "System operations should be done using Sys trait" }, { path = "std::fs::remove_dir_all", reason = "System operations should be done using Sys trait" }, { path = "std::fs::remove_dir", reason = "System operations should be done using Sys trait" }, { path = "std::fs::remove_file", reason = "System operations should be done using Sys trait" }, { path = "std::fs::rename", reason = "System operations should be done using Sys trait" }, { path = "std::fs::set_permissions", reason = "System operations should be done using Sys trait" }, { path = "std::fs::symlink_metadata", reason = "System operations should be done using Sys trait" }, { path = "std::fs::write", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::canonicalize", reason = "System operations should be done using Sys trait" }, { path = "std::path::Path::exists", reason = "System operations should be done using Sys trait" }, ] which-8.0.0/deny.toml000064400000000000000000000254451046102023000126010ustar 00000000000000# This template contains all of the possible sections and their default values # Note that all fields that take a lint level have these possible values: # * deny - An error will be produced and the check will fail # * warn - A warning will be produced, but the check will not fail # * allow - No warning or error will be produced, though in some cases a note # will be # The values provided in this template are the default values that will be used # when any section or field is not specified in your own configuration # Root options # The graph table configures how the dependency graph is constructed and thus # which crates the checks are performed against [graph] # If 1 or more target triples (and optionally, target_features) are specified, # only the specified targets will be checked when running `cargo deny check`. # This means, if a particular package is only ever used as a target specific # dependency, such as, for example, the `nix` crate only being used via the # `target_family = "unix"` configuration, that only having windows targets in # this list would mean the nix crate, as well as any of its exclusive # dependencies not shared by any other crates, would be ignored, as the target # list here is effectively saying which targets you are building for. targets = [ # The triple can be any string, but only the target triples built in to # rustc (as of 1.40) can be checked against actual config expressions #"x86_64-unknown-linux-musl", # You can also specify which target_features you promise are enabled for a # particular target. target_features are currently not validated against # the actual valid features supported by the target architecture. #{ triple = "wasm32-unknown-unknown", features = ["atomics"] }, ] # When creating the dependency graph used as the source of truth when checks are # executed, this field can be used to prune crates from the graph, removing them # from the view of cargo-deny. This is an extremely heavy hammer, as if a crate # is pruned from the graph, all of its dependencies will also be pruned unless # they are connected to another crate in the graph that hasn't been pruned, # so it should be used with care. The identifiers are [Package ID Specifications] # (https://doc.rust-lang.org/cargo/reference/pkgid-spec.html) #exclude = [] # If true, metadata will be collected with `--all-features`. Note that this can't # be toggled off if true, if you want to conditionally enable `--all-features` it # is recommended to pass `--all-features` on the cmd line instead all-features = false # If true, metadata will be collected with `--no-default-features`. The same # caveat with `all-features` applies no-default-features = false # If set, these feature will be enabled when collecting metadata. If `--features` # is specified on the cmd line they will take precedence over this option. #features = [] # The output table provides options for how/if diagnostics are outputted [output] # When outputting inclusion graphs in diagnostics that include features, this # option can be used to specify the depth at which feature edges will be added. # This option is included since the graphs can be quite large and the addition # of features from the crate(s) to all of the graph roots can be far too verbose. # This option can be overridden via `--feature-depth` on the cmd line feature-depth = 1 # This section is considered when running `cargo deny check advisories` # More documentation for the advisories section can be found here: # https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html [advisories] # The path where the advisory databases are cloned/fetched into #db-path = "$CARGO_HOME/advisory-dbs" # The url(s) of the advisory databases to use #db-urls = ["https://github.com/rustsec/advisory-db"] # A list of advisory IDs to ignore. Note that ignored advisories will still # output a note when they are encountered. ignore = [ #"RUSTSEC-0000-0000", #{ id = "RUSTSEC-0000-0000", reason = "you can specify a reason the advisory is ignored" }, #"a-crate-that-is-yanked@0.1.1", # you can also ignore yanked crate versions if you wish #{ crate = "a-crate-that-is-yanked@0.1.1", reason = "you can specify why you are ignoring the yanked crate" }, ] # If this is true, then cargo deny will use the git executable to fetch advisory database. # If this is false, then it uses a built-in git library. # Setting this to true can be helpful if you have special authentication requirements that cargo-deny does not support. # See Git Authentication for more information about setting up git authentication. #git-fetch-with-cli = true # This section is considered when running `cargo deny check licenses` # More documentation for the licenses section can be found here: # https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html [licenses] # List of explicitly allowed licenses # See https://spdx.org/licenses/ for list of possible licenses # [possible values: any SPDX 3.11 short identifier (+ optional exception)]. allow = [ "MIT", "Apache-2.0", ] # The confidence threshold for detecting a license from license text. # The higher the value, the more closely the license text must be to the # canonical license text of a valid SPDX license file. # [possible values: any between 0.0 and 1.0]. confidence-threshold = 0.8 # Allow 1 or more licenses on a per-crate basis, so that particular licenses # aren't accepted for every possible crate as with the normal allow list exceptions = [ # Each entry is the crate and version constraint, and its specific allow # list #{ allow = ["Zlib"], crate = "adler32" }, ] # Some crates don't have (easily) machine readable licensing information, # adding a clarification entry for it allows you to manually specify the # licensing information #[[licenses.clarify]] # The package spec the clarification applies to #crate = "ring" # The SPDX expression for the license requirements of the crate #expression = "MIT AND ISC AND OpenSSL" # One or more files in the crate's source used as the "source of truth" for # the license expression. If the contents match, the clarification will be used # when running the license check, otherwise the clarification will be ignored # and the crate will be checked normally, which may produce warnings or errors # depending on the rest of your configuration #license-files = [ # Each entry is a crate relative path, and the (opaque) hash of its contents #{ path = "LICENSE", hash = 0xbd0eed23 } #] [licenses.private] # If true, ignores workspace crates that aren't published, or are only # published to private registries. # To see how to mark a crate as unpublished (to the official registry), # visit https://doc.rust-lang.org/cargo/reference/manifest.html#the-publish-field. ignore = false # One or more private registries that you might publish crates to, if a crate # is only published to private registries, and ignore is true, the crate will # not have its license(s) checked registries = [ #"https://sekretz.com/registry ] # This section is considered when running `cargo deny check bans`. # More documentation about the 'bans' section can be found here: # https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html [bans] # Lint level for when multiple versions of the same crate are detected multiple-versions = "warn" # Lint level for when a crate version requirement is `*` wildcards = "allow" # The graph highlighting used when creating dotgraphs for crates # with multiple versions # * lowest-version - The path to the lowest versioned duplicate is highlighted # * simplest-path - The path to the version with the fewest edges is highlighted # * all - Both lowest-version and simplest-path are used highlight = "all" # The default lint level for `default` features for crates that are members of # the workspace that is being checked. This can be overridden by allowing/denying # `default` on a crate-by-crate basis if desired. workspace-default-features = "allow" # The default lint level for `default` features for external crates that are not # members of the workspace. This can be overridden by allowing/denying `default` # on a crate-by-crate basis if desired. external-default-features = "allow" # List of crates that are allowed. Use with care! allow = [ #"ansi_term@0.11.0", #{ crate = "ansi_term@0.11.0", reason = "you can specify a reason it is allowed" }, ] # List of crates to deny deny = [ #"ansi_term@0.11.0", #{ crate = "ansi_term@0.11.0", reason = "you can specify a reason it is banned" }, # Wrapper crates can optionally be specified to allow the crate when it # is a direct dependency of the otherwise banned crate #{ crate = "ansi_term@0.11.0", wrappers = ["this-crate-directly-depends-on-ansi_term"] }, ] # List of features to allow/deny # Each entry the name of a crate and a version range. If version is # not specified, all versions will be matched. #[[bans.features]] #crate = "reqwest" # Features to not allow #deny = ["json"] # Features to allow #allow = [ # "rustls", # "__rustls", # "__tls", # "hyper-rustls", # "rustls", # "rustls-pemfile", # "rustls-tls-webpki-roots", # "tokio-rustls", # "webpki-roots", #] # If true, the allowed features must exactly match the enabled feature set. If # this is set there is no point setting `deny` #exact = true # Certain crates/versions that will be skipped when doing duplicate detection. skip = [ #"ansi_term@0.11.0", #{ crate = "ansi_term@0.11.0", reason = "you can specify a reason why it can't be updated/removed" }, ] # Similarly to `skip` allows you to skip certain crates during duplicate # detection. Unlike skip, it also includes the entire tree of transitive # dependencies starting at the specified crate, up to a certain depth, which is # by default infinite. skip-tree = [ #"ansi_term@0.11.0", # will be skipped along with _all_ of its direct and transitive dependencies #{ crate = "ansi_term@0.11.0", depth = 20 }, ] # This section is considered when running `cargo deny check sources`. # More documentation about the 'sources' section can be found here: # https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html [sources] # Lint level for what to happen when a crate from a crate registry that is not # in the allow list is encountered unknown-registry = "warn" # Lint level for what to happen when a crate from a git repository that is not # in the allow list is encountered unknown-git = "warn" # List of URLs for allowed crate registries. Defaults to the crates.io index # if not specified. If it is specified but empty, no registries are allowed. allow-registry = ["https://github.com/rust-lang/crates.io-index"] # List of URLs for allowed Git repositories allow-git = [] [sources.allow-org] # 1 or more github.com organizations to allow git sources for github = [""] # 1 or more gitlab.com organizations to allow git sources for gitlab = [""] # 1 or more bitbucket.org organizations to allow git sources for bitbucket = [""] which-8.0.0/src/checker.rs000064400000000000000000000044321046102023000134770ustar 00000000000000use crate::sys::Sys; use crate::sys::SysMetadata; use crate::{NonFatalError, NonFatalErrorHandler}; use std::path::Path; pub fn is_valid( sys: impl Sys, path: &Path, nonfatal_error_handler: &mut F, ) -> bool { exists(&sys, path, nonfatal_error_handler) && is_executable(&sys, path, nonfatal_error_handler) } fn is_executable( sys: impl Sys, path: &Path, nonfatal_error_handler: &mut F, ) -> bool { if sys.is_windows() && path.extension().is_some() { true } else { let ret = sys .is_valid_executable(path) .map_err(|e| nonfatal_error_handler.handle(NonFatalError::Io(e))) .unwrap_or(false); #[cfg(feature = "tracing")] tracing::trace!("{} EXEC_OK = {ret}", path.display()); ret } } fn exists( sys: impl Sys, path: &Path, nonfatal_error_handler: &mut F, ) -> bool { { if sys.is_windows() { let ret = sys .symlink_metadata(path) .map(|metadata| { #[cfg(feature = "tracing")] tracing::trace!( "{} is_file() = {}, is_symlink() = {}", path.display(), metadata.is_file(), metadata.is_symlink() ); metadata.is_file() || metadata.is_symlink() }) .map_err(|e| { nonfatal_error_handler.handle(NonFatalError::Io(e)); }) .unwrap_or(false); #[cfg(feature = "tracing")] tracing::trace!( "{} has_extension = {}, checker::exists() = {ret}", path.display(), path.extension().is_some() ); ret } else { let ret = sys.metadata(path).map(|metadata| metadata.is_file()); #[cfg(feature = "tracing")] tracing::trace!("{} is_file() = {ret:?}", path.display()); match ret { Ok(ret) => ret, Err(e) => { nonfatal_error_handler.handle(NonFatalError::Io(e)); false } } } } } which-8.0.0/src/error.rs000064400000000000000000000023251046102023000132230ustar 00000000000000use std::{fmt, io}; pub type Result = std::result::Result; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Error { /// An executable binary with that name was not found CannotFindBinaryPath, /// There was nowhere to search and the provided name wasn't an absolute path CannotGetCurrentDirAndPathListEmpty, /// Failed to canonicalize the path found CannotCanonicalize, } impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::CannotFindBinaryPath => write!(f, "cannot find binary path"), Error::CannotGetCurrentDirAndPathListEmpty => write!( f, "no path to search and provided name is not an absolute path" ), Error::CannotCanonicalize => write!(f, "cannot canonicalize path"), } } } #[derive(Debug)] #[non_exhaustive] pub enum NonFatalError { Io(io::Error), } impl std::error::Error for NonFatalError {} impl fmt::Display for NonFatalError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Io(e) => write!(f, "{e}"), } } } which-8.0.0/src/finder.rs000064400000000000000000000272441046102023000133500ustar 00000000000000use crate::checker::is_valid; use crate::helper::has_executable_extension; use crate::sys::Sys; use crate::sys::SysReadDirEntry; use crate::{error::*, NonFatalErrorHandler}; #[cfg(feature = "regex")] use regex::Regex; #[cfg(feature = "regex")] use std::borrow::Borrow; use std::borrow::Cow; use std::ffi::OsStr; #[cfg(feature = "regex")] use std::io; use std::path::{Component, Path, PathBuf}; use std::vec; trait PathExt { fn has_separator(&self) -> bool; fn to_absolute

(self, cwd: P) -> PathBuf where P: AsRef; } impl PathExt for PathBuf { fn has_separator(&self) -> bool { self.components().count() > 1 } fn to_absolute

(self, cwd: P) -> PathBuf where P: AsRef, { if self.is_absolute() { self } else { let mut new_path = PathBuf::from(cwd.as_ref()); new_path.extend( self.components() .skip_while(|c| matches!(c, Component::CurDir)), ); new_path } } } pub struct Finder { sys: TSys, } impl Finder { pub fn new(sys: TSys) -> Self { Finder { sys } } pub fn find<'a, T, U, V, F: NonFatalErrorHandler + 'a>( self, binary_name: T, paths: Option, cwd: Option, nonfatal_error_handler: F, ) -> Result + 'a> where TSys: 'a, T: AsRef, U: AsRef, V: AsRef + 'a, { let path = PathBuf::from(&binary_name); #[cfg(feature = "tracing")] tracing::debug!( "query binary_name = {:?}, paths = {:?}, cwd = {:?}", binary_name.as_ref().to_string_lossy(), paths.as_ref().map(|p| p.as_ref().to_string_lossy()), cwd.as_ref().map(|p| p.as_ref().display()) ); let ret = match cwd { Some(cwd) if path.has_separator() => { WhichFindIterator::new_cwd(path, cwd.as_ref(), self.sys, nonfatal_error_handler) } _ => { #[cfg(feature = "tracing")] tracing::trace!("{} has no path seperators, so only paths in PATH environment variable will be searched.", path.display()); // Search binary in PATHs(defined in environment variable). let paths = paths.ok_or(Error::CannotGetCurrentDirAndPathListEmpty)?; let paths = self.sys.env_split_paths(paths.as_ref()); if paths.is_empty() { return Err(Error::CannotGetCurrentDirAndPathListEmpty); } WhichFindIterator::new_paths(path, paths, self.sys, nonfatal_error_handler) } }; #[cfg(feature = "tracing")] let ret = ret.inspect(|p| { tracing::debug!("found path {}", p.display()); }); Ok(ret) } #[cfg(feature = "regex")] pub fn find_re( self, binary_regex: impl std::borrow::Borrow, paths: Option, nonfatal_error_handler: F, ) -> Result> where T: AsRef, { WhichFindRegexIter::new(self.sys, paths, binary_regex, nonfatal_error_handler) } } struct WhichFindIterator { sys: TSys, paths: PathsIter>, nonfatal_error_handler: F, } impl WhichFindIterator { pub fn new_cwd(binary_name: PathBuf, cwd: &Path, sys: TSys, nonfatal_error_handler: F) -> Self { let path_extensions = if sys.is_windows() { sys.env_windows_path_ext() } else { Cow::Borrowed(Default::default()) }; Self { sys, paths: PathsIter { paths: vec![binary_name.to_absolute(cwd)].into_iter(), current_path_with_index: None, path_extensions, }, nonfatal_error_handler, } } pub fn new_paths( binary_name: PathBuf, paths: Vec, sys: TSys, nonfatal_error_handler: F, ) -> Self { let path_extensions = if sys.is_windows() { sys.env_windows_path_ext() } else { Cow::Borrowed(Default::default()) }; let paths = paths .iter() .map(|p| tilde_expansion(&sys, p).join(&binary_name)) .collect::>(); Self { sys, paths: PathsIter { paths: paths.into_iter(), current_path_with_index: None, path_extensions, }, nonfatal_error_handler, } } } impl Iterator for WhichFindIterator { type Item = PathBuf; fn next(&mut self) -> Option { for path in &mut self.paths { if is_valid(&self.sys, &path, &mut self.nonfatal_error_handler) { return Some(correct_casing( &self.sys, path, &mut self.nonfatal_error_handler, )); } } None } } struct PathsIter

where P: Iterator, { paths: P, current_path_with_index: Option<(PathBuf, usize)>, path_extensions: Cow<'static, [String]>, } impl

Iterator for PathsIter

where P: Iterator, { type Item = PathBuf; fn next(&mut self) -> Option { if self.path_extensions.is_empty() { self.paths.next() } else if let Some((p, index)) = self.current_path_with_index.take() { let next_index = index + 1; if next_index < self.path_extensions.len() { self.current_path_with_index = Some((p.clone(), next_index)); } // Append the extension. let mut p = p.into_os_string(); p.push(&self.path_extensions[index]); let ret = PathBuf::from(p); #[cfg(feature = "tracing")] tracing::trace!("possible extension: {}", ret.display()); Some(ret) } else { let p = self.paths.next()?; if has_executable_extension(&p, &self.path_extensions) { #[cfg(feature = "tracing")] tracing::trace!( "{} already has an executable extension, not modifying it further", p.display() ); } else { #[cfg(feature = "tracing")] tracing::trace!( "{} has no extension, using PATHEXT environment variable to infer one", p.display() ); // Appended paths with windows executable extensions. // e.g. path `c:/windows/bin[.ext]` will expand to: // [c:/windows/bin.ext] // c:/windows/bin[.ext].COM // c:/windows/bin[.ext].EXE // c:/windows/bin[.ext].CMD // ... self.current_path_with_index = Some((p.clone(), 0)); } Some(p) } } } fn tilde_expansion(sys: TSys, p: &Path) -> Cow<'_, Path> { let mut component_iter = p.components(); if let Some(Component::Normal(o)) = component_iter.next() { if o == "~" { let new_path = sys.home_dir(); if let Some(mut new_path) = new_path { new_path.extend(component_iter); #[cfg(feature = "tracing")] tracing::trace!( "found tilde, substituting in user's home directory to get {}", new_path.display() ); return Cow::Owned(new_path); } else { #[cfg(feature = "tracing")] tracing::trace!("found tilde in path, but user's home directory couldn't be found"); } } } Cow::Borrowed(p) } fn correct_casing( sys: TSys, mut p: PathBuf, nonfatal_error_handler: &mut F, ) -> PathBuf { if sys.is_windows() { if let (Some(parent), Some(file_name)) = (p.parent(), p.file_name()) { if let Ok(iter) = sys.read_dir(parent) { for e in iter { match e { Ok(e) => { if e.file_name().eq_ignore_ascii_case(file_name) { p.pop(); p.push(e.file_name()); break; } } Err(e) => { nonfatal_error_handler.handle(NonFatalError::Io(e)); } } } } } } p } #[cfg(feature = "regex")] struct WhichFindRegexIter, F: NonFatalErrorHandler> { sys: TSys, re: B, paths: vec::IntoIter, nonfatal_error_handler: F, current_read_dir_iter: Option>>>, } #[cfg(feature = "regex")] impl, F: NonFatalErrorHandler> WhichFindRegexIter { pub fn new>( sys: TSys, paths: Option, re: B, nonfatal_error_handler: F, ) -> Result { let p = paths.ok_or(Error::CannotGetCurrentDirAndPathListEmpty)?; let paths = sys.env_split_paths(p.as_ref()); Ok(WhichFindRegexIter { sys, re, paths: paths.into_iter(), nonfatal_error_handler, current_read_dir_iter: None, }) } } #[cfg(feature = "regex")] impl, F: NonFatalErrorHandler> Iterator for WhichFindRegexIter { type Item = PathBuf; fn next(&mut self) -> Option { loop { if let Some(iter) = &mut self.current_read_dir_iter { match iter.next() { Some(Ok(path)) => { if let Some(unicode_file_name) = path.file_name().to_str() { if self.re.borrow().is_match(unicode_file_name) { return Some(path.path()); } else { #[cfg(feature = "tracing")] tracing::debug!("regex filtered out {}", unicode_file_name); } } else { #[cfg(feature = "tracing")] tracing::debug!("regex unable to evaluate filename as it's not valid unicode. Lossy filename conversion: {}", path.file_name().to_string_lossy()); } } Some(Err(e)) => { self.nonfatal_error_handler.handle(NonFatalError::Io(e)); } None => { self.current_read_dir_iter = None; } } } else { let path = self.paths.next(); if let Some(path) = path { match self.sys.read_dir(&path) { Ok(new_read_dir_iter) => { self.current_read_dir_iter = Some(new_read_dir_iter); } Err(e) => { self.nonfatal_error_handler.handle(NonFatalError::Io(e)); } } } else { return None; } } } } } which-8.0.0/src/helper.rs000064400000000000000000000023121046102023000133450ustar 00000000000000use std::path::Path; /// Check if given path has extension which in the given vector. pub fn has_executable_extension, S: AsRef>(path: T, pathext: &[S]) -> bool { let ext = path.as_ref().extension().and_then(|e| e.to_str()); match ext { Some(ext) => pathext .iter() .any(|e| !e.as_ref().is_empty() && ext.eq_ignore_ascii_case(&e.as_ref()[1..])), _ => false, } } #[cfg(test)] mod test { use super::*; use std::path::PathBuf; #[test] fn test_extension_in_extension_vector() { // Case insensitive assert!(has_executable_extension( PathBuf::from("foo.exe"), &[".COM", ".EXE", ".CMD"] )); assert!(has_executable_extension( PathBuf::from("foo.CMD"), &[".COM", ".EXE", ".CMD"] )); } #[test] fn test_extension_not_in_extension_vector() { assert!(!has_executable_extension( PathBuf::from("foo.bar"), &[".COM", ".EXE", ".CMD"] )); } #[test] fn test_invalid_exts() { assert!(!has_executable_extension( PathBuf::from("foo.bar"), &["", "."] )); } } which-8.0.0/src/lib.rs000064400000000000000000000550671046102023000126530ustar 00000000000000//! which //! //! A Rust equivalent of Unix command `which(1)`. //! # Example: //! //! To find which rustc executable binary is using: //! //! ```no_run //! # #[cfg(feature = "real-sys")] //! # { //! use which::which; //! use std::path::PathBuf; //! //! let result = which("rustc").unwrap(); //! assert_eq!(result, PathBuf::from("/usr/bin/rustc")); //! # } //! ``` mod checker; mod error; mod finder; mod helper; pub mod sys; use std::fmt; use std::path; use std::ffi::{OsStr, OsString}; pub use crate::error::*; use crate::finder::Finder; use crate::sys::Sys; /// Find an executable binary's path by name. /// /// If given an absolute path, returns it if the file exists and is executable. /// /// If given a relative path, returns an absolute path to the file if /// it exists and is executable. /// /// If given a string without path separators, looks for a file named /// `binary_name` at each directory in `$PATH` and if it finds an executable /// file there, returns it. /// /// # Example /// /// ```no_run /// use which::which; /// use std::path::PathBuf; /// /// let result = which::which("rustc").unwrap(); /// assert_eq!(result, PathBuf::from("/usr/bin/rustc")); /// /// ``` #[cfg(feature = "real-sys")] pub fn which>(binary_name: T) -> Result { which_all(binary_name).and_then(|mut i| i.next().ok_or(Error::CannotFindBinaryPath)) } /// Find an executable binary's path by name, ignoring `cwd`. /// /// If given an absolute path, returns it if the file exists and is executable. /// /// Does not resolve relative paths. /// /// If given a string without path separators, looks for a file named /// `binary_name` at each directory in `$PATH` and if it finds an executable /// file there, returns it. /// /// # Example /// /// ```no_run /// use which::which; /// use std::path::PathBuf; /// /// let result = which::which_global("rustc").unwrap(); /// assert_eq!(result, PathBuf::from("/usr/bin/rustc")); /// /// ``` #[cfg(feature = "real-sys")] pub fn which_global>(binary_name: T) -> Result { which_all_global(binary_name).and_then(|mut i| i.next().ok_or(Error::CannotFindBinaryPath)) } /// Find all binaries with `binary_name` using `cwd` to resolve relative paths. #[cfg(feature = "real-sys")] pub fn which_all>(binary_name: T) -> Result> { let cwd = sys::RealSys.current_dir().ok(); Finder::new(&sys::RealSys).find(binary_name, sys::RealSys.env_path(), cwd, Noop) } /// Find all binaries with `binary_name` ignoring `cwd`. #[cfg(feature = "real-sys")] pub fn which_all_global>( binary_name: T, ) -> Result> { Finder::new(&sys::RealSys).find( binary_name, sys::RealSys.env_path(), Option::<&Path>::None, Noop, ) } /// Find all binaries matching a regular expression in a the system PATH. /// /// Only available when feature `regex` is enabled. /// /// # Arguments /// /// * `regex` - A regular expression to match binaries with /// /// # Examples /// /// Find Python executables: /// /// ```no_run /// use regex::Regex; /// use which::which; /// use std::path::PathBuf; /// /// let re = Regex::new(r"python\d$").unwrap(); /// let binaries: Vec = which::which_re(re).unwrap().collect(); /// let python_paths = vec![PathBuf::from("/usr/bin/python2"), PathBuf::from("/usr/bin/python3")]; /// assert_eq!(binaries, python_paths); /// ``` /// /// Find all cargo subcommand executables on the path: /// /// ``` /// use which::which_re; /// use regex::Regex; /// /// which_re(Regex::new("^cargo-.*").unwrap()).unwrap() /// .for_each(|pth| println!("{}", pth.to_string_lossy())); /// ``` #[cfg(all(feature = "regex", feature = "real-sys"))] pub fn which_re( regex: impl std::borrow::Borrow, ) -> Result> { which_re_in(regex, sys::RealSys.env_path()) } /// Find `binary_name` in the path list `paths`, using `cwd` to resolve relative paths. #[cfg(feature = "real-sys")] pub fn which_in(binary_name: T, paths: Option, cwd: V) -> Result where T: AsRef, U: AsRef, V: AsRef, { which_in_all(binary_name, paths, cwd) .and_then(|mut i| i.next().ok_or(Error::CannotFindBinaryPath)) } /// Find all binaries matching a regular expression in a list of paths. /// /// Only available when feature `regex` is enabled. /// /// # Arguments /// /// * `regex` - A regular expression to match binaries with /// * `paths` - A string containing the paths to search /// (separated in the same way as the PATH environment variable) /// /// # Examples /// /// ```no_run /// use regex::Regex; /// use which::which; /// use std::path::PathBuf; /// /// let re = Regex::new(r"python\d$").unwrap(); /// let paths = Some("/usr/bin:/usr/local/bin"); /// let binaries: Vec = which::which_re_in(re, paths).unwrap().collect(); /// let python_paths = vec![PathBuf::from("/usr/bin/python2"), PathBuf::from("/usr/bin/python3")]; /// assert_eq!(binaries, python_paths); /// ``` #[cfg(all(feature = "regex", feature = "real-sys"))] pub fn which_re_in( regex: impl std::borrow::Borrow, paths: Option, ) -> Result> where T: AsRef, { Finder::new(&sys::RealSys).find_re(regex, paths, Noop) } /// Find all binaries with `binary_name` in the path list `paths`, using `cwd` to resolve relative paths. #[cfg(feature = "real-sys")] pub fn which_in_all<'a, T, U, V>( binary_name: T, paths: Option, cwd: V, ) -> Result + 'a> where T: AsRef, U: AsRef, V: AsRef + 'a, { Finder::new(&sys::RealSys).find(binary_name, paths, Some(cwd), Noop) } /// Find all binaries with `binary_name` in the path list `paths`, ignoring `cwd`. #[cfg(feature = "real-sys")] pub fn which_in_global( binary_name: T, paths: Option, ) -> Result> where T: AsRef, U: AsRef, { Finder::new(&sys::RealSys).find(binary_name, paths, Option::<&Path>::None, Noop) } /// A wrapper containing all functionality in this crate. pub struct WhichConfig { cwd: CwdOption, custom_path_list: Option, binary_name: Option, nonfatal_error_handler: F, #[cfg(feature = "regex")] regex: Option, sys: TSys, } enum CwdOption { Unspecified, UseSysCwd, RefuseCwd, UseCustomCwd(path::PathBuf), } /// A handler for non-fatal errors which does nothing with them. #[derive(Default, Debug, Clone)] pub struct Noop; /// Defines what should happen when a nonfatal error is encountered. A nonfatal error may represent a problem, /// but it doesn't necessarily require `which` to stop its search. /// /// This trait is implemented for any closure or function that takes a single argument which is a [`NonFatalError`]. /// You may also implement it for your own types. pub trait NonFatalErrorHandler { fn handle(&mut self, e: NonFatalError); } impl NonFatalErrorHandler for Noop { fn handle(&mut self, _: NonFatalError) { // Do nothing } } impl NonFatalErrorHandler for T where T: FnMut(NonFatalError), { fn handle(&mut self, e: NonFatalError) { (self)(e); } } #[cfg(feature = "real-sys")] impl Default for WhichConfig<&sys::RealSys, F> { fn default() -> Self { Self { cwd: CwdOption::Unspecified, custom_path_list: None, binary_name: None, nonfatal_error_handler: F::default(), #[cfg(feature = "regex")] regex: None, sys: &sys::RealSys, } } } #[cfg(feature = "regex")] type Regex = regex::Regex; #[cfg(not(feature = "regex"))] type Regex = (); #[cfg(feature = "real-sys")] impl WhichConfig<&sys::RealSys, Noop> { pub fn new() -> Self { Self::new_with_sys(&sys::RealSys) } } impl WhichConfig { /// Creates a new `WhichConfig` with the given `sys::Sys`. /// /// This is useful for providing all the system related /// functionality to this crate. pub fn new_with_sys(sys: TSys) -> Self { Self { cwd: CwdOption::Unspecified, custom_path_list: None, binary_name: None, nonfatal_error_handler: Noop, #[cfg(feature = "regex")] regex: None, sys, } } } impl<'a, TSys: Sys + 'a, F: NonFatalErrorHandler + 'a> WhichConfig { /// Whether or not to use the current working directory. `true` by default. /// /// # Panics /// /// If regex was set previously, and you've just passed in `use_cwd: true`, this will panic. pub fn system_cwd(mut self, use_cwd: bool) -> Self { #[cfg(feature = "regex")] if self.regex.is_some() && use_cwd { panic!("which can't use regex and cwd at the same time!") } // Otherwise, keep custom cwd if specified. self.cwd = if use_cwd { CwdOption::UseSysCwd } else { CwdOption::RefuseCwd }; self } /// Sets a custom path for resolving relative paths. /// /// # Panics /// /// If regex was set previously, this will panic. pub fn custom_cwd(mut self, cwd: path::PathBuf) -> Self { #[cfg(feature = "regex")] if self.regex.is_some() { panic!("which can't use regex and cwd at the same time!") } self.cwd = CwdOption::UseCustomCwd(cwd); self } /// Sets the path name regex to search for. You ***MUST*** call this, or [`Self::binary_name`] prior to searching. /// /// When `Regex` is disabled this function takes the unit type as a stand in. The parameter will change when /// `Regex` is enabled. /// /// # Panics /// /// If the `regex` feature wasn't turned on for this crate this will always panic. Additionally if a /// `cwd` (aka current working directory) or `binary_name` was set previously, this will panic, as those options /// are incompatible with `regex`. #[allow(unused_variables)] #[allow(unused_mut)] pub fn regex(mut self, regex: Regex) -> Self { #[cfg(not(feature = "regex"))] { panic!("which's regex feature was not enabled in your Cargo.toml!") } #[cfg(feature = "regex")] { if matches!(self.cwd, CwdOption::UseSysCwd) || matches!(self.cwd, CwdOption::UseCustomCwd(_)) { panic!("which can't use regex and cwd at the same time!") } if self.binary_name.is_some() { panic!("which can't use `binary_name` and `regex` at the same time!"); } self.regex = Some(regex); self } } /// Sets the path name to search for. You ***MUST*** call this, or [`Self::regex`] prior to searching. /// /// # Panics /// /// If a `regex` was set previously this will panic as this is not compatible with `regex`. pub fn binary_name(mut self, name: OsString) -> Self { #[cfg(feature = "regex")] if self.regex.is_some() { panic!("which can't use `binary_name` and `regex` at the same time!"); } self.binary_name = Some(name); self } /// Uses the given string instead of the `PATH` env variable. pub fn custom_path_list(mut self, custom_path_list: OsString) -> Self { self.custom_path_list = Some(custom_path_list); self } /// Uses the `PATH` env variable. Enabled by default. pub fn system_path_list(mut self) -> Self { self.custom_path_list = None; self } /// Sets a closure that will receive non-fatal errors. You can also pass in other types /// that implement [`NonFatalErrorHandler`]. /// /// # Example /// ``` /// # #[cfg(feature = "real-sys")] /// # { /// # use which::WhichConfig; /// let mut nonfatal_errors = Vec::new(); /// /// WhichConfig::new() /// .binary_name("tar".into()) /// .nonfatal_error_handler(|e| nonfatal_errors.push(e)) /// .all_results() /// .unwrap() /// .collect::>(); /// /// if !nonfatal_errors.is_empty() { /// println!("nonfatal errors encountered: {nonfatal_errors:?}"); /// } /// # } /// ``` /// /// You could also log it if you choose /// /// ``` /// # #[cfg(feature = "real-sys")] /// # { /// # use which::WhichConfig; /// WhichConfig::new() /// .binary_name("tar".into()) /// .nonfatal_error_handler(|e| eprintln!("{e}")) /// .all_results() /// .unwrap() /// .collect::>(); /// # } /// ``` pub fn nonfatal_error_handler(self, handler: NewF) -> WhichConfig { WhichConfig { custom_path_list: self.custom_path_list, cwd: self.cwd, binary_name: self.binary_name, nonfatal_error_handler: handler, #[cfg(feature = "regex")] regex: self.regex, sys: self.sys, } } /// Finishes configuring, runs the query and returns the first result. pub fn first_result(self) -> Result { self.all_results() .and_then(|mut i| i.next().ok_or(Error::CannotFindBinaryPath)) } /// Finishes configuring, runs the query and returns all results. pub fn all_results(self) -> Result + 'a> { let paths = self.custom_path_list.or_else(|| self.sys.env_path()); #[cfg(feature = "regex")] if let Some(regex) = self.regex { return Finder::new(self.sys) .find_re(regex, paths, self.nonfatal_error_handler) .map(|i| Box::new(i) as Box + 'a>); } let cwd = match self.cwd { CwdOption::RefuseCwd => None, CwdOption::UseCustomCwd(custom) => Some(custom), CwdOption::UseSysCwd | CwdOption::Unspecified => self.sys.current_dir().ok(), }; Finder::new(self.sys) .find( self.binary_name.expect( "binary_name not set! You must set binary_name or regex before searching!", ), paths, cwd, self.nonfatal_error_handler, ) .map(|i| Box::new(i) as Box + 'a>) } } /// An owned, immutable wrapper around a `PathBuf` containing the path of an executable. /// /// The constructed `PathBuf` is the output of `which` or `which_in`, but `which::Path` has the /// advantage of being a type distinct from `std::path::Path` and `std::path::PathBuf`. /// /// It can be beneficial to use `which::Path` instead of `std::path::Path` when you want the type /// system to enforce the need for a path that exists and points to a binary that is executable. /// /// Since `which::Path` implements `Deref` for `std::path::Path`, all methods on `&std::path::Path` /// are also available to `&which::Path` values. #[derive(Clone, PartialEq, Eq)] pub struct Path { inner: path::PathBuf, } impl Path { /// Returns the path of an executable binary by name. /// /// This calls `which` and maps the result into a `Path`. #[cfg(feature = "real-sys")] pub fn new>(binary_name: T) -> Result { which(binary_name).map(|inner| Path { inner }) } /// Returns the paths of all executable binaries by a name. /// /// this calls `which_all` and maps the results into `Path`s. #[cfg(feature = "real-sys")] pub fn all>(binary_name: T) -> Result> { which_all(binary_name).map(|inner| inner.map(|inner| Path { inner })) } /// Returns the path of an executable binary by name in the path list `paths` and using the /// current working directory `cwd` to resolve relative paths. /// /// This calls `which_in` and maps the result into a `Path`. #[cfg(feature = "real-sys")] pub fn new_in(binary_name: T, paths: Option, cwd: V) -> Result where T: AsRef, U: AsRef, V: AsRef, { which_in(binary_name, paths, cwd).map(|inner| Path { inner }) } /// Returns all paths of an executable binary by name in the path list `paths` and using the /// current working directory `cwd` to resolve relative paths. /// /// This calls `which_in_all` and maps the results into a `Path`. #[cfg(feature = "real-sys")] pub fn all_in<'a, T, U, V>( binary_name: T, paths: Option, cwd: V, ) -> Result + 'a> where T: AsRef, U: AsRef, V: AsRef + 'a, { which_in_all(binary_name, paths, cwd).map(|inner| inner.map(|inner| Path { inner })) } /// Returns a reference to a `std::path::Path`. pub fn as_path(&self) -> &path::Path { self.inner.as_path() } /// Consumes the `which::Path`, yielding its underlying `std::path::PathBuf`. pub fn into_path_buf(self) -> path::PathBuf { self.inner } } impl fmt::Debug for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.inner, f) } } impl std::ops::Deref for Path { type Target = path::Path; fn deref(&self) -> &path::Path { self.inner.deref() } } impl AsRef for Path { fn as_ref(&self) -> &path::Path { self.as_path() } } impl AsRef for Path { fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl PartialEq for Path { fn eq(&self, other: &path::PathBuf) -> bool { self.inner == *other } } impl PartialEq for path::PathBuf { fn eq(&self, other: &Path) -> bool { *self == other.inner } } /// An owned, immutable wrapper around a `PathBuf` containing the _canonical_ path of an /// executable. /// /// The constructed `PathBuf` is the result of `which` or `which_in` followed by /// `Path::canonicalize`, but `CanonicalPath` has the advantage of being a type distinct from /// `std::path::Path` and `std::path::PathBuf`. /// /// It can be beneficial to use `CanonicalPath` instead of `std::path::Path` when you want the type /// system to enforce the need for a path that exists, points to a binary that is executable, is /// absolute, has all components normalized, and has all symbolic links resolved /// /// Since `CanonicalPath` implements `Deref` for `std::path::Path`, all methods on /// `&std::path::Path` are also available to `&CanonicalPath` values. #[derive(Clone, PartialEq, Eq)] pub struct CanonicalPath { inner: path::PathBuf, } impl CanonicalPath { /// Returns the canonical path of an executable binary by name. /// /// This calls `which` and `Path::canonicalize` and maps the result into a `CanonicalPath`. #[cfg(feature = "real-sys")] pub fn new>(binary_name: T) -> Result { which(binary_name) .and_then(|p| { sys::RealSys .canonicalize(&p) .map_err(|_| Error::CannotCanonicalize) }) .map(|inner| CanonicalPath { inner }) } /// Returns the canonical paths of an executable binary by name. /// /// This calls `which_all` and `Path::canonicalize` and maps the results into `CanonicalPath`s. #[cfg(feature = "real-sys")] pub fn all>( binary_name: T, ) -> Result>> { which_all(binary_name).map(|inner| { inner.map(|inner| { sys::RealSys .canonicalize(&inner) .map_err(|_| Error::CannotCanonicalize) .map(|inner| CanonicalPath { inner }) }) }) } /// Returns the canonical path of an executable binary by name in the path list `paths` and /// using the current working directory `cwd` to resolve relative paths. /// /// This calls `which_in` and `Path::canonicalize` and maps the result into a `CanonicalPath`. #[cfg(feature = "real-sys")] pub fn new_in(binary_name: T, paths: Option, cwd: V) -> Result where T: AsRef, U: AsRef, V: AsRef, { which_in(binary_name, paths, cwd) .and_then(|p| { sys::RealSys .canonicalize(&p) .map_err(|_| Error::CannotCanonicalize) }) .map(|inner| CanonicalPath { inner }) } /// Returns all of the canonical paths of an executable binary by name in the path list `paths` and /// using the current working directory `cwd` to resolve relative paths. /// /// This calls `which_in_all` and `Path::canonicalize` and maps the result into a `CanonicalPath`. #[cfg(feature = "real-sys")] pub fn all_in<'a, T, U, V>( binary_name: T, paths: Option, cwd: V, ) -> Result> + 'a> where T: AsRef, U: AsRef, V: AsRef + 'a, { which_in_all(binary_name, paths, cwd).map(|inner| { inner.map(|inner| { sys::RealSys .canonicalize(&inner) .map_err(|_| Error::CannotCanonicalize) .map(|inner| CanonicalPath { inner }) }) }) } /// Returns a reference to a `std::path::Path`. pub fn as_path(&self) -> &path::Path { self.inner.as_path() } /// Consumes the `which::CanonicalPath`, yielding its underlying `std::path::PathBuf`. pub fn into_path_buf(self) -> path::PathBuf { self.inner } } impl fmt::Debug for CanonicalPath { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.inner, f) } } impl std::ops::Deref for CanonicalPath { type Target = path::Path; fn deref(&self) -> &path::Path { self.inner.deref() } } impl AsRef for CanonicalPath { fn as_ref(&self) -> &path::Path { self.as_path() } } impl AsRef for CanonicalPath { fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl PartialEq for CanonicalPath { fn eq(&self, other: &path::PathBuf) -> bool { self.inner == *other } } impl PartialEq for path::PathBuf { fn eq(&self, other: &CanonicalPath) -> bool { *self == other.inner } } which-8.0.0/src/sys.rs000064400000000000000000000230661046102023000127150ustar 00000000000000use std::borrow::Cow; use std::ffi::OsStr; use std::ffi::OsString; use std::io; use std::path::Path; use std::path::PathBuf; pub trait SysReadDirEntry { /// Gets the file name of the directory entry, not the full path. fn file_name(&self) -> OsString; /// Gets the full path of the directory entry. fn path(&self) -> PathBuf; } pub trait SysMetadata { /// Gets if the path is a symlink. fn is_symlink(&self) -> bool; /// Gets if the path is a file. fn is_file(&self) -> bool; } /// Represents the system that `which` interacts with to get information /// about the environment and file system. /// /// ### How to use in Wasm without WASI /// /// WebAssembly without WASI does not have a filesystem, but using this crate is possible in `wasm32-unknown-unknown` targets by disabling default features: /// /// ```toml /// which = { version = "...", default-features = false } /// ``` /// // Then providing your own implementation of the `which::sys::Sys` trait: /// /// ```rs /// use which::WhichConfig; /// /// struct WasmSys; /// /// impl which::sys::Sys for WasmSys { /// // it is up to you to implement this trait based on the /// // environment you are running WebAssembly in /// } /// /// let paths = WhichConfig::new_with_sys(WasmSys) /// .all_results() /// .unwrap() /// .collect::>(); /// ``` pub trait Sys { type ReadDirEntry: SysReadDirEntry; type Metadata: SysMetadata; /// Check if the current platform is Windows. /// /// This can be set to true in wasm32-unknown-unknown targets that /// are running on Windows systems. fn is_windows(&self) -> bool; /// Gets the current working directory. fn current_dir(&self) -> io::Result; /// Gets the home directory of the current user. fn home_dir(&self) -> Option; /// Splits a platform-specific PATH variable into a list of paths. fn env_split_paths(&self, paths: &OsStr) -> Vec; /// Gets the value of the PATH environment variable. fn env_path(&self) -> Option; /// Gets the value of the PATHEXT environment variable. If not on Windows, simply return None. fn env_path_ext(&self) -> Option; /// Gets and parses the PATHEXT environment variable on Windows. /// /// Override this to enable caching the parsed PATHEXT. /// /// Note: This will only be called when `is_windows()` returns `true` /// and isn't conditionally compiled with `#[cfg(windows)]` so that it /// can work in Wasm. fn env_windows_path_ext(&self) -> Cow<'static, [String]> { Cow::Owned(parse_path_ext(self.env_path_ext())) } /// Gets the metadata of the provided path, following symlinks. fn metadata(&self, path: &Path) -> io::Result; /// Gets the metadata of the provided path, not following symlinks. fn symlink_metadata(&self, path: &Path) -> io::Result; /// Reads the directory entries of the provided path. fn read_dir( &self, path: &Path, ) -> io::Result>>>; /// Checks if the provided path is a valid executable. fn is_valid_executable(&self, path: &Path) -> io::Result; } impl SysReadDirEntry for std::fs::DirEntry { fn file_name(&self) -> OsString { self.file_name() } fn path(&self) -> PathBuf { self.path() } } impl SysMetadata for std::fs::Metadata { fn is_symlink(&self) -> bool { self.file_type().is_symlink() } fn is_file(&self) -> bool { self.file_type().is_file() } } #[cfg(feature = "real-sys")] #[derive(Default, Clone, Copy)] pub struct RealSys; #[cfg(feature = "real-sys")] impl RealSys { #[inline] pub(crate) fn canonicalize(&self, path: &Path) -> io::Result { #[allow(clippy::disallowed_methods)] // ok, sys implementation std::fs::canonicalize(path) } } #[cfg(feature = "real-sys")] impl Sys for RealSys { type ReadDirEntry = std::fs::DirEntry; type Metadata = std::fs::Metadata; #[inline] fn is_windows(&self) -> bool { // Again, do not change the code to directly use `#[cfg(windows)]` // because we want to allow people to implement this code in Wasm // and then tell at runtime if running on a Windows system. cfg!(windows) } #[inline] fn current_dir(&self) -> io::Result { #[allow(clippy::disallowed_methods)] // ok, sys implementation std::env::current_dir() } #[inline] fn home_dir(&self) -> Option { // Home dir shim, use env_home crate when possible. Otherwise, return None #[cfg(any(windows, unix, target_os = "redox"))] { env_home::env_home_dir() } #[cfg(not(any(windows, unix, target_os = "redox")))] { None } } #[inline] fn env_split_paths(&self, paths: &OsStr) -> Vec { #[allow(clippy::disallowed_methods)] // ok, sys implementation std::env::split_paths(paths).collect() } fn env_windows_path_ext(&self) -> Cow<'static, [String]> { use std::sync::OnceLock; // Sample %PATHEXT%: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC // PATH_EXTENSIONS is then [".COM", ".EXE", ".BAT", …]. // (In one use of PATH_EXTENSIONS we skip the dot, but in the other we need it; // hence its retention.) static PATH_EXTENSIONS: OnceLock> = OnceLock::new(); let path_extensions = PATH_EXTENSIONS.get_or_init(|| parse_path_ext(self.env_path_ext())); Cow::Borrowed(path_extensions) } #[inline] fn env_path(&self) -> Option { #[allow(clippy::disallowed_methods)] // ok, sys implementation std::env::var_os("PATH") } #[inline] fn env_path_ext(&self) -> Option { #[allow(clippy::disallowed_methods)] // ok, sys implementation std::env::var_os("PATHEXT") } #[inline] fn read_dir( &self, path: &Path, ) -> io::Result>>> { #[allow(clippy::disallowed_methods)] // ok, sys implementation let iter = std::fs::read_dir(path)?; Ok(Box::new(iter)) } #[inline] fn metadata(&self, path: &Path) -> io::Result { #[allow(clippy::disallowed_methods)] // ok, sys implementation std::fs::metadata(path) } #[inline] fn symlink_metadata(&self, path: &Path) -> io::Result { #[allow(clippy::disallowed_methods)] // ok, sys implementation std::fs::symlink_metadata(path) } #[cfg(any(unix, target_os = "wasi", target_os = "redox"))] fn is_valid_executable(&self, path: &Path) -> io::Result { use rustix::fs as rfs; rfs::access(path, rfs::Access::EXEC_OK) .map(|_| true) .map_err(|e| io::Error::from_raw_os_error(e.raw_os_error())) } #[cfg(windows)] fn is_valid_executable(&self, path: &Path) -> io::Result { winsafe::GetBinaryType(&path.display().to_string()) .map(|_| true) .map_err(|e| io::Error::from_raw_os_error(e.raw() as i32)) } } impl Sys for &T where T: Sys, { type ReadDirEntry = T::ReadDirEntry; type Metadata = T::Metadata; fn is_windows(&self) -> bool { (*self).is_windows() } fn current_dir(&self) -> io::Result { (*self).current_dir() } fn home_dir(&self) -> Option { (*self).home_dir() } fn env_split_paths(&self, paths: &OsStr) -> Vec { (*self).env_split_paths(paths) } fn env_path(&self) -> Option { (*self).env_path() } fn env_path_ext(&self) -> Option { (*self).env_path_ext() } fn metadata(&self, path: &Path) -> io::Result { (*self).metadata(path) } fn symlink_metadata(&self, path: &Path) -> io::Result { (*self).symlink_metadata(path) } fn read_dir( &self, path: &Path, ) -> io::Result>>> { (*self).read_dir(path) } fn is_valid_executable(&self, path: &Path) -> io::Result { (*self).is_valid_executable(path) } } fn parse_path_ext(pathext: Option) -> Vec { pathext .and_then(|pathext| { // If tracing feature enabled then this lint is incorrect, so disable it. #[allow(clippy::manual_ok_err)] match pathext.into_string() { Ok(pathext) => Some(pathext), Err(_) => { #[cfg(feature = "tracing")] tracing::error!("pathext is not valid unicode"); None } } }) .map(|pathext| { pathext .split(';') .filter_map(|s| { if s.as_bytes().first() == Some(&b'.') { Some(s.to_owned()) } else { // Invalid segment; just ignore it. #[cfg(feature = "tracing")] tracing::debug!("PATHEXT segment \"{s}\" missing leading dot, ignoring"); None } }) .collect() }) // PATHEXT not being set or not being a proper Unicode string is exceedingly // improbable and would probably break Windows badly. Still, don't crash: .unwrap_or_default() } which-8.0.0/tests/basic.rs000064400000000000000000000657041046102023000135400ustar 00000000000000#![allow(clippy::disallowed_methods)] extern crate which; #[cfg(feature = "real-sys")] mod real_sys { #[cfg(all(unix, feature = "regex"))] use regex::Regex; use std::ffi::{OsStr, OsString}; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::{env, vec}; use tempfile::TempDir; #[derive(Debug)] struct TestFixture { /// Temp directory. pub tempdir: TempDir, /// $PATH pub paths: OsString, /// Binaries created in $PATH pub bins: Vec, } const SUBDIRS: &[&str] = &["a", "b", "c"]; const BIN_NAME: &str = "bin"; #[allow(clippy::unnecessary_cast)] #[cfg(unix)] fn mk_bin(dir: &Path, path: &str, extension: &str) -> io::Result { use std::os::unix::fs::OpenOptionsExt; let bin = dir.join(path).with_extension(extension); #[cfg(any(target_os = "macos", target_os = "linux"))] let mode = rustix::fs::Mode::XUSR.bits() as u32; let mode = 0o666 | mode; fs::OpenOptions::new() .write(true) .create(true) .mode(mode) .open(&bin) .and_then(|_f| bin.canonicalize()) } fn touch(dir: &Path, path: &str, extension: &str) -> io::Result { let b = dir.join(path).with_extension(extension); fs::File::create(&b).and_then(|_f| b.canonicalize()) } #[cfg(windows)] fn mk_bin(dir: &Path, path: &str, extension: &str) -> io::Result { touch(dir, path, extension) } impl TestFixture { // tmp/a/bin // tmp/a/bin.exe // tmp/a/bin.cmd // tmp/b/bin // tmp/b/bin.exe // tmp/b/bin.cmd // tmp/c/bin // tmp/c/bin.exe // tmp/c/bin.cmd pub fn new() -> TestFixture { let tempdir = tempfile::tempdir().unwrap(); let mut builder = fs::DirBuilder::new(); builder.recursive(true); let mut paths = vec![]; let mut bins = vec![]; for d in SUBDIRS.iter() { let p = tempdir.path().join(d); builder.create(&p).unwrap(); bins.push(mk_bin(&p, BIN_NAME, "").unwrap()); bins.push(mk_bin(&p, BIN_NAME, "exe").unwrap()); bins.push(mk_bin(&p, BIN_NAME, "cmd").unwrap()); paths.push(p); } let p = tempdir.path().join("win-bin"); builder.create(&p).unwrap(); bins.push(mk_bin(&p, "win-bin", "exe").unwrap()); paths.push(p); TestFixture { tempdir, paths: env::join_paths(paths).unwrap(), bins, } } #[cfg(unix)] pub fn new_with_tilde_path() -> TestFixture { let tempdir = tempfile::tempdir().unwrap(); let mut builder = fs::DirBuilder::new(); builder.recursive(true); let mut paths = vec![]; let mut bins = vec![]; for d in SUBDIRS.iter() { let p = PathBuf::from("~").join(d); let p_bin = tempdir.path().join(d); builder.create(&p_bin).unwrap(); bins.push(mk_bin(&p_bin, BIN_NAME, "").unwrap()); bins.push(mk_bin(&p_bin, BIN_NAME, "exe").unwrap()); bins.push(mk_bin(&p_bin, BIN_NAME, "cmd").unwrap()); paths.push(p); } let p = tempdir.path().join("win-bin"); builder.create(&p).unwrap(); bins.push(mk_bin(&p, "win-bin", "exe").unwrap()); paths.push(p); TestFixture { tempdir, paths: env::join_paths(paths).unwrap(), bins, } } #[allow(dead_code)] pub fn touch(&self, path: &str, extension: &str) -> io::Result { touch(self.tempdir.path(), path, extension) } pub fn mk_bin(&self, path: &str, extension: &str) -> io::Result { mk_bin(self.tempdir.path(), path, extension) } } fn _which>(f: &TestFixture, path: T) -> which::Result { which::CanonicalPath::new_in(path, Some(f.paths.clone()), f.tempdir.path()) } fn _which_uncanonicalized>(f: &TestFixture, path: T) -> which::Result { which::which_in(path, Some(f.paths.clone()), f.tempdir.path()) } fn _which_all<'a, T: AsRef + 'a>( f: &'a TestFixture, path: T, ) -> which::Result> + 'a> { which::CanonicalPath::all_in(path, Some(f.paths.clone()), f.tempdir.path()) } #[test] #[cfg(unix)] fn it_works() { use std::process::Command; let result = which::Path::new("rustc"); assert!(result.is_ok()); let which_result = Command::new("which").arg("rustc").output(); assert_eq!( String::from(result.unwrap().to_str().unwrap()), String::from_utf8(which_result.unwrap().stdout) .unwrap() .trim() ); } #[test] #[cfg(unix)] fn test_which() { let f = TestFixture::new(); assert_eq!(_which(&f, BIN_NAME).unwrap(), f.bins[0]) } #[test] #[cfg(windows)] fn test_which() { let f = TestFixture::new(); assert_eq!(_which(&f, BIN_NAME).unwrap(), f.bins[1]) } #[test] #[cfg(unix)] fn test_which_tilde() { let old_home = env::var_os("HOME"); let f = TestFixture::new_with_tilde_path(); env::set_var("HOME", f.tempdir.path().as_os_str()); assert_eq!(_which(&f, BIN_NAME).unwrap(), f.bins[0]); if let Some(old_home) = old_home { env::set_var("HOME", old_home); } else { env::remove_var("HOME"); } } // Windows test_which_tilde intentionally omitted because // we don't want to pollute the home directory. // It's non-trivial to adjust which directory Windows thinks // is the home directory. At this time, tilde expansion has // no Windows specific behavior. It works as normal on Windows. #[test] #[cfg(all(unix, feature = "regex"))] fn test_which_re_in_with_matches() { let f = TestFixture::new(); f.mk_bin("a/bin_0", "").unwrap(); f.mk_bin("b/bin_1", "").unwrap(); let re = Regex::new(r"bin_\d").unwrap(); let result: Vec = which::which_re_in(re, Some(f.paths)).unwrap().collect(); let temp = f.tempdir; assert_eq!( result, vec![temp.path().join("a/bin_0"), temp.path().join("b/bin_1")] ) } #[test] #[cfg(all(unix, feature = "regex"))] fn test_which_re_in_without_matches() { let f = TestFixture::new(); let re = Regex::new(r"bi[^n]").unwrap(); let result: Vec = which::which_re_in(re, Some(f.paths)).unwrap().collect(); assert_eq!(result, Vec::::new()) } #[test] #[cfg(all(unix, feature = "regex"))] fn test_which_re_accepts_owned_and_borrow() { which::which_re(Regex::new(r".").unwrap()) .unwrap() .for_each(drop); which::which_re(&Regex::new(r".").unwrap()) .unwrap() .for_each(drop); which::which_re_in(Regex::new(r".").unwrap(), Some("pth")) .unwrap() .for_each(drop); which::which_re_in(&Regex::new(r".").unwrap(), Some("pth")) .unwrap() .for_each(drop); } #[test] #[cfg(unix)] fn test_which_extension() { let f = TestFixture::new(); let b = Path::new(&BIN_NAME).with_extension(""); assert_eq!(_which(&f, b).unwrap(), f.bins[0]) } #[test] #[cfg(windows)] fn test_which_extension() { let f = TestFixture::new(); let b = Path::new(&BIN_NAME).with_extension("cmd"); assert_eq!(_which(&f, b).unwrap(), f.bins[2]) } #[test] #[cfg(windows)] fn test_which_no_extension() { let f = TestFixture::new(); let b = Path::new("win-bin"); let which_result = which::which_in(b, Some(&f.paths), ".").unwrap(); // Make sure the extension is the correct case. assert_eq!(which_result.extension(), f.bins[9].extension()); assert_eq!(fs::canonicalize(&which_result).unwrap(), f.bins[9]) } #[test] fn test_which_not_found() { let f = TestFixture::new(); assert!(_which(&f, "a").is_err()); } #[test] fn test_which_second() { let f = TestFixture::new(); let b = f.mk_bin("b/another", env::consts::EXE_EXTENSION).unwrap(); assert_eq!(_which(&f, "another").unwrap(), b); } #[test] fn test_which_all() { let f = TestFixture::new(); let actual = _which_all(&f, BIN_NAME) .unwrap() .map(|c| c.unwrap()) .collect::>(); let mut expected = f .bins .iter() .map(|p| p.canonicalize().unwrap()) .collect::>(); #[cfg(windows)] { expected.retain(|p| p.file_stem().unwrap() == BIN_NAME); expected .retain(|p| p.extension().map(|ext| ext == "exe" || ext == "cmd") == Some(true)); } #[cfg(not(windows))] { expected.retain(|p| p.file_name().unwrap() == BIN_NAME); } assert_eq!(actual, expected); } #[test] #[cfg(unix)] fn test_which_absolute() { let f = TestFixture::new(); assert_eq!( _which(&f, &f.bins[3]).unwrap(), f.bins[3].canonicalize().unwrap() ); } #[test] #[cfg(windows)] fn test_which_absolute() { let f = TestFixture::new(); assert_eq!( _which(&f, &f.bins[4]).unwrap(), f.bins[4].canonicalize().unwrap() ); } #[test] #[cfg(windows)] fn test_which_absolute_path_case() { // Test that an absolute path with an uppercase extension // is accepted. let f = TestFixture::new(); let p = &f.bins[4]; assert_eq!(_which(&f, p).unwrap(), f.bins[4].canonicalize().unwrap()); } #[test] #[cfg(unix)] fn test_which_absolute_extension() { let f = TestFixture::new(); // Don't append EXE_EXTENSION here. let b = f.bins[3].parent().unwrap().join(BIN_NAME); assert_eq!(_which(&f, b).unwrap(), f.bins[3].canonicalize().unwrap()); } #[test] #[cfg(windows)] fn test_which_absolute_extension() { let f = TestFixture::new(); // Don't append EXE_EXTENSION here. let b = f.bins[4].parent().unwrap().join(BIN_NAME); assert_eq!(_which(&f, b).unwrap(), f.bins[4].canonicalize().unwrap()); } #[test] #[cfg(unix)] fn test_which_relative() { let f = TestFixture::new(); assert_eq!( _which(&f, "b/bin").unwrap(), f.bins[3].canonicalize().unwrap() ); } #[test] #[cfg(windows)] fn test_which_relative() { let f = TestFixture::new(); assert_eq!( _which(&f, "b/bin").unwrap(), f.bins[4].canonicalize().unwrap() ); } #[test] #[cfg(unix)] fn test_which_relative_extension() { // test_which_relative tests a relative path without an extension, // so test a relative path with an extension here. let f = TestFixture::new(); let b = Path::new("b/bin").with_extension(env::consts::EXE_EXTENSION); assert_eq!(_which(&f, b).unwrap(), f.bins[3].canonicalize().unwrap()); } #[test] #[cfg(windows)] fn test_which_relative_extension() { // test_which_relative tests a relative path without an extension, // so test a relative path with an extension here. let f = TestFixture::new(); let b = Path::new("b/bin").with_extension("cmd"); assert_eq!(_which(&f, b).unwrap(), f.bins[5].canonicalize().unwrap()); } #[test] #[cfg(windows)] fn test_which_relative_extension_case() { // Test that a relative path with an uppercase extension // is accepted. let f = TestFixture::new(); let b = Path::new("b/bin").with_extension("EXE"); assert_eq!(_which(&f, b).unwrap(), f.bins[4].canonicalize().unwrap()); } #[test] #[cfg(unix)] fn test_which_relative_leading_dot() { let f = TestFixture::new(); assert_eq!( _which(&f, "./b/bin").unwrap(), f.bins[3].canonicalize().unwrap() ); } #[test] #[cfg(windows)] fn test_which_relative_leading_dot() { let f = TestFixture::new(); assert_eq!( _which(&f, "./b/bin").unwrap(), f.bins[4].canonicalize().unwrap() ); } #[test] #[cfg(all(unix, not(target_os = "macos")))] fn test_which_relative_leading_dot_uncanonicalized() { let f = TestFixture::new(); let actual = _which_uncanonicalized(&f, "./b/bin").unwrap(); assert_eq!(actual, f.bins[3].canonicalize().unwrap()); assert!( !actual.display().to_string().contains("/./"), "'{}' should not contain a CurDir component", actual.display() ); } #[test] #[cfg(unix)] fn test_which_non_executable() { // Shouldn't return non-executable files. let f = TestFixture::new(); f.touch("b/another", "").unwrap(); assert!(_which(&f, "another").is_err()); } #[test] #[cfg(unix)] fn test_which_absolute_non_executable() { // Shouldn't return non-executable files, even if given an absolute path. let f = TestFixture::new(); let b = f.touch("b/another", "").unwrap(); assert!(_which(&f, b).is_err()); } #[test] #[cfg(unix)] fn test_which_relative_non_executable() { // Shouldn't return non-executable files. let f = TestFixture::new(); f.touch("b/another", "").unwrap(); assert!(_which(&f, "b/another").is_err()); } #[test] fn test_failure() { let f = TestFixture::new(); let run = || -> which::Result { let p = _which(&f, "./b/bin")?; Ok(p.into_path_buf()) }; let _ = run(); } #[test] #[cfg(windows)] fn windows_no_extension_but_executable() { let this_executable = std::env::current_exe().unwrap(); let new_name = this_executable.parent().unwrap().join("test_executable"); std::fs::copy(&this_executable, &new_name).unwrap(); let found_executable = which::which_in_global( new_name.file_name().unwrap(), Some(this_executable.parent().unwrap()), ) .unwrap() .next() .unwrap(); assert_eq!(found_executable, new_name); std::fs::remove_file(new_name).unwrap(); } } mod in_memory { use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::ffi::OsStr; use std::ffi::OsString; use std::io; use std::io::Error; use std::io::ErrorKind; use std::path::Component; use std::path::Path; use std::path::PathBuf; struct Metadata { is_symlink: bool, is_file: bool, } impl which::sys::SysMetadata for Metadata { fn is_symlink(&self) -> bool { self.is_symlink } fn is_file(&self) -> bool { self.is_file } } struct ReadDirEntry { path: PathBuf, } impl which::sys::SysReadDirEntry for ReadDirEntry { fn file_name(&self) -> OsString { self.path.file_name().unwrap().to_os_string() } fn path(&self) -> PathBuf { self.path.clone() } } #[derive(Debug, Clone)] enum DirectoryEntry { Directory(Directory), File(File), Symlink(Symlink), } impl DirectoryEntry { pub fn unwrap_directory(&self) -> &Directory { match self { DirectoryEntry::Directory(d) => d, _ => unreachable!(), } } pub fn unwrap_directory_mut(&mut self) -> &mut Directory { match self { DirectoryEntry::Directory(d) => d, _ => unreachable!(), } } pub fn as_metadata(&self) -> Metadata { Metadata { is_symlink: matches!(self, DirectoryEntry::Symlink(_)), is_file: matches!(self, DirectoryEntry::File(_)), } } } #[derive(Debug, Default, Clone)] struct Directory { entries: BTreeMap, } #[derive(Debug, Clone)] struct File { is_valid_executable: bool, } #[derive(Debug, Clone)] struct Symlink { to: PathBuf, } #[derive(Debug, Clone)] struct InMemorySys { is_windows: bool, cwd: PathBuf, home_dir: Option, env_vars: HashMap, root_dir: DirectoryEntry, } impl InMemorySys { pub fn new() -> Self { Self { is_windows: false, cwd: PathBuf::from("/project"), home_dir: None, env_vars: Default::default(), root_dir: DirectoryEntry::Directory(Directory::default()), } } pub fn set_home_dir(&mut self, path: impl AsRef) { self.home_dir = Some(path.as_ref().to_path_buf()); } pub fn set_env_var(&mut self, name: impl AsRef, value: impl AsRef) { self.env_vars .insert(name.as_ref().to_os_string(), value.as_ref().to_os_string()); } pub fn create_symlink(&mut self, from: impl AsRef, to: impl AsRef) { self.insert_dir_entry( from, DirectoryEntry::Symlink(Symlink { to: to.as_ref().to_path_buf(), }), ); } pub fn write_executable(&mut self, path: impl AsRef) { self.insert_dir_entry( path, DirectoryEntry::File(File { is_valid_executable: true, }), ); } pub fn write_non_executable(&mut self, path: impl AsRef) { self.insert_dir_entry( path, DirectoryEntry::File(File { is_valid_executable: false, }), ); } fn insert_dir_entry(&mut self, path: impl AsRef, entry: DirectoryEntry) { // not super efficient, but good enough for testing let dir_path = path.as_ref().parent().unwrap(); self.create_directory(dir_path); let dir_entry = self.with_entry_mut(dir_path).unwrap(); let dir = dir_entry.unwrap_directory_mut(); let name = path.as_ref().file_name().unwrap(); dir.entries.insert(name.to_os_string(), entry); } pub fn create_directory(&mut self, path: impl AsRef) { // lazy implementation let mut ancestors = path .as_ref() .ancestors() .collect::>() .into_iter() .rev() .peekable(); while let Some(ancestor) = ancestors.next() { let entry = self.with_entry_mut(ancestor).unwrap(); match entry { DirectoryEntry::Directory(d) => { if let Some(next_name) = ancestors.peek().and_then(|a| a.file_name()) { if !d.entries.contains_key(next_name) { d.entries.insert( next_name.to_os_string(), DirectoryEntry::Directory(Default::default()), ); } } } _ => unreachable!("Not a directory."), } } } fn with_entry_mut(&mut self, path: impl AsRef) -> Option<&mut DirectoryEntry> { let mut current_entry = &mut self.root_dir; let mut components = path.as_ref().components().peekable(); while let Some(component) = components.next() { match component { Component::RootDir => { let is_last = components.peek().is_none(); if is_last { return Some(current_entry); } } Component::Normal(os_str) => { let is_last = components.peek().is_none(); let entry = current_entry .unwrap_directory_mut() .entries .get_mut(os_str)?; if is_last { return Some(entry); } current_entry = entry; } Component::CurDir | Component::ParentDir | Component::Prefix(_) => todo!(), } } None } fn get_entry(&self, path: &Path) -> Option<&DirectoryEntry> { let mut current_entry = &self.root_dir; let mut components = path.components().peekable(); while let Some(component) = components.next() { match component { Component::RootDir => continue, Component::Normal(os_str) => { let entry = current_entry.unwrap_directory().entries.get(os_str)?; if components.peek().is_none() { return Some(entry); } else { current_entry = entry; } } Component::CurDir | Component::ParentDir | Component::Prefix(_) => todo!(), } } unreachable!() } fn get_entry_follow_symlink(&self, path: &Path) -> Option<&DirectoryEntry> { let mut current_path = path.to_path_buf(); let mut seen = HashSet::new(); loop { let entry = self.get_entry(¤t_path)?; if let DirectoryEntry::Symlink(symlink) = &entry { if !seen.insert(current_path.clone()) { return None; // symlink loop } current_path = symlink.to.clone(); continue; } return Some(entry); } } } impl which::sys::Sys for InMemorySys { type ReadDirEntry = ReadDirEntry; type Metadata = Metadata; fn is_windows(&self) -> bool { self.is_windows } fn current_dir(&self) -> io::Result { Ok(self.cwd.clone()) } fn home_dir(&self) -> Option { self.home_dir.clone() } fn env_split_paths(&self, paths: &OsStr) -> Vec { paths .to_string_lossy() .split(if self.is_windows { ";" } else { ":" }) .map(PathBuf::from) .collect() } fn env_path(&self) -> Option { self.env_vars.get(OsStr::new("PATH")).cloned() } fn env_path_ext(&self) -> Option { self.env_vars.get(OsStr::new("PATHEXT")).cloned() } fn metadata(&self, path: &Path) -> io::Result { let entry = self .get_entry_follow_symlink(path) .ok_or_else(|| Error::new(ErrorKind::NotFound, "metadata: entry not found"))?; Ok(entry.as_metadata()) } fn symlink_metadata(&self, path: &Path) -> io::Result { let entry = self .get_entry(path) .ok_or_else(|| Error::new(ErrorKind::NotFound, "metadata: entry not found"))?; Ok(entry.as_metadata()) } fn read_dir( &self, path: &Path, ) -> io::Result>>> { let entry = self .get_entry_follow_symlink(path) .ok_or_else(|| Error::new(ErrorKind::NotFound, "metadata: entry not found"))?; match &entry { DirectoryEntry::Directory(dir) => { let entries = dir .entries .keys() .map(|name| { Ok(ReadDirEntry { path: path.join(name), }) }) .collect::>(); Ok(Box::new(entries.into_iter())) } // should use ErrorKind::NotADirectory once upgrading rust version _ => Err(Error::new(ErrorKind::Other, "Not a directory")), } } fn is_valid_executable(&self, path: &Path) -> io::Result { let entry = self.get_entry_follow_symlink(path).ok_or_else(|| { Error::new(ErrorKind::NotFound, "is_valid_executable: entry not found") })?; match &entry { DirectoryEntry::File(file) => Ok(file.is_valid_executable), _ => Ok(false), } } } #[test] fn basic() { let mut sys = InMemorySys::new(); sys.set_env_var("PATH", "/sub/dir1/:/sub/dir2/"); sys.write_non_executable("/sub/dir1/exec1"); sys.write_executable("/sub/dir2/exec1"); // will get this one sys.write_executable("/sub/dir2/exec2"); let config = which::WhichConfig::new_with_sys(sys).binary_name(OsString::from("exec1")); let result = config.first_result().unwrap(); assert_eq!(result, PathBuf::from("/sub/dir2/exec1")); } #[test] fn symlink() { let mut sys = InMemorySys::new(); sys.set_env_var("PATH", "/sub/dir1/"); sys.create_symlink("/sub/dir1/exec", "/sub/dir2/exec"); sys.write_executable("/sub/dir2/exec"); let config = which::WhichConfig::new_with_sys(sys).binary_name(OsString::from("exec")); let result = config.first_result().unwrap(); assert_eq!(result, PathBuf::from("/sub/dir1/exec")); } #[test] fn tilde_path() { let mut sys = InMemorySys::new(); sys.set_home_dir("/home/user/"); sys.set_env_var("PATH", "/dir/:~/sub/"); sys.write_executable("/home/user/sub/exec"); let config = which::WhichConfig::new_with_sys(sys).binary_name(OsString::from("exec")); let result = config.first_result().unwrap(); assert_eq!(result, PathBuf::from("/home/user/sub/exec")); } }