Skip to main content

path_dedot/
lib.rs

1/*!
2# Path Dedot
3
4This is a library for extending `Path` and `PathBuf` in order to parse the path which contains dots.
5
6Please read the following examples to know the parsing rules.
7
8## Examples
9
10If a path starts with a single dot, the dot means your program's **current working directory** (CWD).
11
12```rust
13use std::path::Path;
14use std::env;
15
16use path_dedot::*;
17
18let p = Path::new("./path/to/123/456");
19
20# if cfg!(unix) {
21assert_eq!(Path::join(env::current_dir().unwrap().as_path(), Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap());
22# }
23```
24
25If 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**.
26
27```rust
28use std::path::Path;
29use std::env;
30
31use path_dedot::*;
32
33let p = Path::new("../path/to/123/456");
34
35let cwd = env::current_dir().unwrap();
36
37let cwd_parent = cwd.parent();
38
39# if cfg!(unix) {
40match cwd_parent {
41   Some(cwd_parent) => {
42      assert_eq!(Path::join(&cwd_parent, Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap());
43   }
44   None => {
45      assert_eq!(Path::join(Path::new("/"), Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap());
46   }
47}
48# }
49```
50
51In addition to starting with, the **Single Dot** and **Double Dots** can also be placed to other positions. **Single Dot** means noting and will be ignored. **Double Dots** means the parent.
52
53```rust
54use std::path::Path;
55
56use path_dedot::*;
57
58let p = Path::new("/path/to/../123/456/./777");
59
60# if cfg!(unix) {
61assert_eq!("/path/123/456/777", p.parse_dot().unwrap().to_str().unwrap());
62# }
63```
64
65```rust
66use std::path::Path;
67
68use path_dedot::*;
69
70let p = Path::new("/path/to/../123/456/./777/..");
71
72# if cfg!(unix) {
73assert_eq!("/path/123/456", p.parse_dot().unwrap().to_str().unwrap());
74# }
75```
76
77You should notice that `parse_dot` method does **not** aim to get an **absolute path**. A path which does not start with a `MAIN_SEPARATOR`, **Single Dot** and **Double Dots**, will not have each of them after the `parse_dot` method is used.
78
79```rust
80use std::path::Path;
81
82use path_dedot::*;
83
84let p = Path::new("path/to/../123/456/./777/..");
85
86# if cfg!(unix) {
87assert_eq!("path/123/456", p.parse_dot().unwrap().to_str().unwrap());
88# }
89```
90
91**Double Dots** which is not placed at the start cannot get the parent beyond the original path. Why not? With this constraint, you can insert an absolute path to the start as a virtual root in order to protect your file system from being exposed.
92
93```rust
94use std::path::Path;
95
96use path_dedot::*;
97
98let p = Path::new("path/to/../../../../123/456/./777/..");
99
100# if cfg!(unix) {
101assert_eq!("123/456", p.parse_dot().unwrap().to_str().unwrap());
102# }
103```
104
105```rust
106use std::path::Path;
107
108use path_dedot::*;
109
110let p = Path::new("/path/to/../../../../123/456/./777/..");
111
112# if cfg!(unix) {
113assert_eq!("/123/456", p.parse_dot().unwrap().to_str().unwrap());
114# }
115```
116
117If a path is entirely consumed by its **Double Dots**, an empty path will be returned.
118
119```rust
120use std::path::Path;
121
122use path_dedot::*;
123
124let p = Path::new("path/to/../../..");
125
126assert_eq!("", p.parse_dot().unwrap().to_str().unwrap());
127```
128
129### Starting from a given current working directory
130
131With the `parse_dot_from` function, you can provide the current working directory that the relative paths should be resolved from.
132
133```rust
134use std::env;
135use std::path::Path;
136
137use path_dedot::*;
138
139let p = Path::new("../path/to/123/456");
140let cwd = env::current_dir().unwrap();
141
142println!("{}", p.parse_dot_from(cwd).to_str().unwrap());
143```
144
145## Caching
146
147The `parse_dot` method requires the CWD only when the input path starts with a **Single Dot** or **Double Dots**, and by default, it creates a new `PathBuf` instance of the CWD every time in its 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.
148
149In order to parse paths with better performance, the `fixed_workdir` feature can be enabled.
150
151```toml
152[dependencies.path-dedot]
153version = "*"
154features = ["fixed_workdir"]
155```
156
157## Benchmark
158
159#### No-cache
160
161```bash
162cargo bench
163```
164
165#### fixed_workdir
166
167```bash
168cargo bench --features fixed_workdir
169```
170
171*/
172
173#![cfg_attr(docsrs, feature(doc_cfg))]
174
175use std::{
176    borrow::Cow,
177    io,
178    path::{Path, PathBuf},
179};
180
181mod parse_dot;
182
183#[macro_use]
184mod macros;
185
186#[cfg(any(unix, target_family = "wasm"))]
187mod unix;
188
189#[cfg(windows)]
190mod windows;
191
192#[cfg(feature = "fixed_workdir")]
193use std::sync::LazyLock;
194
195pub use parse_dot::*;
196#[cfg(windows)]
197pub use windows::ParsePrefix;
198
199impl ParseDot for PathBuf {
200    #[inline]
201    fn parse_dot(&self) -> io::Result<Cow<'_, Path>> {
202        self.as_path().parse_dot()
203    }
204
205    #[inline]
206    fn parse_dot_from(&self, cwd: impl AsRef<Path>) -> Cow<'_, Path> {
207        self.as_path().parse_dot_from(cwd)
208    }
209}
210
211#[cfg(feature = "fixed_workdir")]
212/// Current working directory.
213pub static CWD: LazyLock<PathBuf> = LazyLock::new(|| std::env::current_dir().unwrap());