Skip to main content

gix_path/
convert.rs

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
17/// Like [`into_bstr()`], but takes `OsStr` as input for a lossless, but fallible, conversion.
18pub 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
31/// Like [`into_bstr()`], but takes `OsString` as input for a lossless, but fallible, conversion.
32pub 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
45/// Like [`into_bstr()`], but takes `Cow<OsStr>` as input for a lossless, but fallible, conversion.
46pub 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
53/// Convert the given path either into its raw bytes on Unix or its UTF-8 encoded counterpart on non-Unix platforms.
54///
55/// On non-Unix platforms, if the source `Path` contains ill-formed, lone surrogates, the UTF-8 conversion will fail
56/// causing a [`gix_error::Error`] with the encoding failure as its source to be returned.
57pub 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
64/// Join `path` to `base` such that they are separated with a `/`, i.e. `base/path`.
65pub 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
74/// Given `input` bytes, produce a `Path` from them ignoring encoding entirely if on Unix.
75///
76/// On non-Unix platforms, invalid UTF-8 returns an error with the encoding failure as its source.
77pub 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
88/// Similar to [`from_byte_slice()`], but takes either borrowed or owned `input`.
89pub 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
97/// Similar to [`from_bstr()`], but takes and produces owned data.
98pub 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
132/// Assures the given bytes use the native path separator.
133pub 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
141/// Convert paths with slashes to backslashes on Windows and do nothing on Unix,
142/// returning an error for invalid UTF-8 on non-Unix platforms.
143pub 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
154/// Replace Windows path separators with slashes, but only do so on Windows.
155pub 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
166/// Replace Windows path separators with slashes, which typically resembles a Unix path, unconditionally.
167///
168/// **Note** Do not use these and prefer the conditional versions of this method.
169pub fn to_unix_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
170    replace(path, b'\\', b'/')
171}
172
173/// Find slashes and replace them with backslashes, unconditionally.
174///
175/// **Note** Do not use these and prefer the conditional versions of this method.
176pub fn to_windows_separators<'a>(path: impl Into<Cow<'a, BStr>>) -> Cow<'a, BStr> {
177    replace(path, b'/', b'\\')
178}
179
180/// Resolve relative components virtually, eliminating intermediate `..` without accessing the filesystem.
181///
182/// For example, this turns `a/./b/c/.././..` into `a`, and turns `/a/../b/..` into `/`.
183///
184/// ```
185/// # fn main() {
186/// # use std::path::Path;
187/// # use gix_path::normalize;
188/// for (input, expected) in [
189///     ("a/./b/c/.././..", "a"),
190///     ("/a/../b/..", "/"),
191///     ("/base/a/..", "/base"),
192///     ("./a/..", "."),
193///     ("./a/../..", "/"),
194///     (".///", ".///"),
195///     ("a//b", "a//b"),
196///     ("/base/../base", "/base"),
197/// ] {
198///     let input = Path::new(input);
199///     let expected = Path::new(expected);
200///     assert_eq!(normalize(input.into(), Path::new("/cwd")), Some(expected.into()));
201/// }
202/// # }
203/// ```
204///
205/// Leading `.` components as well as duplicate separators are left untouched.
206///
207/// This is particularly useful when manipulating paths that are based on user input, and not
208/// resolving intermediate symlinks keeps the path similar to what the user provided. If that's not
209/// desirable, use [`realpath()`](crate::realpath()) instead.
210///
211/// Note that we will use the `current_dir` if we run out of path components to pop off, which
212/// is expected to be absolute as typical return value of `std::env::current_dir()` or
213/// `gix_fs::current_dir(…)` when `core.precomposeUnicode` is known. As a `current_dir` like `/c`
214/// can be exhausted by paths like `../../r`, `None` will be returned to indicate the inability to
215/// produce a logically consistent path.
216pub fn normalize<'a>(path: Cow<'a, Path>, current_dir: &Path) -> Option<Cow<'a, Path>> {
217    normalize_inner(path, current_dir, false)
218}
219
220/// Like [`normalize()`], but treats `..` components beyond the filesystem root as no-ops.
221/// Returns an error if normalization exhausts an empty or relative `current_dir`.
222pub 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
261/// Like [`normalize()`], but also removes `.` components and duplicate or trailing separators.
262///
263/// If cleaning leaves no components, `current_dir` is returned. Already-clean borrowed paths remain borrowed.
264pub 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
299/// Rebuild the worktree-relative `relative_path` to be relative to `prefix`, which is the
300/// worktree-relative path equivalent to the position of the user, or current working directory.
301///
302/// This is a no-op if `prefix` is empty.
303///
304/// Note that both `relative_path` and `prefix` are assumed to be [normalized](normalize()), and
305/// failure to do so will lead to incorrect results.
306///
307/// Note that both input paths are expected to be equal in terms of case too, as comparisons will
308/// be case-sensitive.
309pub 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}