1use std::{
2 borrow::Cow,
3 ffi::{OsStr, OsString},
4 path::{Component, Path, PathBuf},
5};
6
7use gix_error::ExnMessageResult;
8
9use bstr::{BStr, BString};
10#[cfg(not(unix))]
11use gix_error::ResultExt;
12
13#[cfg(not(unix))]
14fn utf8_error() -> gix_error::Message {
15 gix_error::validation("Could not convert to UTF8 or from UTF8 due to ill-formed input")
16}
17
18pub fn os_str_into_bstr(path: &OsStr) -> ExnMessageResult<&BStr> {
20 let path = try_into_bstr(Cow::Borrowed(path.as_ref()))?;
21 match path {
22 Cow::Borrowed(path) => Ok(path),
23 Cow::Owned(_) => unreachable!("borrowed cows stay borrowed"),
24 }
25}
26
27pub fn os_string_into_bstring(path: OsString) -> ExnMessageResult<BString> {
29 let path = try_into_bstr(Cow::Owned(path.into()))?;
30 match path {
31 Cow::Borrowed(_path) => unreachable!("borrowed cows stay borrowed"),
32 Cow::Owned(path) => Ok(path),
33 }
34}
35
36pub fn try_os_str_into_bstr(path: Cow<'_, OsStr>) -> ExnMessageResult<Cow<'_, BStr>> {
38 match path {
39 Cow::Borrowed(path) => os_str_into_bstr(path).map(Cow::Borrowed),
40 Cow::Owned(path) => os_string_into_bstring(path).map(Cow::Owned),
41 }
42}
43
44pub fn try_into_bstr<'a>(path: impl Into<Cow<'a, Path>>) -> ExnMessageResult<Cow<'a, BStr>> {
49 let path = path.into();
50 let path_str = match path {
51 Cow::Owned(path) => Cow::Owned({
52 #[cfg(unix)]
53 let p: BString = {
54 use std::os::unix::ffi::OsStringExt;
55 path.into_os_string().into_vec().into()
56 };
57 #[cfg(not(unix))]
58 let p: BString = String::from_utf8(path.into_os_string().into_encoded_bytes())
59 .or_raise(utf8_error)?
60 .into();
61 p
62 }),
63 Cow::Borrowed(path) => Cow::Borrowed({
64 #[cfg(unix)]
65 let p: &BStr = {
66 use std::os::unix::ffi::OsStrExt;
67 path.as_os_str().as_bytes().into()
68 };
69 #[cfg(not(unix))]
70 let p: &BStr = std::str::from_utf8(path.as_os_str().as_encoded_bytes())
71 .or_raise(utf8_error)?
72 .as_bytes()
73 .into();
74 p
75 }),
76 };
77 Ok(path_str)
78}
79
80pub fn into_bstr<'a>(path: impl Into<Cow<'a, Path>>) -> Cow<'a, BStr> {
82 try_into_bstr(path).expect("prefix path doesn't contain ill-formed UTF-8")
83}
84
85pub fn join_bstr_unix_pathsep<'a, 'b>(base: impl Into<Cow<'a, BStr>>, path: impl Into<&'b BStr>) -> Cow<'a, BStr> {
87 let mut base = base.into();
88 if !base.is_empty() && base.last() != Some(&b'/') {
89 base.to_mut().push(b'/');
90 }
91 base.to_mut().extend_from_slice(path.into());
92 base
93}
94
95pub fn try_from_byte_slice(input: &[u8]) -> ExnMessageResult<&Path> {
101 #[cfg(unix)]
102 let p = {
103 use std::os::unix::ffi::OsStrExt;
104 OsStr::from_bytes(input).as_ref()
105 };
106 #[cfg(not(unix))]
107 let p = Path::new(std::str::from_utf8(input).or_raise(utf8_error)?);
108 Ok(p)
109}
110
111pub fn try_from_bstr<'a>(input: impl Into<Cow<'a, BStr>>) -> ExnMessageResult<Cow<'a, Path>> {
113 let input = input.into();
114 match input {
115 Cow::Borrowed(input) => try_from_byte_slice(input).map(Cow::Borrowed),
116 Cow::Owned(input) => try_from_bstring(input).map(Cow::Owned),
117 }
118}
119
120pub fn from_bstr<'a>(input: impl Into<Cow<'a, BStr>>) -> Cow<'a, Path> {
122 try_from_bstr(input).expect("prefix path doesn't contain ill-formed UTF-8")
123}
124
125pub fn try_from_bstring(input: impl Into<BString>) -> ExnMessageResult<PathBuf> {
127 let input = input.into();
128 #[cfg(unix)]
129 let p = {
130 use std::os::unix::ffi::OsStringExt;
131 std::ffi::OsString::from_vec(input.into()).into()
132 };
133 #[cfg(not(unix))]
134 let p = PathBuf::from(String::from_utf8(input.into()).or_raise(utf8_error)?);
135 Ok(p)
136}
137
138pub fn from_bstring(input: impl Into<BString>) -> PathBuf {
140 try_from_bstring(input).expect("well-formed UTF-8 on windows")
141}
142
143pub fn from_byte_slice(input: &[u8]) -> &Path {
145 try_from_byte_slice(input).expect("well-formed UTF-8 on windows")
146}
147
148fn replace<'a>(path: impl Into<Cow<'a, BStr>>, find: u8, replace: u8) -> Cow<'a, BStr> {
149 let path = path.into();
150 match path {
151 Cow::Owned(mut path) => {
152 for b in path.iter_mut().filter(|b| **b == find) {
153 *b = replace;
154 }
155 path.into()
156 }
157 Cow::Borrowed(path) => {
158 if !path.contains(&find) {
159 return path.into();
160 }
161 let mut path = path.to_owned();
162 for b in path.iter_mut().filter(|b| **b == find) {
163 *b = replace;
164 }
165 path.into()
166 }
167 }
168}
169
170pub fn to_native_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
172 #[cfg(not(windows))]
173 let p = to_unix_separators(path);
174 #[cfg(windows)]
175 let p = to_windows_separators(path);
176 p
177}
178
179pub fn to_native_path_on_windows<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, std::path::Path> {
182 #[cfg(not(windows))]
183 {
184 crate::from_bstr(path)
185 }
186 #[cfg(windows)]
187 {
188 crate::from_bstr(to_windows_separators(path))
189 }
190}
191
192pub fn to_unix_separators_on_windows<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
194 #[cfg(windows)]
195 {
196 to_unix_separators(path)
197 }
198 #[cfg(not(windows))]
199 {
200 path.into()
201 }
202}
203
204pub fn to_unix_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
208 replace(path, b'\\', b'/')
209}
210
211pub fn to_windows_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
215 replace(path, b'/', b'\\')
216}
217
218pub fn normalize<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Option<Cow<'a, Path>> {
255 normalize_inner(path, current_dir, false)
256}
257
258pub fn normalize_saturating<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Cow<'a, Path> {
260 normalize_inner(path, current_dir, true).expect("saturating normalization always produces a path")
261}
262
263fn normalize_inner<'a>(path: Cow<'a, Path>, current_dir: &Path, saturate_at_root: bool) -> Option<Cow<'a, Path>> {
264 use std::path::Component::ParentDir;
265
266 if !path.components().any(|c| matches!(c, ParentDir)) {
267 return Some(path);
268 }
269 let mut current_dir_opt = Some(current_dir);
270 let was_relative = path.is_relative();
271 let components = path.components();
272 let mut path = PathBuf::new();
273 for component in components {
274 if let ParentDir = component {
275 while matches!(path.components().next_back(), Some(Component::CurDir)) {
276 path.pop();
277 }
278 if path.as_os_str().is_empty() {
279 path.push(current_dir_opt.take()?);
280 }
281 if !path.pop() && !saturate_at_root {
282 return None;
283 }
284 } else {
285 path.push(component);
286 }
287 }
288
289 if (path.as_os_str().is_empty() || path == current_dir) && was_relative {
290 Cow::Borrowed(Path::new("."))
291 } else {
292 path.into()
293 }
294 .into()
295}
296
297pub fn normalize_and_clean<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Option<Cow<'a, Path>> {
301 fn needs_cleaning(path: &Path) -> bool {
302 use std::path::Component::CurDir;
303
304 if path.as_os_str().is_empty() || path.components().any(|component| matches!(component, CurDir)) {
305 return true;
306 }
307
308 let mut components = path
309 .as_os_str()
310 .as_encoded_bytes()
311 .split(|byte| std::path::is_separator(*byte as char));
312 let Some(first) = components.next() else { return true };
313 first == b"." || components.any(|component| component.is_empty() || component == b".")
314 }
315
316 let path = normalize(path, current_dir)?;
317 if !needs_cleaning(path.as_ref()) {
318 return Some(path);
319 }
320
321 let mut cleaned: PathBuf = path
322 .components()
323 .filter(|component| !matches!(component, Component::CurDir))
324 .collect();
325 if cleaned.as_os_str().is_empty() {
326 cleaned.push(current_dir);
327 }
328 if cleaned.as_os_str() == path.as_os_str() {
329 Some(path)
330 } else {
331 Some(Cow::Owned(cleaned))
332 }
333}
334
335pub fn relativize_with_prefix<'a>(relative_path: &'a Path, prefix: &Path) -> Cow<'a, Path> {
346 if prefix.as_os_str().is_empty() {
347 return Cow::Borrowed(relative_path);
348 }
349 debug_assert!(
350 relative_path.components().all(|c| matches!(c, Component::Normal(_))),
351 "BUG: all input is expected to be normalized, but relative_path was not"
352 );
353 debug_assert!(
354 prefix.components().all(|c| matches!(c, Component::Normal(_))),
355 "BUG: all input is expected to be normalized, but prefix was not"
356 );
357
358 let mut buf = PathBuf::new();
359 let mut rpc = relative_path.components().peekable();
360 let mut equal_thus_far = true;
361 for pcomp in prefix.components() {
362 if equal_thus_far && let (Component::Normal(pname), Some(Component::Normal(rpname))) = (pcomp, rpc.peek()) {
363 if &pname == rpname {
364 rpc.next();
365 continue;
366 } else {
367 equal_thus_far = false;
368 }
369 }
370 buf.push(Component::ParentDir);
371 }
372 buf.extend(rpc);
373 if buf.as_os_str().is_empty() {
374 Cow::Borrowed(Path::new("."))
375 } else {
376 Cow::Owned(buf)
377 }
378}