git_internal/internal/object/
signature.rs1use std::{fmt::Display, str::FromStr};
13
14use bstr::ByteSlice;
15use chrono::Offset;
16
17use crate::errors::GitError;
18
19#[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 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 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 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#[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 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
118pub 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 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 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 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 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 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 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 Ok(Signature {
204 signature_type,
205 name,
206 email,
207 timestamp,
208 timezone,
209 })
210 }
211
212 pub fn to_data(&self) -> Result<Vec<u8>, GitError> {
214 let mut sign = Vec::new();
216
217 sign.extend_from_slice(&self.signature_type.to_bytes());
219 sign.extend_from_slice(&[0x20]);
220
221 sign.extend_from_slice(self.name.as_bytes());
223 sign.extend_from_slice(&[0x20]);
224
225 sign.extend_from_slice(format!("<{}>", self.email).as_bytes());
227 sign.extend_from_slice(&[0x20]);
228
229 sign.extend_from_slice(self.timestamp.to_string().as_bytes());
231 sign.extend_from_slice(&[0x20]);
232
233 sign.extend_from_slice(self.timezone.as_bytes());
235
236 Ok(sign)
238 }
239
240 pub fn new(sign_type: SignatureType, author: String, email: String) -> Signature {
242 let local_time = chrono::Local::now();
244
245 let offset = local_time.offset().fix().local_minus_utc();
247
248 let offset_str = format_timezone(offset);
250
251 Signature {
253 signature_type: sign_type, name: author, email, timestamp: chrono::Utc::now().timestamp() as usize, timezone: offset_str, }
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]
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]
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]
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]
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]
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 #[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 let naive_datetime = DateTime::from_timestamp(sign.timestamp as i64, 0).unwrap();
363 println!("Formatted DateTime: {}", naive_datetime.naive_local());
364 }
365
366 #[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 #[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 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}