Skip to main content

git_internal/internal/object/
commit.rs

1//! The Commit object is a data structure used to represent a specific version of a project's
2//! files at a particular point in time. In Git, the commit object is a fundamental data structure
3//! that is used to track changes to a repository's files over time. Whenever a developer makes
4//! changes to the files in a repository, they create a new commit object that records those changes.
5//!
6//! Each commit object in Git contains the following information:
7//!
8//! - A unique SHA-1/ SHA-256 hash that identifies the commit.
9//! - The author and committer of the commit (which may be different people).
10//! - The date and time the commit was made.
11//! - A commit message that describes the changes made in the commit.
12//! - A reference to the parent commit or commits (in the case of a merge commit) that the new commit is based on.
13//! - The contents of the files in the repository at the time the commit was made.
14use std::fmt::Display;
15
16use bstr::ByteSlice;
17
18use crate::{
19    errors::GitError,
20    hash::{HashKind, ObjectHash},
21    internal::object::{ObjectTrait, ObjectType, signature::Signature},
22};
23
24/// The `Commit` struct is used to represent a commit object.
25///
26/// - The tree object SHA-1/SHA-256 hashpoints to the top level tree for this commit, which reflects the complete
27///   state of the repository at the time of the commit. The tree object in turn points to blobs and
28///   subtrees which represent the files in the repository.
29/// - The parent commit SHAs allow Git to construct a linked list of commits and build the full
30///   commit history. By chaining together commits in this fashion, Git is able to represent the entire
31///   history of a repository with a single commit object at its root.
32/// - The author and committer fields contain the name, email address, timestamp and timezone.
33/// - The message field contains the commit message, which maybe include signed or DCO.
34#[derive(
35    Eq,
36    Debug,
37    Clone,
38    serde::Serialize,
39    serde::Deserialize,
40    rkyv::Archive,
41    rkyv::Serialize,
42    rkyv::Deserialize,
43)]
44pub struct Commit {
45    pub id: ObjectHash,
46    pub tree_id: ObjectHash,
47    pub parent_commit_ids: Vec<ObjectHash>,
48    pub author: Signature,
49    pub committer: Signature,
50    pub message: String,
51}
52impl PartialEq for Commit {
53    fn eq(&self, other: &Self) -> bool {
54        self.id == other.id
55    }
56}
57
58impl Display for Commit {
59    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
60        writeln!(f, "tree: {}", self.tree_id)?;
61        for parent in self.parent_commit_ids.iter() {
62            writeln!(f, "parent: {parent}")?;
63        }
64        writeln!(f, "author {}", self.author)?;
65        writeln!(f, "committer {}", self.committer)?;
66        writeln!(f, "{}", self.message)
67    }
68}
69
70impl Commit {
71    /// Create a commit and derive its ID with an explicit repository `kind`.
72    ///
73    /// Does not consult the thread-local [`HashKind`]. `tree_id` and every
74    /// parent ID must belong to `kind`; a cross-kind reference fails closed
75    /// with [`GitError::InvalidHashValue`]. Never panics.
76    pub fn new_with_kind(
77        kind: HashKind,
78        author: Signature,
79        committer: Signature,
80        tree_id: ObjectHash,
81        parent_commit_ids: Vec<ObjectHash>,
82        message: &str,
83    ) -> Result<Commit, GitError> {
84        tree_id.ensure_kind(kind)?;
85        for parent in &parent_commit_ids {
86            parent.ensure_kind(kind)?;
87        }
88        let mut commit = Commit {
89            id: ObjectHash::zero_for_kind(kind),
90            tree_id,
91            parent_commit_ids,
92            author,
93            committer,
94            message: message.to_string(),
95        };
96        let data = commit.to_data()?;
97        commit.id = ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Commit, &data)?;
98        Ok(commit)
99    }
100
101    /// Convenience variant of [`Commit::new_with_kind`] that generates author and
102    /// committer signatures from the current time (see [`Commit::from_tree_id`]).
103    pub fn from_tree_id_with_kind(
104        kind: HashKind,
105        tree_id: ObjectHash,
106        parent_commit_ids: Vec<ObjectHash>,
107        message: &str,
108    ) -> Result<Commit, GitError> {
109        let now = chrono::Utc::now().timestamp();
110        let author =
111            Signature::from_data(format!("author mega <admin@mega.org> {now} +0800").into_bytes())?;
112        let committer = Signature::from_data(
113            format!("committer mega <admin@mega.org> {now} +0800").into_bytes(),
114        )?;
115        Commit::new_with_kind(kind, author, committer, tree_id, parent_commit_ids, message)
116    }
117
118    /// Create a commit using the thread-local [`HashKind`]; see [`Commit::new_with_kind`].
119    pub fn new(
120        author: Signature,
121        committer: Signature,
122        tree_id: ObjectHash,
123        parent_commit_ids: Vec<ObjectHash>,
124        message: &str,
125    ) -> Commit {
126        let mut commit = Commit {
127            id: ObjectHash::default(),
128            tree_id,
129            parent_commit_ids,
130            author,
131            committer,
132            message: message.to_string(),
133        };
134        // Calculate the hash of the commit object
135        // The hash is calculated from the type and data of the commit object
136        let hash = ObjectHash::from_type_and_data(ObjectType::Commit, &commit.to_data().unwrap());
137        commit.id = hash;
138        commit
139    }
140
141    /// Creates a new commit object from a tree ID and a list of parent commit IDs.
142    /// This function generates the author and committer signatures using the current time
143    /// and a fixed email address.
144    /// It also sets the commit message to the provided string.
145    /// # Arguments
146    /// - `tree_id`: The SHA1/ SHA-256 hash of the tree object that this commit points to.
147    /// - `parent_commit_ids`: A vector of SHA1/ SHA-256 hashes of the parent commits.
148    /// - `message`: A string containing the commit message.
149    /// # Returns
150    /// A new `Commit` object with the specified tree ID, parent commit IDs, and commit message.
151    /// The author and committer signatures are generated using the current time and a fixed email address.
152    /// Uses the thread-local [`HashKind`]; see [`Commit::from_tree_id_with_kind`].
153    pub fn from_tree_id(
154        tree_id: ObjectHash,
155        parent_commit_ids: Vec<ObjectHash>,
156        message: &str,
157    ) -> Commit {
158        let author = Signature::from_data(
159            format!(
160                "author mega <admin@mega.org> {} +0800",
161                chrono::Utc::now().timestamp()
162            )
163            .to_string()
164            .into_bytes(),
165        )
166        .unwrap();
167        let committer = Signature::from_data(
168            format!(
169                "committer mega <admin@mega.org> {} +0800",
170                chrono::Utc::now().timestamp()
171            )
172            .to_string()
173            .into_bytes(),
174        )
175        .unwrap();
176        Commit::new(author, committer, tree_id, parent_commit_ids, message)
177    }
178
179    /// Formats the commit message by extracting the first meaningful line.
180    ///
181    /// If the message contains a PGP signature, it returns the first non-empty line
182    /// after the signature block. Otherwise, it returns the first non-empty line
183    /// in the message. If no such line exists, it returns the original message.
184    pub fn format_message(&self) -> String {
185        let mut lines = self.message.lines();
186
187        // If a PGP signature is present, skip lines until after the signature ends
188        if let Some(pos) = self
189            .message
190            .lines()
191            .position(|line| line.contains("-----END PGP SIGNATURE-----"))
192        {
193            return self
194                .message
195                .lines()
196                .skip(pos + 1)
197                .find(|line| !line.trim().is_empty())
198                .map(|line| line.to_owned())
199                .unwrap_or_else(|| self.message.clone());
200        }
201
202        // Return the first non-empty line from the start
203        lines
204            .find(|line| !line.trim().is_empty())
205            .map(|line| line.to_owned())
206            .unwrap_or_else(|| self.message.clone())
207    }
208}
209
210/// Parse one `tree`/`parent` reference of a commit body as an ID of the
211/// commit's own repository `kind`. Fails closed with the full `HashError`
212/// diagnostic (operation, kind, expected/actual lengths); never infers the
213/// algorithm from the hex length.
214fn parse_commit_reference(kind: HashKind, field: &str, raw: &[u8]) -> Result<ObjectHash, GitError> {
215    let hex = std::str::from_utf8(raw).map_err(|_| {
216        GitError::InvalidHashValue(format!(
217            "commit {field} id is not UTF-8: expected {} {kind} hex chars, got {} bytes",
218            kind.hex_len(),
219            raw.len()
220        ))
221    })?;
222    ObjectHash::from_hex_for_kind(kind, hex)
223        .map_err(|e| GitError::InvalidHashValue(format!("commit {field} id: {e}")))
224}
225
226impl ObjectTrait for Commit {
227    /// Parse a commit body. `tree`/`parent` references are parsed as IDs of
228    /// `hash.kind()` — the repository kind of the commit being loaded — so a
229    /// 64-hex reference is never guessed to be SHA-256 by length alone and the
230    /// thread-local kind is not consulted. Structural errors fail closed with
231    /// [`GitError::InvalidCommitObject`]; reference errors carry the
232    /// [`crate::hash::HashError`] diagnostic in [`GitError::InvalidHashValue`].
233    fn from_bytes(data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
234    where
235        Self: Sized,
236    {
237        let kind = hash.kind();
238
239        // `tree <id>` line.
240        let tree_end = data.find_byte(0x0a).ok_or(GitError::InvalidCommitObject)?;
241        let tree_hex = data[..tree_end]
242            .strip_prefix(b"tree ")
243            .ok_or(GitError::InvalidCommitObject)?;
244        let tree_id = parse_commit_reference(kind, "tree", tree_hex)?;
245        let mut commit = &data[tree_end + 1..];
246
247        // Zero or more `parent <id>` lines, then exactly the `author` line: any other
248        // header in between is a malformed body (no substring search for "author").
249        let mut parent_commit_ids: Vec<ObjectHash> = Vec::new();
250        loop {
251            let line_end = commit
252                .find_byte(0x0a)
253                .ok_or(GitError::InvalidCommitObject)?;
254            let line = &commit[..line_end];
255            if let Some(parent_hex) = line.strip_prefix(b"parent ") {
256                parent_commit_ids.push(parse_commit_reference(kind, "parent", parent_hex)?);
257                commit = &commit[line_end + 1..];
258            } else if line.starts_with(b"author ") {
259                break;
260            } else {
261                return Err(GitError::InvalidCommitObject);
262            }
263        }
264
265        // `author` and `committer` lines (0x0a is the newline character).
266        let author_end = commit
267            .find_byte(0x0a)
268            .ok_or(GitError::InvalidCommitObject)?;
269        let author = Signature::from_data(commit[..author_end].to_vec())?;
270        commit = &commit[author_end + 1..];
271        let committer_end = commit
272            .find_byte(0x0a)
273            .ok_or(GitError::InvalidCommitObject)?;
274        if !commit.starts_with(b"committer ") {
275            return Err(GitError::InvalidCommitObject);
276        }
277        let committer = Signature::from_data(commit[..committer_end].to_vec())?;
278
279        // The rest is the message
280        let message = unsafe { String::from_utf8_unchecked(commit[committer_end + 1..].to_vec()) };
281        Ok(Commit {
282            id: hash,
283            tree_id,
284            parent_commit_ids,
285            author,
286            committer,
287            message,
288        })
289    }
290
291    fn get_type(&self) -> ObjectType {
292        ObjectType::Commit
293    }
294
295    fn get_size(&self) -> usize {
296        self.to_data().map(|data| data.len()).unwrap_or(0)
297    }
298
299    /// [Git-Internals-Git-Objects](https://git-scm.com/book/en/v2/Git-Internals-Git-Objects)
300    fn to_data(&self) -> Result<Vec<u8>, GitError> {
301        let mut data = Vec::new();
302
303        data.extend(b"tree ");
304        data.extend(self.tree_id.to_string().as_bytes());
305        data.extend(&[0x0a]);
306
307        for parent_tree_id in &self.parent_commit_ids {
308            data.extend(b"parent ");
309            data.extend(parent_tree_id.to_string().as_bytes());
310            data.extend(&[0x0a]);
311        }
312
313        data.extend(self.author.to_data()?);
314        data.extend(&[0x0a]);
315        data.extend(self.committer.to_data()?);
316        data.extend(&[0x0a]);
317        // Important! or Git Server can't parse & reply: unpack-objects abnormal exit
318        // We can move [0x0a] to message instead here.
319        // data.extend(&[0x0a]);
320        data.extend(self.message.as_bytes());
321
322        Ok(data)
323    }
324}
325
326#[cfg(test)]
327mod tests {
328    use std::str::FromStr;
329
330    use super::*;
331    use crate::hash::{HashKind, set_hash_kind_for_test};
332
333    /// Create a basic commit object for testing
334    fn basic_commit() -> Commit {
335        let _guard = set_hash_kind_for_test(HashKind::Sha1);
336        let raw_commit = br#"tree 341e54913a3a43069f2927cc0f703e5a9f730df1
337author benjamin.747 <benjamin.747@outlook.com> 1757467768 +0800
338committer benjamin.747 <benjamin.747@outlook.com> 1757491219 +0800
339gpgsig -----BEGIN PGP SIGNATURE-----
340
341 iQJNBAABCAA3FiEEs4MaYUV7JcjxsVMPyqxGczTZ6K4FAmjBMC4ZHGJlbmphbWlu
342 Ljc0N0BvdXRsb29rLmNvbQAKCRDKrEZzNNnorj73EADNpsyLAHsB3NgoeH+uy9Vq
343 G2+LRtlvqv3QMK7vbQUadXHlQYWk25SIk+WJ1kG1AnUy5fqOrLSDTA1ny+qwpH8O
344 +2sKCF/S1wlzqGWjCcRH5/ir9srsGIn9HbNqBjmU22NJ6Dt2jnqoUvtWfPwyqwWg
345 VpjYlj390cFdXTpH5hMvtlmUQB+zCSKtWQW2Ur64h/UsGtllARlACi+KHQQmA2/p
346 FLWNddvfJQpPM597DkGohQTD68g0PqOBhUkOHduHq7VHy68DVW+07bPNXK8JhJ8S
347 4dyV1sZwcVcov0GcKl0wUbEqzy4gf+zV7DQhkfrSRQMBdo5vCWahYj1AbgaTiu8a
348 hscshYDuWWqpxBU/+nCxOPskV29uUG1sRyXp3DqmKJZpnO9CVdw3QaVrqnMEeh2S
349 t/wYRI9aI1A+Mi/DETom5ifTVygMkK+3m1h7pAMOlblFEdZx2sDXPRG2IEUcatr4
350 Jb2+7PUJQXxUQnwHC7xHHxRh6a2h8TfEJfSoEyrgzxZ0CRxJ6XMJaJu0UwZ2xMsx
351 Lgmeu6miB/imwxz5R5RL2yVHbgllSlO5l12AIeBaPoarKXYPSALigQnKCXu5OM3x
352 Jq5qsSGtxdr6S1VgLyYHR4o69bQjzBp9K47J3IXqvrpo/ZiO/6Mspk2ZRWhGj82q
353 e3qERPp5b7+hA+M7jKPyJg==
354 =UeLf
355 -----END PGP SIGNATURE-----
356
357test parse commit from bytes
358"#;
359
360        let hash = ObjectHash::from_str("57d7685c60213a9da465cf900f31933be3a7ee39").unwrap();
361        Commit::from_bytes(raw_commit, hash).unwrap()
362    }
363
364    /// Create a basic commit object with SHA-256 for testing
365    fn basic_commit_sha256() -> Commit {
366        let _guard = set_hash_kind_for_test(HashKind::Sha256);
367        let raw_commit = br#"tree 0250024cf99636335fff1070e4220c5d8f67cb8633572d54b304629ad5382760
368parent 33324c6819589e8eed81d6c72f216469151a0f2dbe7f42ba021d8b63049eb754
369author jackieismpc <jackieismpc@gmail.com> 1764061895 +0800
370committer jackieismpc <jackieismpc@gmail.com> 1764061895 +0800
371gpgsig-sha256 -----BEGIN PGP SIGNATURE-----
372
373 iQIzBAABCAAdFiEEzW/BI6wDXimDk/4lItD7G/h4TUsFAmklcscACgkQItD7G/h4
374 TUtKFRAAtJq9tdl9XdND1ef2dXVQYCkQQlSdNHe2AR/QRVOPI39ZjD5aajRmZoE2
375 rKDenNML1ruiGEm+K3ntRDjus+3QF5Xkhj1D6eImQt6RXyOlo64I+GLRKlzw80Sl
376 hrd+l1eeuS4n46Z0U9fo1Qgc/crSn2VhUtLHJjvRntJoOb1vNreI2Y42Zmal3oVT
377 fQNQ7mqzh3KuWoa8T6nVrLaLH1vl9qhRgkPcIRbFf+ECbB96qykHqcbdHuneSgfx
378 +REpr1cedilkQlX81JrQ8Ntf4QFUPPHALl27/G6oPLT714cflEbvcFw7rNR+ktcD
379 ZJIMu5Cl7X3/v5e0od/hF9uPfiLHckUsOXiMFLfqRdZx/5XeQFWRpq4eYcW7e89e
380 3wJoBA2lCk8SHTBfsprKMpAweXJF9FCjRT5f9Zse2grqH81aQeNJnpSOoCq86oc/
381 nxhi8+rbIbClLCGQoGF7sE/fvmKqcex++JnXHcHTtK002Gnh3oHX07sbahlcGuYY
382 kg4QhXiLTQ5GfXnEnTPdFqbOVG02vEEsNeRgkmOz4c8Pm1FTDyOkuXd/Igvy7A9R
383 MZwQcJ6E4MnsMnoH8FKswGqCD7ftwtJtRzryORBVzvPKALufIXDVLyBbae9dxdej
384 bcpUK1bGtDljlwNtbLIOu+F1y2OVh7Tn3zxaQLcEhbUe2tP6rGk=
385 =nJMO
386 -----END PGP SIGNATURE-----
387
388signed sha256 commit for test"#;
389        let hash = ObjectHash::from_str(
390            "ed43b50437e260a4d8fedacbaa38bad28b54cc424925e4180d9f186afaa0508c",
391        )
392        .unwrap();
393        Commit::from_bytes(raw_commit.as_bytes(), hash).unwrap()
394    }
395
396    /// Test creating a Commit from bytes with PGP signature
397    #[test]
398    fn test_from_bytes_with_gpgsig() {
399        let commit = basic_commit();
400
401        assert_eq!(
402            commit.id,
403            ObjectHash::from_str("57d7685c60213a9da465cf900f31933be3a7ee39").unwrap()
404        );
405
406        assert_eq!(
407            commit.tree_id,
408            ObjectHash::from_str("341e54913a3a43069f2927cc0f703e5a9f730df1").unwrap()
409        );
410
411        assert_eq!(commit.author.name, "benjamin.747");
412        assert_eq!(commit.author.email, "benjamin.747@outlook.com");
413
414        assert_eq!(commit.committer.name, "benjamin.747");
415
416        // check message content(must contains gpgsig and content)
417        assert!(commit.message.contains("-----BEGIN PGP SIGNATURE-----"));
418        assert!(commit.message.contains("-----END PGP SIGNATURE-----"));
419        assert!(commit.message.contains("test parse commit from bytes"));
420    }
421
422    /// Test creating a Commit from bytes with SHA-256
423    #[test]
424    fn test_from_bytes_with_gpgsig_sha256() {
425        let commit = basic_commit_sha256();
426        assert_eq!(
427            commit.id,
428            ObjectHash::from_str(
429                "ed43b50437e260a4d8fedacbaa38bad28b54cc424925e4180d9f186afaa0508c"
430            )
431            .unwrap()
432        );
433        assert_eq!(
434            commit.tree_id,
435            ObjectHash::from_str(
436                "0250024cf99636335fff1070e4220c5d8f67cb8633572d54b304629ad5382760"
437            )
438            .unwrap()
439        );
440        assert_eq!(commit.author.name, "jackieismpc");
441        assert_eq!(commit.author.email, "jackieismpc@gmail.com");
442        assert_eq!(commit.committer.name, "jackieismpc");
443        // // check message content (must contain gpgsig-sha256 and content)
444        assert!(commit.message.contains("-----BEGIN PGP SIGNATURE-----"));
445        assert!(commit.message.contains("-----END PGP SIGNATURE-----"));
446        assert!(commit.message.contains("signed sha256 commit for test"));
447    }
448
449    /// Test formatting commit message with PGP signature
450    #[test]
451    fn test_format_message_with_pgp_signature() {
452        let _guard = set_hash_kind_for_test(HashKind::Sha1);
453        let commit = basic_commit();
454        assert_eq!(commit.format_message(), "test parse commit from bytes");
455    }
456
457    /// Test formatting commit message with SHA-256 PGP signature
458    #[test]
459    fn test_format_message_with_pgp_signature_sha256() {
460        let _guard = set_hash_kind_for_test(HashKind::Sha256);
461        let commit = basic_commit_sha256();
462        assert_eq!(commit.format_message(), "signed sha256 commit for test");
463    }
464}