1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
use crate::fs::{errors, open_dir, path_requires_dir, MaybeOwnedFile};
use std::ffi::OsStr;
use std::io;
use std::path::{Component, Path};
pub(super) fn open_parent<'path, 'borrow>(
start: MaybeOwnedFile<'borrow>,
path: &'path Path,
) -> io::Result<(MaybeOwnedFile<'borrow>, &'path OsStr)> {
let (dirname, basename) = split_parent(path).ok_or_else(errors::no_such_file_or_directory)?;
let dir = if dirname.as_os_str().is_empty() {
start
} else {
MaybeOwnedFile::owned(open_dir(&start, dirname)?)
};
Ok((dir, basename.as_os_str()))
}
fn split_parent(path: &Path) -> Option<(&Path, Component)> {
if path.as_os_str().is_empty() {
return None;
}
if !path_requires_dir(path) {
let mut comps = path.components();
if let Some(p) = comps.next_back() {
match p {
Component::Normal(_) | Component::CurDir => return Some((comps.as_path(), p)),
_ => (),
}
}
}
Some((path, Component::CurDir))
}
#[test]
fn split_parent_basics() {
assert_eq!(
split_parent(Path::new("foo/bar/qux")).unwrap(),
(
Path::new("foo/bar"),
Component::Normal(Path::new("qux").as_ref())
)
);
assert_eq!(
split_parent(Path::new("foo/bar")).unwrap(),
(
Path::new("foo"),
Component::Normal(Path::new("bar").as_ref())
)
);
assert_eq!(
split_parent(Path::new("foo")).unwrap(),
(Path::new(""), Component::Normal(Path::new("foo").as_ref()))
);
}
#[test]
fn split_parent_special_cases() {
assert!(split_parent(Path::new("")).is_none());
assert_eq!(
split_parent(Path::new("foo/")).unwrap(),
(Path::new("foo"), Component::CurDir)
);
assert_eq!(
split_parent(Path::new("foo/.")).unwrap(),
(Path::new("foo"), Component::CurDir)
);
assert_eq!(
split_parent(Path::new(".")).unwrap(),
(Path::new(""), Component::CurDir)
);
assert_eq!(
split_parent(Path::new("..")).unwrap(),
(Path::new(".."), Component::CurDir)
);
assert_eq!(
split_parent(Path::new("../..")).unwrap(),
(Path::new("../.."), Component::CurDir)
);
assert_eq!(
split_parent(Path::new("../foo")).unwrap(),
(
Path::new(".."),
Component::Normal(Path::new("foo").as_ref())
)
);
assert_eq!(
split_parent(Path::new("foo/..")).unwrap(),
(Path::new("foo/.."), Component::CurDir)
);
assert_eq!(
split_parent(Path::new("/foo")).unwrap(),
(Path::new("/"), Component::Normal(Path::new("foo").as_ref()))
);
assert_eq!(
split_parent(Path::new("/foo/")).unwrap(),
(Path::new("/foo"), Component::CurDir)
);
assert_eq!(
split_parent(Path::new("/")).unwrap(),
(Path::new("/"), Component::CurDir)
);
}