1use std::fmt;
4use std::str::FromStr;
5
6use crate::{Oid, OidError};
7
8#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct Commit {
11 pub hash: Oid,
13 pub decoration: Option<String>,
15 pub headers: Vec<Header>,
17 pub message: String,
19}
20
21#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct Header {
24 pub key: String,
26 pub value: String,
28}
29
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub struct ParseCommitError;
33
34impl fmt::Display for ParseCommitError {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.write_str("missing `commit <hash>` line")
37 }
38}
39
40impl std::error::Error for ParseCommitError {}
41
42impl From<OidError> for ParseCommitError {
43 fn from(_: OidError) -> Self {
44 Self
45 }
46}
47
48impl Commit {
49 pub fn header(&self, name: &str) -> Option<&str> {
51 self.headers
52 .iter()
53 .find(|header| header.key.eq_ignore_ascii_case(name))
54 .map(|header| header.value.as_str())
55 }
56}
57
58impl FromStr for Commit {
59 type Err = ParseCommitError;
60
61 fn from_str(input: &str) -> Result<Self, Self::Err> {
62 let mut hash = None;
63 let mut decoration = None;
64 let mut headers = Vec::new();
65 let mut lines = input.split('\n').peekable();
66
67 while let Some(&line) = lines.peek() {
68 if line.is_empty() {
69 lines.next();
70 break;
71 }
72 if let Some(value) = line.strip_prefix("commit ") {
73 let (oid, rest) = match value.trim().split_once(char::is_whitespace) {
74 Some((oid, rest)) => (oid, Some(rest.trim().to_owned())),
75 None => (value.trim(), None),
76 };
77 hash = Some(oid.parse()?);
78 decoration = rest;
79 lines.next();
80 continue;
81 }
82 if let Some(header) = Header::parse(line) {
83 headers.push(header);
84 lines.next();
85 continue;
86 }
87 break;
88 }
89
90 Ok(Self {
91 hash: hash.ok_or(ParseCommitError)?,
92 decoration,
93 headers,
94 message: lines.collect::<Vec<_>>().join("\n"),
95 })
96 }
97}
98
99impl fmt::Display for Commit {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 write!(f, "commit {}", self.hash)?;
102 if let Some(decoration) = &self.decoration {
103 write!(f, " {decoration}")?;
104 }
105 writeln!(f)?;
106 for header in &self.headers {
107 writeln!(f, "{}: {}", header.key, header.value)?;
108 }
109 if !self.message.is_empty() {
110 writeln!(f)?;
111 f.write_str(&self.message)?;
112 if !self.message.ends_with('\n') {
113 writeln!(f)?;
114 }
115 }
116 writeln!(f)
117 }
118}
119
120impl Header {
121 fn parse(line: &str) -> Option<Self> {
123 let (key, value) = line.split_once(':')?;
124 let key = key.trim();
125 if key.is_empty() || key.chars().any(char::is_whitespace) {
126 return None;
127 }
128 Some(Self {
129 key: key.to_owned(),
130 value: value.trim_start().to_owned(),
131 })
132 }
133}
134
135#[cfg(test)]
136#[allow(clippy::unwrap_used)]
137mod tests {
138 use super::*;
139
140 #[test]
141 fn parses_headers_only() {
142 let commit = Commit::from_str("commit abc\nAuthor: A\n\n").unwrap();
143
144 assert_eq!(commit.hash.as_str(), "abc");
145 assert_eq!(commit.decoration, None);
146 assert_eq!(commit.header("author"), Some("A"));
147 assert!(commit.message.is_empty());
148 }
149
150 #[test]
151 fn parses_sha256_hash() {
152 let oid = "0".repeat(64);
153 let input = format!("commit {oid}\n\n");
154 let commit = Commit::from_str(&input).unwrap();
155
156 assert_eq!(commit.hash.as_str(), oid);
157 }
158
159 #[test]
160 fn parses_decoration_after_hash() {
161 let commit = Commit::from_str("commit abc (HEAD -> main)\n\n").unwrap();
162
163 assert_eq!(commit.hash.as_str(), "abc");
164 assert_eq!(commit.decoration.as_deref(), Some("(HEAD -> main)"));
165 }
166
167 #[test]
168 fn parses_message_with_indent_preserved() {
169 let input = "commit abc\nAuthor: A\n\n Subject\n\n Body\n";
170 let commit = Commit::from_str(input).unwrap();
171
172 assert_eq!(commit.message, " Subject\n\n Body\n");
173 }
174
175 #[test]
176 fn rejects_input_without_commit_line() {
177 assert_eq!(
178 Commit::from_str("Author: A\nDate: B\n"),
179 Err(ParseCommitError),
180 );
181 assert_eq!(Commit::from_str(""), Err(ParseCommitError));
182 }
183
184 #[test]
185 fn rejects_non_hex_hash() {
186 assert_eq!(
187 Commit::from_str("commit not-hex\n\n"),
188 Err(ParseCommitError),
189 );
190 }
191
192 #[test]
193 fn display_matches_decoder_line_encoding() {
194 let lines = [
195 "commit abc",
196 "Author: A",
197 "",
198 " Subject",
199 "",
200 " Body",
201 "",
202 ];
203 let commit: Commit = lines.join("\n").parse().unwrap();
204 let expected: String = lines.iter().map(|line| format!("{line}\n")).collect();
205
206 assert_eq!(commit.to_string(), expected);
207 }
208}