1use crate::commit::{assemble_identity, format_git_timestamp};
17use crate::git_date::tm::date_overflows;
18use crate::objects::{HashAlgo, ObjectKind};
19use time::format_description::well_known::Rfc3339;
20use time::{OffsetDateTime, UtcOffset};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum SignatureTimestamp {
25 Valid(i64),
27 Sentinel,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Signature {
35 pub name: String,
37 pub email: String,
39 pub time: OffsetDateTime,
41}
42
43impl Signature {
44 pub fn new(
71 name: impl Into<String>,
72 email: impl Into<String>,
73 time: OffsetDateTime,
74 ) -> Result<Self, SignatureError> {
75 let signature = Self {
76 name: name.into(),
77 email: email.into(),
78 time,
79 };
80 signature.validate()?;
81 Ok(signature)
82 }
83
84 pub fn cleaned(name: &str, email: &str, time: OffsetDateTime) -> Result<Self, SignatureError> {
119 Self::new(clean_ident_part(name), clean_ident_part(email), time)
120 }
121
122 pub fn validate(&self) -> Result<(), SignatureError> {
132 for (field, value) in [
133 (SignatureField::Name, &self.name),
134 (SignatureField::Email, &self.email),
135 ] {
136 if let Some(ch) = value
137 .chars()
138 .find(|&c| c == '<' || c == '>' || (c.is_ascii_control() && c != '\t'))
139 {
140 return Err(SignatureError::ForbiddenCharacter { field, ch });
141 }
142 }
143 if self.time.unix_timestamp() < 0 {
144 return Err(SignatureError::BeforeEpoch);
145 }
146 if self.time.offset().seconds_past_minute() != 0 {
147 return Err(SignatureError::SubMinuteOffset);
148 }
149 Ok(())
150 }
151
152 #[must_use]
155 pub fn reflog_name_email(&self) -> String {
156 format!("{} <{}>", self.name, self.email)
157 }
158
159 #[must_use]
164 pub fn header_line(&self) -> String {
165 format!(
166 "{} <{}> {}",
167 self.name,
168 self.email,
169 format_git_timestamp(self.time)
170 )
171 }
172
173 #[must_use]
175 pub fn format_rfc3339(&self) -> Option<String> {
176 self.time.format(&Rfc3339).ok()
177 }
178
179 #[must_use]
203 pub fn from_header_lossy(line: &str) -> Self {
204 if let Some(sig) = parse_signature(line) {
205 return sig;
206 }
207 let (name, email) = parse_identity_name_email(line)
208 .unwrap_or_else(|| (line.trim().to_owned(), String::new()));
209 Self {
210 name,
211 email,
212 time: OffsetDateTime::UNIX_EPOCH,
213 }
214 }
215}
216
217#[cfg(feature = "serde-models")]
222impl serde::Serialize for Signature {
223 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
224 where
225 S: serde::Serializer,
226 {
227 use serde::ser::SerializeStruct;
228
229 let date = self
230 .format_rfc3339()
231 .unwrap_or_else(|| format_git_timestamp(self.time));
232 let mut out = serializer.serialize_struct("Signature", 3)?;
233 out.serialize_field("name", &self.name)?;
234 out.serialize_field("email", &self.email)?;
235 out.serialize_field("date", &date)?;
236 out.end()
237 }
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum SignatureField {
243 Name,
245 Email,
247}
248
249impl std::fmt::Display for SignatureField {
250 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251 f.write_str(match self {
252 Self::Name => "name",
253 Self::Email => "email",
254 })
255 }
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
260#[non_exhaustive]
261pub enum SignatureError {
262 #[error("signature {field} contains forbidden character {ch:?}")]
264 ForbiddenCharacter {
265 field: SignatureField,
267 ch: char,
269 },
270 #[error("signature time is before the Unix epoch")]
272 BeforeEpoch,
273 #[error("signature UTC offset is not a whole number of minutes")]
275 SubMinuteOffset,
276 #[error("not an identity line of the form 'Name <email> <unix-seconds> <+HHMM>'")]
278 Malformed,
279}
280
281fn clean_ident_part(part: &str) -> String {
285 let is_crud = |c: char| {
286 c.is_whitespace()
287 || c.is_ascii_control()
288 || matches!(c, '.' | ',' | ':' | ';' | '<' | '>' | '"' | '\\' | '\'')
289 };
290 part.chars()
291 .filter(|&c| c != '<' && c != '>' && !(c.is_ascii_control() && c != '\t'))
292 .collect::<String>()
293 .trim_matches(is_crud)
294 .to_owned()
295}
296
297impl std::str::FromStr for Signature {
298 type Err = SignatureError;
299
300 fn from_str(line: &str) -> Result<Self, Self::Err> {
308 let ends_at_timezone =
309 parse_signature_times(line).is_some_and(|t| t.tz_hhmm_range.end == line.len());
310 if !ends_at_timezone || line.matches('<').count() != 1 || line.matches('>').count() != 1 {
311 return Err(SignatureError::Malformed);
312 }
313 let signature = parse_signature(line).ok_or(SignatureError::Malformed)?;
314 signature.validate()?;
315 Ok(signature)
316 }
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct ParsedSignatureTimes {
322 pub unix_seconds: i64,
324 pub tz_offset_secs: i64,
326 pub tz_hhmm_range: std::ops::Range<usize>,
328}
329
330fn scan_decimal_timestamp(bytes: &[u8], mut i: usize) -> Option<(u128, usize)> {
333 const MAX_DIGITS: usize = 21;
334 let start = i;
335 let mut count = 0usize;
336 while i < bytes.len() && bytes[i].is_ascii_digit() {
337 count += 1;
338 if count > MAX_DIGITS {
339 return Some((u128::MAX, i));
340 }
341 i += 1;
342 }
343 if count == 0 {
344 return None;
345 }
346 let s = std::str::from_utf8(&bytes[start..i]).ok()?;
347 let v: u128 = s.parse().ok()?;
348 Some((v, i))
349}
350
351fn skip_fsck_date_leading_ws(bytes: &[u8], mut i: usize) -> usize {
353 while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
354 i += 1;
355 }
356 i
357}
358
359fn parse_tz_hhmm_offset(offset: &str) -> Option<i64> {
360 let b = offset.as_bytes();
361 if b.len() < 5 {
362 return None;
363 }
364 if !(b[0] == b'+' || b[0] == b'-') {
365 return None;
366 }
367 let sign = if b[0] == b'-' { -1i64 } else { 1i64 };
368 let hours: i64 = std::str::from_utf8(&b[1..3]).ok()?.parse().ok()?;
369 let minutes: i64 = std::str::from_utf8(&b[3..5]).ok()?.parse().ok()?;
370 Some(sign * (hours * 3600 + minutes * 60))
371}
372
373#[must_use]
375pub fn parse_signature_times(ident: &str) -> Option<ParsedSignatureTimes> {
376 match parse_signature_tail(ident)? {
377 SignatureTail::Valid(p) => Some(p),
378 SignatureTail::Overflow | SignatureTail::NonNumeric => None,
379 }
380}
381
382#[derive(Debug, Clone, PartialEq, Eq)]
384pub enum SignatureTail {
385 Valid(ParsedSignatureTimes),
387 Overflow,
390 NonNumeric,
392}
393
394#[must_use]
396pub fn parse_signature_tail(ident: &str) -> Option<SignatureTail> {
397 let bytes = ident.as_bytes();
398 let gt = ident.rfind('>')?;
399 let mut i = skip_fsck_date_leading_ws(bytes, gt + 1);
400 if i >= bytes.len() || !bytes[i].is_ascii_digit() {
401 return Some(SignatureTail::NonNumeric);
402 }
403 let (raw, after_digits) = scan_decimal_timestamp(bytes, i)?;
404 if after_digits >= bytes.len() || bytes[after_digits] != b' ' {
405 return None;
406 }
407 i = after_digits + 1;
408 if i + 5 > bytes.len() {
409 return None;
410 }
411 let tz_slice = ident.get(i..i + 5)?;
412 let tz_offset_secs = parse_tz_hhmm_offset(tz_slice)?;
413 let tz_hhmm_range = i..i + 5;
414 if raw == u128::MAX || raw > u64::MAX as u128 || date_overflows(raw as u64) {
415 return Some(SignatureTail::Overflow);
416 }
417 let unix_seconds = i64::try_from(raw).ok()?;
418 Some(SignatureTail::Valid(ParsedSignatureTimes {
419 unix_seconds,
420 tz_offset_secs,
421 tz_hhmm_range,
422 }))
423}
424
425#[must_use]
430pub fn parse_signature(ident: &str) -> Option<Signature> {
431 let ParsedSignatureTimes {
432 unix_seconds,
433 tz_offset_secs,
434 ..
435 } = match parse_signature_tail(ident)? {
436 SignatureTail::Valid(p) => p,
437 SignatureTail::Overflow | SignatureTail::NonNumeric => return None,
438 };
439 let (name, email) = parse_identity_name_email(ident)?;
440 let offset_secs = i32::try_from(tz_offset_secs).ok()?;
441 let offset = UtcOffset::from_whole_seconds(offset_secs).ok()?;
442 let utc = OffsetDateTime::from_unix_timestamp(unix_seconds).ok()?;
443 Some(Signature {
444 name,
445 email,
446 time: utc.to_offset(offset),
447 })
448}
449
450fn parse_identity_name_email(ident: &str) -> Option<(String, String)> {
451 let lt = ident.find('<')?;
452 let name = ident[..lt].trim_end().to_owned();
453 let rest = &ident[lt + 1..];
454 let gt = rest.find('>')?;
455 let email = rest[..gt].trim().to_owned();
456 Some((name, email))
457}
458
459pub fn signature_timestamp_for_pretty(ident: &str) -> SignatureTimestamp {
461 match parse_signature_times(ident) {
462 Some(p) => SignatureTimestamp::Valid(p.unix_seconds),
463 None => SignatureTimestamp::Sentinel,
464 }
465}
466
467#[must_use]
471pub fn committer_timestamp_for_until_filter(ident: &str) -> i64 {
472 match signature_timestamp_for_pretty(ident) {
473 SignatureTimestamp::Valid(ts) => ts,
474 SignatureTimestamp::Sentinel => 0,
475 }
476}
477
478#[must_use]
480pub fn timestamp_for_at_ct(ts: SignatureTimestamp) -> Option<i64> {
481 match ts {
482 SignatureTimestamp::Valid(v) => Some(v),
483 SignatureTimestamp::Sentinel => None,
484 }
485}
486
487pub fn fsck_commit_idents(
494 data: &[u8],
495 hash_algo: HashAlgo,
496) -> Result<(), crate::fsck_standalone::FsckError> {
497 crate::fsck_standalone::fsck_object(
498 ObjectKind::Commit,
499 data,
500 crate::fsck_standalone::FsckObjectOptions::new(hash_algo),
501 )
502}
503
504#[must_use]
506pub fn committer_unix_seconds_for_ordering(ident: &str) -> i64 {
507 match signature_timestamp_for_pretty(ident) {
508 SignatureTimestamp::Valid(ts) => ts,
509 SignatureTimestamp::Sentinel => 0,
510 }
511}
512
513#[must_use]
515pub fn committer_unix_seconds_for_ordering_bytes(ident: &[u8]) -> i64 {
516 let Ok(ident) = std::str::from_utf8(ident) else {
517 return 0;
518 };
519 committer_unix_seconds_for_ordering(ident)
520}
521
522#[must_use]
524pub fn committer_timestamp_for_until_filter_bytes(ident: &[u8]) -> i64 {
525 let Ok(ident) = std::str::from_utf8(ident) else {
526 return 0;
527 };
528 committer_timestamp_for_until_filter(ident)
529}
530
531#[derive(Debug, Clone, PartialEq, Eq)]
533pub struct AuthorContact {
534 pub name: String,
536 pub email: String,
538}
539
540impl AuthorContact {
541 pub fn signature(
554 &self,
555 date_override: Option<&str>,
556 now: OffsetDateTime,
557 ) -> Result<Signature, SignatureError> {
558 let line = author_identity_line(self, date_override, now);
559 let time = parse_signature(&line)
560 .ok_or(SignatureError::Malformed)?
561 .time;
562 Signature::new(self.name.clone(), self.email.clone(), time)
563 }
564}
565
566#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
568#[non_exhaustive]
569pub enum AuthorArgError {
570 #[error("invalid author: expected 'Name <email>' or a bare email address")]
572 InvalidFormat,
573 #[error("invalid author: empty email")]
575 EmptyEmail,
576 #[error("invalid author: trailing text after '>'")]
578 TrailingText,
579}
580
581pub fn parse_author_arg(raw: &str) -> Result<AuthorContact, AuthorArgError> {
587 let s = raw.trim();
588 if s.is_empty() {
589 return Err(AuthorArgError::InvalidFormat);
590 }
591 if s.contains('\n') || s.contains('\r') {
592 return Err(AuthorArgError::InvalidFormat);
593 }
594 if let Some(lt) = s.find('<') {
595 let rest = &s[lt + 1..];
596 let gt = rest.find('>').ok_or(AuthorArgError::InvalidFormat)?;
597 let email = &rest[..gt];
598 if email.is_empty() {
599 return Err(AuthorArgError::EmptyEmail);
600 }
601 let after = rest[gt + 1..].trim();
602 if !after.is_empty() {
603 return Err(AuthorArgError::TrailingText);
604 }
605 let name = s[..lt].trim_end_matches(|c: char| c.is_ascii_whitespace());
606 return Ok(AuthorContact {
607 name: name.to_owned(),
608 email: email.to_owned(),
609 });
610 }
611 if s.contains('@') && !s.chars().any(char::is_whitespace) {
612 return Ok(AuthorContact {
613 name: String::new(),
614 email: s.to_owned(),
615 });
616 }
617 Err(AuthorArgError::InvalidFormat)
618}
619
620#[must_use]
622pub fn author_identity_line(
623 contact: &AuthorContact,
624 date_override: Option<&str>,
625 now: OffsetDateTime,
626) -> String {
627 assemble_identity(&contact.name, &contact.email, date_override, now)
628}
629
630#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
632#[non_exhaustive]
633pub enum CommitIdentityError {
634 #[error("invalid identity: embedded control character")]
636 EmbeddedControl,
637 #[error("invalid identity: expected 'Name <email>', a bare email, or a full header line with timestamp")]
639 Unrecognized,
640 #[error(transparent)]
642 Author(#[from] AuthorArgError),
643}
644
645fn identity_contains_embedded_control(raw: &str) -> bool {
646 raw.bytes()
647 .any(|b| b == b'\n' || b == b'\r' || (b < 0x20 && b != b'\t'))
648}
649
650#[must_use]
652pub fn replace_identity_date_suffix(identity: &str, date_suffix: &str) -> String {
653 let suffix = date_suffix.trim();
654 if let Some((name, email)) = parse_identity_name_email(identity) {
655 if email.is_empty() && !name.is_empty() && name.contains('@') {
656 return format!("{} {suffix}", name.trim());
657 }
658 if email.is_empty() {
659 return format!("{} {suffix}", identity.trim_end());
660 }
661 return format!("{} <{email}> {suffix}", name);
662 }
663 format!("{} {suffix}", identity.trim_end())
664}
665
666pub fn prepare_commit_identity_line(
677 raw: &str,
678 date_override: Option<&str>,
679 now: OffsetDateTime,
680) -> Result<String, CommitIdentityError> {
681 if identity_contains_embedded_control(raw) {
682 return Err(CommitIdentityError::EmbeddedControl);
683 }
684 let trimmed = raw.trim();
685 if trimmed.is_empty() {
686 return Err(CommitIdentityError::Author(AuthorArgError::InvalidFormat));
687 }
688 if matches!(parse_signature_tail(trimmed), Some(SignatureTail::Valid(_))) {
689 let line = trimmed.to_owned();
690 return Ok(match date_override {
691 Some(suffix) => replace_identity_date_suffix(&line, suffix),
692 None => line,
693 });
694 }
695 if let Some(suffix) = date_override {
696 if parse_identity_name_email(trimmed).is_some() {
697 return Ok(replace_identity_date_suffix(trimmed, suffix));
698 }
699 }
700 let contact = parse_author_arg(trimmed)?;
701 Ok(author_identity_line(&contact, date_override, now))
702}
703
704pub(crate) fn prepare_commit_author_from_parent(
707 parent_author: &str,
708 parent_author_raw: &[u8],
709 author_date: Option<&str>,
710 now: OffsetDateTime,
711) -> Result<(String, Vec<u8>), CommitIdentityError> {
712 if let Some(suffix) = author_date {
713 if identity_contains_embedded_control(parent_author) {
714 return Err(CommitIdentityError::EmbeddedControl);
715 }
716 let trimmed = parent_author.trim();
717 if trimmed.is_empty() {
718 return Err(CommitIdentityError::Author(AuthorArgError::InvalidFormat));
719 }
720 return Ok((replace_identity_date_suffix(trimmed, suffix), Vec::new()));
721 }
722 if !parent_author_raw.is_empty() {
723 return Ok((parent_author.to_owned(), parent_author_raw.to_vec()));
724 }
725 Ok((
726 prepare_commit_identity_line(parent_author, None, now)?,
727 Vec::new(),
728 ))
729}
730
731#[cfg(test)]
732mod tests {
733 use super::*;
734
735 #[test]
736 fn cleaned_signatures_are_one_valid_line() {
737 let time = OffsetDateTime::from_unix_timestamp(1_700_000_000)
738 .unwrap_or(OffsetDateTime::UNIX_EPOCH);
739 for (name, email, line) in [
740 (
741 "Ada Lovelace",
742 "ada@example.com",
743 "Ada Lovelace <ada@example.com>",
744 ),
745 (
746 "Eve\nencoding bogus",
747 "e>v<e@x",
748 "Eveencoding bogus <eve@x>",
749 ),
750 (" \"Bob\", ", "<bob@example.com>.", "Bob <bob@example.com>"),
751 ("Tab\there\r\n", "\u{7f}x@y", "Tab\there <x@y>"),
752 ("<>", "", " <>"),
753 ] {
754 let sig = Signature::cleaned(name, email, time);
755 let sig = sig.unwrap_or_else(|e| panic!("{name:?}: {e}"));
756 assert_eq!(
757 sig.header_line(),
758 format!("{line} 1700000000 +0000"),
759 "{name:?}"
760 );
761 assert!(sig.validate().is_ok());
762 assert!(!sig.header_line().contains('\n'));
763 }
764 let before = OffsetDateTime::from_unix_timestamp(-1).unwrap_or(OffsetDateTime::UNIX_EPOCH);
765 assert_eq!(
766 Signature::cleaned("A", "a@x", before),
767 Err(SignatureError::BeforeEpoch)
768 );
769 }
770
771 #[test]
772 fn non_numeric_author_date_is_non_numeric_tail() {
773 let ident = "A <e@x> totally_bogus -0700";
774 assert!(matches!(
775 parse_signature_tail(ident),
776 Some(SignatureTail::NonNumeric)
777 ));
778 }
779
780 #[test]
781 fn u128_max_digit_count_is_overflow_tail() {
782 let ident = "A <e@x> 18446744073709551617 -0700";
783 assert!(matches!(
784 parse_signature_tail(ident),
785 Some(SignatureTail::Overflow)
786 ));
787 }
788
789 #[test]
790 fn parse_author_arg_name_and_email() {
791 let c = parse_author_arg("A U Thor <author@example.com>").expect("parse");
792 assert_eq!(c.name, "A U Thor");
793 assert_eq!(c.email, "author@example.com");
794 }
795
796 #[test]
797 fn parse_author_arg_bare_email() {
798 let c = parse_author_arg("nobody@example.com").expect("parse");
799 assert!(c.name.is_empty());
800 assert_eq!(c.email, "nobody@example.com");
801 }
802
803 #[test]
804 fn parse_author_arg_rejects_empty_email_in_brackets() {
805 assert_eq!(parse_author_arg("Name <>"), Err(AuthorArgError::EmptyEmail));
806 }
807
808 #[test]
809 fn parse_author_arg_rejects_trailing_garbage() {
810 assert_eq!(
811 parse_author_arg("A <a@b.com> extra"),
812 Err(AuthorArgError::TrailingText)
813 );
814 }
815
816 #[test]
817 fn parse_author_arg_rejects_embedded_newline() {
818 assert_eq!(
819 parse_author_arg("Bad\nInjected <x@y.example>"),
820 Err(AuthorArgError::InvalidFormat)
821 );
822 }
823
824 #[test]
825 fn parse_signature_preserves_positive_offset() {
826 let ident = "Ada Lovelace <ada@example.com> 1700000000 +0530";
827 let sig = parse_signature(ident).expect("parse");
828 assert_eq!(sig.name, "Ada Lovelace");
829 assert_eq!(sig.email, "ada@example.com");
830 assert_eq!(
831 sig.format_rfc3339().as_deref(),
832 Some("2023-11-15T03:43:20+05:30")
833 );
834 }
835
836 #[test]
837 fn parse_signature_preserves_negative_offset() {
838 let ident = "Ada Lovelace <ada@example.com> 1700000000 -0800";
839 let sig = parse_signature(ident).expect("parse");
840 assert_eq!(
841 sig.format_rfc3339().as_deref(),
842 Some("2023-11-14T14:13:20-08:00")
843 );
844 }
845
846 #[test]
847 fn signature_from_str_round_trips_header_line() {
848 let line = "Ada Lovelace <ada@example.com> 1700000000 +0530";
849 let sig: Signature = line.parse().expect("parse");
850 assert_eq!(sig.name, "Ada Lovelace");
851 assert_eq!(sig.header_line(), line);
852 }
853
854 #[test]
855 fn signature_from_str_rejects_contact_and_injected_lines() {
856 for line in [
857 "Ada <ada@example.com>",
858 "A <a@b> <c@d> 1 +0000",
859 "Name <a@b>\nInjected: x 1 +0000",
860 "A <e@x> totally_bogus -0700",
861 "A <a@b> 1 +0000 trailing",
862 "A <a@b> 1 +00000",
863 ] {
864 assert_eq!(
865 line.parse::<Signature>(),
866 Err(SignatureError::Malformed),
867 "{line:?}"
868 );
869 }
870 assert!(matches!(
871 "Bad\u{1} <a@b> 1 +0000".parse::<Signature>(),
872 Err(SignatureError::ForbiddenCharacter { .. })
873 ));
874 }
875
876 #[test]
877 fn author_contact_signature_applies_date_override() {
878 let now = OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("epoch");
879 let contact = parse_author_arg("Doc <doc@example.com>").expect("contact");
880 assert_eq!(
881 contact.signature(None, now).expect("now").header_line(),
882 "Doc <doc@example.com> 1700000000 +0000"
883 );
884 assert_eq!(
885 contact
886 .signature(Some("1234567890 -0800"), now)
887 .expect("override")
888 .header_line(),
889 "Doc <doc@example.com> 1234567890 -0800"
890 );
891 assert_eq!(
892 contact.signature(Some("not a date"), now),
893 Err(SignatureError::Malformed)
894 );
895 }
896
897 #[test]
898 fn parse_signature_malformed_identity_is_none() {
899 assert!(parse_signature("A <e@x> totally_bogus -0700").is_none());
900 assert!(parse_signature("not an identity").is_none());
901 }
902
903 #[test]
904 fn prepare_commit_identity_line_expands_contact_form() {
905 let now = OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("epoch");
906 let line =
907 prepare_commit_identity_line("Doc <doc@example.com>", None, now).expect("prepare");
908 assert!(parse_signature(&line).is_some(), "full line: {line}");
909 }
910
911 #[test]
912 fn prepare_commit_identity_line_accepts_full_header() {
913 let ident = "Ada Lovelace <ada@example.com> 1700000000 +0530";
914 let now = OffsetDateTime::from_unix_timestamp(1).expect("epoch");
915 let line = prepare_commit_identity_line(ident, None, now).expect("prepare");
916 assert_eq!(line, ident);
917 }
918
919 #[test]
920 fn prepare_commit_identity_line_rejects_embedded_newline() {
921 let now = OffsetDateTime::from_unix_timestamp(1).expect("epoch");
922 assert_eq!(
923 prepare_commit_identity_line("Name <a@b>\nInjected", None, now),
924 Err(CommitIdentityError::EmbeddedControl)
925 );
926 }
927
928 #[test]
929 fn prepare_commit_identity_line_rejects_bare_name_without_email() {
930 let now = OffsetDateTime::from_unix_timestamp(1).expect("epoch");
931 assert!(matches!(
932 prepare_commit_identity_line("no email here", None, now),
933 Err(CommitIdentityError::Author(AuthorArgError::InvalidFormat))
934 ));
935 }
936
937 #[test]
938 fn prepare_commit_identity_line_date_override_rewrites_non_numeric_tail() {
939 let ident = "A U Thor <author@example.com> totally_bogus -0700";
940 let now = OffsetDateTime::from_unix_timestamp(1).expect("epoch");
941 let line =
942 prepare_commit_identity_line(ident, Some("946684800 +0000"), now).expect("override");
943 assert_eq!(line, "A U Thor <author@example.com> 946684800 +0000");
944 assert!(parse_signature(&line).is_some());
945 }
946
947 #[test]
948 fn prepare_commit_author_from_parent_date_override_rewrites_non_numeric_tail() {
949 let parent = "A U Thor <author@example.com> totally_bogus -0700";
950 let now = OffsetDateTime::from_unix_timestamp(1).expect("epoch");
951 let (line, raw) = prepare_commit_author_from_parent(
952 parent,
953 parent.as_bytes(),
954 Some("946684800 +0000"),
955 now,
956 )
957 .expect("override");
958 assert!(raw.is_empty());
959 assert_eq!(line, "A U Thor <author@example.com> 946684800 +0000");
960 }
961}