Skip to main content

nu_path/
dots.rs

1#[cfg(windows)]
2use omnipath::WinPathExt;
3use std::path::{Component, Path, PathBuf, Prefix};
4
5/// Returns whether a path component is n-dots.
6fn is_ndots(s: &std::ffi::OsStr) -> bool {
7    s.as_encoded_bytes().iter().all(|c| *c == b'.') && s.len() >= 3
8}
9
10/// Normalize the path, expanding occurrences of n-dots.
11///
12/// It performs the same normalization as `nu_path::components()`, except it also expands n-dots,
13/// such as "..." and "....", into multiple "..".
14///
15/// The resulting path will use platform-specific path separators, regardless of what path separators was used in the input.
16pub fn expand_ndots(path: impl AsRef<Path>) -> PathBuf {
17    let path = path.as_ref();
18
19    let mut result = PathBuf::with_capacity(path.as_os_str().len());
20    let mut has_special_prefix = false;
21    for component in crate::components(path) {
22        match component {
23            Component::Normal(s) if is_ndots(s) => {
24                let n = s.len();
25                // Push ".." to the path (n - 1) times.
26                for _ in 0..n - 1 {
27                    result.push("..");
28                }
29            }
30            Component::Prefix(prefix) => {
31                match prefix.kind() {
32                    Prefix::Disk(_) => {
33                        // Here, only the disk letter gets parsed as prefix,
34                        // so the following RootDir component makes sense
35                    }
36                    _ => {
37                        has_special_prefix = true;
38                    }
39                }
40                result.push(component)
41            }
42            Component::RootDir if has_special_prefix => {
43                // Ignore; this would add a trailing backslash to the path that wasn't in the input
44            }
45            _ => result.push(component),
46        }
47    }
48
49    result
50}
51
52/// Normalize the path, expanding occurrences of "." and "..".
53///
54/// It performs the same normalization as `nu_path::components()`, except it also expands ".."
55/// when its preceding component is a normal component, ignoring the possibility of symlinks.
56/// In other words, it operates on the lexical structure of the path.
57///
58/// This won't expand "/.." even though the parent directory of "/" is often
59/// considered to be itself.
60///
61/// The resulting path will use platform-specific path separators, regardless of what path separators was used in the input.
62pub fn expand_dots(path: impl AsRef<Path>) -> PathBuf {
63    // Check if the last component of the path is a normal component.
64    fn last_component_is_normal(path: &Path) -> bool {
65        matches!(path.components().next_back(), Some(Component::Normal(_)))
66    }
67
68    let path = path.as_ref();
69
70    let mut has_special_prefix = false;
71    let mut result = PathBuf::with_capacity(path.as_os_str().len());
72    for component in crate::components(path) {
73        match component {
74            Component::ParentDir if last_component_is_normal(&result) => {
75                result.pop();
76            }
77            Component::CurDir if last_component_is_normal(&result) => {
78                // no-op
79            }
80            Component::Prefix(prefix) => {
81                match prefix.kind() {
82                    Prefix::Disk(_) => {
83                        // Here, only the disk letter gets parsed as prefix,
84                        // so the following RootDir component makes sense
85                    }
86                    _ => {
87                        has_special_prefix = true;
88                    }
89                }
90                result.push(component)
91            }
92            Component::RootDir if has_special_prefix => {
93                // Ignore; this would add a trailing backslash to the path that wasn't in the input
94            }
95            _ => {
96                let prev_component = result.components().next_back();
97                if prev_component == Some(Component::RootDir) && component == Component::ParentDir {
98                    continue;
99                }
100                result.push(component)
101            }
102        }
103    }
104
105    simiplified(&result)
106}
107
108/// Expand ndots, but only if it looks like it probably contains them, because there is some lossy
109/// path normalization that happens.
110pub fn expand_ndots_safe(path: impl AsRef<Path>) -> PathBuf {
111    let string = path.as_ref().to_string_lossy();
112
113    // Don't use it if it contains ://, because that looks like a URL scheme and the path normalization
114    // will mess with that.
115    // Don't use it if it starts with `./`, as to not break golang wildcard syntax
116    // (since generally you're probably not using `./` with ndots)
117    // Otherwise use it only if some component consists solely of at least `...`. A mere substring
118    // such as `origin/main...` is not an n-dots component, and normalizing it would needlessly
119    // rewrite the separators (e.g. to backslashes on Windows). Splitting with `components()` keeps
120    // this check in line with how `expand_ndots` tokenizes the path.
121    if !string.contains("://")
122        && !string.starts_with("./")
123        && path
124            .as_ref()
125            .components()
126            .any(|c| matches!(c, Component::Normal(s) if is_ndots(s)))
127    {
128        expand_ndots(path)
129    } else {
130        path.as_ref().to_owned()
131    }
132}
133
134#[cfg(windows)]
135fn simiplified(path: &std::path::Path) -> PathBuf {
136    path.to_winuser_path()
137        .unwrap_or_else(|_| path.to_path_buf())
138}
139
140#[cfg(not(windows))]
141fn simiplified(path: &std::path::Path) -> PathBuf {
142    path.to_path_buf()
143}
144
145#[cfg(test)]
146mod test_expand_ndots {
147    use super::*;
148    use crate::assert_path_eq;
149
150    #[test]
151    fn empty_path() {
152        let path = Path::new("");
153        assert_path_eq!(expand_ndots(path), "");
154    }
155
156    #[test]
157    fn root_dir() {
158        let path = Path::new("/");
159        let expected = if cfg!(windows) { "\\" } else { "/" };
160        assert_path_eq!(expand_ndots(path), expected);
161    }
162
163    #[test]
164    fn two_dots() {
165        let path = Path::new("..");
166        assert_path_eq!(expand_ndots(path), "..");
167    }
168
169    #[test]
170    fn three_dots() {
171        let path = Path::new("...");
172        let expected = if cfg!(windows) { r"..\.." } else { "../.." };
173        assert_path_eq!(expand_ndots(path), expected);
174    }
175
176    #[test]
177    fn five_dots() {
178        let path = Path::new(".....");
179        let expected = if cfg!(windows) {
180            r"..\..\..\.."
181        } else {
182            "../../../.."
183        };
184        assert_path_eq!(expand_ndots(path), expected);
185    }
186
187    #[test]
188    fn three_dots_with_trailing_slash() {
189        let path = Path::new("/tmp/.../");
190        let expected = if cfg!(windows) {
191            r"\tmp\..\..\"
192        } else {
193            "/tmp/../../"
194        };
195        assert_path_eq!(expand_ndots(path), expected);
196    }
197
198    #[test]
199    fn filenames_with_dots() {
200        let path = Path::new("...foo.../");
201        let expected = if cfg!(windows) {
202            r"...foo...\"
203        } else {
204            "...foo.../"
205        };
206        assert_path_eq!(expand_ndots(path), expected);
207    }
208
209    #[test]
210    fn multiple_ndots() {
211        let path = Path::new("..././...");
212        let expected = if cfg!(windows) {
213            r"..\..\..\.."
214        } else {
215            "../../../.."
216        };
217        assert_path_eq!(expand_ndots(path), expected);
218    }
219
220    #[test]
221    fn trailing_dots() {
222        let path = Path::new("/foo/bar/..");
223        let expected = if cfg!(windows) {
224            r"\foo\bar\.."
225        } else {
226            "/foo/bar/.."
227        };
228        assert_path_eq!(expand_ndots(path), expected);
229    }
230
231    #[test]
232    fn dots_inside_component_untouched() {
233        // `...` only counts as n-dots when it is a whole path component (#16858)
234        assert_path_eq!(expand_ndots_safe("origin/main..."), "origin/main...");
235        assert_path_eq!(expand_ndots_safe("a.../b"), "a.../b");
236        // a non-ndots path is returned as is, so the doubled slash survives
237        assert_path_eq!(expand_ndots_safe("origin//main..."), "origin//main...");
238    }
239
240    #[test]
241    fn drive_relative_ndots() {
242        // `C:...` is the prefix `C:` followed by an n-dots component
243        let expected = if cfg!(windows) { r"C:..\.." } else { "C:..." };
244        assert_path_eq!(expand_ndots_safe("C:..."), expected);
245    }
246
247    #[test]
248    fn backslash_separated_ndots() {
249        // `\` is a separator only on Windows; elsewhere `a\...\b` is a single file name
250        let expected = if cfg!(windows) {
251            r"a\..\..\b"
252        } else {
253            r"a\...\b"
254        };
255        assert_path_eq!(expand_ndots_safe(r"a\...\b"), expected);
256    }
257
258    #[test]
259    fn leading_dot_slash() {
260        let path = Path::new("./...");
261        assert_path_eq!(expand_ndots_safe(path), "./...");
262    }
263
264    #[test]
265    fn unc_share_no_dots() {
266        let path = Path::new(r"\\server\share");
267        assert_path_eq!(expand_ndots(path), path);
268    }
269
270    #[test]
271    fn unc_file_no_dots() {
272        let path = Path::new(r"\\server\share\dir\file.nu");
273        assert_path_eq!(expand_ndots(path), path);
274    }
275
276    #[test]
277    fn verbatim_no_dots() {
278        let path = Path::new(r"\\?\pictures\elephants");
279        assert_path_eq!(expand_ndots(path), path);
280    }
281
282    #[test]
283    fn verbatim_unc_share_no_dots() {
284        let path = Path::new(r"\\?\UNC\server\share");
285        assert_path_eq!(expand_ndots(path), path);
286    }
287
288    #[test]
289    fn verbatim_unc_file_no_dots() {
290        let path = Path::new(r"\\?\UNC\server\share\dir\file.nu");
291        assert_path_eq!(expand_ndots(path), path);
292    }
293
294    #[test]
295    fn verbatim_disk_no_dots() {
296        let path = Path::new(r"\\?\c:\");
297        assert_path_eq!(expand_ndots(path), path);
298    }
299
300    #[test]
301    fn device_path_no_dots() {
302        let path = Path::new(r"\\.\CON");
303        assert_path_eq!(expand_ndots(path), path);
304    }
305
306    #[test]
307    fn disk_no_dots() {
308        let path = Path::new(r"c:\Users\Ellie\nu_scripts");
309        assert_path_eq!(expand_ndots(path), path);
310    }
311}
312
313#[cfg(test)]
314mod test_expand_dots {
315    use super::*;
316    use crate::assert_path_eq;
317
318    #[test]
319    fn empty_path() {
320        let path = Path::new("");
321        assert_path_eq!(expand_dots(path), "");
322    }
323
324    #[test]
325    fn single_dot() {
326        let path = Path::new("./");
327        let expected = if cfg!(windows) { r".\" } else { "./" };
328        assert_path_eq!(expand_dots(path), expected);
329    }
330
331    #[test]
332    fn more_single_dots() {
333        let path = Path::new("././.");
334        let expected = ".";
335        assert_path_eq!(expand_dots(path), expected);
336    }
337
338    #[test]
339    fn double_dots() {
340        let path = Path::new("../../..");
341        let expected = if cfg!(windows) {
342            r"..\..\.."
343        } else {
344            "../../.."
345        };
346        assert_path_eq!(expand_dots(path), expected);
347    }
348
349    #[test]
350    fn backtrack_once() {
351        let path = Path::new("/foo/bar/../baz/");
352        let expected = if cfg!(windows) {
353            r"\foo\baz\"
354        } else {
355            "/foo/baz/"
356        };
357        assert_path_eq!(expand_dots(path), expected);
358    }
359
360    #[test]
361    fn backtrack_to_root() {
362        let path = Path::new("/foo/bar/../../../../baz");
363        let expected = if cfg!(windows) { r"\baz" } else { "/baz" };
364        assert_path_eq!(expand_dots(path), expected);
365    }
366
367    #[test]
368    fn unc_share_no_dots() {
369        let path = Path::new(r"\\server\share");
370        assert_path_eq!(expand_dots(path), path);
371    }
372
373    #[test]
374    fn unc_file_no_dots() {
375        let path = Path::new(r"\\server\share\dir\file.nu");
376        assert_path_eq!(expand_dots(path), path);
377    }
378
379    #[test]
380    #[ignore = "bug in upstream library"]
381    fn verbatim_no_dots() {
382        // omnipath::windows::sys::Path::to_winuser_path seems to turn this verbatim path into a device path
383        let path = Path::new(r"\\?\pictures\elephants");
384        assert_path_eq!(expand_dots(path), path);
385    }
386
387    #[cfg_attr(not(windows), ignore = "only for Windows")]
388    #[test]
389    fn verbatim_unc_share_no_dots() {
390        let path = Path::new(r"\\?\UNC\server\share");
391        let expected = Path::new(r"\\server\share");
392        assert_path_eq!(expand_dots(path), expected);
393    }
394
395    #[cfg_attr(not(windows), ignore = "only for Windows")]
396    #[test]
397    fn verbatim_unc_file_no_dots() {
398        let path = Path::new(r"\\?\UNC\server\share\dir\file.nu");
399        let expected = Path::new(r"\\server\share\dir\file.nu");
400        assert_path_eq!(expand_dots(path), expected);
401    }
402
403    #[cfg_attr(not(windows), ignore = "only for Windows")]
404    #[test]
405    fn verbatim_disk_no_dots() {
406        let path = Path::new(r"\\?\C:\");
407        let expected = Path::new(r"C:\");
408        assert_path_eq!(expand_dots(path), expected);
409    }
410
411    #[test]
412    fn device_path_no_dots() {
413        let path = Path::new(r"\\.\CON");
414        assert_path_eq!(expand_dots(path), path);
415    }
416
417    #[test]
418    fn disk_no_dots() {
419        let path = Path::new(r"c:\Users\Ellie\nu_scripts");
420        assert_path_eq!(expand_dots(path), path);
421    }
422}