1use gix_error::{OptionExt, Result};
2use std::{
3 borrow::Cow,
4 ffi::{OsStr, OsString},
5 path::{Component, Path, PathBuf},
6};
7
8use bstr::{BStr, BString};
9#[cfg(not(unix))]
10use gix_error::ResultExt;
11
12#[cfg(not(unix))]
13fn utf8_error() -> gix_error::Message {
14 gix_error::validation("Could not convert to UTF8 or from UTF8 due to ill-formed input")
15}
16
17pub fn os_str_into_bstr(path: &OsStr) -> Result<&BStr> {
19 #[cfg(unix)]
20 let bytes = {
21 use std::os::unix::ffi::OsStrExt;
22 path.as_bytes()
23 };
24 #[cfg(not(unix))]
25 let bytes = std::str::from_utf8(path.as_encoded_bytes())
26 .or_raise(utf8_error)?
27 .as_bytes();
28 Ok(bytes.into())
29}
30
31pub fn os_string_into_bstring(path: OsString) -> Result<BString> {
33 #[cfg(unix)]
34 let bytes = {
35 use std::os::unix::ffi::OsStringExt;
36 path.into_vec()
37 };
38 #[cfg(not(unix))]
39 let bytes = String::from_utf8(path.into_encoded_bytes())
40 .or_raise(utf8_error)?
41 .into_bytes();
42 Ok(bytes.into())
43}
44
45pub fn try_os_str_into_bstr(path: Cow<'_, OsStr>) -> Result<Cow<'_, BStr>> {
47 match path {
48 Cow::Borrowed(path) => os_str_into_bstr(path).map(Cow::Borrowed),
49 Cow::Owned(path) => os_string_into_bstring(path).map(Cow::Owned),
50 }
51}
52
53pub fn into_bstr<'a>(path: impl Into<Cow<'a, Path>>) -> Result<Cow<'a, BStr>> {
58 match path.into() {
59 Cow::Owned(path) => os_string_into_bstring(path.into_os_string()).map(Cow::Owned),
60 Cow::Borrowed(path) => os_str_into_bstr(path.as_os_str()).map(Cow::Borrowed),
61 }
62}
63
64pub fn join_bstr_unix_pathsep<'a, 'b>(base: impl Into<Cow<'a, BStr>>, path: impl Into<&'b BStr>) -> Cow<'a, BStr> {
66 let mut base = base.into();
67 if !base.is_empty() && base.last() != Some(&b'/') {
68 base.to_mut().push(b'/');
69 }
70 base.to_mut().extend_from_slice(path.into());
71 base
72}
73
74pub fn from_byte_slice(input: &[u8]) -> Result<&Path> {
78 #[cfg(unix)]
79 let p = {
80 use std::os::unix::ffi::OsStrExt;
81 OsStr::from_bytes(input).as_ref()
82 };
83 #[cfg(not(unix))]
84 let p = Path::new(std::str::from_utf8(input).or_raise(utf8_error)?);
85 Ok(p)
86}
87
88pub fn from_bstr<'a>(input: impl Into<Cow<'a, BStr>>) -> Result<Cow<'a, Path>> {
90 let input = input.into();
91 match input {
92 Cow::Borrowed(input) => from_byte_slice(input).map(Cow::Borrowed),
93 Cow::Owned(input) => from_bstring(input).map(Cow::Owned),
94 }
95}
96
97pub fn from_bstring(input: impl Into<BString>) -> Result<PathBuf> {
99 let input = input.into();
100 #[cfg(unix)]
101 let p = {
102 use std::os::unix::ffi::OsStringExt;
103 std::ffi::OsString::from_vec(input.into()).into()
104 };
105 #[cfg(not(unix))]
106 let p = PathBuf::from(String::from_utf8(input.into()).or_raise(utf8_error)?);
107 Ok(p)
108}
109
110fn replace<'a>(path: impl Into<Cow<'a, BStr>>, find: u8, replace: u8) -> Cow<'a, BStr> {
111 let path = path.into();
112 match path {
113 Cow::Owned(mut path) => {
114 for b in path.iter_mut().filter(|b| **b == find) {
115 *b = replace;
116 }
117 path.into()
118 }
119 Cow::Borrowed(path) => {
120 if !path.contains(&find) {
121 return path.into();
122 }
123 let mut path = path.to_owned();
124 for b in path.iter_mut().filter(|b| **b == find) {
125 *b = replace;
126 }
127 path.into()
128 }
129 }
130}
131
132pub fn to_native_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
134 #[cfg(not(windows))]
135 let p = to_unix_separators(path);
136 #[cfg(windows)]
137 let p = to_windows_separators(path);
138 p
139}
140
141pub fn to_native_path_on_windows<'a>(path: impl Into<Cow<'a, BStr>>) -> Result<Cow<'a, std::path::Path>> {
144 #[cfg(not(windows))]
145 {
146 crate::from_bstr(path)
147 }
148 #[cfg(windows)]
149 {
150 crate::from_bstr(to_windows_separators(path))
151 }
152}
153
154pub fn to_unix_separators_on_windows<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
156 #[cfg(windows)]
157 {
158 to_unix_separators(path)
159 }
160 #[cfg(not(windows))]
161 {
162 path.into()
163 }
164}
165
166pub fn to_unix_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
170 replace(path, b'\\', b'/')
171}
172
173pub fn to_windows_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
177 replace(path, b'/', b'\\')
178}
179
180pub fn normalize<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Option<Cow<'a, Path>> {
217 normalize_inner(path, current_dir, false)
218}
219
220pub fn normalize_saturating<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Result<Cow<'a, Path>> {
223 normalize_inner(path, current_dir, true)
224 .ok_or_raise(|| gix_error::validation("Cannot normalize a path after exhausting the current directory"))
225}
226
227fn normalize_inner<'a>(path: Cow<'a, Path>, current_dir: &Path, saturate_at_root: bool) -> Option<Cow<'a, Path>> {
228 use std::path::Component::ParentDir;
229
230 if !path.components().any(|c| matches!(c, ParentDir)) {
231 return Some(path);
232 }
233 let mut current_dir_opt = Some(current_dir);
234 let was_relative = path.is_relative();
235 let components = path.components();
236 let mut path = PathBuf::new();
237 for component in components {
238 if let ParentDir = component {
239 while matches!(path.components().next_back(), Some(Component::CurDir)) {
240 path.pop();
241 }
242 if path.as_os_str().is_empty() {
243 path.push(current_dir_opt.take()?);
244 }
245 if !path.pop() && !saturate_at_root {
246 return None;
247 }
248 } else {
249 path.push(component);
250 }
251 }
252
253 if (path.as_os_str().is_empty() || path == current_dir) && was_relative {
254 Cow::Borrowed(Path::new("."))
255 } else {
256 path.into()
257 }
258 .into()
259}
260
261pub fn normalize_and_clean<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Option<Cow<'a, Path>> {
265 fn needs_cleaning(path: &Path) -> bool {
266 use std::path::Component::CurDir;
267
268 if path.as_os_str().is_empty() || path.components().any(|component| matches!(component, CurDir)) {
269 return true;
270 }
271
272 let mut components = path
273 .as_os_str()
274 .as_encoded_bytes()
275 .split(|byte| std::path::is_separator(*byte as char));
276 let Some(first) = components.next() else { return true };
277 first == b"." || components.any(|component| component.is_empty() || component == b".")
278 }
279
280 let path = normalize(path, current_dir)?;
281 if !needs_cleaning(path.as_ref()) {
282 return Some(path);
283 }
284
285 let mut cleaned: PathBuf = path
286 .components()
287 .filter(|component| !matches!(component, Component::CurDir))
288 .collect();
289 if cleaned.as_os_str().is_empty() {
290 cleaned.push(current_dir);
291 }
292 if cleaned.as_os_str() == path.as_os_str() {
293 Some(path)
294 } else {
295 Some(Cow::Owned(cleaned))
296 }
297}
298
299pub fn relativize_with_prefix<'a>(relative_path: &'a Path, prefix: &Path) -> Cow<'a, Path> {
310 if prefix.as_os_str().is_empty() {
311 return Cow::Borrowed(relative_path);
312 }
313 debug_assert!(
314 relative_path.components().all(|c| matches!(c, Component::Normal(_))),
315 "BUG: all input is expected to be normalized, but relative_path was not"
316 );
317 debug_assert!(
318 prefix.components().all(|c| matches!(c, Component::Normal(_))),
319 "BUG: all input is expected to be normalized, but prefix was not"
320 );
321
322 let mut buf = PathBuf::new();
323 let mut rpc = relative_path.components().peekable();
324 let mut equal_thus_far = true;
325 for pcomp in prefix.components() {
326 if equal_thus_far && let (Component::Normal(pname), Some(Component::Normal(rpname))) = (pcomp, rpc.peek()) {
327 if &pname == rpname {
328 rpc.next();
329 continue;
330 } else {
331 equal_thus_far = false;
332 }
333 }
334 buf.push(Component::ParentDir);
335 }
336 buf.extend(rpc);
337 if buf.as_os_str().is_empty() {
338 Cow::Borrowed(Path::new("."))
339 } else {
340 Cow::Owned(buf)
341 }
342}