//! Parsers for git's machine-readable output: `git status --porcelain=v2 //! -z --branch`, `git --version` and `git for-each-ref` with NUL-separated //! fields. Every input is untrusted: malformed records are skipped or //! reported as [`VcsError::BadOutput`], never a panic (property-tested). use crate::VcsError; /// The state of a file on one side (index or work tree). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum FileState { /// No change. Unmodified, /// Content or type changed. Modified, /// New in the index. Added, /// Deleted. Deleted, /// Renamed (index side only in porcelain v2). Renamed, /// Copied. Copied, /// Not tracked. Untracked, /// Ignored (only when ignored files are asked for). Ignored, /// Unmerged: a conflict waits for resolution. Conflicted, } impl FileState { /// The contract's name: `unmodified`, `modified`, `added`, `deleted`, /// `renamed`, `copied`, `untracked`, `ignored` or `conflicted`. pub fn as_str(self) -> &'static str { match self { Self::Unmodified => "unmodified", Self::Modified => "modified", Self::Added => "added", Self::Deleted => "deleted", Self::Renamed => "renamed", Self::Copied => "copied", Self::Untracked => "untracked", Self::Ignored => "ignored", Self::Conflicted => "conflicted", } } /// The state of one letter of porcelain v2's `XY` field. fn from_code(code: u8) -> Self { match code { b'M' | b'T' => Self::Modified, b'A' => Self::Added, b'D' => Self::Deleted, b'R' => Self::Renamed, b'C' => Self::Copied, b'U' => Self::Conflicted, b'?' => Self::Untracked, b'!' => Self::Ignored, _ => Self::Unmodified, } } } /// One changed, untracked or conflicted file. #[derive(Debug, Clone, PartialEq, Eq)] pub struct FileStatus { /// Path with `/` separators (relative to the repository root as git /// prints it; [`crate::Repo::status`] makes it project-relative). pub path: String, /// The path before a rename or copy. pub orig_path: Option, /// State in the index (staged). pub index: FileState, /// State in the work tree (not staged). pub worktree: FileState, } /// Where HEAD points. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Head { /// The current branch; `None` when detached. pub branch: Option, /// HEAD is detached. pub detached: bool, /// The commit of HEAD; `None` before the first commit. pub head: Option, /// The upstream branch, e.g. `origin/main`. pub upstream: Option, /// Commits ahead of the upstream. pub ahead: Option, /// Commits behind the upstream. pub behind: Option, } /// A parsed `git status`. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Status { /// Branch information. pub head: Head, /// Files with a change, in git's order. pub files: Vec, } /// Text of a path from git, which on Unix may hold bytes that are not /// UTF-8; those become U+FFFD. fn path_text(bytes: &[u8]) -> String { String::from_utf8_lossy(bytes).into_owned() } /// Splits `record` at the first `fields` spaces: the fields, then the /// rest (the path, which may contain spaces). fn split_fields(record: &[u8], fields: usize) -> Option<(Vec<&[u8]>, &[u8])> { let mut parts = record.splitn(fields + 1, |b| *b == b' '); let head: Vec<&[u8]> = parts.by_ref().take(fields).collect(); let rest = parts.next()?; (head.len() == fields).then_some((head, rest)) } /// The two states of an `XY` field. fn xy(field: &[u8]) -> Option<(FileState, FileState)> { match field { [x, y] => Some((FileState::from_code(*x), FileState::from_code(*y))), _ => None, } } /// Applies one `# branch.*` header to `head`. fn header(head: &mut Head, record: &[u8]) { let text = String::from_utf8_lossy(record); let Some(rest) = text.strip_prefix("# ") else { return; }; let (key, value) = rest.split_once(' ').unwrap_or((rest, "")); match key { "branch.oid" if value != "(initial)" && !value.is_empty() => { head.head = Some(value.to_string()); } "branch.head" => { if value == "(detached)" { head.detached = true; head.branch = None; } else if !value.is_empty() { head.branch = Some(value.to_string()); } } "branch.upstream" if !value.is_empty() => head.upstream = Some(value.to_string()), "branch.ab" => { let mut parts = value.split(' '); head.ahead = parts .next() .and_then(|a| a.strip_prefix('+')) .and_then(|a| a.parse().ok()); head.behind = parts .next() .and_then(|b| b.strip_prefix('-')) .and_then(|b| b.parse().ok()); } _ => {} } } /// Parses `git status --porcelain=v2 -z --branch` output. /// /// Records of unknown types are skipped (newer git versions may add some). /// /// # Errors /// [`VcsError::BadOutput`] for a changed-file record without its fields or /// a rename without its original path. pub fn parse_status(bytes: &[u8]) -> Result { let mut status = Status::default(); let mut records = bytes.split(|b| *b == 0).filter(|r| !r.is_empty()); let bad = |record: &[u8]| VcsError::BadOutput(format!("status record {:?}", path_text(record))); while let Some(record) = records.next() { match record.first() { Some(b'#') => header(&mut status.head, record), Some(b'1') => { let (fields, path) = split_fields(record, 8).ok_or_else(|| bad(record))?; let (index, worktree) = fields .get(1) .and_then(|f| xy(f)) .ok_or_else(|| bad(record))?; status.files.push(FileStatus { path: path_text(path), orig_path: None, index, worktree, }); } Some(b'2') => { let (fields, path) = split_fields(record, 9).ok_or_else(|| bad(record))?; let (index, worktree) = fields .get(1) .and_then(|f| xy(f)) .ok_or_else(|| bad(record))?; let orig = records.next().ok_or_else(|| bad(record))?; status.files.push(FileStatus { path: path_text(path), orig_path: Some(path_text(orig)), index, worktree, }); } Some(b'u') => { let (_, path) = split_fields(record, 10).ok_or_else(|| bad(record))?; status.files.push(FileStatus { path: path_text(path), orig_path: None, index: FileState::Conflicted, worktree: FileState::Conflicted, }); } Some(kind @ (b'?' | b'!')) => { let path = record.get(2..).ok_or_else(|| bad(record))?; let state = FileState::from_code(*kind); status.files.push(FileStatus { path: path_text(path), orig_path: None, index: state, worktree: state, }); } _ => {} } } Ok(status) } /// A git version as three numbers. pub type Version = (u32, u32, u32); /// Parses `git --version` output such as `git version 2.47.1.windows.1` /// or `git version 2.39.5 (Apple Git-154)`. /// /// # Returns /// The version, or `None` if the text has none. A missing patch number /// counts as 0. pub fn parse_version(text: &str) -> Option { let rest = text.trim().strip_prefix("git version ")?; let number = rest.split_whitespace().next()?; let mut parts = number.split('.').map(|p| { let digits: String = p.chars().take_while(char::is_ascii_digit).collect(); digits.parse::().ok() }); let major = parts.next().flatten()?; let minor = parts.next().flatten()?; let patch = parts.next().flatten().unwrap_or(0); Some((major, minor, patch)) } /// A branch from `git for-each-ref`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RefEntry { /// The full ref name, e.g. `refs/heads/main`. pub refname: String, /// The commit it points to. pub head: String, /// Its upstream, short form (`origin/main`), if any. pub upstream: Option, /// It is the checked-out branch. pub current: bool, /// It is a symbolic ref (such as `refs/remotes/origin/HEAD`). pub symbolic: bool, } /// The `--format` that [`parse_refs`] reads. pub const REF_FORMAT: &str = "%(refname)%00%(objectname)%00%(upstream:short)%00%(HEAD)%00%(symref)"; /// Parses `git for-each-ref --format=REF_FORMAT` output: one ref per line, /// fields separated by NUL. Ref names cannot hold line breaks or NUL /// (`git check-ref-format`), so the split is safe. Lines with too few /// fields are skipped. pub fn parse_refs(bytes: &[u8]) -> Vec { bytes .split(|b| *b == b'\n') .filter_map(|line| { let mut fields = line.split(|b| *b == 0).map(path_text); let refname = fields.next().filter(|r| !r.is_empty())?; let head = fields.next()?; let upstream = fields.next().filter(|u| !u.is_empty()); let current = fields.next()? == "*"; let symbolic = fields.next().is_some_and(|s| !s.trim().is_empty()); Some(RefEntry { refname, head, upstream, current, symbolic, }) }) .collect() } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::indexing_slicing)] use proptest::prelude::*; use super::*; #[test] fn parses_headers_and_every_record_type() { let out = b"# branch.oid 1234abcd\0# branch.head main\0# branch.upstream origin/main\0# branch.ab +2 -3\0\ 1 .M N... 100644 100644 100644 aaa bbb src/a file.php\0\ 2 R. N... 100644 100644 100644 aaa bbb R100 new name.php\0old name.php\0\ u UU N... 100644 100644 100644 100644 a b c conflict.php\0\ ? new dir/x.php\0! vendor/y.php\0"; let status = parse_status(out).unwrap(); assert_eq!( status.head, Head { branch: Some("main".into()), detached: false, head: Some("1234abcd".into()), upstream: Some("origin/main".into()), ahead: Some(2), behind: Some(3), } ); let files: Vec<_> = status .files .iter() .map(|f| { ( f.path.as_str(), f.orig_path.as_deref(), f.index.as_str(), f.worktree.as_str(), ) }) .collect(); assert_eq!( files, vec![ ("src/a file.php", None, "unmodified", "modified"), ( "new name.php", Some("old name.php"), "renamed", "unmodified" ), ("conflict.php", None, "conflicted", "conflicted"), ("new dir/x.php", None, "untracked", "untracked"), ("vendor/y.php", None, "ignored", "ignored"), ] ); } #[test] fn initial_and_detached_heads() { let initial = parse_status(b"# branch.oid (initial)\0# branch.head main\0").unwrap(); assert_eq!(initial.head.head, None); assert_eq!(initial.head.branch.as_deref(), Some("main")); let detached = parse_status(b"# branch.oid abc\0# branch.head (detached)\0").unwrap(); assert!(detached.head.detached); assert_eq!(detached.head.branch, None); } #[test] fn invalid_utf8_paths_become_replacement_characters() { let status = parse_status(b"? caf\xe9.php\0").unwrap(); assert_eq!(status.files[0].path, "caf\u{fffd}.php"); } #[test] fn malformed_records_are_errors_not_panics() { assert!(parse_status(b"1 .M\0").is_err()); assert!(parse_status(b"2 R. N... 1 1 1 a b R100 new").is_err()); assert!(parse_status(b"z unknown\0").unwrap().files.is_empty()); } #[test] fn versions() { assert_eq!( parse_version("git version 2.47.1.windows.1\n"), Some((2, 47, 1)) ); assert_eq!( parse_version("git version 2.39.5 (Apple Git-154)"), Some((2, 39, 5)) ); assert_eq!(parse_version("git version 2.30"), Some((2, 30, 0))); assert_eq!(parse_version("hello"), None); } #[test] fn refs() { let refs = parse_refs( b"refs/heads/main\0abc\0origin/main\0*\0\nrefs/remotes/origin/HEAD\0abc\0\0 \0refs/remotes/origin/main\nbroken\n", ); assert_eq!(refs.len(), 2); assert!(refs[0].current); assert_eq!(refs[0].upstream.as_deref(), Some("origin/main")); assert!(refs[1].symbolic); } proptest! { #[test] fn status_parser_never_panics(bytes in proptest::collection::vec(any::(), 0..512)) { let _ = parse_status(&bytes); } #[test] fn status_parser_survives_record_shaped_noise( parts in proptest::collection::vec( prop_oneof![ Just(b"1 ".to_vec()), Just(b"2 ".to_vec()), Just(b"u ".to_vec()), Just(b"? ".to_vec()), Just(b"# branch.ab ".to_vec()), Just(b"# branch.head ".to_vec()), Just(vec![0u8]), Just(b" ".to_vec()), proptest::collection::vec(any::(), 0..8), ], 0..48, ) ) { let bytes: Vec = parts.concat(); let _ = parse_status(&bytes); } #[test] fn version_and_ref_parsers_never_panic(bytes in proptest::collection::vec(any::(), 0..256)) { let _ = parse_version(&String::from_utf8_lossy(&bytes)); let _ = parse_refs(&bytes); } } }