//! Commit preamble parsed from `git log`-style diff input. use std::fmt; use std::str::FromStr; use crate::{Oid, OidError}; /// Parsed commit preamble. #[derive(Clone, Debug, Eq, PartialEq)] pub struct CommitHeader { /// Object identifier from the `commit ` line. pub hash: Oid, /// Ref decoration following the hash (e.g. `(HEAD -> main, origin/main)`). pub decoration: Option, /// Signature verification output between the commit hash and headers. pub signature: Vec, /// Headers in input order with original key casing (e.g. `Author`, `Date`). pub headers: Vec
, /// Commit message, verbatim and including any source indentation. pub message: String, } /// One `Key: value` header line. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Header { /// Header name (e.g. `Author`). pub key: String, /// Header value, with leading whitespace after the colon trimmed. pub value: String, } /// Error returned when no `commit ` line is found in the input. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ParseCommitError; impl fmt::Display for ParseCommitError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("missing `commit ` line") } } impl std::error::Error for ParseCommitError {} impl From for ParseCommitError { fn from(_: OidError) -> Self { Self } } impl CommitHeader { /// Returns the first header value matching `name` (case-insensitive). pub fn header(&self, name: &str) -> Option<&str> { self.headers .iter() .find(|header| header.key.eq_ignore_ascii_case(name)) .map(|header| header.value.as_str()) } } impl FromStr for CommitHeader { type Err = ParseCommitError; fn from_str(input: &str) -> Result { let mut hash = None; let mut decoration = None; let mut signature = Vec::new(); let mut headers = Vec::new(); let mut lines = input.split('\n').peekable(); while let Some(&line) = lines.peek() { if line.is_empty() { lines.next(); break; } if let Some(value) = line.strip_prefix("commit ") { let (oid, rest) = match value.trim().split_once(char::is_whitespace) { Some((oid, rest)) => (oid, Some(rest.trim().to_owned())), None => (value.trim(), None), }; hash = Some(oid.parse()?); decoration = rest; lines.next(); continue; } if let Some(header) = Header::parse(line) { headers.push(header); lines.next(); continue; } if hash.is_some() && headers.is_empty() { signature.push(line.to_owned()); lines.next(); continue; } break; } Ok(Self { hash: hash.ok_or(ParseCommitError)?, decoration, signature, headers, message: lines.collect::>().join("\n"), }) } } impl fmt::Display for CommitHeader { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "commit {}", self.hash)?; if let Some(decoration) = &self.decoration { write!(f, " {decoration}")?; } writeln!(f)?; for line in &self.signature { writeln!(f, "{line}")?; } for header in &self.headers { writeln!(f, "{}: {}", header.key, header.value)?; } if !self.message.is_empty() { writeln!(f)?; f.write_str(&self.message)?; if !self.message.ends_with('\n') { writeln!(f)?; } } writeln!(f) } } impl Header { /// Parses one `Key: value` line, returning `None` if the shape is invalid. fn parse(line: &str) -> Option { let (key, value) = line.split_once(':')?; let key = key.trim(); if key.is_empty() || key.chars().any(char::is_whitespace) { return None; } Some(Self { key: key.to_owned(), value: value.trim_start().to_owned(), }) } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; const SHA1: &str = "1234567890abcdef1234567890abcdef12345678"; #[test] fn parses_headers_only() { let input = format!("commit {SHA1}\nAuthor: A\n\n"); let commit = CommitHeader::from_str(&input).unwrap(); assert_eq!(commit.hash.to_string(), SHA1); assert_eq!(commit.decoration, None); assert_eq!(commit.header("author"), Some("A")); assert!(commit.message.is_empty()); } #[test] fn parses_sha256_hash() { let oid = "0".repeat(64); let input = format!("commit {oid}\n\n"); let commit = CommitHeader::from_str(&input).unwrap(); assert_eq!(commit.hash.to_string(), oid); } #[test] fn parses_decoration_after_hash() { let input = format!("commit {SHA1} (HEAD -> main)\n\n"); let commit = CommitHeader::from_str(&input).unwrap(); assert_eq!(commit.hash.to_string(), SHA1); assert_eq!(commit.decoration.as_deref(), Some("(HEAD -> main)")); } #[test] fn parses_signature_before_headers() { let input = format!("commit {SHA1}\nGood signature\nNo principal matched.\nAuthor: A\nDate: B\n\n"); let commit = CommitHeader::from_str(&input).unwrap(); assert_eq!( commit.signature, ["Good signature", "No principal matched."] ); assert_eq!(commit.header("author"), Some("A")); assert_eq!(commit.header("date"), Some("B")); assert!(commit.message.is_empty()); } #[test] fn parses_message_with_indent_preserved() { let input = format!("commit {SHA1}\nAuthor: A\n\n Subject\n\n Body\n"); let commit = CommitHeader::from_str(&input).unwrap(); assert_eq!(commit.message, " Subject\n\n Body\n"); } #[test] fn rejects_input_without_commit_line() { assert_eq!( CommitHeader::from_str("Author: A\nDate: B\n"), Err(ParseCommitError), ); assert_eq!(CommitHeader::from_str(""), Err(ParseCommitError)); } #[test] fn rejects_non_hex_hash() { assert_eq!( CommitHeader::from_str("commit not-hex\n\n"), Err(ParseCommitError), ); } #[test] fn display_matches_decoder_line_encoding() { let lines = [ "commit 1234567890abcdef1234567890abcdef12345678", "Good signature", "Author: A", "", " Subject", "", " Body", "", ]; let commit: CommitHeader = lines.join("\n").parse().unwrap(); let expected: String = lines.iter().map(|line| format!("{line}\n")).collect(); assert_eq!(commit.to_string(), expected); } }