Skip to main content

rustik_diff/
commit.rs

1//! Commit preamble parsed from `git log`-style diff input.
2
3use std::fmt;
4use std::str::FromStr;
5
6use crate::{Oid, OidError};
7
8/// Parsed commit preamble.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct CommitHeader {
11    /// Object identifier from the `commit <oid>` line.
12    pub hash: Oid,
13    /// Ref decoration following the hash (e.g. `(HEAD -> main, origin/main)`).
14    pub decoration: Option<String>,
15    /// Signature verification output between the commit hash and headers.
16    pub signature: Vec<String>,
17    /// Headers in input order with original key casing (e.g. `Author`, `Date`).
18    pub headers: Vec<Header>,
19    /// Commit message, verbatim and including any source indentation.
20    pub message: String,
21}
22
23/// One `Key: value` header line.
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct Header {
26    /// Header name (e.g. `Author`).
27    pub key: String,
28    /// Header value, with leading whitespace after the colon trimmed.
29    pub value: String,
30}
31
32/// Error returned when no `commit <hash>` line is found in the input.
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub struct ParseCommitError;
35
36impl fmt::Display for ParseCommitError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.write_str("missing `commit <hash>` line")
39    }
40}
41
42impl std::error::Error for ParseCommitError {}
43
44impl From<OidError> for ParseCommitError {
45    fn from(_: OidError) -> Self {
46        Self
47    }
48}
49
50impl CommitHeader {
51    /// Returns the first header value matching `name` (case-insensitive).
52    pub fn header(&self, name: &str) -> Option<&str> {
53        self.headers
54            .iter()
55            .find(|header| header.key.eq_ignore_ascii_case(name))
56            .map(|header| header.value.as_str())
57    }
58}
59
60impl FromStr for CommitHeader {
61    type Err = ParseCommitError;
62
63    fn from_str(input: &str) -> Result<Self, Self::Err> {
64        let mut hash = None;
65        let mut decoration = None;
66        let mut signature = Vec::new();
67        let mut headers = Vec::new();
68        let mut lines = input.split('\n').peekable();
69
70        while let Some(&line) = lines.peek() {
71            if line.is_empty() {
72                lines.next();
73                break;
74            }
75            if let Some(value) = line.strip_prefix("commit ") {
76                let (oid, rest) = match value.trim().split_once(char::is_whitespace) {
77                    Some((oid, rest)) => (oid, Some(rest.trim().to_owned())),
78                    None => (value.trim(), None),
79                };
80                hash = Some(oid.parse()?);
81                decoration = rest;
82                lines.next();
83                continue;
84            }
85            if let Some(header) = Header::parse(line) {
86                headers.push(header);
87                lines.next();
88                continue;
89            }
90            if hash.is_some() && headers.is_empty() {
91                signature.push(line.to_owned());
92                lines.next();
93                continue;
94            }
95            break;
96        }
97
98        Ok(Self {
99            hash: hash.ok_or(ParseCommitError)?,
100            decoration,
101            signature,
102            headers,
103            message: lines.collect::<Vec<_>>().join("\n"),
104        })
105    }
106}
107
108impl fmt::Display for CommitHeader {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(f, "commit {}", self.hash)?;
111        if let Some(decoration) = &self.decoration {
112            write!(f, " {decoration}")?;
113        }
114        writeln!(f)?;
115        for line in &self.signature {
116            writeln!(f, "{line}")?;
117        }
118        for header in &self.headers {
119            writeln!(f, "{}: {}", header.key, header.value)?;
120        }
121        if !self.message.is_empty() {
122            writeln!(f)?;
123            f.write_str(&self.message)?;
124            if !self.message.ends_with('\n') {
125                writeln!(f)?;
126            }
127        }
128        writeln!(f)
129    }
130}
131
132impl Header {
133    /// Parses one `Key: value` line, returning `None` if the shape is invalid.
134    fn parse(line: &str) -> Option<Self> {
135        let (key, value) = line.split_once(':')?;
136        let key = key.trim();
137        if key.is_empty() || key.chars().any(char::is_whitespace) {
138            return None;
139        }
140        Some(Self {
141            key: key.to_owned(),
142            value: value.trim_start().to_owned(),
143        })
144    }
145}
146
147#[cfg(test)]
148#[allow(clippy::unwrap_used)]
149mod tests {
150    use super::*;
151
152    const SHA1: &str = "1234567890abcdef1234567890abcdef12345678";
153
154    #[test]
155    fn parses_headers_only() {
156        let input = format!("commit {SHA1}\nAuthor: A\n\n");
157        let commit = CommitHeader::from_str(&input).unwrap();
158
159        assert_eq!(commit.hash.to_string(), SHA1);
160        assert_eq!(commit.decoration, None);
161        assert_eq!(commit.header("author"), Some("A"));
162        assert!(commit.message.is_empty());
163    }
164
165    #[test]
166    fn parses_sha256_hash() {
167        let oid = "0".repeat(64);
168        let input = format!("commit {oid}\n\n");
169        let commit = CommitHeader::from_str(&input).unwrap();
170
171        assert_eq!(commit.hash.to_string(), oid);
172    }
173
174    #[test]
175    fn parses_decoration_after_hash() {
176        let input = format!("commit {SHA1} (HEAD -> main)\n\n");
177        let commit = CommitHeader::from_str(&input).unwrap();
178
179        assert_eq!(commit.hash.to_string(), SHA1);
180        assert_eq!(commit.decoration.as_deref(), Some("(HEAD -> main)"));
181    }
182
183    #[test]
184    fn parses_signature_before_headers() {
185        let input =
186            format!("commit {SHA1}\nGood signature\nNo principal matched.\nAuthor: A\nDate: B\n\n");
187        let commit = CommitHeader::from_str(&input).unwrap();
188
189        assert_eq!(
190            commit.signature,
191            ["Good signature", "No principal matched."]
192        );
193        assert_eq!(commit.header("author"), Some("A"));
194        assert_eq!(commit.header("date"), Some("B"));
195        assert!(commit.message.is_empty());
196    }
197
198    #[test]
199    fn parses_message_with_indent_preserved() {
200        let input = format!("commit {SHA1}\nAuthor: A\n\n    Subject\n\n    Body\n");
201        let commit = CommitHeader::from_str(&input).unwrap();
202
203        assert_eq!(commit.message, "    Subject\n\n    Body\n");
204    }
205
206    #[test]
207    fn rejects_input_without_commit_line() {
208        assert_eq!(
209            CommitHeader::from_str("Author: A\nDate: B\n"),
210            Err(ParseCommitError),
211        );
212        assert_eq!(CommitHeader::from_str(""), Err(ParseCommitError));
213    }
214
215    #[test]
216    fn rejects_non_hex_hash() {
217        assert_eq!(
218            CommitHeader::from_str("commit not-hex\n\n"),
219            Err(ParseCommitError),
220        );
221    }
222
223    #[test]
224    fn display_matches_decoder_line_encoding() {
225        let lines = [
226            "commit 1234567890abcdef1234567890abcdef12345678",
227            "Good signature",
228            "Author: A",
229            "",
230            "    Subject",
231            "",
232            "    Body",
233            "",
234        ];
235        let commit: CommitHeader = lines.join("\n").parse().unwrap();
236        let expected: String = lines.iter().map(|line| format!("{line}\n")).collect();
237
238        assert_eq!(commit.to_string(), expected);
239    }
240}