Skip to main content

git_internal/internal/object/
signature.rs

1//! In a Git commit, the author signature contains the name, email address, timestamp, and timezone
2//! of the person who authored the commit. This information is stored in a specific format, which
3//! consists of the following fields:
4//!
5//! - Name: The name of the author, encoded as a UTF-8 string.
6//! - Email: The email address of the author, encoded as a UTF-8 string.
7//! - Timestamp: The timestamp of when the commit was authored, encoded as a decimal number of seconds
8//!   since the Unix epoch (January 1, 1970, 00:00:00 UTC).
9//! - Timezone: The timezone offset of the author's local time from Coordinated Universal Time (UTC),
10//!   encoded as a string in the format "+HHMM" or "-HHMM".
11//!
12use std::{fmt::Display, str::FromStr};
13
14use bstr::ByteSlice;
15use chrono::Offset;
16
17use crate::errors::GitError;
18
19/// In addition to the author signature, Git also includes a "committer" signature, which indicates
20/// who committed the changes to the repository. The committer signature is similar in structure to
21/// the author signature, but includes the name, email address, and timestamp of the committer instead.
22/// This can be useful in situations where multiple people are working on a project and changes are
23/// being reviewed and merged by someone other than the original author.
24///
25/// In the following example, it's has the only one who authored and committed.
26/// ```bash
27/// author Eli Ma <eli@patch.sh> 1678102132 +0800
28/// committer Quanyi Ma <eli@patch.sh> 1678102132 +0800
29/// ```
30///
31/// So, we design a `SignatureType` enum to indicate the signature type.
32#[derive(
33    PartialEq,
34    Eq,
35    Debug,
36    Clone,
37    serde::Serialize,
38    serde::Deserialize,
39    rkyv::Archive,
40    rkyv::Serialize,
41    rkyv::Deserialize,
42)]
43pub enum SignatureType {
44    Author,
45    Committer,
46    Tagger,
47}
48
49impl Display for SignatureType {
50    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
51        match self {
52            SignatureType::Author => write!(f, "author"),
53            SignatureType::Committer => write!(f, "committer"),
54            SignatureType::Tagger => write!(f, "tagger"),
55        }
56    }
57}
58impl FromStr for SignatureType {
59    type Err = GitError;
60    /// The `from_str` method is used to convert a string to a `SignatureType` enum.
61    fn from_str(s: &str) -> Result<Self, Self::Err> {
62        match s {
63            "author" => Ok(SignatureType::Author),
64            "committer" => Ok(SignatureType::Committer),
65            "tagger" => Ok(SignatureType::Tagger),
66            _ => Err(GitError::InvalidSignatureType(s.to_string())),
67        }
68    }
69}
70impl SignatureType {
71    /// The `from_data` method is used to convert a `Vec<u8>` to a `SignatureType` enum.
72    pub fn from_data(data: Vec<u8>) -> Result<Self, GitError> {
73        let s = String::from_utf8(data.to_vec())
74            .map_err(|e| GitError::ConversionError(e.to_string()))?;
75        SignatureType::from_str(s.as_str())
76    }
77
78    /// The `to_bytes` method is used to convert a `SignatureType` enum to a `Vec<u8>`.
79    pub fn to_bytes(&self) -> Vec<u8> {
80        match self {
81            SignatureType::Author => "author".to_string().into_bytes(),
82            SignatureType::Committer => "committer".to_string().into_bytes(),
83            SignatureType::Tagger => "tagger".to_string().into_bytes(),
84        }
85    }
86}
87
88/// Represents a Git signature, including the author's name, email, timestamp, and timezone.
89#[derive(
90    PartialEq,
91    Eq,
92    Debug,
93    Clone,
94    serde::Serialize,
95    serde::Deserialize,
96    rkyv::Archive,
97    rkyv::Serialize,
98    rkyv::Deserialize,
99)]
100pub struct Signature {
101    pub signature_type: SignatureType,
102    pub name: String,
103    pub email: String,
104    pub timestamp: usize,
105    pub timezone: String,
106}
107
108impl Display for Signature {
109    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
110        writeln!(f, "{} <{}>", self.name, self.email).unwrap();
111        // format the timestamp to a human-readable date format
112        let date =
113            chrono::DateTime::<chrono::Utc>::from_timestamp(self.timestamp as i64, 0).unwrap();
114        writeln!(f, "Date: {} {}", date, self.timezone)
115    }
116}
117
118/// Format a UTC offset in seconds as Git's canonical `[+-]HHMM` timezone.
119///
120/// The sign is applied once to the whole offset, so negative half-hour zones
121/// render as `-0230` (never `-02-30`), matching what
122/// [`Signature::from_data`] accepts.
123pub fn format_timezone(offset_seconds: i32) -> String {
124    let sign = if offset_seconds < 0 { '-' } else { '+' };
125    let total_minutes = offset_seconds.unsigned_abs() / 60;
126    format!("{sign}{:02}{:02}", total_minutes / 60, total_minutes % 60)
127}
128
129impl Signature {
130    /// The `from_data` method is used to convert a `Vec<u8>` to a `Signature` struct.
131    ///
132    /// Parses `<role> <name> <<email>> <timestamp> <tz>`. Every structural
133    /// problem (missing role/`<`/`>`/space separators, non-UTF-8 text, a
134    /// non-numeric timestamp, a timezone that is not `[+-]HHMM`) fails closed
135    /// with [`GitError::InvalidSignatureType`] instead of panicking, so callers
136    /// such as `Commit::from_bytes` can reject a malformed object body. An
137    /// empty name (`author <mail> 1 +0000`) is accepted, as in Git.
138    pub fn from_data(data: Vec<u8>) -> Result<Signature, GitError> {
139        let sign = data;
140        let malformed = |what: &str| {
141            GitError::InvalidSignatureType(format!(
142                "malformed signature line ({what}): {:?}",
143                String::from_utf8_lossy(&sign)
144            ))
145        };
146        let utf8 = |bytes: &[u8], what: &str| -> Result<String, GitError> {
147            std::str::from_utf8(bytes)
148                .map(str::to_string)
149                .map_err(|_| malformed(what))
150        };
151
152        // `<role>` up to the first space.
153        let name_start = sign
154            .find_byte(0x20)
155            .ok_or_else(|| malformed("missing role separator"))?;
156        let role = utf8(&sign[..name_start], "role")?;
157        let signature_type = SignatureType::from_str(&role)?;
158
159        // `<name> <<email>>`: `<` must follow the role separator; the name is the text
160        // between them minus its single trailing space (it may be empty).
161        let email_start = sign
162            .find_byte(0x3C)
163            .filter(|&i| i > name_start)
164            .ok_or_else(|| malformed("missing '<' before email"))?;
165        let email_end = sign
166            .find_byte(0x3E)
167            .filter(|&i| i > email_start)
168            .ok_or_else(|| malformed("missing '>' after email"))?;
169        // A non-empty name must be followed by exactly one space before `<`.
170        let name_bytes = &sign[name_start + 1..email_start];
171        let name_bytes = match name_bytes.strip_suffix(b" ") {
172            Some(stripped) => stripped,
173            None if name_bytes.is_empty() => name_bytes,
174            None => return Err(malformed("missing space before '<'")),
175        };
176        let name = utf8(name_bytes, "name")?;
177        let email = utf8(&sign[email_start + 1..email_end], "email")?;
178
179        // `> <timestamp> <tz>`: exactly one space after `>`, a decimal timestamp and a
180        // non-empty timezone.
181        if sign.get(email_end + 1) != Some(&0x20) {
182            return Err(malformed("missing space after email"));
183        }
184        let rest = &sign[email_end + 2..];
185        let timestamp_split = rest
186            .find_byte(0x20)
187            .ok_or_else(|| malformed("missing timezone separator"))?;
188        let timestamp = utf8(&rest[..timestamp_split], "timestamp")?
189            .parse::<usize>()
190            .map_err(|_| malformed("non-numeric timestamp"))?;
191        // Timezone must be Git's canonical `[+-]HHMM` (what `git fsck` calls a
192        // well-formed timezone); anything else is rejected.
193        let timezone = utf8(&rest[timestamp_split + 1..], "timezone")?;
194        let tz = timezone.as_bytes();
195        let tz_ok = tz.len() == 5
196            && (tz[0] == b'+' || tz[0] == b'-')
197            && tz[1..].iter().all(u8::is_ascii_digit);
198        if !tz_ok {
199            return Err(malformed("timezone is not [+-]HHMM"));
200        }
201
202        // Return a Result object indicating success
203        Ok(Signature {
204            signature_type,
205            name,
206            email,
207            timestamp,
208            timezone,
209        })
210    }
211
212    /// The `to_data` method is used to convert a `Signature` struct to a `Vec<u8>`.
213    pub fn to_data(&self) -> Result<Vec<u8>, GitError> {
214        // Create a new empty vector to store the encoded data.
215        let mut sign = Vec::new();
216
217        // Append the author name bytes to the data vector, followed by a space byte.
218        sign.extend_from_slice(&self.signature_type.to_bytes());
219        sign.extend_from_slice(&[0x20]);
220
221        // Append the name bytes to the data vector, followed by a space byte.
222        sign.extend_from_slice(self.name.as_bytes());
223        sign.extend_from_slice(&[0x20]);
224
225        // Append the email address bytes to the data vector, enclosed in angle brackets.
226        sign.extend_from_slice(format!("<{}>", self.email).as_bytes());
227        sign.extend_from_slice(&[0x20]);
228
229        // Append the timestamp integer bytes to the data vector, followed by a space byte.
230        sign.extend_from_slice(self.timestamp.to_string().as_bytes());
231        sign.extend_from_slice(&[0x20]);
232
233        // Append the timezone string bytes to the data vector.
234        sign.extend_from_slice(self.timezone.as_bytes());
235
236        // Return the data vector as a Result object indicating success.
237        Ok(sign)
238    }
239
240    /// Represents a signature with author, email, timestamp, and timezone information.
241    pub fn new(sign_type: SignatureType, author: String, email: String) -> Signature {
242        // Get the current local time (with timezone)
243        let local_time = chrono::Local::now();
244
245        // Get the offset from UTC in minutes (local time - UTC time)
246        let offset = local_time.offset().fix().local_minus_utc();
247
248        // Format the offset as Git's canonical `[+-]HHMM` (e.g., "+0800", "-0230").
249        let offset_str = format_timezone(offset);
250
251        // Return the Signature struct with the provided information
252        Signature {
253            signature_type: sign_type, // The type of signature (e.g., commit, merge)
254            name: author,              // The author's name
255            email,                     // The author's email
256            timestamp: chrono::Utc::now().timestamp() as usize, // The timestamp of the signature (seconds since Unix epoch)
257            timezone: offset_str, // The timezone offset (e.g., "+0800")
258        }
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use std::str::FromStr;
265
266    use chrono::DateTime;
267
268    use crate::internal::object::signature::{Signature, SignatureType};
269
270    /// Test conversion from string to SignatureType enum.
271    #[test]
272    fn test_signature_type_from_str() {
273        assert_eq!(
274            SignatureType::from_str("author").unwrap(),
275            SignatureType::Author
276        );
277
278        assert_eq!(
279            SignatureType::from_str("committer").unwrap(),
280            SignatureType::Committer
281        );
282    }
283
284    /// Test conversion from SignatureType enum to string.
285    #[test]
286    fn test_signature_type_from_data() {
287        assert_eq!(
288            SignatureType::from_data("author".to_string().into_bytes()).unwrap(),
289            SignatureType::Author
290        );
291
292        assert_eq!(
293            SignatureType::from_data("committer".to_string().into_bytes()).unwrap(),
294            SignatureType::Committer
295        );
296    }
297
298    /// Test conversion from SignatureType enum to bytes.
299    #[test]
300    fn test_signature_type_to_bytes() {
301        assert_eq!(
302            SignatureType::Author.to_bytes(),
303            "author".to_string().into_bytes()
304        );
305
306        assert_eq!(
307            SignatureType::Committer.to_bytes(),
308            "committer".to_string().into_bytes()
309        );
310    }
311
312    /// Test conversion from data bytes to Signature struct.
313    #[test]
314    fn test_signature_new_from_data() {
315        let sign = Signature::from_data(
316            "author Quanyi Ma <eli@patch.sh> 1678101573 +0800"
317                .to_string()
318                .into_bytes(),
319        )
320        .unwrap();
321
322        assert_eq!(sign.signature_type, SignatureType::Author);
323        assert_eq!(sign.name, "Quanyi Ma");
324        assert_eq!(sign.email, "eli@patch.sh");
325        assert_eq!(sign.timestamp, 1678101573);
326        assert_eq!(sign.timezone, "+0800");
327    }
328
329    /// Test conversion from Signature struct to data bytes.
330    #[test]
331    fn test_signature_to_data() {
332        let sign = Signature::from_data(
333            "committer Quanyi Ma <eli@patch.sh> 1678101573 +0800"
334                .to_string()
335                .into_bytes(),
336        )
337        .unwrap();
338
339        let dest = sign.to_data().unwrap();
340
341        assert_eq!(
342            dest,
343            "committer Quanyi Ma <eli@patch.sh> 1678101573 +0800"
344                .to_string()
345                .into_bytes()
346        );
347    }
348
349    /// When the test case run in the GitHub Action, the timezone is +0000, so we ignore it.
350    #[test]
351    fn test_signature_with_time() {
352        let sign = Signature::new(
353            SignatureType::Author,
354            "MEGA".to_owned(),
355            "admin@mega.com".to_owned(),
356        );
357        assert_eq!(sign.signature_type, SignatureType::Author);
358        assert_eq!(sign.name, "MEGA");
359        assert_eq!(sign.email, "admin@mega.com");
360        // assert_eq!(sign.timezone, "+0800");//it depends on the local timezone
361
362        let naive_datetime = DateTime::from_timestamp(sign.timestamp as i64, 0).unwrap();
363        println!("Formatted DateTime: {}", naive_datetime.naive_local());
364    }
365
366    /// `format_timezone` always yields canonical `[+-]HHMM`, including negative half-hour zones.
367    #[test]
368    fn signature_format_timezone_is_canonical() {
369        use crate::internal::object::signature::format_timezone;
370        assert_eq!(format_timezone(0), "+0000");
371        assert_eq!(format_timezone(8 * 3600), "+0800");
372        assert_eq!(format_timezone(5 * 3600 + 30 * 60), "+0530");
373        assert_eq!(format_timezone(-(2 * 3600 + 30 * 60)), "-0230");
374        assert_eq!(format_timezone(-3600), "-0100");
375        assert_eq!(format_timezone(-(9 * 3600 + 30 * 60)), "-0930");
376        assert_eq!(format_timezone(12 * 3600 + 45 * 60), "+1245");
377    }
378
379    /// `Signature::new` output must always be accepted by the strict `from_data` parser.
380    #[test]
381    fn signature_new_round_trips_through_from_data() {
382        for role in [
383            SignatureType::Author,
384            SignatureType::Committer,
385            SignatureType::Tagger,
386        ] {
387            let sig = Signature::new(role, "n m".to_string(), "e@x".to_string());
388            let parsed = Signature::from_data(sig.to_data().unwrap()).unwrap();
389            assert_eq!(parsed.to_data().unwrap(), sig.to_data().unwrap());
390            assert_eq!(parsed.timezone.len(), 5);
391        }
392        // Non-UTF-8 role is reported as InvalidSignatureType.
393        let mut bad = vec![0xffu8, 0xfe, b' '];
394        bad.extend(b"n <e> 1 +0000");
395        assert!(matches!(
396            Signature::from_data(bad),
397            Err(crate::errors::GitError::InvalidSignatureType(_))
398        ));
399    }
400}