Skip to main content

gix_object/commit/
mod.rs

1use bstr::{BStr, ByteSlice};
2use gix_error::ExnMessageResult;
3
4use crate::parse::parse_signature;
5use crate::{Commit, CommitRef, TagRef};
6
7/// The well-known field name for signatures on SHA-1 commits.
8pub const SIGNATURE_FIELD_NAME: &str = "gpgsig";
9/// The well-known field name for signatures on SHA-256 commits.
10pub const SIGNATURE_FIELD_NAME_SHA256: &str = "gpgsig-sha256";
11
12/// Return the signature field name Git uses for `hash_kind`.
13pub fn signature_field_name(hash_kind: gix_hash::Kind) -> &'static str {
14    #[cfg(feature = "sha256")]
15    if hash_kind == gix_hash::Kind::Sha256 {
16        return SIGNATURE_FIELD_NAME_SHA256;
17    }
18    let _ = hash_kind;
19    SIGNATURE_FIELD_NAME
20}
21
22mod decode;
23///
24pub mod message;
25
26/// A parsed commit message that assumes a title separated from the body by two consecutive newlines.
27///
28/// Titles can have any amount of whitespace
29#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub struct MessageRef<'a> {
32    /// The title of the commit, as separated from the body with two consecutive newlines. The newlines are not included.
33    /// Without a body separator, a final LF or CRLF is also excluded. All other whitespace is preserved.
34    #[cfg_attr(feature = "serde", serde(borrow))]
35    pub title: &'a BStr,
36    /// All bytes not consumed by the title, excluding the separating newlines.
37    ///
38    /// The body is `None` if there was now title separation or the body was empty after the separator.
39    pub body: Option<&'a BStr>,
40}
41
42///
43pub mod ref_iter;
44
45mod write;
46
47/// Lifecycle
48impl<'a> CommitRef<'a> {
49    /// Deserialize a commit from the given `data` bytes while avoiding most allocations, using `object_hash` to know
50    /// what kind of hash to expect for validation.
51    pub fn from_bytes(mut data: &'a [u8], object_hash: gix_hash::Kind) -> ExnMessageResult<CommitRef<'a>> {
52        let input = &mut data;
53        match decode::commit(input, object_hash) {
54            Ok(tag) => Ok(tag),
55            Err(err) => Err(err),
56        }
57    }
58}
59
60/// Access
61impl<'a> CommitRef<'a> {
62    /// Return the `tree` fields hash digest.
63    pub fn tree(&self) -> gix_hash::ObjectId {
64        gix_hash::ObjectId::from_hex(self.tree).expect("prior validation of tree hash during parsing")
65    }
66
67    /// Returns an iterator of parent object ids
68    pub fn parents(&self) -> impl Iterator<Item = gix_hash::ObjectId> + '_ {
69        self.parents
70            .iter()
71            .map(|hex_hash| gix_hash::ObjectId::from_hex(hex_hash).expect("prior validation of hashes during parsing"))
72    }
73
74    /// Returns a convenient iterator over all extra headers.
75    pub fn extra_headers(&self) -> ExtraHeaders<impl Iterator<Item = (&BStr, &BStr)>> {
76        ExtraHeaders::new(
77            self.extra_headers.iter().map(|(k, v)| (*k, v.as_ref())),
78            self.tree().kind(),
79        )
80    }
81
82    /// Return the author, with whitespace trimmed.
83    ///
84    /// This is different from the `author` field which may contain whitespace.
85    pub fn author(&self) -> ExnMessageResult<gix_actor::SignatureRef<'a>> {
86        parse_signature(self.author).map(|signature| signature.trim())
87    }
88
89    /// Return the committer, with whitespace trimmed.
90    ///
91    /// This is different from the `committer` field which may contain whitespace.
92    pub fn committer(&self) -> ExnMessageResult<gix_actor::SignatureRef<'a>> {
93        parse_signature(self.committer).map(|signature| signature.trim())
94    }
95
96    /// Returns a partially parsed message from which more information can be derived.
97    pub fn message(&self) -> MessageRef<'a> {
98        MessageRef::from_bytes(self.message)
99    }
100
101    /// Returns the time at which this commit was created, or a default time if it could not be parsed.
102    pub fn time(&self) -> ExnMessageResult<gix_date::Time> {
103        parse_signature(self.committer).map(|signature| signature.time().unwrap_or_default())
104    }
105}
106
107/// Conversion
108impl CommitRef<'_> {
109    /// Copy all fields of this instance into a fully owned commit, consuming this instance.
110    pub fn into_owned(self) -> ExnMessageResult<Commit> {
111        self.try_into()
112    }
113
114    /// Copy all fields of this instance into a fully owned commit, internally cloning this instance.
115    pub fn to_owned(self) -> ExnMessageResult<Commit> {
116        self.try_into()
117    }
118}
119
120impl Commit {
121    /// Returns a convenient iterator over all extra headers.
122    pub fn extra_headers(&self) -> ExtraHeaders<impl Iterator<Item = (&BStr, &BStr)>> {
123        ExtraHeaders::new(
124            self.extra_headers.iter().map(|(k, v)| (k.as_bstr(), v.as_bstr())),
125            self.tree.kind(),
126        )
127    }
128}
129
130/// An iterator over extra headers in [owned][crate::Commit] and [borrowed][crate::CommitRef] commits.
131pub struct ExtraHeaders<I> {
132    inner: I,
133    hash_kind: gix_hash::Kind,
134}
135
136/// Instantiation and convenience.
137impl<'a, I> ExtraHeaders<I>
138where
139    I: Iterator<Item = (&'a BStr, &'a BStr)>,
140{
141    /// Create a new instance from an iterator over tuples of (name, value) pairs.
142    pub fn new(iter: I, hash_kind: gix_hash::Kind) -> Self {
143        ExtraHeaders { inner: iter, hash_kind }
144    }
145
146    /// Find the _value_ of the _first_ header with the given `name`.
147    pub fn find(mut self, name: &str) -> Option<&'a BStr> {
148        self.inner
149            .find_map(move |(k, v)| if k == name.as_bytes().as_bstr() { Some(v) } else { None })
150    }
151
152    /// Find the entry index with the given name, or return `None` if unavailable.
153    pub fn find_pos(self, name: &str) -> Option<usize> {
154        self.inner
155            .enumerate()
156            .find_map(|(pos, (field, _value))| (field == name).then_some(pos))
157    }
158
159    /// Return an iterator over all _values_ of headers with the given `name`.
160    pub fn find_all(self, name: &'a str) -> impl Iterator<Item = &'a BStr> {
161        self.inner
162            .filter_map(move |(k, v)| if k == name.as_bytes().as_bstr() { Some(v) } else { None })
163    }
164
165    /// Return an iterator over all git mergetags.
166    ///
167    /// A merge tag is a tag object embedded within the respective header field of a commit, making
168    /// it a child object of sorts.
169    pub fn mergetags(self) -> impl Iterator<Item = ExnMessageResult<TagRef<'a>>> {
170        let hash_kind = self.hash_kind;
171        self.find_all("mergetag").map(move |b| TagRef::from_bytes(b, hash_kind))
172    }
173
174    /// Return the cryptographic signature provided by gpg/pgp verbatim.
175    pub fn pgp_signature(self) -> Option<&'a BStr> {
176        let field_name = signature_field_name(self.hash_kind);
177        self.find(field_name)
178    }
179}