pax_global_header00006660000000000000000000000064143242661050014515gustar00rootroot0000000000000052 comment=161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/000077500000000000000000000000001432426610500220545ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/.github/000077500000000000000000000000001432426610500234145ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/.github/dependabot.yml000066400000000000000000000004301432426610500262410ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily open-pull-requests-limit: 10 commit-message: prefix: "cargo prod" prefix-development: "cargo dev" include: "scope" reviewers: - johnstonskj rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/.github/workflows/000077500000000000000000000000001432426610500254515ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/.github/workflows/cargo-audit.yml000066400000000000000000000004401432426610500303710ustar00rootroot00000000000000name: Security audit on: push: paths: - '**/Cargo.toml' - '**/Cargo.lock' jobs: security_audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/.github/workflows/rust.yml000066400000000000000000000010101432426610500271610ustar00rootroot00000000000000name: Rust on: [push] jobs: build: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v1 - name: Install dependencies run: rustup component add rustfmt - name: Format run: cargo fmt -- --check - name: Build run: cargo build --verbose - name: Run tests run: cargo test --all-features --verbose - name: Docs run: cargo doc --no-deps rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/.gitignore000066400000000000000000000010021432426610500240350ustar00rootroot00000000000000## ------------------------------------------------------------------------------------------------ # Files created by development tools /.idea/ *.iml **/*.rs~ **/*.md~ ## ------------------------------------------------------------------------------------------------ # Files created by cargo (build, fmt, make, etc.) /.cargo /target /docs Cargo.lock **/*.rs.bk ## ------------------------------------------------------------------------------------------------ # Files required for CI integration (Travis) /ci rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/Cargo.toml000066400000000000000000000005551432426610500240110ustar00rootroot00000000000000[package] name = "search_path" description = "Provides a very simple search path file finder." authors = ["Simon Johnston "] version = "0.1.4" edition = "2018" documentation = "https://docs.rs/search_path/" repository = "https://github.com/johnstonskj/rust-search_path.git" license = "MIT" readme = "README.md" publish = true [dependencies] rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/LICENSE000066400000000000000000000020571432426610500230650ustar00rootroot00000000000000MIT License Copyright (c) 2019 Simon Johnston 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. rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/README.md000066400000000000000000000045251432426610500233410ustar00rootroot00000000000000# Crate search_path Provides a very simple search path file finder. ![MIT License](https://img.shields.io/badge/license-mit-118811.svg) ![Minimum Rust Version](https://img.shields.io/badge/Min%20Rust-1.50-green.svg) [![crates.io](https://img.shields.io/crates/v/search_path.svg)](https://crates.io/crates/search_path) [![docs.rs](https://docs.rs/search_path/badge.svg)](https://docs.rs/search_path) ![Build](https://github.com/johnstonskj/rust-search_path/workflows/Rust/badge.svg) ![Audit](https://github.com/johnstonskj/rust-search_path/workflows/Security%20audit/badge.svg) [![GitHub stars](https://img.shields.io/github/stars/johnstonskj/rust-search_path.svg)](https://github.com/johnstonskj/rust-search_path/stargazers) ----- The `SearchPath` type allows for the finding of files using a series of search directories. This is akin to the mechanism a shell uses to find executables using the `PATH` environment variable. It can be constructed with a search path from an environment variable, from a string, or from a list of either string or `Path`/`PathBuf` values. Typically the _find_ methods return the first matching file or directory, but the `find_all` method specifically collects and returns a list of all matching paths. # Constructors The `SearchPath` type also has `From<>` implementations for `PathBuf`, `Vec`, `Vec<&Path>`, `Vec<&str>`, `String`, and `&str`. In the case of vector values, or a single `PathBuf`, each path value will be used as-is without trying to split it into components. In the case of individual `String` and `&str` values the value will be split using the platform specific path separator into individual paths components. # Example The following example shows the common pattern of finding an executable command on the command line. ```rust use search_path::SearchPath; use std::path::PathBuf; fn which_command(cmd_name: &str) -> Option { let search_path = SearchPath::new("PATH").unwrap(); search_path.find_file(&PathBuf::from(cmd_name)) } ``` ----- ## Changes **Version 0.1.4** * Added new constructor `path` as a simple shortcut. **Version 0.1.3** * Added implementation of IntoIterator to extract paths. **Version 0.1.2** * Added a dedup method. **Version 0.1.1** * Completed documentation. * Added Github builds. * Fixed bug in test cases for Windows builds. **Version 0.1.0** * Initial commit. rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/src/000077500000000000000000000000001432426610500226435ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/src/lib.rs000066400000000000000000000324071432426610500237650ustar00rootroot00000000000000/*! Provides a very simple search path file finder. The `SearchPath` type allows for the finding of files using a series of search directories. This is akin to the mechanism a shell uses to find executables using the `PATH` environment variable. It can be constructed with a search path from an environment variable, from a string, or from a list of either string or `Path`/`PathBuf` values. Typically the _find_ methods return the first matching file or directory, but the `find_all` method specifically collects and returns a list of all matching paths. # Constructors The `SearchPath` type also has `From<>` implementations for `PathBuf`, `Vec`, `Vec<&Path>`, `Vec<&str>`, `String`, and `&str`. In the case of vector values, or a single `PathBuf`, each path value will be used as-is without trying to split it into components. In the case of individual `String` and `&str` values the value will be split using the platform specific path separator into individual paths components. # Example The following example shows the common pattern of finding an executable command on the command line. ```rust use search_path::SearchPath; use std::path::PathBuf; fn which_command(cmd_name: &str) -> Option { let search_path = SearchPath::new("PATH").expect("How do you live with no $PATH?"); search_path.find_file(&PathBuf::from(cmd_name)) } ``` */ #![warn( // ---------- Stylistic future_incompatible, nonstandard_style, rust_2018_idioms, trivial_casts, trivial_numeric_casts, // ---------- Public missing_debug_implementations, missing_docs, unreachable_pub, // ---------- Unsafe unsafe_code, // ---------- Unused unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, )] use std::env; use std::error::Error; use std::fmt::{Display, Formatter}; use std::path::{Path, PathBuf}; // ------------------------------------------------------------------------------------------------ // Public Types // ------------------------------------------------------------------------------------------------ /// /// This is the search path itself, it wraps a list of file paths which can then be used to find /// file system entries. See the [module](index.html) description for an overview. /// #[derive(Clone, Debug, PartialEq)] pub struct SearchPath { paths: Vec, } // ------------------------------------------------------------------------------------------------ // Private Types // ------------------------------------------------------------------------------------------------ #[cfg(target_family = "windows")] const PATH_SEPARATOR_CHAR: char = ';'; #[cfg(not(target_family = "windows"))] const PATH_SEPARATOR_CHAR: char = ':'; const CURRENT_DIR_PATH: &str = "."; // ------------------------------------------------------------------------------------------------ #[derive(Copy, Clone, Debug, PartialEq)] enum FindKind { Any, File, Directory, } // ------------------------------------------------------------------------------------------------ // Public Functions // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // Implementations // ------------------------------------------------------------------------------------------------ impl Default for SearchPath { fn default() -> Self { Self { paths: Default::default(), } } } impl Display for SearchPath { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "{}", self.paths .iter() .map(|p| p.to_string_lossy().to_string()) .collect::>() .join(&PATH_SEPARATOR_CHAR.to_string()) ) } } impl From for SearchPath { fn from(v: PathBuf) -> Self { Self { paths: vec![v] } } } impl From> for SearchPath { fn from(vs: Vec) -> Self { Self { paths: vs } } } impl From> for SearchPath { fn from(vs: Vec<&Path>) -> Self { Self { paths: vs.iter().map(|p| PathBuf::from(p)).collect(), } } } impl From> for SearchPath { fn from(vs: Vec<&str>) -> Self { Self { paths: vs .iter() .filter_map(|p| { if p.trim().is_empty() { None } else { Some(PathBuf::from(p)) } }) .collect(), } } } impl From for SearchPath { fn from(s: String) -> Self { Self::from(s.as_str()) } } impl From<&str> for SearchPath { fn from(s: &str) -> Self { Self::from(s.split(PATH_SEPARATOR_CHAR).collect::>()) } } impl From for Vec { fn from(p: SearchPath) -> Self { p.paths } } impl IntoIterator for SearchPath { type Item = PathBuf; type IntoIter = std::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.paths.into_iter() } } impl SearchPath { /// /// Construct a new search path by parsing the environment variable named `env_var` into /// separate paths. Paths are separated by the `';'` character on Windows, and the `':'` /// character on other platforms. /// /// If the environment variable is not present, or could not be read this function returns /// an error. /// /// ```rust,should_panic /// use search_path::SearchPath; /// /// let search_path = SearchPath::new("CMD_PATH").expect("No $CMD_PATH present"); /// ``` /// /// Constructors do not check for duplicate paths, to remove duplicates see the /// [`dedup`](struct.SearchPath.html#method.dedup)) method. /// pub fn new(env_var: &str) -> Result> { match env::var(env_var) { Ok(path) => Ok(Self::from(path)), Err(e) => Err(Box::new(e)), } } /// /// Construct a new search path by parsing the environment variable named `PATH`. /// pub fn path() -> Result> { Self::new("PATH") } /// /// Construct a new search path by parsing the environment variable named `env_var` into /// separate paths. Paths are separated by the `';'` character on Windows, and the `':'` /// character on other platforms. /// /// If the environment variable is not present, or could not be read this function returns /// the default value provided instead. The default value may be any value that has an /// `Into` implementation for `SearchPath`. /// /// ```rust /// use search_path::SearchPath; /// /// let search_path = SearchPath::new_or("CMD_PATH", "."); /// ``` /// /// Constructors do not check for duplicate paths, to remove duplicates see the /// [`dedup`](struct.SearchPath.html#method.dedup)) method. /// pub fn new_or>(env_var: &str, default: T) -> Self { match Self::new(env_var) { Ok(search_path) => search_path, Err(_) => default.into(), } } /// /// Construct a new search path by parsing the environment variable named `env_var` into /// separate paths. Paths are separated by the `';'` character on Windows, and the `':'` /// character on other platforms. /// /// If the environment variable is not present, or could not be read this function returns /// the value of `Default::default()` implemented for `SearchPath` instead. /// /// ```rust /// use search_path::SearchPath; /// /// let search_path = SearchPath::new_or_default("CMD_PATH"); /// ``` /// /// Constructors do not check for duplicate paths, to remove duplicates see the /// [`dedup`](struct.SearchPath.html#method.dedup)) method. /// pub fn new_or_default(env_var: &str) -> Self { Self::new_or(env_var, SearchPath::default()) } // -------------------------------------------------------------------------------------------- /// /// Return the first file system entity, either file or directory, found in the search path, or /// `None`. /// pub fn find(&self, file_name: &Path) -> Option { self.find_something(file_name, FindKind::Any) } /// /// Return all the file system entities, either file or directory, found in the search path. /// pub fn find_all(&self, file_name: &Path) -> Vec { let mut results: Vec = Default::default(); for path in &self.paths { let mut path = PathBuf::from(path); path.push(file_name); if path.exists() { results.push(path); } } results } /// /// Return the first _file_ found in the search path, or `None`. /// pub fn find_file(&self, file_name: &Path) -> Option { self.find_something(file_name, FindKind::File) } /// /// Return the first _directory_ found in the search path, or `None`. /// pub fn find_directory(&self, file_name: &Path) -> Option { self.find_something(file_name, FindKind::Directory) } /// /// Return the first file found in the search path, or `None`. This method will only /// consider `file_name` if it is not a path, if it has any path components the method /// will also return `None`. /// pub fn find_if_name_only(&self, file_name: &Path) -> Option { if let Some(_) = file_name.parent() { self.find(file_name) } else { None } } fn find_something(&self, file_name: &Path, kind: FindKind) -> Option { for path in &self.paths { let mut path = PathBuf::from(path); path.push(file_name); if (kind == FindKind::Any && path.exists()) || (kind == FindKind::File && path.is_file()) || (kind == FindKind::Directory && path.is_dir()) { return Some(path); } } None } // -------------------------------------------------------------------------------------------- /// /// Return `true` if this instance has no paths to search, else `false`. /// pub fn is_empty(&self) -> bool { self.paths.is_empty() } /// /// Return the current number of paths in the list of paths to search. /// pub fn len(&self) -> usize { self.paths.len() } /// /// Return `true` if the list of paths to search contains the `path` value, else `false`. /// pub fn contains(&self, path: &PathBuf) -> bool { self.paths.contains(path) } /// /// Return `true` if the list of paths to search contains the current directory path, `"."`, /// value, else `false`. /// pub fn contains_cwd(&self) -> bool { self.contains(&PathBuf::from(CURRENT_DIR_PATH)) } /// /// Return an iterator over all the paths in the list of paths to search. /// pub fn iter(&self) -> impl Iterator { self.paths.iter() } // -------------------------------------------------------------------------------------------- /// /// Append the provided `path` to the list of paths to search. /// This operation does not check for duplicate paths, to remove duplicates see the /// [`dedup`](struct.SearchPath.html#method.dedup)) method. /// pub fn append(&mut self, path: PathBuf) { self.paths.push(path) } /// /// Append the current directory path, `"."`, to the list of paths to search. /// This operation does not check for duplicate paths, to remove duplicates see the /// [`dedup`](struct.SearchPath.html#method.dedup)) method. /// pub fn append_cwd(&mut self) { self.append(PathBuf::from(CURRENT_DIR_PATH)) } /// /// Prepend the provided `path` to the list of paths to search. /// This operation does not check for duplicate paths, to remove duplicates see the /// [`dedup`](struct.SearchPath.html#method.dedup)) method. /// pub fn prepend(&mut self, path: PathBuf) { self.paths.insert(0, path) } /// /// Prepend the current directory path, `"."`, to the list of paths to search. /// This operation does not check for duplicate paths, to remove duplicates see the /// [`dedup`](struct.SearchPath.html#method.dedup)) method. /// pub fn prepend_cwd(&mut self) { self.prepend(PathBuf::from(CURRENT_DIR_PATH)) } /// /// Remove the path from the list of paths to search, this has no effect if the path /// was not in the list. /// pub fn remove(&mut self, path: &PathBuf) { self.paths.retain(|p| p != path); } /// /// Ensure that only one copy of a path exists in the list of paths to search. This operation /// will ensure the ordering of paths remains the same and keep the first duplicate it finds /// and remove any subsequent ones. /// pub fn dedup(&mut self) { use std::collections::HashSet; let mut seen: HashSet = Default::default(); self.paths.retain(|p| seen.insert(p.clone())) } } rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/000077500000000000000000000000001432426610500232165ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/a.txt000066400000000000000000000000001432426610500241650ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/a/000077500000000000000000000000001432426610500234365ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/a/b.txt000066400000000000000000000000001432426610500244060ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/b/000077500000000000000000000000001432426610500234375ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/b/a.txt000066400000000000000000000000001432426610500244060ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/b/c.txt000066400000000000000000000000001432426610500244100ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/b/d/000077500000000000000000000000001432426610500236625ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/b/d/no-op.txt000066400000000000000000000000001432426610500254410ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/constructors.rs000066400000000000000000000046731432426610500263460ustar00rootroot00000000000000use search_path::SearchPath; use std::path::{Path, PathBuf}; #[cfg(target_family = "windows")] const SIMPLE_PATH: &str = ".;.."; #[cfg(not(target_family = "windows"))] const SIMPLE_PATH: &str = ".:.."; #[cfg(target_family = "windows")] const NOT_SO_SIMPLE_PATH: &str = ";.;..;"; #[cfg(not(target_family = "windows"))] const NOT_SO_SIMPLE_PATH: &str = ":.:..:"; fn assert_correct(search_path: &SearchPath) { assert_eq!(search_path.len(), 2); assert!(search_path.contains(&PathBuf::from("."))); assert!(search_path.contains(&PathBuf::from(".."))); assert!(search_path.contains_cwd()); assert!(!search_path.contains(&PathBuf::from("tests"))); } // ------------------------------------------------------------------------------------------------ #[test] fn test_no_env_var() { let search_path = SearchPath::new("UNLIKELY_THIS_VAR_EXISTS"); assert!(search_path.is_err()); } #[test] fn test_no_env_var_or() { let search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", SIMPLE_PATH); assert_correct(&search_path); } #[test] fn test_no_env_var_or_default() { let search_path = SearchPath::new_or_default("UNLIKELY_THIS_VAR_EXISTS"); assert_eq!(search_path.len(), 0); } #[test] fn test_ignore_empty() { let search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", ""); assert_eq!(search_path.len(), 0); } #[test] fn test_ignore_empty_split() { let search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", NOT_SO_SIMPLE_PATH); assert_correct(&search_path); } // ------------------------------------------------------------------------------------------------ #[test] fn from_string() { let search_path: SearchPath = String::from(SIMPLE_PATH).into(); assert_correct(&search_path); } #[test] fn from_str() { let search_path: SearchPath = SIMPLE_PATH.into(); assert_correct(&search_path); } #[test] fn from_str_vec() { let search_path: SearchPath = vec![".", ".."].into(); assert_correct(&search_path); } #[test] fn from_pathbuf_vec() { let search_path: SearchPath = vec![PathBuf::from("."), PathBuf::from("..")].into(); assert_correct(&search_path); } #[test] fn from_path_vec() { let search_path: SearchPath = vec![Path::new("."), Path::new("..")].into(); assert_correct(&search_path); } #[test] fn from_pathbuf() { let search_path: SearchPath = PathBuf::from(".").into(); assert_eq!(search_path.len(), 1); assert!(search_path.contains(&PathBuf::from("."))); } rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/000077500000000000000000000000001432426610500234425ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/f/000077500000000000000000000000001432426610500236675ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/f/c/000077500000000000000000000000001432426610500241115ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/f/c/no-op.txt000066400000000000000000000000001432426610500256700ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/f/g/000077500000000000000000000000001432426610500241155ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/f/g/a.txt000066400000000000000000000000001432426610500250640ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/f/g/y.txt000066400000000000000000000000001432426610500251140ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/e/f/x.txt000066400000000000000000000000001432426610500246650ustar00rootroot00000000000000rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/finder.rs000066400000000000000000000070761432426610500250450ustar00rootroot00000000000000use search_path::SearchPath; use std::path::PathBuf; #[cfg(target_family = "windows")] fn make_full_search_path() -> SearchPath { String::from("tests;tests/a;tests/b;tests/c;tests/e/f;tests/e/f/g").into() } #[cfg(not(target_family = "windows"))] fn make_full_search_path() -> SearchPath { String::from("tests:tests/a:tests/b:tests/c:tests/e/f:tests/e/f/g").into() } #[cfg(target_family = "windows")] fn make_partial_search_path() -> SearchPath { String::from("tests/a;tests/c;tests/e/f/g").into() } #[cfg(not(target_family = "windows"))] fn make_partial_search_path() -> SearchPath { String::from("tests/a:tests/c:tests/e/f/g").into() } #[test] fn find_file_full() { let search_path = make_full_search_path(); let result = search_path.find(&PathBuf::from("a.txt")); assert!(result.is_some()); let file = result.unwrap(); assert_eq!(file, PathBuf::from("tests/a.txt")) } #[test] fn find_directory_full() { let search_path = make_full_search_path(); let result = search_path.find(&PathBuf::from("d")); assert!(result.is_some()); let file = result.unwrap(); assert_eq!(file, PathBuf::from("tests/b/d")) } #[test] fn find_file_partial() { let search_path = make_partial_search_path(); let result = search_path.find(&PathBuf::from("a.txt")); assert!(result.is_some()); let file = result.unwrap(); assert_eq!(file, PathBuf::from("tests/e/f/g/a.txt")) } #[test] fn find_no_file_full() { let search_path = make_full_search_path(); let result = search_path.find(&PathBuf::from("none.txt")); assert!(result.is_none()); } #[test] fn find_all_files_full() { let search_path = make_full_search_path(); let files = search_path.find_all(&PathBuf::from("a.txt")); assert_eq!(files.len(), 3); assert_eq!( files, vec![ PathBuf::from("tests/a.txt"), PathBuf::from("tests/b/a.txt"), PathBuf::from("tests/e/f/g/a.txt") ] ) } #[test] fn find_file_only_full() { let search_path = make_full_search_path(); let result = search_path.find_file(&PathBuf::from("a.txt")); assert!(result.is_some()); let file = result.unwrap(); assert_eq!(file, PathBuf::from("tests/a.txt")) } #[test] fn find_no_file_only_full() { let search_path = make_full_search_path(); let result = search_path.find_file(&PathBuf::from("d")); assert!(result.is_none()); } #[test] fn find_directory_only_full() { let search_path = make_full_search_path(); let result = search_path.find_directory(&PathBuf::from("d")); assert!(result.is_some()); let file = result.unwrap(); assert_eq!(file, PathBuf::from("tests/b/d")) } #[test] fn find_no_directory_only_full() { let search_path = make_full_search_path(); let result = search_path.find_directory(&PathBuf::from("a.txt")); assert!(result.is_none()); } #[test] fn find_path_file_full() { let search_path = make_full_search_path(); let result = search_path.find(&PathBuf::from("g/a.txt")); assert!(result.is_some()); let file = result.unwrap(); assert_eq!(file, PathBuf::from("tests/e/f/g/a.txt")) } #[test] fn find_filename_partial() { let search_path = make_partial_search_path(); let result = search_path.find_if_name_only(&PathBuf::from("a.txt")); assert!(result.is_some()); let file = result.unwrap(); assert_eq!(file, PathBuf::from("tests/e/f/g/a.txt")) } #[test] fn find_filename_with_directory_partial() { let search_path = make_partial_search_path(); let result = search_path.find_if_name_only(&PathBuf::from("g/a.txt")); assert!(result.is_none()); } rust-search_path-161a6b0c87d38c238d3eb51d5579d6a3e3e0f5dd/tests/mutability.rs000066400000000000000000000044571432426610500257610ustar00rootroot00000000000000use search_path::SearchPath; use std::path::PathBuf; #[cfg(target_family = "windows")] const SIMPLE_PATH: &str = "a;b;c"; #[cfg(not(target_family = "windows"))] const SIMPLE_PATH: &str = "a:b:c"; #[test] fn test_append() { let mut search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", SIMPLE_PATH); assert!(!search_path.contains(&PathBuf::from("d"))); search_path.append(PathBuf::from("d")); assert!(search_path.contains(&PathBuf::from("d"))); assert_eq!(search_path.iter().last(), Some(&PathBuf::from("d"))); } #[test] fn test_append_cwd() { let mut search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", SIMPLE_PATH); assert!(!search_path.contains(&PathBuf::from("."))); search_path.append_cwd(); assert!(search_path.contains(&PathBuf::from("."))); assert_eq!(search_path.iter().last(), Some(&PathBuf::from("."))); } #[test] fn test_prepend() { let mut search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", SIMPLE_PATH); assert!(!search_path.contains(&PathBuf::from("d"))); search_path.prepend(PathBuf::from("d")); assert!(search_path.contains(&PathBuf::from("d"))); assert_eq!(search_path.iter().next(), Some(&PathBuf::from("d"))); } #[test] fn test_prepend_cwd() { let mut search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", SIMPLE_PATH); assert!(!search_path.contains(&PathBuf::from("."))); search_path.prepend_cwd(); assert!(search_path.contains(&PathBuf::from("."))); assert_eq!(search_path.iter().next(), Some(&PathBuf::from("."))); } #[test] fn test_remove() { let mut search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", SIMPLE_PATH); assert!(search_path.contains(&PathBuf::from("a"))); search_path.remove(&PathBuf::from("a")); assert!(!search_path.contains(&PathBuf::from("a"))); } #[cfg(target_family = "windows")] const DUPLICATES_PATH: &str = "a;b;a;b;c;a;c"; #[cfg(not(target_family = "windows"))] const DUPLICATES_PATH: &str = "a:b:a:b:c:a:c"; #[test] fn test_dedup() { let mut search_path = SearchPath::new_or("UNLIKELY_THIS_VAR_EXISTS", DUPLICATES_PATH); search_path.dedup(); assert_eq!(search_path.len(), 3); assert!(search_path.contains(&PathBuf::from("a"))); assert!(search_path.contains(&PathBuf::from("b"))); assert!(search_path.contains(&PathBuf::from("c"))); }