path-absolutize-3.1.1/.cargo_vcs_info.json0000644000000001360000000000100141510ustar { "git": { "sha1": "0882f98f7864247c17586c19d75b2c3a7eb70d42" }, "path_in_vcs": "" }path-absolutize-3.1.1/Cargo.toml0000644000000030200000000000100121420ustar # 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.60" name = "path-absolutize" version = "3.1.1" authors = ["Magic Len "] include = [ "src/**/*", "Cargo.toml", "README.md", "LICENSE", "benches/bench.rs", ] description = "A library for extending `Path` and `PathBuf` in order to get an absolute path and remove the containing dots." homepage = "https://magiclen.org/path-absolutize" readme = "README.md" keywords = [ "path", "dot", "dedot", "absolute", "canonical", ] categories = [ "parser-implementations", "filesystem", ] license = "MIT" repository = "https://github.com/magiclen/path-absolutize" [[bench]] name = "bench" harness = false [dependencies.path-dedot] version = "3.1.1" [dev-dependencies.bencher] version = "0.1.5" [features] lazy_static_cache = ["path-dedot/lazy_static_cache"] once_cell_cache = ["path-dedot/once_cell_cache"] unsafe_cache = ["path-dedot/unsafe_cache"] use_unix_paths_on_wasm = ["path-dedot/use_unix_paths_on_wasm"] [target."cfg(windows)".dev-dependencies.slash-formatter] version = "3" path-absolutize-3.1.1/Cargo.toml.orig000064400000000000000000000017271046102023000156370ustar 00000000000000[package] name = "path-absolutize" version = "3.1.1" authors = ["Magic Len "] edition = "2021" rust-version = "1.60" repository = "https://github.com/magiclen/path-absolutize" homepage = "https://magiclen.org/path-absolutize" keywords = ["path", "dot", "dedot", "absolute", "canonical"] categories = ["parser-implementations", "filesystem"] description = "A library for extending `Path` and `PathBuf` in order to get an absolute path and remove the containing dots." license = "MIT" include = ["src/**/*", "Cargo.toml", "README.md", "LICENSE", "benches/bench.rs"] [dependencies] path-dedot = "3.1.1" [dev-dependencies] bencher = "0.1.5" [target.'cfg(windows)'.dev-dependencies] slash-formatter = "3" [features] once_cell_cache = ["path-dedot/once_cell_cache"] lazy_static_cache = ["path-dedot/lazy_static_cache"] unsafe_cache = ["path-dedot/unsafe_cache"] use_unix_paths_on_wasm = ["path-dedot/use_unix_paths_on_wasm"] [[bench]] name = "bench" harness = false path-absolutize-3.1.1/LICENSE000064400000000000000000000020661046102023000137520ustar 00000000000000MIT License Copyright (c) 2018 magiclen.org (Ron Li) 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. path-absolutize-3.1.1/README.md000064400000000000000000000172521046102023000142270ustar 00000000000000Path Absolutize ==================== [![CI](https://github.com/magiclen/path-absolutize/actions/workflows/ci.yml/badge.svg)](https://github.com/magiclen/path-absolutize/actions/workflows/ci.yml) This is a library for extending `Path` and `PathBuf` in order to get an absolute path and remove the containing dots. The difference between `absolutize` and `canonicalize` methods is that `absolutize` does not care about whether the file exists and what the file really is. Please read the following examples to know the parsing rules. ## Examples There are two methods you can use. ### absolutize Get an absolute path. The dots in a path will be parsed even if it is already an absolute path (which means the path starts with a `MAIN_SEPARATOR` on Unix-like systems). ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/123/456"); assert_eq!("/path/to/123/456", p.absolutize().unwrap().to_str().unwrap()); ``` ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/./123/../456"); assert_eq!("/path/to/456", p.absolutize().unwrap().to_str().unwrap()); ``` If a path starts with a single dot, the dot means your program's **current working directory** (CWD). ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("./path/to/123/456"); assert_eq!(Path::join(env::current_dir().unwrap().as_path(), Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); ``` If a path starts with a pair of dots, the dots means the parent of the CWD. If the CWD is **root**, the parent is still **root**. ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); let cwd_parent = cwd.parent(); match cwd_parent { Some(cwd_parent) => { assert_eq!(Path::join(&cwd_parent, Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } None => { assert_eq!(Path::join(Path::new("/"), Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } } ``` A path which does not start with a `MAIN_SEPARATOR`, **Single Dot** and **Double Dots**, will act like having a single dot at the start when `absolutize` method is used. ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("path/to/123/456"); assert_eq!(Path::join(env::current_dir().unwrap().as_path(), Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); ``` ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("path/../../to/123/456"); let cwd = env::current_dir().unwrap(); let cwd_parent = cwd.parent(); match cwd_parent { Some(cwd_parent) => { assert_eq!(Path::join(&cwd_parent, Path::new("to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } None => { assert_eq!(Path::join(Path::new("/"), Path::new("to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } } ``` ### Starting from a given current working directory With the `absolutize_from` function, you can provide the current working directory that the relative paths should be resolved from. ```rust use std::env; use std::path::Path; use path_absolutize::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); println!("{}", p.absolutize_from(cwd).unwrap().to_str().unwrap()); ``` ### absolutize_virtually Get an absolute path **only under a specific directory**. The dots in a path will be parsed even if it is already an absolute path (which means the path starts with a `MAIN_SEPARATOR` on Unix-like systems). ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/123/456"); assert_eq!("/path/to/123/456", p.absolutize_virtually("/").unwrap().to_str().unwrap()); ``` ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/./123/../456"); assert_eq!("/path/to/456", p.absolutize_virtually("/").unwrap().to_str().unwrap()); ``` Every absolute path should under the virtual root. ```rust use std::path::Path; use std::io::ErrorKind; use path_absolutize::*; let p = Path::new("/path/to/123/456"); assert_eq!(ErrorKind::InvalidInput, p.absolutize_virtually("/virtual/root").unwrap_err().kind()); ``` Every relative path should under the virtual root. ```rust use std::path::Path; use std::io::ErrorKind; use path_absolutize::*; let p = Path::new("./path/to/123/456"); assert_eq!(ErrorKind::InvalidInput, p.absolutize_virtually("/virtual/root").unwrap_err().kind()); ``` ```rust use std::path::Path; use std::io::ErrorKind; use path_absolutize::*; let p = Path::new("../path/to/123/456"); assert_eq!(ErrorKind::InvalidInput, p.absolutize_virtually("/virtual/root").unwrap_err().kind()); ``` A path which does not start with a `MAIN_SEPARATOR`, **Single Dot** and **Double Dots**, will be located in the virtual root after the `absolutize_virtually` method is used. ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("path/to/123/456"); assert_eq!("/virtual/root/path/to/123/456", p.absolutize_virtually("/virtual/root").unwrap().to_str().unwrap()); ``` ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("path/to/../../../../123/456"); assert_eq!("/virtual/root/123/456", p.absolutize_virtually("/virtual/root").unwrap().to_str().unwrap()); ``` ## Caching By default, the `absolutize` method and the `absolutize_virtually` method create a new `PathBuf` instance of the CWD every time in their operation. Although it allows us to safely change the CWD at runtime by the program itself (e.g. using the `std::env::set_current_dir` function) or outside controls (e.g. using gdb to call `chdir`), we don't need that in most cases. In order to parse paths with better performance, this crate provides three ways to cache the CWD. ### once_cell_cache Enabling the `once_cell_cache` feature can let this crate use `once_cell` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-absolutize] version = "*" features = ["once_cell_cache"] ``` ### lazy_static_cache Enabling the `lazy_static_cache` feature can let this crate use `lazy_static` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-absolutize] version = "*" features = ["lazy_static_cache"] ``` ### unsafe_cache Enabling the `unsafe_cache` feature can let this crate use a mutable static variable to cache the CWD. It allows the program to change the CWD at runtime by the program itself, but it's not thread-safe. You need to use the `update_cwd` function to initialize the CWD first. The function should also be used to update the CWD after the CWD is changed. ```toml [dependencies.path-absolutize] version = "*" features = ["unsafe_cache"] ``` ```rust use std::path::Path; use path_absolutize::*; unsafe { update_cwd(); } let p = Path::new("./path/to/123/456"); println!("{}", p.absolutize().unwrap().to_str().unwrap()); std::env::set_current_dir("/").unwrap(); unsafe { update_cwd(); } println!("{}", p.absolutize().unwrap().to_str().unwrap()); ``` ## Benchmark #### No-cache ```bash cargo bench ``` #### once_cell_cache ```bash cargo bench --features once_cell_cache ``` #### lazy_static_cache ```bash cargo bench --features lazy_static_cache ``` #### unsafe_cache ```bash cargo bench --features unsafe_cache ``` ## Crates.io https://crates.io/crates/path-absolutize ## Documentation https://docs.rs/path-absolutize ## License [MIT](LICENSE)path-absolutize-3.1.1/benches/bench.rs000064400000000000000000000047521046102023000160050ustar 00000000000000use std::path::Path; use bencher::{benchmark_group, benchmark_main, Bencher}; use path_absolutize::Absolutize; fn abs_no_dots(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("path/to/123/456"); bencher.iter(|| path.absolutize()); } fn abs_starts_with_a_single_dot(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("./path/to/123/456"); bencher.iter(|| path.absolutize()); } fn abs_starts_with_double_dots(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("../path/to/123/456"); bencher.iter(|| path.absolutize()); } fn abs_mix(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("./path/to/123/../456"); bencher.iter(|| path.absolutize()); } fn vabs_no_dots(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("path/to/123/456"); let v_root = Path::new("/home"); bencher.iter(|| path.absolutize_virtually(v_root)); } fn vabs_starts_with_a_single_dot(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("./path/to/123/456"); let v_root = Path::new("/home"); bencher.iter(|| path.absolutize_virtually(v_root)); } fn vabs_starts_with_double_dots(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("../path/to/123/456"); let v_root = Path::new("/home"); bencher.iter(|| path.absolutize_virtually(v_root)); } fn vabs_mix(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_absolutize::update_cwd() }; let path = Path::new("./path/to/123/../456"); let v_root = Path::new("/home"); bencher.iter(|| path.absolutize_virtually(v_root)); } benchmark_group!( absolutize, abs_no_dots, abs_starts_with_a_single_dot, abs_starts_with_double_dots, abs_mix ); benchmark_group!( absolutize_virtually, vabs_no_dots, vabs_starts_with_a_single_dot, vabs_starts_with_double_dots, vabs_mix ); benchmark_main!(absolutize, absolutize_virtually); path-absolutize-3.1.1/src/absolutize.rs000064400000000000000000000012211046102023000162530ustar 00000000000000use std::{borrow::Cow, io, path::Path}; /// Let `Path` and `PathBuf` have `absolutize` and `absolutize_virtually` method. pub trait Absolutize { /// Get an absolute path. This works even if the path does not exist. fn absolutize(&self) -> io::Result>; /// Get an absolute path. This works even if the path does not exist. It gets the current working directory as the second argument. fn absolutize_from(&self, cwd: impl AsRef) -> io::Result>; /// Get an absolute path. This works even if the path does not exist. fn absolutize_virtually(&self, virtual_root: impl AsRef) -> io::Result>; } path-absolutize-3.1.1/src/lib.rs000064400000000000000000000241641046102023000146530ustar 00000000000000/*! # Path Absolutize This is a library for extending `Path` and `PathBuf` in order to get an absolute path and remove the containing dots. The difference between `absolutize` and `canonicalize` methods is that `absolutize` does not care about whether the file exists and what the file really is. Please read the following examples to know the parsing rules. ## Examples There are two methods you can use. ### absolutize Get an absolute path. The dots in a path will be parsed even if it is already an absolute path (which means the path starts with a `MAIN_SEPARATOR` on Unix-like systems). ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/path/to/123/456", p.absolutize().unwrap().to_str().unwrap()); # } ``` ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/./123/../456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/path/to/456", p.absolutize().unwrap().to_str().unwrap()); # } ``` If a path starts with a single dot, the dot means your program's **current working directory** (CWD). ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("./path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!(Path::join(env::current_dir().unwrap().as_path(), Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); # } ``` If a path starts with a pair of dots, the dots means the parent of the CWD. If the CWD is **root**, the parent is still **root**. ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); let cwd_parent = cwd.parent(); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } match cwd_parent { Some(cwd_parent) => { assert_eq!(Path::join(&cwd_parent, Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } None => { assert_eq!(Path::join(Path::new("/"), Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } } # } ``` A path which does not start with a `MAIN_SEPARATOR`, **Single Dot** and **Double Dots**, will act like having a single dot at the start when `absolutize` method is used. ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!(Path::join(env::current_dir().unwrap().as_path(), Path::new("path/to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); # } ``` ```rust use std::path::Path; use std::env; use path_absolutize::*; let p = Path::new("path/../../to/123/456"); let cwd = env::current_dir().unwrap(); let cwd_parent = cwd.parent(); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } match cwd_parent { Some(cwd_parent) => { assert_eq!(Path::join(&cwd_parent, Path::new("to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } None => { assert_eq!(Path::join(Path::new("/"), Path::new("to/123/456")).to_str().unwrap(), p.absolutize().unwrap().to_str().unwrap()); } } # } ``` ### Starting from a given current working directory With the `absolutize_from` function, you can provide the current working directory that the relative paths should be resolved from. ```rust use std::env; use std::path::Path; use path_absolutize::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); println!("{}", p.absolutize_from(cwd).unwrap().to_str().unwrap()); ``` ### absolutize_virtually Get an absolute path **only under a specific directory**. The dots in a path will be parsed even if it is already an absolute path (which means the path starts with a `MAIN_SEPARATOR` on Unix-like systems). ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/path/to/123/456", p.absolutize_virtually("/").unwrap().to_str().unwrap()); # } ``` ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("/path/to/./123/../456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/path/to/456", p.absolutize_virtually("/").unwrap().to_str().unwrap()); # } ``` Every absolute path should under the virtual root. ```rust use std::path::Path; use std::io::ErrorKind; use path_absolutize::*; let p = Path::new("/path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!(ErrorKind::InvalidInput, p.absolutize_virtually("/virtual/root").unwrap_err().kind()); # } ``` Every relative path should under the virtual root. ```rust use std::path::Path; use std::io::ErrorKind; use path_absolutize::*; let p = Path::new("./path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!(ErrorKind::InvalidInput, p.absolutize_virtually("/virtual/root").unwrap_err().kind()); # } ``` ```rust use std::path::Path; use std::io::ErrorKind; use path_absolutize::*; let p = Path::new("../path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!(ErrorKind::InvalidInput, p.absolutize_virtually("/virtual/root").unwrap_err().kind()); # } ``` A path which does not start with a `MAIN_SEPARATOR`, **Single Dot** and **Double Dots**, will be located in the virtual root after the `absolutize_virtually` method is used. ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/virtual/root/path/to/123/456", p.absolutize_virtually("/virtual/root").unwrap().to_str().unwrap()); # } ``` ```rust use std::path::Path; use path_absolutize::*; let p = Path::new("path/to/../../../../123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/virtual/root/123/456", p.absolutize_virtually("/virtual/root").unwrap().to_str().unwrap()); # } ``` ## Caching By default, the `absolutize` method and the `absolutize_virtually` method create a new `PathBuf` instance of the CWD every time in their operation. The overhead is obvious. Although it allows us to safely change the CWD at runtime by the program itself (e.g. using the `std::env::set_current_dir` function) or outside controls (e.g. using gdb to call `chdir`), we don't need that in most cases. In order to parse paths with better performance, this crate provides three ways to cache the CWD. ### once_cell_cache Enabling the `once_cell_cache` feature can let this crate use `once_cell` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-absolutize] version = "*" features = ["once_cell_cache"] ``` ### lazy_static_cache Enabling the `lazy_static_cache` feature can let this crate use `lazy_static` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-absolutize] version = "*" features = ["lazy_static_cache"] ``` ### unsafe_cache Enabling the `unsafe_cache` feature can let this crate use a mutable static variable to cache the CWD. It allows the program to change the CWD at runtime by the program itself, but it's not thread-safe. You need to use the `update_cwd` function to initialize the CWD first. The function should also be used to update the CWD after the CWD is changed. ```toml [dependencies.path-absolutize] version = "*" features = ["unsafe_cache"] ``` ```rust use std::path::Path; use path_absolutize::*; # #[cfg(feature = "unsafe_cache")] unsafe { update_cwd(); } let p = Path::new("./path/to/123/456"); println!("{}", p.absolutize().unwrap().to_str().unwrap()); std::env::set_current_dir("/").unwrap(); # #[cfg(feature = "unsafe_cache")] unsafe { update_cwd(); } println!("{}", p.absolutize().unwrap().to_str().unwrap()); ``` ## Benchmark #### No-cache ```bash cargo bench ``` #### once_cell_cache ```bash cargo bench --features once_cell_cache ``` #### lazy_static_cache ```bash cargo bench --features lazy_static_cache ``` #### unsafe_cache ```bash cargo bench --features unsafe_cache ``` */ #[cfg(any( all(feature = "lazy_static_cache", feature = "unsafe_cache"), all(feature = "once_cell_cache", feature = "unsafe_cache"), all(feature = "lazy_static_cache", feature = "once_cell_cache") ))] compile_error!("You can only enable at most one caching mechanism for `path-absolutize`."); pub extern crate path_dedot; use std::{ borrow::Cow, io, path::{Path, PathBuf}, }; #[cfg(feature = "unsafe_cache")] pub use path_dedot::update_cwd; #[cfg(any( feature = "once_cell_cache", feature = "lazy_static_cache", feature = "unsafe_cache" ))] pub use path_dedot::CWD; mod absolutize; #[macro_use] mod macros; #[cfg(any(unix, all(target_family = "wasm", feature = "use_unix_paths_on_wasm")))] mod unix; #[cfg(windows)] mod windows; pub use absolutize::*; impl Absolutize for PathBuf { #[inline] fn absolutize(&self) -> io::Result> { self.as_path().absolutize() } #[inline] fn absolutize_from(&self, cwd: impl AsRef) -> io::Result> { self.as_path().absolutize_from(cwd) } #[inline] fn absolutize_virtually(&self, virtual_root: impl AsRef) -> io::Result> { self.as_path().absolutize_virtually(virtual_root) } } path-absolutize-3.1.1/src/macros.rs000064400000000000000000000007141046102023000153640ustar 00000000000000#[cfg(not(any( feature = "once_cell_cache", feature = "lazy_static_cache", feature = "unsafe_cache" )))] macro_rules! get_cwd { () => { std::env::current_dir()? }; } #[cfg(any(feature = "once_cell_cache", feature = "lazy_static_cache"))] macro_rules! get_cwd { () => { $crate::CWD.as_path() }; } #[cfg(feature = "unsafe_cache")] macro_rules! get_cwd { () => { unsafe { $crate::CWD.as_path() } }; } path-absolutize-3.1.1/src/unix.rs000064400000000000000000000117271046102023000150710ustar 00000000000000use std::{ borrow::Cow, ffi::OsString, io::{self, ErrorKind}, path::{Component, Path, PathBuf}, }; use crate::{ path_dedot::{ParseDot, MAIN_SEPARATOR}, Absolutize, }; impl Absolutize for Path { #[inline] fn absolutize(&self) -> io::Result> { let cwd = get_cwd!(); self.absolutize_from(cwd) } fn absolutize_from(&self, cwd: impl AsRef) -> io::Result> { let mut iter = self.components(); let mut has_change = false; if let Some(first_component) = iter.next() { let mut tokens = Vec::new(); let first_is_root = match first_component { Component::RootDir => { tokens.push(MAIN_SEPARATOR.as_os_str()); true }, Component::CurDir => { has_change = true; let cwd = cwd.as_ref(); for token in cwd.iter() { tokens.push(token); } !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str() }, Component::ParentDir => { has_change = true; let cwd = cwd.as_ref(); match cwd.parent() { Some(cwd_parent) => { for token in cwd_parent.iter() { tokens.push(token); } !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str() }, None => { // don't care about `cwd` is "//" or "///" if cwd == MAIN_SEPARATOR.as_os_str() { tokens.push(MAIN_SEPARATOR.as_os_str()); true } else { false } }, } }, _ => { has_change = true; let cwd = cwd.as_ref(); for token in cwd.iter() { tokens.push(token); } let first_is_root = !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str(); tokens.push(first_component.as_os_str()); first_is_root }, }; for component in iter { match component { Component::CurDir => { // may be unreachable has_change = true; }, Component::ParentDir => { let tokens_length = tokens.len(); if tokens_length > 0 && (tokens_length != 1 || !first_is_root) { tokens.remove(tokens_length - 1); } has_change = true; }, _ => { tokens.push(component.as_os_str()); }, } } let tokens_length = tokens.len(); debug_assert!(tokens_length > 0); let mut size = tokens.iter().fold(tokens_length - 1, |acc, &x| acc + x.len()); if first_is_root && tokens_length > 1 { size -= 1; } if has_change || size != self.as_os_str().len() { let mut path_string = OsString::with_capacity(size); let mut iter = tokens.iter(); path_string.push(iter.next().unwrap()); if tokens_length > 1 { if !first_is_root { path_string.push(MAIN_SEPARATOR.as_os_str()); } for token in iter.take(tokens_length - 2) { path_string.push(token); path_string.push(MAIN_SEPARATOR.as_os_str()); } path_string.push(tokens[tokens_length - 1]); } let path_buf = PathBuf::from(path_string); Ok(Cow::from(path_buf)) } else { Ok(Cow::from(self)) } } else { Ok(Cow::from(cwd.as_ref().to_owned())) } } fn absolutize_virtually(&self, virtual_root: impl AsRef) -> io::Result> { let virtual_root = virtual_root.as_ref().absolutize()?; let path = self.parse_dot()?; if path.is_absolute() { if !path.starts_with(&virtual_root) { return Err(io::Error::from(ErrorKind::InvalidInput)); } Ok(path) } else { let mut virtual_root = virtual_root.into_owned(); virtual_root.push(path); Ok(Cow::from(virtual_root)) } } } path-absolutize-3.1.1/src/windows.rs000064400000000000000000000340751046102023000156010ustar 00000000000000use std::{ borrow::Cow, ffi::OsString, io::{self, ErrorKind}, path::{Component, Path, PathBuf}, }; use crate::{ path_dedot::{ParseDot, ParsePrefix, MAIN_SEPARATOR}, Absolutize, }; impl Absolutize for Path { #[inline] fn absolutize(&self) -> io::Result> { let cwd = get_cwd!(); self.absolutize_from(&cwd) } fn absolutize_from(&self, cwd: impl AsRef) -> io::Result> { let mut iter = self.components(); let mut has_change = false; if let Some(first_component) = iter.next() { let mut tokens = Vec::new(); let (has_prefix, first_is_root) = match first_component { Component::Prefix(prefix) => { tokens.push(prefix.as_os_str()); if let Some(second_component) = iter.next() { match second_component { Component::RootDir => { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) }, Component::CurDir => { // may be unreachable has_change = true; let cwd = cwd.as_ref(); for token in cwd.iter().skip(if cwd.get_path_prefix().is_some() { 1 } else { 0 }) { tokens.push(token); } (true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str()) }, Component::ParentDir => { has_change = true; let cwd = cwd.as_ref(); match cwd.parent() { Some(cwd_parent) => { for token in cwd_parent.iter().skip( if cwd.get_path_prefix().is_some() { 1 } else { 0 }, ) { tokens.push(token); } ( true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str(), ) }, None => { if cwd.get_path_prefix().is_some() { if cwd.is_absolute() { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) } else { (true, false) } } else { // don't care about `cwd` is "\\" or "\\\" if cwd == MAIN_SEPARATOR.as_os_str() { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) } else { (true, false) } } }, } }, _ => { has_change = true; let out = { let cwd = cwd.as_ref(); for token in cwd .iter() .skip(if cwd.get_path_prefix().is_some() { 1 } else { 0 }) { tokens.push(token); } ( true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str(), ) }; tokens.push(second_component.as_os_str()); out }, } } else { tokens.push(MAIN_SEPARATOR.as_os_str()); has_change = true; (true, true) } }, Component::RootDir => { has_change = true; let cwd = cwd.as_ref(); match cwd.get_path_prefix() { Some(prefix) => { tokens.push(prefix.as_os_str()); tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) }, None => { tokens.push(MAIN_SEPARATOR.as_os_str()); (false, true) }, } }, Component::CurDir => { has_change = true; let cwd = cwd.as_ref(); for token in cwd.iter() { tokens.push(token); } if cwd.get_path_prefix().is_some() { (true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str()) } else { (false, !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str()) } }, Component::ParentDir => { has_change = true; let cwd = cwd.as_ref(); match cwd.parent() { Some(cwd_parent) => { for token in cwd_parent.iter() { tokens.push(token); } if cwd.get_path_prefix().is_some() { (true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str()) } else { ( false, !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str(), ) } }, None => match cwd.get_path_prefix() { Some(prefix) => { tokens.push(prefix.as_os_str()); if cwd.is_absolute() { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) } else { (true, false) } }, None => { // don't care about `cwd` is "\\" or "\\\" if cwd == MAIN_SEPARATOR.as_os_str() { tokens.push(MAIN_SEPARATOR.as_os_str()); (false, true) } else { (false, false) } }, }, } }, Component::Normal(token) => { has_change = true; let cwd = cwd.as_ref(); for token in cwd.iter() { tokens.push(token); } let out = if cwd.get_path_prefix().is_some() { (true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str()) } else { (false, !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str()) }; tokens.push(token); out }, }; for component in iter { match component { Component::CurDir => { // may be unreachable has_change = true; }, Component::ParentDir => { let tokens_length = tokens.len(); if tokens_length > 0 && ((tokens_length != 1 || (!first_is_root && !has_prefix)) && (tokens_length != 2 || !(first_is_root && has_prefix))) { tokens.remove(tokens_length - 1); } has_change = true; }, _ => { tokens.push(component.as_os_str()); }, } } let tokens_length = tokens.len(); debug_assert!(tokens_length > 0); let mut size = tokens.iter().fold(tokens_length - 1, |acc, &x| acc + x.len()); if has_prefix { if tokens_length > 1 { size -= 1; if first_is_root { if tokens_length > 2 { size -= 1; } } } } else if first_is_root && tokens_length > 1 { size -= 1; } if has_change || size != self.as_os_str().len() { let mut path_string = OsString::with_capacity(size); let mut iter = tokens.iter(); path_string.push(iter.next().unwrap()); if tokens_length > 1 { if has_prefix { if let Some(token) = iter.next() { path_string.push(token); if tokens_length > 2 { if !first_is_root { path_string.push(MAIN_SEPARATOR.as_os_str()); } for token in iter.take(tokens_length - 3) { path_string.push(token); path_string.push(MAIN_SEPARATOR.as_os_str()); } path_string.push(tokens[tokens_length - 1]); } } } else { if !first_is_root { path_string.push(MAIN_SEPARATOR.as_os_str()); } for token in iter.take(tokens_length - 2) { path_string.push(token); path_string.push(MAIN_SEPARATOR.as_os_str()); } path_string.push(tokens[tokens_length - 1]); } } let path_buf = PathBuf::from(path_string); Ok(Cow::from(path_buf)) } else { Ok(Cow::from(self)) } } else { Ok(Cow::from(cwd.as_ref().to_owned())) } } fn absolutize_virtually(&self, virtual_root: impl AsRef) -> io::Result> { let virtual_root = virtual_root.as_ref().absolutize()?; let path = self.parse_dot()?; if path.is_absolute() { let path_lowercase = path .to_str() .ok_or_else(|| io::Error::new(ErrorKind::Other, "The path is not valid UTF-8."))? .to_lowercase(); let virtual_root_lowercase = virtual_root .to_str() .ok_or_else(|| { io::Error::new(ErrorKind::Other, "The virtual root is not valid UTF-8.") })? .to_lowercase(); if !&path_lowercase.starts_with(&virtual_root_lowercase) { return Err(io::Error::from(ErrorKind::InvalidInput)); } Ok(path) } else if let Some(prefix) = path.get_path_prefix() { let prefix = prefix.as_os_str().to_str().ok_or_else(|| { io::Error::new(ErrorKind::Other, "The prefix of the path is not valid UTF-8.") })?; let prefix_lowercase = prefix.to_lowercase(); let virtual_root_prefix_lowercase = virtual_root .get_path_prefix() .unwrap() .as_os_str() .to_str() .ok_or_else(|| { io::Error::new( ErrorKind::Other, "The prefix of the virtual root is not valid UTF-8.", ) })? .to_lowercase(); if prefix_lowercase == virtual_root_prefix_lowercase { let path = path.to_str().ok_or_else(|| { io::Error::new(ErrorKind::Other, "The path is not valid UTF-8.") })?; let path_without_prefix = Path::new(&path[prefix.len()..]); let mut virtual_root = virtual_root.into_owned(); virtual_root.push(path_without_prefix); Ok(Cow::from(virtual_root)) } else { Err(io::Error::from(ErrorKind::InvalidInput)) } } else { let mut virtual_root = virtual_root.into_owned(); virtual_root.push(path); Ok(Cow::from(virtual_root)) } } }