gix_discover/
parse.rs

1use std::path::PathBuf;
2
3use bstr::ByteSlice;
4
5///
6pub mod gitdir {
7    use bstr::BString;
8
9    /// The error returned by [`parse::gitdir()`][super::gitdir()].
10    #[derive(Debug, thiserror::Error)]
11    #[allow(missing_docs)]
12    pub enum Error {
13        #[error("Format should be 'gitdir: <path>', but got: {:?}", .input)]
14        InvalidFormat { input: BString },
15        #[error("Couldn't decode {:?} as UTF8", .input)]
16        IllformedUtf8 { input: BString },
17    }
18}
19
20/// Parse typical `gitdir` files as seen in worktrees and submodules.
21pub fn gitdir(input: &[u8]) -> Result<PathBuf, gitdir::Error> {
22    let path = input
23        .strip_prefix(b"gitdir: ")
24        .ok_or_else(|| gitdir::Error::InvalidFormat { input: input.into() })?
25        .as_bstr();
26    let path = path.trim_end().as_bstr();
27    if path.is_empty() {
28        return Err(gitdir::Error::InvalidFormat { input: input.into() });
29    }
30    Ok(gix_path::try_from_bstr(path)
31        .map_err(|_| gitdir::Error::IllformedUtf8 { input: input.into() })?
32        .into_owned())
33}