use std::fmt;
use std::str::FromStr;
use crate::{Oid, OidError};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Commit {
pub hash: Oid,
pub decoration: Option<String>,
pub headers: Vec<Header>,
pub message: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Header {
pub key: String,
pub value: String,
}
#[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 <hash>` line")
}
}
impl std::error::Error for ParseCommitError {}
impl From<OidError> for ParseCommitError {
fn from(_: OidError) -> Self {
Self
}
}
impl Commit {
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 Commit {
type Err = ParseCommitError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let mut hash = None;
let mut decoration = None;
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;
}
break;
}
Ok(Self {
hash: hash.ok_or(ParseCommitError)?,
decoration,
headers,
message: lines.collect::<Vec<_>>().join("\n"),
})
}
}
impl fmt::Display for Commit {
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 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 {
fn parse(line: &str) -> Option<Self> {
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::*;
#[test]
fn parses_headers_only() {
let commit = Commit::from_str("commit abc\nAuthor: A\n\n").unwrap();
assert_eq!(commit.hash.as_str(), "abc");
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 = Commit::from_str(&input).unwrap();
assert_eq!(commit.hash.as_str(), oid);
}
#[test]
fn parses_decoration_after_hash() {
let commit = Commit::from_str("commit abc (HEAD -> main)\n\n").unwrap();
assert_eq!(commit.hash.as_str(), "abc");
assert_eq!(commit.decoration.as_deref(), Some("(HEAD -> main)"));
}
#[test]
fn parses_message_with_indent_preserved() {
let input = "commit abc\nAuthor: A\n\n Subject\n\n Body\n";
let commit = Commit::from_str(input).unwrap();
assert_eq!(commit.message, " Subject\n\n Body\n");
}
#[test]
fn rejects_input_without_commit_line() {
assert_eq!(
Commit::from_str("Author: A\nDate: B\n"),
Err(ParseCommitError),
);
assert_eq!(Commit::from_str(""), Err(ParseCommitError));
}
#[test]
fn rejects_non_hex_hash() {
assert_eq!(
Commit::from_str("commit not-hex\n\n"),
Err(ParseCommitError),
);
}
#[test]
fn display_matches_decoder_line_encoding() {
let lines = [
"commit abc",
"Author: A",
"",
" Subject",
"",
" Body",
"",
];
let commit: Commit = lines.join("\n").parse().unwrap();
let expected: String = lines.iter().map(|line| format!("{line}\n")).collect();
assert_eq!(commit.to_string(), expected);
}
}