Vendor things

This commit is contained in:
John Doty 2024-03-08 11:03:01 -08:00
parent 5deceec006
commit 977e3c17e5
19434 changed files with 10682014 additions and 0 deletions

View file

@ -0,0 +1 @@
{"files":{"CHANGELOG.md":"66b8ad6c0bd9e6fcad662bd8784d0b92bcfc6b57cdf1df63d985c925b821516a","Cargo.toml":"5e158650a21b22c6ba2ce18abe79103b5042d78860396ce4d00c31ad36b25df8","LICENSE.txt":"0041560f5d419c30e1594567f3b7ac2bc078ff6a68f437e0348ba85d9cf99112","README.md":"1fbcd4bacd07328f84265715a825cd6811930117bb129e22625b020d12f47b45","deny.toml":"4e30f727201c8bb41500a57ca14a80f15bb29793b8c7fa6b815b5412f17af58c","src/checker.rs":"35ca1342931df0ac0b84e2c677ca1af3d74ade995c6aa0deeb9e4c3114f476b0","src/error.rs":"00315874353628366851cd0817a60059cb2c784fd315407a2c30f38021b18dc6","src/finder.rs":"dfd444a84353b5e0d3efceccff394f8c86bfc64bf56891bda406450e148100d8","src/helper.rs":"42cf60a98c017fcbf96d8cbf5880398b4f191c4b2445c43028c35ad57a1b846a","src/lib.rs":"0962694a7b8a1f66c3ac2871e484ffa1641cf93947fd9c668848f789bebf94ab","tests/basic.rs":"d3c9f35073b4c4f6ad977baaeb3d8668c170253d005cfc258749a0cbe8429512"},"package":"87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"}

10
third-party/vendor/which/CHANGELOG.md vendored Normal file
View file

@ -0,0 +1,10 @@
# CHANGELOG
## 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)

59
third-party/vendor/which/Cargo.toml vendored Normal file
View file

@ -0,0 +1,59 @@
# 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.63"
name = "which"
version = "4.4.2"
authors = ["Harry Fei <tiziyuanfang@gmail.com>"]
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
[dependencies.either]
version = "1.6.1"
[dependencies.regex]
version = "1.5.5"
optional = true
[dependencies.rustix]
version = "0.38.10"
features = [
"fs",
"std",
]
default-features = false
[dev-dependencies.tempfile]
version = "3.3.0"
[target."cfg(any(windows, unix, target_os = \"redox\"))".dependencies.home]
version = "0.5.5"
[target."cfg(windows)".dependencies.once_cell]
version = "1"

19
third-party/vendor/which/LICENSE.txt vendored Normal file
View file

@ -0,0 +1,19 @@
Copyright (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.

39
third-party/vendor/which/README.md vendored Normal file
View file

@ -0,0 +1,39 @@
[![Build Status](https://github.com/harryfei/which-rs/actions/workflows/rust.yml/badge.svg)](https://github.com/harryfei/which-rs/actions/workflows/rust.yml)
# which
A Rust equivalent of Unix command "which". Locate installed executable in cross platforms.
## Support platforms
* Linux
* Windows
* macOS
## 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.63. Increasing the MSRV is considered a breaking change and thus requires a major version bump.
## Documentation
The documentation is [available online](https://docs.rs/which/).

270
third-party/vendor/which/deny.toml vendored Normal file
View file

@ -0,0 +1,270 @@
# 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
# 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
#{ triple = "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 = []
# 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 database is cloned/fetched into
db-path = "~/.cargo/advisory-db"
# The url(s) of the advisory databases to use
db-urls = ["https://github.com/rustsec/advisory-db"]
# The lint level for security vulnerabilities
vulnerability = "deny"
# The lint level for unmaintained crates
unmaintained = "warn"
# The lint level for crates that have been yanked from their source registry
yanked = "warn"
# The lint level for crates with security notices. Note that as of
# 2019-12-17 there are no security notice advisories in
# https://github.com/rustsec/advisory-db
notice = "warn"
# A list of advisory IDs to ignore. Note that ignored advisories will still
# output a note when they are encountered.
ignore = [
#"RUSTSEC-0000-0000",
]
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
# lower than the range specified will be ignored. Note that ignored advisories
# will still output a note when they are encountered.
# * None - CVSS Score 0.0
# * Low - CVSS Score 0.1 - 3.9
# * Medium - CVSS Score 4.0 - 6.9
# * High - CVSS Score 7.0 - 8.9
# * Critical - CVSS Score 9.0 - 10.0
#severity-threshold =
# 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]
# The lint level for crates which do not have a detectable license
unlicensed = "deny"
# 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",
]
# List of explicitly disallowed licenses
# See https://spdx.org/licenses/ for list of possible licenses
# [possible values: any SPDX 3.11 short identifier (+ optional exception)].
deny = [
#"Nokia",
]
# Lint level for licenses considered copyleft
copyleft = "deny"
# Blanket approval or denial for OSI-approved or FSF Free/Libre licenses
# * both - The license will be approved if it is both OSI-approved *AND* FSF
# * either - The license will be approved if it is either OSI-approved *OR* FSF
# * osi - The license will be approved if it is OSI approved
# * fsf - The license will be approved if it is FSF Free
# * osi-only - The license will be approved if it is OSI-approved *AND NOT* FSF
# * fsf-only - The license will be approved if it is FSF *AND NOT* OSI-approved
# * neither - This predicate is ignored and the default lint level is used
allow-osi-fsf-free = "neither"
# Lint level used when no other predicates are matched
# 1. License isn't in the allow or deny lists
# 2. License isn't copyleft
# 3. License isn't OSI/FSF, or allow-osi-fsf-free = "neither"
default = "deny"
# 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"], name = "adler32", version = "*" },
]
# 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 name of the crate the clarification applies to
#name = "ring"
# The optional version constraint for the crate
#version = "*"
# 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 = [
#{ name = "ansi_term", version = "=0.11.0" },
]
# List of crates to deny
deny = [
# Each entry the name of a crate and a version range. If version is
# not specified, all versions will be matched.
#{ name = "ansi_term", version = "=0.11.0" },
#
# Wrapper crates can optionally be specified to allow the crate when it
# is a direct dependency of the otherwise banned crate
#{ name = "ansi_term", version = "=0.11.0", wrappers = [] },
]
# 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]]
#name = "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 = [
#{ name = "ansi_term", version = "=0.11.0" },
]
# 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 = [
#{ name = "ansi_term", version = "=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 = []

74
third-party/vendor/which/src/checker.rs vendored Normal file
View file

@ -0,0 +1,74 @@
use crate::finder::Checker;
use std::fs;
use std::path::Path;
pub struct ExecutableChecker;
impl ExecutableChecker {
pub fn new() -> ExecutableChecker {
ExecutableChecker
}
}
impl Checker for ExecutableChecker {
#[cfg(any(unix, target_os = "wasi"))]
fn is_valid(&self, path: &Path) -> bool {
use rustix::fs as rfs;
rfs::access(path, rfs::Access::EXEC_OK).is_ok()
}
#[cfg(windows)]
fn is_valid(&self, _path: &Path) -> bool {
true
}
}
pub struct ExistedChecker;
impl ExistedChecker {
pub fn new() -> ExistedChecker {
ExistedChecker
}
}
impl Checker for ExistedChecker {
#[cfg(target_os = "windows")]
fn is_valid(&self, path: &Path) -> bool {
fs::symlink_metadata(path)
.map(|metadata| {
let file_type = metadata.file_type();
file_type.is_file() || file_type.is_symlink()
})
.unwrap_or(false)
}
#[cfg(not(target_os = "windows"))]
fn is_valid(&self, path: &Path) -> bool {
fs::metadata(path)
.map(|metadata| metadata.is_file())
.unwrap_or(false)
}
}
pub struct CompositeChecker {
checkers: Vec<Box<dyn Checker>>,
}
impl CompositeChecker {
pub fn new() -> CompositeChecker {
CompositeChecker {
checkers: Vec::new(),
}
}
pub fn add_checker(mut self, checker: Box<dyn Checker>) -> CompositeChecker {
self.checkers.push(checker);
self
}
}
impl Checker for CompositeChecker {
fn is_valid(&self, path: &Path) -> bool {
self.checkers.iter().all(|checker| checker.is_valid(path))
}
}

26
third-party/vendor/which/src/error.rs vendored Normal file
View file

@ -0,0 +1,26 @@
use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Error {
BadAbsolutePath,
BadRelativePath,
CannotFindBinaryPath,
CannotGetCurrentDir,
CannotCanonicalize,
}
impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::BadAbsolutePath => write!(f, "bad absolute path"),
Error::BadRelativePath => write!(f, "bad relative path"),
Error::CannotFindBinaryPath => write!(f, "cannot find binary path"),
Error::CannotGetCurrentDir => write!(f, "cannot get current directory"),
Error::CannotCanonicalize => write!(f, "cannot canonicalize path"),
}
}
}

259
third-party/vendor/which/src/finder.rs vendored Normal file
View file

@ -0,0 +1,259 @@
use crate::checker::CompositeChecker;
use crate::error::*;
#[cfg(windows)]
use crate::helper::has_executable_extension;
use either::Either;
#[cfg(feature = "regex")]
use regex::Regex;
#[cfg(feature = "regex")]
use std::borrow::Borrow;
use std::borrow::Cow;
use std::env;
use std::ffi::OsStr;
#[cfg(any(feature = "regex", target_os = "windows"))]
use std::fs;
use std::iter;
use std::path::{Component, Path, PathBuf};
// Home dir shim, use home crate when possible. Otherwise, return None
#[cfg(any(windows, unix, target_os = "redox"))]
use home::home_dir;
#[cfg(not(any(windows, unix, target_os = "redox")))]
fn home_dir() -> Option<std::path::PathBuf> {
None
}
pub trait Checker {
fn is_valid(&self, path: &Path) -> bool;
}
trait PathExt {
fn has_separator(&self) -> bool;
fn to_absolute<P>(self, cwd: P) -> PathBuf
where
P: AsRef<Path>;
}
impl PathExt for PathBuf {
fn has_separator(&self) -> bool {
self.components().count() > 1
}
fn to_absolute<P>(self, cwd: P) -> PathBuf
where
P: AsRef<Path>,
{
if self.is_absolute() {
self
} else {
let mut new_path = PathBuf::from(cwd.as_ref());
new_path.push(self);
new_path
}
}
}
pub struct Finder;
impl Finder {
pub fn new() -> Finder {
Finder
}
pub fn find<T, U, V>(
&self,
binary_name: T,
paths: Option<U>,
cwd: Option<V>,
binary_checker: CompositeChecker,
) -> Result<impl Iterator<Item = PathBuf>>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
V: AsRef<Path>,
{
let path = PathBuf::from(&binary_name);
let binary_path_candidates = match cwd {
Some(cwd) if path.has_separator() => {
// Search binary in cwd if the path have a path separator.
Either::Left(Self::cwd_search_candidates(path, cwd).into_iter())
}
_ => {
// Search binary in PATHs(defined in environment variable).
let p = paths.ok_or(Error::CannotFindBinaryPath)?;
let paths: Vec<_> = env::split_paths(&p).collect();
Either::Right(Self::path_search_candidates(path, paths).into_iter())
}
};
Ok(binary_path_candidates
.filter(move |p| binary_checker.is_valid(p))
.map(correct_casing))
}
#[cfg(feature = "regex")]
pub fn find_re<T>(
&self,
binary_regex: impl Borrow<Regex>,
paths: Option<T>,
binary_checker: CompositeChecker,
) -> Result<impl Iterator<Item = PathBuf>>
where
T: AsRef<OsStr>,
{
let p = paths.ok_or(Error::CannotFindBinaryPath)?;
// Collect needs to happen in order to not have to
// change the API to borrow on `paths`.
#[allow(clippy::needless_collect)]
let paths: Vec<_> = env::split_paths(&p).collect();
let matching_re = paths
.into_iter()
.flat_map(fs::read_dir)
.flatten()
.flatten()
.map(|e| e.path())
.filter(move |p| {
if let Some(unicode_file_name) = p.file_name().unwrap().to_str() {
binary_regex.borrow().is_match(unicode_file_name)
} else {
false
}
})
.filter(move |p| binary_checker.is_valid(p));
Ok(matching_re)
}
fn cwd_search_candidates<C>(binary_name: PathBuf, cwd: C) -> impl IntoIterator<Item = PathBuf>
where
C: AsRef<Path>,
{
let path = binary_name.to_absolute(cwd);
Self::append_extension(iter::once(path))
}
fn path_search_candidates<P>(
binary_name: PathBuf,
paths: P,
) -> impl IntoIterator<Item = PathBuf>
where
P: IntoIterator<Item = PathBuf>,
{
let new_paths = paths
.into_iter()
.map(move |p| tilde_expansion(&p).join(binary_name.clone()));
Self::append_extension(new_paths)
}
#[cfg(not(windows))]
fn append_extension<P>(paths: P) -> impl IntoIterator<Item = PathBuf>
where
P: IntoIterator<Item = PathBuf>,
{
paths
}
#[cfg(windows)]
fn append_extension<P>(paths: P) -> impl IntoIterator<Item = PathBuf>
where
P: IntoIterator<Item = PathBuf>,
{
use once_cell::sync::Lazy;
// 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: Lazy<Vec<String>> = Lazy::new(|| {
env::var("PATHEXT")
.map(|pathext| {
pathext
.split(';')
.filter_map(|s| {
if s.as_bytes().first() == Some(&b'.') {
Some(s.to_owned())
} else {
// Invalid segment; just ignore it.
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()
});
paths
.into_iter()
.flat_map(move |p| -> Box<dyn Iterator<Item = _>> {
// Check if path already have executable extension
if has_executable_extension(&p, &PATH_EXTENSIONS) {
Box::new(iter::once(p))
} else {
let bare_file = p.extension().map(|_| p.clone());
// 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
// ...
Box::new(
bare_file
.into_iter()
.chain(PATH_EXTENSIONS.iter().map(move |e| {
// Append the extension.
let mut p = p.clone().into_os_string();
p.push(e);
PathBuf::from(p)
})),
)
}
})
}
}
fn tilde_expansion(p: &PathBuf) -> Cow<'_, PathBuf> {
let mut component_iter = p.components();
if let Some(Component::Normal(o)) = component_iter.next() {
if o == "~" {
let mut new_path = home_dir().unwrap_or_default();
new_path.extend(component_iter);
Cow::Owned(new_path)
} else {
Cow::Borrowed(p)
}
} else {
Cow::Borrowed(p)
}
}
#[cfg(target_os = "windows")]
fn correct_casing(mut p: PathBuf) -> PathBuf {
if let (Some(parent), Some(file_name)) = (p.parent(), p.file_name()) {
if let Ok(iter) = fs::read_dir(parent) {
for e in iter.filter_map(std::result::Result::ok) {
if e.file_name().eq_ignore_ascii_case(file_name) {
p.pop();
p.push(e.file_name());
break;
}
}
}
}
p
}
#[cfg(not(target_os = "windows"))]
fn correct_casing(p: PathBuf) -> PathBuf {
p
}

40
third-party/vendor/which/src/helper.rs vendored Normal file
View file

@ -0,0 +1,40 @@
use std::path::Path;
/// Check if given path has extension which in the given vector.
pub fn has_executable_extension<T: AsRef<Path>, S: AsRef<str>>(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| 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"]
));
}
}

634
third-party/vendor/which/src/lib.rs vendored Normal file
View file

@ -0,0 +1,634 @@
//! which
//!
//! A Rust equivalent of Unix command `which(1)`.
//! # Example:
//!
//! To find which rustc executable binary is using:
//!
//! ```no_run
//! use which::which;
//! use std::path::PathBuf;
//!
//! let result = which("rustc").unwrap();
//! assert_eq!(result, PathBuf::from("/usr/bin/rustc"));
//!
//! ```
#![forbid(unsafe_code)]
mod checker;
mod error;
mod finder;
#[cfg(windows)]
mod helper;
#[cfg(feature = "regex")]
use std::borrow::Borrow;
use std::env;
use std::fmt;
use std::path;
use std::ffi::{OsStr, OsString};
use crate::checker::{CompositeChecker, ExecutableChecker, ExistedChecker};
pub use crate::error::*;
use crate::finder::Finder;
/// 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"));
///
/// ```
pub fn which<T: AsRef<OsStr>>(binary_name: T) -> Result<path::PathBuf> {
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"));
///
/// ```
pub fn which_global<T: AsRef<OsStr>>(binary_name: T) -> Result<path::PathBuf> {
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.
pub fn which_all<T: AsRef<OsStr>>(binary_name: T) -> Result<impl Iterator<Item = path::PathBuf>> {
let cwd = env::current_dir().ok();
let binary_checker = build_binary_checker();
let finder = Finder::new();
finder.find(binary_name, env::var_os("PATH"), cwd, binary_checker)
}
/// Find all binaries with `binary_name` ignoring `cwd`.
pub fn which_all_global<T: AsRef<OsStr>>(
binary_name: T,
) -> Result<impl Iterator<Item = path::PathBuf>> {
let binary_checker = build_binary_checker();
let finder = Finder::new();
finder.find(
binary_name,
env::var_os("PATH"),
Option::<&Path>::None,
binary_checker,
)
}
/// 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<PathBuf> = 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(feature = "regex")]
pub fn which_re(regex: impl Borrow<Regex>) -> Result<impl Iterator<Item = path::PathBuf>> {
which_re_in(regex, env::var_os("PATH"))
}
/// Find `binary_name` in the path list `paths`, using `cwd` to resolve relative paths.
pub fn which_in<T, U, V>(binary_name: T, paths: Option<U>, cwd: V) -> Result<path::PathBuf>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
V: AsRef<path::Path>,
{
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<PathBuf> = 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(feature = "regex")]
pub fn which_re_in<T>(
regex: impl Borrow<Regex>,
paths: Option<T>,
) -> Result<impl Iterator<Item = path::PathBuf>>
where
T: AsRef<OsStr>,
{
let binary_checker = build_binary_checker();
let finder = Finder::new();
finder.find_re(regex, paths, binary_checker)
}
/// Find all binaries with `binary_name` in the path list `paths`, using `cwd` to resolve relative paths.
pub fn which_in_all<T, U, V>(
binary_name: T,
paths: Option<U>,
cwd: V,
) -> Result<impl Iterator<Item = path::PathBuf>>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
V: AsRef<path::Path>,
{
let binary_checker = build_binary_checker();
let finder = Finder::new();
finder.find(binary_name, paths, Some(cwd), binary_checker)
}
/// Find all binaries with `binary_name` in the path list `paths`, ignoring `cwd`.
pub fn which_in_global<T, U>(
binary_name: T,
paths: Option<U>,
) -> Result<impl Iterator<Item = path::PathBuf>>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
{
let binary_checker = build_binary_checker();
let finder = Finder::new();
finder.find(binary_name, paths, Option::<&Path>::None, binary_checker)
}
fn build_binary_checker() -> CompositeChecker {
CompositeChecker::new()
.add_checker(Box::new(ExistedChecker::new()))
.add_checker(Box::new(ExecutableChecker::new()))
}
/// A wrapper containing all functionality in this crate.
pub struct WhichConfig {
cwd: Option<either::Either<bool, path::PathBuf>>,
custom_path_list: Option<OsString>,
binary_name: Option<OsString>,
#[cfg(feature = "regex")]
regex: Option<Regex>,
}
impl Default for WhichConfig {
fn default() -> Self {
Self {
cwd: Some(either::Either::Left(true)),
custom_path_list: None,
binary_name: None,
#[cfg(feature = "regex")]
regex: None,
}
}
}
#[cfg(feature = "regex")]
type Regex = regex::Regex;
#[cfg(not(feature = "regex"))]
type Regex = ();
impl WhichConfig {
pub fn new() -> Self {
Self::default()
}
/// 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!")
}
self.cwd = Some(either::Either::Left(use_cwd));
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 = Some(either::Either::Right(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 self.cwd != Some(either::Either::Left(false)) && self.cwd.is_some() {
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
}
/// Finishes configuring, runs the query and returns the first result.
pub fn first_result(self) -> Result<path::PathBuf> {
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<impl Iterator<Item = path::PathBuf>> {
let binary_checker = build_binary_checker();
let finder = Finder::new();
let paths = self.custom_path_list.or_else(|| env::var_os("PATH"));
#[cfg(feature = "regex")]
if let Some(regex) = self.regex {
return finder
.find_re(regex, paths, binary_checker)
.map(|i| Box::new(i) as Box<dyn Iterator<Item = path::PathBuf>>);
}
let cwd = match self.cwd {
Some(either::Either::Left(false)) => None,
Some(either::Either::Right(custom)) => Some(custom),
None | Some(either::Either::Left(true)) => env::current_dir().ok(),
};
finder
.find(
self.binary_name.expect(
"binary_name not set! You must set binary_name or regex before searching!",
),
paths,
cwd,
binary_checker,
)
.map(|i| Box::new(i) as Box<dyn Iterator<Item = path::PathBuf>>)
}
}
/// 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`.
pub fn new<T: AsRef<OsStr>>(binary_name: T) -> Result<Path> {
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.
pub fn all<T: AsRef<OsStr>>(binary_name: T) -> Result<impl Iterator<Item = Path>> {
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`.
pub fn new_in<T, U, V>(binary_name: T, paths: Option<U>, cwd: V) -> Result<Path>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
V: AsRef<path::Path>,
{
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`.
pub fn all_in<T, U, V>(
binary_name: T,
paths: Option<U>,
cwd: V,
) -> Result<impl Iterator<Item = Path>>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
V: AsRef<path::Path>,
{
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<path::Path> for Path {
fn as_ref(&self) -> &path::Path {
self.as_path()
}
}
impl AsRef<OsStr> for Path {
fn as_ref(&self) -> &OsStr {
self.as_os_str()
}
}
impl PartialEq<path::PathBuf> for Path {
fn eq(&self, other: &path::PathBuf) -> bool {
self.inner == *other
}
}
impl PartialEq<Path> 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`.
pub fn new<T: AsRef<OsStr>>(binary_name: T) -> Result<CanonicalPath> {
which(binary_name)
.and_then(|p| p.canonicalize().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.
pub fn all<T: AsRef<OsStr>>(
binary_name: T,
) -> Result<impl Iterator<Item = Result<CanonicalPath>>> {
which_all(binary_name).map(|inner| {
inner.map(|inner| {
inner
.canonicalize()
.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`.
pub fn new_in<T, U, V>(binary_name: T, paths: Option<U>, cwd: V) -> Result<CanonicalPath>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
V: AsRef<path::Path>,
{
which_in(binary_name, paths, cwd)
.and_then(|p| p.canonicalize().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`.
pub fn all_in<T, U, V>(
binary_name: T,
paths: Option<U>,
cwd: V,
) -> Result<impl Iterator<Item = Result<CanonicalPath>>>
where
T: AsRef<OsStr>,
U: AsRef<OsStr>,
V: AsRef<path::Path>,
{
which_in_all(binary_name, paths, cwd).map(|inner| {
inner.map(|inner| {
inner
.canonicalize()
.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<path::Path> for CanonicalPath {
fn as_ref(&self) -> &path::Path {
self.as_path()
}
}
impl AsRef<OsStr> for CanonicalPath {
fn as_ref(&self) -> &OsStr {
self.as_os_str()
}
}
impl PartialEq<path::PathBuf> for CanonicalPath {
fn eq(&self, other: &path::PathBuf) -> bool {
self.inner == *other
}
}
impl PartialEq<CanonicalPath> for path::PathBuf {
fn eq(&self, other: &CanonicalPath) -> bool {
*self == other.inner
}
}

451
third-party/vendor/which/tests/basic.rs vendored Normal file
View file

@ -0,0 +1,451 @@
extern crate which;
#[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<PathBuf>,
}
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<PathBuf> {
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<PathBuf> {
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<PathBuf> {
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<PathBuf> {
touch(self.tempdir.path(), path, extension)
}
pub fn mk_bin(&self, path: &str, extension: &str) -> io::Result<PathBuf> {
mk_bin(self.tempdir.path(), path, extension)
}
}
fn _which<T: AsRef<OsStr>>(f: &TestFixture, path: T) -> which::Result<which::CanonicalPath> {
which::CanonicalPath::new_in(path, Some(f.paths.clone()), f.tempdir.path())
}
fn _which_all<'a, T: AsRef<OsStr> + 'a>(
f: &'a TestFixture,
path: T,
) -> which::Result<impl Iterator<Item = which::Result<which::CanonicalPath>> + '_> {
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<PathBuf> = 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<PathBuf> = which::which_re_in(re, Some(f.paths)).unwrap().collect();
assert_eq!(result, Vec::<PathBuf>::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::<Vec<_>>();
let mut expected = f
.bins
.iter()
.map(|p| p.canonicalize().unwrap())
.collect::<Vec<_>>();
#[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(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<PathBuf> {
let p = _which(&f, "./b/bin")?;
Ok(p.into_path_buf())
};
let _ = run();
}