Skip to main content

gix_path/
convert.rs

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
18/// Like [`into_bstr()`], but takes `OsStr` as input for a lossless, but fallible, conversion.
19pub 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
27/// Like [`into_bstr()`], but takes `OsString` as input for a lossless, but fallible, conversion.
28pub 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
36/// Like [`into_bstr()`], but takes `Cow<OsStr>` as input for a lossless, but fallible, conversion.
37pub 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
44/// Convert the given path either into its raw bytes on Unix or its UTF-8 encoded counterpart on non-Unix platforms.
45///
46/// On non-Unix platforms, if the source `Path` contains ill-formed, lone surrogates, the UTF-8 conversion will fail
47/// causing an [`Exn<Message>`](gix_error::Exn) with the encoding failure as its source to be returned.
48pub 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
80/// Similar to [`try_into_bstr()`] but **panics** if malformed surrogates are encountered on Windows.
81pub 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
85/// Join `path` to `base` such that they are separated with a `/`, i.e. `base/path`.
86pub 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
95/// Given `input` bytes, produce a `Path` from them ignoring encoding entirely if on Unix.
96///
97/// On non-Unix platforms, the input is required to be valid UTF-8, which is guaranteed if we wrote it before.
98/// There are some potential Git versions and Windows installations which produce malformed UTF-16
99/// if certain emojis are in the path. It's as rare as it sounds, but possible.
100pub 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
111/// Similar to [`from_byte_slice()`], but takes either borrowed or owned `input`.
112pub 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
120/// Similar to [`try_from_bstr()`], but **panics** if malformed surrogates are encountered on Windows.
121pub 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
125/// Similar to [`try_from_bstr()`], but takes and produces owned data.
126pub 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
138/// Similar to [`try_from_bstring()`], but will **panic** if there is ill-formed UTF-8 in the `input`.
139pub fn from_bstring(input: impl Into<BString>) -> PathBuf {
140    try_from_bstring(input).expect("well-formed UTF-8 on windows")
141}
142
143/// Similar to [`try_from_byte_slice()`], but will **panic** if there is ill-formed UTF-8 in the `input`.
144pub 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
170/// Assures the given bytes use the native path separator.
171pub 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
179/// Convert paths with slashes to backslashes on Windows and do nothing on Unix,
180/// but **panic** if unpaired surrogates are encountered on Windows.
181pub 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
192/// Replace Windows path separators with slashes, but only do so on Windows.
193pub 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
204/// Replace Windows path separators with slashes, which typically resembles a Unix path, unconditionally.
205///
206/// **Note** Do not use these and prefer the conditional versions of this method.
207pub fn to_unix_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
208    replace(path, b'\\', b'/')
209}
210
211/// Find slashes and replace them with backslashes, unconditionally.
212///
213/// **Note** Do not use these and prefer the conditional versions of this method.
214pub fn to_windows_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
215    replace(path, b'/', b'\\')
216}
217
218/// Resolve relative components virtually, eliminating intermediate `..` without accessing the filesystem.
219///
220/// For example, this turns `a/./b/c/.././..` into `a`, and turns `/a/../b/..` into `/`.
221///
222/// ```
223/// # fn main() {
224/// # use std::path::Path;
225/// # use gix_path::normalize;
226/// for (input, expected) in [
227///     ("a/./b/c/.././..", "a"),
228///     ("/a/../b/..", "/"),
229///     ("/base/a/..", "/base"),
230///     ("./a/..", "."),
231///     ("./a/../..", "/"),
232///     (".///", ".///"),
233///     ("a//b", "a//b"),
234///     ("/base/../base", "/base"),
235/// ] {
236///     let input = Path::new(input);
237///     let expected = Path::new(expected);
238///     assert_eq!(normalize(input.into(), Path::new("/cwd")), Some(expected.into()));
239/// }
240/// # }
241/// ```
242///
243/// Leading `.` components as well as duplicate separators are left untouched.
244///
245/// This is particularly useful when manipulating paths that are based on user input, and not
246/// resolving intermediate symlinks keeps the path similar to what the user provided. If that's not
247/// desirable, use [`realpath()`](crate::realpath()) instead.
248///
249/// Note that we will use the `current_dir` if we run out of path components to pop off, which
250/// is expected to be absolute as typical return value of `std::env::current_dir()` or
251/// `gix_fs::current_dir(…)` when `core.precomposeUnicode` is known. As a `current_dir` like `/c`
252/// can be exhausted by paths like `../../r`, `None` will be returned to indicate the inability to
253/// produce a logically consistent path.
254pub fn normalize<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Option<Cow<'a, Path>> {
255    normalize_inner(path, current_dir, false)
256}
257
258/// Like [`normalize()`], but treats `..` components beyond the filesystem root as no-ops.
259pub 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
297/// Like [`normalize()`], but also removes `.` components and duplicate or trailing separators.
298///
299/// If cleaning leaves no components, `current_dir` is returned. Already-clean borrowed paths remain borrowed.
300pub 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
335/// Rebuild the worktree-relative `relative_path` to be relative to `prefix`, which is the
336/// worktree-relative path equivalent to the position of the user, or current working directory.
337///
338/// This is a no-op if `prefix` is empty.
339///
340/// Note that both `relative_path` and `prefix` are assumed to be [normalized](normalize()), and
341/// failure to do so will lead to incorrect results.
342///
343/// Note that both input paths are expected to be equal in terms of case too, as comparisons will
344/// be case-sensitive.
345pub 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}