Skip to main content

gix_object/commit/
mod.rs

1use bstr::{BStr, ByteSlice};
2use gix_error::Result;
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) -> Result<CommitRef<'a>> {
52        decode::commit(&mut data, object_hash)
53    }
54}
55
56/// Access
57impl<'a> CommitRef<'a> {
58    /// Return the `tree` fields hash digest.
59    pub fn tree(&self) -> gix_hash::ObjectId {
60        gix_hash::ObjectId::from_hex(self.tree).expect("prior validation of tree hash during parsing")
61    }
62
63    /// Returns an iterator of parent object ids
64    pub fn parents(&self) -> impl Iterator<Item = gix_hash::ObjectId> + '_ {
65        self.parents
66            .iter()
67            .map(|hex_hash| gix_hash::ObjectId::from_hex(hex_hash).expect("prior validation of hashes during parsing"))
68    }
69
70    /// Returns a convenient iterator over all extra headers.
71    pub fn extra_headers(&self) -> ExtraHeaders<impl Iterator<Item = (&BStr, &BStr)>> {
72        ExtraHeaders::new(
73            self.extra_headers.iter().map(|(k, v)| (*k, v.as_ref())),
74            self.tree().kind(),
75        )
76    }
77
78    /// Return the author, with whitespace trimmed.
79    ///
80    /// This is different from the `author` field which may contain whitespace.
81    pub fn author(&self) -> Result<gix_actor::SignatureRef<'a>> {
82        parse_signature(self.author).map(|signature| signature.trim())
83    }
84
85    /// Return the committer, with whitespace trimmed.
86    ///
87    /// This is different from the `committer` field which may contain whitespace.
88    pub fn committer(&self) -> Result<gix_actor::SignatureRef<'a>> {
89        parse_signature(self.committer).map(|signature| signature.trim())
90    }
91
92    /// Returns a partially parsed message from which more information can be derived.
93    pub fn message(&self) -> MessageRef<'a> {
94        MessageRef::from_bytes(self.message)
95    }
96
97    /// Returns the time at which this commit was created, or a default time if it could not be parsed.
98    pub fn time(&self) -> Result<gix_date::Time> {
99        parse_signature(self.committer).map(|signature| signature.time().unwrap_or_default())
100    }
101}
102
103/// Conversion
104impl CommitRef<'_> {
105    /// Copy all fields of this instance into a fully owned commit, consuming this instance.
106    pub fn into_owned(self) -> Result<Commit> {
107        self.try_into()
108    }
109
110    /// Copy all fields of this instance into a fully owned commit, internally cloning this instance.
111    pub fn to_owned(self) -> Result<Commit> {
112        self.try_into()
113    }
114}
115
116impl Commit {
117    /// Returns a convenient iterator over all extra headers.
118    pub fn extra_headers(&self) -> ExtraHeaders<impl Iterator<Item = (&BStr, &BStr)>> {
119        ExtraHeaders::new(
120            self.extra_headers.iter().map(|(k, v)| (k.as_bstr(), v.as_bstr())),
121            self.tree.kind(),
122        )
123    }
124}
125
126/// An iterator over extra headers in [owned][crate::Commit] and [borrowed][crate::CommitRef] commits.
127pub struct ExtraHeaders<I> {
128    inner: I,
129    hash_kind: gix_hash::Kind,
130}
131
132/// Instantiation and convenience.
133impl<'a, I> ExtraHeaders<I>
134where
135    I: Iterator<Item = (&'a BStr, &'a BStr)>,
136{
137    /// Create a new instance from an iterator over tuples of (name, value) pairs.
138    pub fn new(iter: I, hash_kind: gix_hash::Kind) -> Self {
139        ExtraHeaders { inner: iter, hash_kind }
140    }
141
142    /// Find the _value_ of the _first_ header with the given `name`.
143    pub fn find(mut self, name: &str) -> Option<&'a BStr> {
144        self.inner
145            .find_map(move |(k, v)| if k == name.as_bytes().as_bstr() { Some(v) } else { None })
146    }
147
148    /// Find the entry index with the given name, or return `None` if unavailable.
149    pub fn find_pos(self, name: &str) -> Option<usize> {
150        self.inner
151            .enumerate()
152            .find_map(|(pos, (field, _value))| (field == name).then_some(pos))
153    }
154
155    /// Return an iterator over all _values_ of headers with the given `name`.
156    pub fn find_all(self, name: &'a str) -> impl Iterator<Item = &'a BStr> {
157        self.inner
158            .filter_map(move |(k, v)| if k == name.as_bytes().as_bstr() { Some(v) } else { None })
159    }
160
161    /// Return an iterator over all git mergetags.
162    ///
163    /// A merge tag is a tag object embedded within the respective header field of a commit, making
164    /// it a child object of sorts.
165    pub fn mergetags(self) -> impl Iterator<Item = Result<TagRef<'a>>> {
166        let hash_kind = self.hash_kind;
167        self.find_all("mergetag").map(move |b| TagRef::from_bytes(b, hash_kind))
168    }
169
170    /// Return the cryptographic signature provided by gpg/pgp verbatim.
171    pub fn pgp_signature(self) -> Option<&'a BStr> {
172        let field_name = signature_field_name(self.hash_kind);
173        self.find(field_name)
174    }
175}