git-cliff-core 2.14.2

Core library of git-cliff
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
use std::sync::LazyLock;

use git_conventional::{Commit as ConventionalCommit, Footer as ConventionalFooter};
#[cfg(feature = "repo")]
use git2::{Commit as GitCommit, Signature as CommitSignature};
use regex::Regex;
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::value::Value;

use crate::config::{CommitParser, GitConfig, LinkParser, TextProcessor};
use crate::error::{Error as AppError, Result};

/// Regular expression for matching SHA1 and a following commit message
/// separated by a whitespace.
//static SHA1_REGEX: Lazy<Regex> = lazy_regex!(r#"^\b([a-f0-9]{40})\b (.*)$"#);
static SHA1_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\b([a-f0-9]{40})\b (.*)$").expect("valid SHA1 regex"));

/// Object representing a link
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all(serialize = "camelCase"))]
pub struct Link {
    /// Text of the link.
    pub text: String,
    /// URL of the link
    pub href: String,
}

/// A conventional commit footer.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
struct Footer<'a> {
    /// Token of the footer.
    ///
    /// This is the part of the footer preceding the separator. For example, for
    /// the `Signed-off-by: <user.name>` footer, this would be `Signed-off-by`.
    token: &'a str,
    /// The separator between the footer token and its value.
    ///
    /// This is typically either `:` or `#`.
    separator: &'a str,
    /// The value of the footer.
    value: &'a str,
    /// A flag to signal that the footer describes a breaking change.
    breaking: bool,
}

impl<'a> From<&'a ConventionalFooter<'a>> for Footer<'a> {
    fn from(footer: &'a ConventionalFooter<'a>) -> Self {
        Self {
            token: footer.token().as_str(),
            separator: footer.separator().as_str(),
            value: footer.value(),
            breaking: footer.breaking(),
        }
    }
}

/// Commit signature that indicates authorship.
#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct Signature {
    /// Name on the signature.
    pub name: Option<String>,
    /// Email on the signature.
    pub email: Option<String>,
    /// Time of the signature.
    pub timestamp: i64,
}

#[cfg(feature = "repo")]
impl<'a> From<CommitSignature<'a>> for Signature {
    fn from(signature: CommitSignature<'a>) -> Self {
        Self {
            name: signature.name().ok().map(String::from),
            email: signature.email().ok().map(String::from),
            timestamp: signature.when().seconds(),
        }
    }
}

/// Statistics about the changes in a single commit.
#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct CommitStatistics {
    /// Total number of files changed in the commit.
    pub files_changed: usize,
    /// Total number of inserted lines in the commit.
    pub additions: usize,
    /// Total number of deleted lines in the commit.
    pub deletions: usize,
}

/// Commit range (from..to)
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Range {
    /// Full commit SHA the range starts at
    from: String,
    /// Full commit SHA the range ends at
    to: String,
}

impl Range {
    /// Creates a new [`Range`] from [`crate::commit::Commit`].
    #[must_use]
    pub fn new(from: &Commit, to: &Commit) -> Self {
        Self {
            from: from.id.clone(),
            to: to.id.clone(),
        }
    }
}

/// Common commit object that is parsed from a repository.
#[derive(Debug, Default, Clone, PartialEq, Deserialize)]
#[serde(rename_all(serialize = "camelCase"))]
pub struct Commit<'a> {
    /// Commit ID.
    pub id: String,
    /// Commit message including title, description and summary.
    pub message: String,
    /// Conventional commit.
    #[serde(skip_deserializing)]
    pub conv: Option<ConventionalCommit<'a>>,
    /// Commit group based on a commit parser or its conventional type.
    pub group: Option<String>,
    /// Default commit scope based on (inherited from) conventional type or a
    /// commit parser.
    pub default_scope: Option<String>,
    /// Commit scope for overriding the default one.
    pub scope: Option<String>,
    /// A list of links found in the commit
    pub links: Vec<Link>,
    /// Commit author.
    pub author: Signature,
    /// Committer.
    pub committer: Signature,
    /// Whether if the commit has two or more parents.
    pub merge_commit: bool,
    /// Per-commit diff statistics exposed to the template context.
    #[serde(default)]
    pub statistics: CommitStatistics,
    /// Arbitrary data to be used with the `--from-context` CLI option.
    pub extra: Option<Value>,
    /// Remote metadata of the commit.
    pub remote: Option<crate::contributor::RemoteContributor>,
    /// GitHub metadata of the commit.
    #[cfg(feature = "github")]
    #[deprecated(note = "Use `remote` field instead")]
    pub github: crate::contributor::RemoteContributor,
    /// GitLab metadata of the commit.
    #[cfg(feature = "gitlab")]
    #[deprecated(note = "Use `remote` field instead")]
    pub gitlab: crate::contributor::RemoteContributor,
    /// Gitea metadata of the commit.
    #[cfg(feature = "gitea")]
    #[deprecated(note = "Use `remote` field instead")]
    pub gitea: crate::contributor::RemoteContributor,
    /// Bitbucket metadata of the commit.
    #[cfg(feature = "bitbucket")]
    #[deprecated(note = "Use `remote` field instead")]
    pub bitbucket: crate::contributor::RemoteContributor,
    /// Azure DevOps metadata of the commit.
    #[cfg(feature = "azure_devops")]
    #[deprecated(note = "Use `remote` field instead")]
    pub azure_devops: crate::contributor::RemoteContributor,

    /// Raw message of the normal commit, works as a placeholder for converting
    /// normal commit into conventional commit.
    ///
    /// Despite the name, it is not actually a raw message.
    /// In fact, it is pre-processed by [`Commit::preprocess`], and only be
    /// generated when serializing into `context` the first time.
    pub raw_message: Option<String>,
}

impl From<String> for Commit<'_> {
    fn from(message: String) -> Self {
        if let Some(captures) = SHA1_REGEX.captures(&message) &&
            let (Some(id), Some(message)) = (
                captures.get(1).map(|v| v.as_str()),
                captures.get(2).map(|v| v.as_str()),
            )
        {
            return Commit {
                id: id.to_string(),
                message: message.to_string(),
                ..Default::default()
            };
        }
        Commit {
            id: String::new(),
            message,
            ..Default::default()
        }
    }
}

#[cfg(feature = "repo")]
impl From<&GitCommit<'_>> for Commit<'_> {
    fn from(commit: &GitCommit<'_>) -> Self {
        Commit {
            id: commit.id().to_string(),
            message: commit.message().unwrap_or_default().trim_end().to_string(),
            author: commit.author().into(),
            committer: commit.committer().into(),
            merge_commit: commit.parent_count() > 1,
            ..Default::default()
        }
    }
}

impl Commit<'_> {
    /// Constructs a new instance.
    #[must_use]
    pub fn new(id: String, message: String) -> Self {
        Self {
            id,
            message,
            ..Default::default()
        }
    }

    /// Get raw message for converting into conventional commit.
    #[must_use]
    pub fn raw_message(&self) -> &str {
        self.raw_message.as_deref().unwrap_or(&self.message)
    }

    /// Processes the commit.
    ///
    /// * converts commit to a conventional commit
    /// * sets the group for the commit
    /// * extracts links and generates URLs
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip_all,
            fields(id = self.id)
        )
    )]
    pub fn process(&self, config: &GitConfig) -> Result<Self> {
        crate::set_progress_message!(
            "Converting the commit to conventional format, setting its group, and extracting links"
        );
        let mut commit = self.clone();
        commit = commit.preprocess(&config.commit_preprocessors)?;
        if config.conventional_commits {
            if !config.require_conventional && config.filter_unconventional && !config.split_commits
            {
                commit = commit.into_conventional()?;
            } else if let Ok(conv_commit) = commit.clone().into_conventional() {
                commit = conv_commit;
            }
        }

        commit = commit.parse(
            &config.commit_parsers,
            config.protect_breaking_commits,
            config.filter_commits,
        )?;

        commit = commit.parse_links(&config.link_parsers);

        Ok(commit)
    }

    /// Returns the commit with its conventional type set.
    pub fn into_conventional(mut self) -> Result<Self> {
        match ConventionalCommit::parse(Box::leak(self.raw_message().to_string().into_boxed_str()))
        {
            Ok(conv) => {
                self.conv = Some(conv);
                Ok(self)
            }
            Err(e) => Err(AppError::ParseError(e)),
        }
    }

    /// Preprocesses the commit using [`TextProcessor`]s.
    ///
    /// Modifies the commit [`message`] using regex or custom OS command.
    ///
    /// [`message`]: Commit::message
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip_all,
            fields(id = self.id)
        )
    )]
    pub fn preprocess(mut self, preprocessors: &[TextProcessor]) -> Result<Self> {
        crate::set_progress_message!("Preprocessing the commit message using text processors");
        preprocessors.iter().try_for_each(|preprocessor| {
            preprocessor.replace(&mut self.message, vec![("COMMIT_SHA", &self.id)])?;
            Ok::<(), AppError>(())
        })?;
        Ok(self)
    }

    /// States if the commit is skipped in the provided `CommitParser`.
    ///
    /// Returns `false` if `protect_breaking_commits` is enabled in the config
    /// and the commit is breaking, or the parser's `skip` field is None or
    /// `false`. Returns `true` otherwise.
    fn skip_commit(&self, parser: &CommitParser, protect_breaking: bool) -> bool {
        parser.skip.unwrap_or(false) &&
            !(self.conv.as_ref().is_some_and(ConventionalCommit::breaking) && protect_breaking)
    }

    /// Parses the commit using [`CommitParser`]s.
    ///
    /// Sets the [`group`] and [`scope`] of the commit.
    ///
    /// [`group`]: Commit::group
    /// [`scope`]: Commit::scope
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip_all,
            fields(id = self.id)
        )
    )]
    pub fn parse(
        mut self,
        parsers: &[CommitParser],
        protect_breaking: bool,
        filter: bool,
    ) -> Result<Self> {
        crate::set_progress_message!("Parsing the commit and setting its group and scope");
        let lookup_context = serde_json::to_value(&self).map_err(|e| {
            AppError::FieldError(format!("failed to convert context into value: {e}",))
        })?;
        // Set when a `continue` parser matches, so the commit isn't filtered out
        // at the end even though no parser returned early.
        let mut matched = false;
        'parsers: for parser in parsers {
            if let Some(sha) = parser.sha.as_ref() &&
                sha.to_lowercase() != self.id
            {
                continue 'parsers;
            }
            let mut regex_checks = Vec::new();
            if let Some(message_regex) = parser.message.as_ref() {
                if !message_regex.is_match(self.message.trim()) {
                    continue 'parsers;
                }
                regex_checks.push((message_regex, self.message.clone()));
            }
            let body = self
                .conv
                .as_ref()
                .and_then(ConventionalCommit::body)
                .map(ToString::to_string);
            if let Some(body_regex) = parser.body.as_ref() {
                let body_text = body.clone().unwrap_or_default();
                if !body_regex.is_match(body_text.trim()) {
                    continue 'parsers;
                }
                regex_checks.push((body_regex, body_text));
            }
            if let Some(footer_regex) = parser.footer.as_ref() {
                let Some(footers) = self.conv.as_ref().map(ConventionalCommit::footers) else {
                    continue 'parsers;
                };
                let Some(matched_footer) = footers
                    .iter()
                    .map(ToString::to_string)
                    .find(|f| footer_regex.is_match(f.trim()))
                else {
                    continue 'parsers;
                };
                regex_checks.push((footer_regex, matched_footer));
            }
            if let (Some(field_name), Some(pattern_regex)) =
                (parser.field.as_ref(), parser.pattern.as_ref())
            {
                let values = if field_name == "body" {
                    vec![body.clone()].into_iter().collect()
                } else {
                    let Some(field_value) = tera::dotted_pointer(&lookup_context, field_name)
                    else {
                        tracing::trace!("Field '{field_name}' is absent; trying the next parser");
                        continue 'parsers;
                    };
                    match field_value {
                        Value::String(s) => Some(vec![s.clone()]),
                        Value::Number(_) | Value::Bool(_) | Value::Null => {
                            Some(vec![field_value.to_string()])
                        }
                        Value::Array(arr) => {
                            let mut values = Vec::new();
                            for item in arr {
                                match item {
                                    Value::String(s) => values.push(s.clone()),
                                    Value::Number(_) | Value::Bool(_) | Value::Null => {
                                        values.push(item.to_string());
                                    }
                                    _ => {}
                                }
                            }
                            Some(values)
                        }
                        Value::Object(_) => None,
                    }
                };
                match values {
                    Some(values) => {
                        if values.is_empty() {
                            tracing::trace!("Field '{field_name}' is present but empty");
                        }
                        let Some(matched_value) = values
                            .into_iter()
                            .find(|v| pattern_regex.is_match(v.trim()))
                        else {
                            continue 'parsers;
                        };
                        regex_checks.push((pattern_regex, matched_value));
                    }
                    None => {
                        return Err(AppError::FieldError(format!(
                            "field '{field_name}' is missing or has unsupported type (expected a \
                             String, Number, Bool, or Null — or an Array of these scalar values)",
                        )));
                    }
                }
            }
            if regex_checks.is_empty() {
                if parser.sha.is_none() {
                    continue 'parsers;
                }
                if self.skip_commit(parser, protect_breaking) {
                    return Err(AppError::GroupError(String::from("Skipping commit")));
                } else {
                    self.group = parser.group.clone().or(self.group);
                    self.scope = parser.scope.clone().or(self.scope);
                    self.default_scope = parser.default_scope.clone().or(self.default_scope);
                    if parser.r#continue.unwrap_or(false) {
                        matched = true;
                        continue;
                    }
                    return Ok(self);
                }
            } else if self.skip_commit(parser, protect_breaking) {
                return Err(AppError::GroupError(String::from("Skipping commit")));
            } else {
                let regex_replace = |mut value: String| {
                    for (regex, text) in &regex_checks {
                        for mat in regex.find_iter(text) {
                            value = regex.replace(mat.as_str(), value).to_string();
                        }
                    }
                    value
                };
                if parser.r#continue.unwrap_or(false) {
                    // Only override the fields this parser sets, so later
                    // parsers can fill in the rest.
                    if let Some(group) = parser.group.clone() {
                        self.group = Some(regex_replace(group));
                    }
                    if let Some(scope) = parser.scope.clone() {
                        self.scope = Some(regex_replace(scope));
                    }
                    if parser.default_scope.is_some() {
                        self.default_scope.clone_from(&parser.default_scope);
                    }
                    matched = true;
                    continue 'parsers;
                }
                if matched {
                    // Preserve fields contributed by preceding parsers.
                    self.group = parser.group.clone().map(regex_replace).or(self.group);
                    self.scope = parser.scope.clone().map(regex_replace).or(self.scope);
                    if parser.default_scope.is_some() {
                        self.default_scope.clone_from(&parser.default_scope);
                    }
                } else {
                    // Keep the original first-match-wins behavior when
                    // no preceding parser continued.
                    self.group = parser.group.clone().map(regex_replace);
                    self.scope = parser.scope.clone().map(regex_replace);
                    self.default_scope.clone_from(&parser.default_scope);
                }
                return Ok(self);
            }
        }
        if filter && !matched {
            Err(AppError::GroupError(String::from(
                "Commit does not belong to any group",
            )))
        } else {
            Ok(self)
        }
    }

    /// Parses the commit using [`LinkParser`]s.
    ///
    /// Sets the [`links`] of the commit.
    ///
    /// [`links`]: Commit::links
    #[must_use]
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip_all,
            fields(id = self.id)
        )
    )]
    pub fn parse_links(mut self, parsers: &[LinkParser]) -> Self {
        crate::set_progress_message!("Parsing links for the commit using link parsers");
        for parser in parsers {
            let regex = &parser.pattern;
            let replace = &parser.href;
            for mat in regex.find_iter(&self.message) {
                let m = mat.as_str();
                let text = if let Some(text_replace) = &parser.text {
                    regex.replace(m, text_replace).to_string()
                } else {
                    m.to_string()
                };
                let href = regex.replace(m, replace);
                self.links.push(Link {
                    text,
                    href: href.to_string(),
                });
            }
        }
        self
    }

    /// Returns an iterator over this commit's [`Footer`]s, if this is a
    /// conventional commit.
    ///
    /// If this commit is not conventional, the returned iterator will be empty.
    fn footers(&self) -> impl Iterator<Item = Footer<'_>> {
        self.conv
            .iter()
            .flat_map(|conv| conv.footers().iter().map(Footer::from))
    }
}

impl Serialize for Commit<'_> {
    #[allow(deprecated)]
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        /// A wrapper to serialize commit footers from an iterator using
        /// `Serializer::collect_seq` without having to allocate in order to
        /// `collect` the footers  into a new to `Vec`.
        struct SerializeFooters<'a>(&'a Commit<'a>);
        impl Serialize for SerializeFooters<'_> {
            fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                serializer.collect_seq(self.0.footers())
            }
        }

        let mut commit = serializer.serialize_struct("Commit", 21)?;
        commit.serialize_field("id", &self.id)?;
        if let Some(conv) = &self.conv {
            commit.serialize_field("message", conv.description())?;
            commit.serialize_field("body", &conv.body())?;
            commit.serialize_field("footers", &SerializeFooters(self))?;
            commit.serialize_field(
                "group",
                self.group.as_ref().unwrap_or(&conv.type_().to_string()),
            )?;
            commit.serialize_field("breaking_description", &conv.breaking_description())?;
            commit.serialize_field("breaking", &conv.breaking())?;
            commit.serialize_field(
                "scope",
                &self
                    .scope
                    .as_deref()
                    .or_else(|| conv.scope().map(|v| v.as_str()))
                    .or(self.default_scope.as_deref()),
            )?;
        } else {
            commit.serialize_field("message", &self.message)?;
            commit.serialize_field("group", &self.group)?;
            commit.serialize_field(
                "scope",
                &self.scope.as_deref().or(self.default_scope.as_deref()),
            )?;
        }

        commit.serialize_field("links", &self.links)?;
        commit.serialize_field("author", &self.author)?;
        commit.serialize_field("committer", &self.committer)?;
        commit.serialize_field("conventional", &self.conv.is_some())?;
        commit.serialize_field("merge_commit", &self.merge_commit)?;
        commit.serialize_field("statistics", &self.statistics)?;
        commit.serialize_field("extra", &self.extra)?;
        #[cfg(feature = "github")]
        commit.serialize_field("github", &self.github)?;
        #[cfg(feature = "gitlab")]
        commit.serialize_field("gitlab", &self.gitlab)?;
        #[cfg(feature = "gitea")]
        commit.serialize_field("gitea", &self.gitea)?;
        #[cfg(feature = "bitbucket")]
        commit.serialize_field("bitbucket", &self.bitbucket)?;
        #[cfg(feature = "azure_devops")]
        commit.serialize_field("azure_devops", &self.azure_devops)?;
        if let Some(remote) = &self.remote {
            commit.serialize_field("remote", remote)?;
        }
        commit.serialize_field("raw_message", &self.raw_message())?;
        commit.end()
    }
}

/// Deserialize commits into conventional commits if they are convertible.
///
/// Serialized commits cannot be deserialized into commits that have
/// [`Commit::conv`]. Thus, we need to manually convert them using
/// [`Commit::into_conventional`].
///
/// This function is to be used only in [`crate::release::Release::commits`].
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub(crate) fn commits_to_conventional_commits<'de, 'a, D: Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<Vec<Commit<'a>>, D::Error> {
    crate::set_progress_message!("Converting commits to conventional commits");
    let commits = Vec::<Commit<'a>>::deserialize(deserializer)?;
    let commits = commits
        .into_iter()
        .map(|commit| commit.clone().into_conventional().unwrap_or(commit))
        .collect();
    Ok(commits)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn conventional_commit() -> Result<()> {
        let test_cases = vec![
            (
                Commit::new(
                    String::from("123123"),
                    String::from("test(commit): add test"),
                ),
                true,
            ),
            (
                Commit::new(String::from("124124"), String::from("xyz")),
                false,
            ),
        ];

        for (commit, is_conventional) in &test_cases {
            assert_eq!(is_conventional, &commit.clone().into_conventional().is_ok());
        }

        let commit = test_cases[0].0.clone().parse(
            &[CommitParser {
                sha: None,
                message: Regex::new("test*").ok(),
                body: None,
                footer: None,
                group: Some(String::from("test_group")),
                default_scope: Some(String::from("test_scope")),
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("test_group")), commit.group);
        assert_eq!(Some(String::from("test_scope")), commit.default_scope);

        Ok(())
    }

    #[test]
    fn conventional_footers() {
        let cfg = crate::config::GitConfig {
            conventional_commits: true,
            ..Default::default()
        };
        let test_cases = vec![
            (
                Commit::new(
                    String::from("123123"),
                    String::from(
                        "test(commit): add test\n\nSigned-off-by: Test User <test@example.com>",
                    ),
                ),
                vec![Footer {
                    token: "Signed-off-by",
                    separator: ":",
                    value: "Test User <test@example.com>",
                    breaking: false,
                }],
            ),
            (
                Commit::new(
                    String::from("123124"),
                    String::from(
                        "fix(commit): break stuff\n\nBREAKING CHANGE: This commit breaks \
                         stuff\nSigned-off-by: Test User <test@example.com>",
                    ),
                ),
                vec![
                    Footer {
                        token: "BREAKING CHANGE",
                        separator: ":",
                        value: "This commit breaks stuff",
                        breaking: true,
                    },
                    Footer {
                        token: "Signed-off-by",
                        separator: ":",
                        value: "Test User <test@example.com>",
                        breaking: false,
                    },
                ],
            ),
        ];

        for (commit, footers) in &test_cases {
            let commit = commit.process(&cfg).expect("commit should process");
            assert_eq!(&commit.footers().collect::<Vec<_>>(), footers);
        }
    }

    #[test]
    fn parse_link() -> Result<()> {
        let test_cases = vec![
            (
                Commit::new(
                    String::from("123123"),
                    String::from("test(commit): add test\n\nBody with issue #123"),
                ),
                true,
            ),
            (
                Commit::new(
                    String::from("123123"),
                    String::from("test(commit): add test\n\nImlement RFC456\n\nFixes: #456"),
                ),
                true,
            ),
        ];

        for (commit, is_conventional) in &test_cases {
            assert_eq!(is_conventional, &commit.clone().into_conventional().is_ok());
        }

        let commit = Commit::new(
            String::from("123123"),
            String::from("test(commit): add test\n\nImlement RFC456\n\nFixes: #455"),
        );

        let commit = commit.parse_links(&[
            LinkParser {
                pattern: Regex::new("RFC(\\d+)")?,
                href: String::from("rfc://$1"),
                text: None,
            },
            LinkParser {
                pattern: Regex::new("#(\\d+)")?,
                href: String::from("https://github.com/$1"),
                text: None,
            },
        ]);
        assert_eq!(
            vec![
                Link {
                    text: String::from("RFC456"),
                    href: String::from("rfc://456"),
                },
                Link {
                    text: String::from("#455"),
                    href: String::from("https://github.com/455"),
                }
            ],
            commit.links
        );

        Ok(())
    }

    #[test]
    fn parse_commit() {
        assert_eq!(
            Commit::new(String::new(), String::from("test: no sha1 given")),
            Commit::from(String::from("test: no sha1 given"))
        );

        assert_eq!(
            Commit::new(
                String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6"),
                String::from("feat: do something")
            ),
            Commit::from(String::from(
                "8f55e69eba6e6ce811ace32bd84cc82215673cb6 feat: do something"
            ))
        );

        assert_eq!(
            Commit::new(
                String::from("3bdd0e690c4cd5bd00e5201cc8ef3ce3fb235853"),
                String::from("chore: do something")
            ),
            Commit::from(String::from(
                "3bdd0e690c4cd5bd00e5201cc8ef3ce3fb235853 chore: do something"
            ))
        );

        assert_eq!(
            Commit::new(
                String::new(),
                String::from("thisisinvalidsha1 style: add formatting")
            ),
            Commit::from(String::from("thisisinvalidsha1 style: add formatting"))
        );
    }

    #[test]
    fn parse_body() -> Result<()> {
        let mut commit = Commit::new(
            String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6"),
            String::from(
                "fix: do something

Introduce something great

BREAKING CHANGE: drop support for something else
Refs: #123
",
            ),
        );
        commit.author = Signature {
            name: Some("John Doe".to_string()),
            email: None,
            timestamp: 0x0,
        };
        commit.remote = Some(crate::contributor::RemoteContributor {
            username: None,
            pr_author: None,
            pr_title: Some("feat: do something".to_string()),
            pr_number: None,
            pr_numbers: vec![],
            pr_labels: vec![String::from("feature"), String::from("deprecation")],
            is_first_time: true,
        });
        let commit = commit.into_conventional()?;
        let commit = commit.parse_links(&[
            LinkParser {
                pattern: Regex::new("RFC(\\d+)")?,
                href: String::from("rfc://$1"),
                text: None,
            },
            LinkParser {
                pattern: Regex::new("#(\\d+)")?,
                href: String::from("https://github.com/$1"),
                text: None,
            },
        ]);

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: Regex::new("something great").ok(),
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("Test group")), parsed_commit.group);

        Ok(())
    }

    #[test]
    fn parse_commit_field() -> Result<()> {
        let mut commit = Commit::new(
            String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6"),
            String::from(
                "fix: do something

Introduce something great

BREAKING CHANGE: drop support for something else
Refs: #123
",
            ),
        );
        commit.author = Signature {
            name: Some("John Doe".to_string()),
            email: None,
            timestamp: 0x0,
        };
        commit.remote = Some(crate::contributor::RemoteContributor {
            username: None,
            pr_author: None,
            pr_title: Some("feat: do something".to_string()),
            pr_number: None,
            pr_numbers: vec![],
            pr_labels: vec![String::from("feature"), String::from("deprecation")],
            is_first_time: true,
        });
        let commit = commit.into_conventional()?;
        let commit = commit.parse_links(&[
            LinkParser {
                pattern: Regex::new("RFC(\\d+)")?,
                href: String::from("rfc://$1"),
                text: None,
            },
            LinkParser {
                pattern: Regex::new("#(\\d+)")?,
                href: String::from("https://github.com/$1"),
                text: None,
            },
        ]);

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("author.name")),
                pattern: Regex::new("John Doe").ok(),
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("Test group")), parsed_commit.group);

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("remote.pr_title")),
                pattern: Regex::new("feat: do something").ok(),
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("Test group")), parsed_commit.group);

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("body")),
                pattern: Regex::new("something great").ok(),
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("Test group")), parsed_commit.group);

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("remote.pr_labels")),
                pattern: Regex::new("feature|deprecation").ok(),
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("Test group")), parsed_commit.group);

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("links")),
                pattern: Regex::new(".*").ok(),
            }],
            false,
            false,
        )?;
        assert_eq!(None, parsed_commit.group);

        let parse_result = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("remote")),
                pattern: Regex::new(".*").ok(),
            }],
            false,
            false,
        );
        assert!(
            parse_result.is_err(),
            "Expected error when using unsupported field `remote`, but got Ok"
        );

        Ok(())
    }

    #[test]
    fn parse_commit_multiple_parsers() -> Result<()> {
        let commit = Commit::new(
            String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6"),
            String::from("feat(deep): support multiple parsers"),
        );
        let commit = commit.into_conventional()?;

        // Without `continue`, the first matching parser wins and short-circuits:
        // the scope-only parser matches, so the group from the later parser is
        // never applied.
        let parsers = vec![
            CommitParser {
                sha: None,
                message: Regex::new("\\(deep\\)").ok(),
                body: None,
                footer: None,
                group: None,
                default_scope: None,
                scope: Some(String::from("Deep Scope")),
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
            CommitParser {
                sha: None,
                message: Regex::new("^feat").ok(),
                body: None,
                footer: None,
                group: Some(String::from("Features")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];
        let parsed = commit.clone().parse(&parsers, false, false)?;
        assert_eq!(Some(String::from("Deep Scope")), parsed.scope);
        assert_eq!(None, parsed.group);

        // With `continue = true` on the composing parsers, the commit picks up
        // the scope from the first and the group from the second.
        let parsers = vec![
            CommitParser {
                sha: None,
                message: Regex::new("\\(deep\\)").ok(),
                body: None,
                footer: None,
                group: None,
                default_scope: None,
                scope: Some(String::from("Deep Scope")),
                skip: None,
                r#continue: Some(true),
                field: None,
                pattern: None,
            },
            CommitParser {
                sha: None,
                message: Regex::new("^feat").ok(),
                body: None,
                footer: None,
                group: Some(String::from("Features")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: Some(true),
                field: None,
                pattern: None,
            },
        ];
        let parsed = commit.clone().parse(&parsers, false, true)?;
        assert_eq!(Some(String::from("Deep Scope")), parsed.scope);
        assert_eq!(Some(String::from("Features")), parsed.group);

        // A `continue` parser that matches keeps the commit even when filtering
        // is on and it only set a scope (no group).
        let scope_only = vec![CommitParser {
            sha: None,
            message: Regex::new("^feat").ok(),
            body: None,
            footer: None,
            group: None,
            default_scope: None,
            scope: Some(String::from("Deep Scope")),
            skip: None,
            r#continue: Some(true),
            field: None,
            pattern: None,
        }];
        let parsed = commit.clone().parse(&scope_only, false, true)?;
        assert_eq!(Some(String::from("Deep Scope")), parsed.scope);
        assert_eq!(None, parsed.group);

        // A `continue` parser can set the scope and a following terminal parser
        // (no `continue`) can set the group without wiping the scope. The
        // terminal parser only overwrites the fields it actually sets, so the
        // scope from the first parser is kept instead of being reset to None.
        let parsers = vec![
            CommitParser {
                sha: None,
                message: Regex::new("\\(deep\\)").ok(),
                body: None,
                footer: None,
                group: None,
                default_scope: None,
                scope: Some(String::from("Deep Scope")),
                skip: None,
                r#continue: Some(true),
                field: None,
                pattern: None,
            },
            CommitParser {
                sha: None,
                message: Regex::new("^feat").ok(),
                body: None,
                footer: None,
                group: Some(String::from("Features")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];
        let parsed = commit.clone().parse(&parsers, false, false)?;
        assert_eq!(Some(String::from("Deep Scope")), parsed.scope);
        assert_eq!(Some(String::from("Features")), parsed.group);

        // Without a preceding `continue` match, terminal parsers retain the
        // original behavior of clearing fields they do not set.
        let mut populated_commit = commit;
        populated_commit.group = Some(String::from("Old Group"));
        populated_commit.scope = Some(String::from("Old Scope"));
        populated_commit.default_scope = Some(String::from("Old Default Scope"));
        let terminal = vec![CommitParser {
            message: Regex::new("^feat").ok(),
            group: Some(String::from("Features")),
            ..Default::default()
        }];
        let parsed = populated_commit.parse(&terminal, false, false)?;
        assert_eq!(Some(String::from("Features")), parsed.group);
        assert_eq!(None, parsed.scope);
        assert_eq!(None, parsed.default_scope);

        Ok(())
    }

    #[test]
    fn parse_commit_missing_field_falls_through_to_next_parser() -> Result<()> {
        let commit = Commit::new(
            String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6"),
            String::from("feat: first feature"),
        );
        // `commit.remote` is `None` by default (this is a LOCAL / non-PR commit),
        // so `remote.pr_labels` cannot be resolved.
        // The first parser must be skipped (not abort the chain) so the
        // catch-all parser below can still match and group the commit.
        let parsers = [
            CommitParser {
                sha: None,
                message: Some(Regex::new("^feat")?),
                body: None,
                footer: None,
                group: Some(String::from("Bug fixes")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("remote.pr_labels")),
                pattern: Regex::new("bug").ok(),
            },
            CommitParser {
                sha: None,
                message: Some(Regex::new(".*")?),
                body: None,
                footer: None,
                group: Some(String::from("Miscellaneous")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];
        let parsed = commit.parse(&parsers, false, false)?;
        assert_eq!(
            Some(String::from("Miscellaneous")),
            parsed.group,
            "a missing field on parser #1 must fall through to the catch-all parser #2"
        );
        Ok(())
    }

    #[test]
    fn parse_commit_footer_requires_conventional_data() -> Result<()> {
        let parsers = [
            CommitParser {
                sha: None,
                message: Regex::new("^feat:.*?remove").ok(),
                body: None,
                footer: Regex::new("^BREAKING CHANGE:").ok(),
                group: Some(String::from("Removed")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
            CommitParser {
                sha: None,
                message: Some(Regex::new(".*")?),
                body: None,
                footer: None,
                group: Some(String::from("Miscellaneous")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];

        let commit = Commit::new(
            String::new(),
            String::from("feat: remove old api\n\nBREAKING CHANGE: drop legacy support"),
        )
        .parse(&parsers, false, false)?;
        assert_eq!(
            Some(String::from("Miscellaneous")),
            commit.group,
            "footer requires conventional data; must not match the combined parser"
        );

        Ok(())
    }

    #[test]
    fn parse_commit_and_semantics_message_footer() -> Result<()> {
        let parsers = [
            CommitParser {
                sha: None,
                message: Regex::new("^feat:.*?remove").ok(),
                body: None,
                footer: Regex::new("^BREAKING CHANGE:").ok(),
                group: Some(String::from("Removed")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
            CommitParser {
                sha: None,
                message: Some(Regex::new(".*")?),
                body: None,
                footer: None,
                group: Some(String::from("Miscellaneous")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];

        let commit = Commit::new(String::new(), String::from("feat: remove old api"))
            .into_conventional()?
            .parse(&parsers, false, false)?;
        assert_eq!(
            Some(String::from("Miscellaneous")),
            commit.group,
            "message matches but footer doesn't; must not match the combined parser"
        );

        let commit = Commit::new(
            String::new(),
            String::from("feat: remove old api\n\nBREAKING CHANGE: drop legacy support"),
        )
        .into_conventional()?
        .parse(&parsers, false, false)?;
        assert_eq!(Some(String::from("Removed")), commit.group);

        Ok(())
    }

    #[test]
    fn parse_commit_and_semantics_message_body() -> Result<()> {
        let parsers = [
            CommitParser {
                sha: None,
                message: Regex::new("^fix:").ok(),
                body: Regex::new("security").ok(),
                footer: None,
                group: Some(String::from("Security")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
            CommitParser {
                sha: None,
                message: Some(Regex::new(".*")?),
                body: None,
                footer: None,
                group: Some(String::from("Miscellaneous")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];

        let commit = Commit::new(
            String::new(),
            String::from("fix: patch bug\n\nregular body"),
        )
        .into_conventional()?
        .parse(&parsers, false, false)?;
        assert_eq!(
            Some(String::from("Miscellaneous")),
            commit.group,
            "message matches but body doesn't; must not match the combined parser"
        );

        let commit = Commit::new(
            String::new(),
            String::from("fix: patch bug\n\nfix a security bug"),
        )
        .into_conventional()?
        .parse(&parsers, false, false)?;
        assert_eq!(Some(String::from("Security")), commit.group);

        Ok(())
    }

    #[test]
    fn parse_commit_and_semantics_footer_field() -> Result<()> {
        let parsers = [
            CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: Regex::new("^BREAKING CHANGE:").ok(),
                group: Some(String::from("Removed")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("message")),
                pattern: Regex::new("remove").ok(),
            },
            CommitParser {
                sha: None,
                message: Some(Regex::new(".*")?),
                body: None,
                footer: None,
                group: Some(String::from("Miscellaneous")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];

        let commit = Commit::new(String::new(), String::from("feat: remove old api"))
            .into_conventional()?
            .parse(&parsers, false, false)?;
        assert_eq!(
            Some(String::from("Miscellaneous")),
            commit.group,
            "field pattern matches but footer doesn't; must not match the combined parser"
        );

        let commit = Commit::new(
            String::new(),
            String::from("feat: remove old api\n\nBREAKING CHANGE: drop legacy support"),
        )
        .into_conventional()?
        .parse(&parsers, false, false)?;
        assert_eq!(Some(String::from("Removed")), commit.group);

        Ok(())
    }

    #[test]
    fn parse_commit_and_semantics_sha_message() -> Result<()> {
        let sha = String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6");
        let parsers = [
            CommitParser {
                sha: Some(sha.clone()),
                message: Regex::new("^feat:").ok(),
                body: None,
                footer: None,
                group: Some(String::from("Added")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
            CommitParser {
                sha: None,
                message: Some(Regex::new(".*")?),
                body: None,
                footer: None,
                group: Some(String::from("Miscellaneous")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: None,
                pattern: None,
            },
        ];

        let commit = Commit::new(sha.clone(), String::from("fix: patch bug"))
            .parse(&parsers, false, false)?;
        assert_eq!(
            Some(String::from("Miscellaneous")),
            commit.group,
            "sha matches but message doesn't; must not match the combined parser"
        );

        let commit = Commit::new(
            String::from("0000000000000000000000000000000000000000"),
            String::from("feat: add feature"),
        )
        .parse(&parsers, false, false)?;
        assert_eq!(
            Some(String::from("Miscellaneous")),
            commit.group,
            "message matches but sha doesn't; must not match the combined parser"
        );

        let commit =
            Commit::new(sha, String::from("feat: add feature")).parse(&parsers, false, false)?;
        assert_eq!(Some(String::from("Added")), commit.group);

        Ok(())
    }

    #[test]
    fn commit_sha() {
        let commit = Commit::new(
            String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6"),
            String::from("feat: do something"),
        );

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: Some(String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6")),
                message: None,
                body: None,
                footer: None,
                group: None,
                default_scope: None,
                scope: None,
                skip: Some(true),
                r#continue: None,
                field: None,
                pattern: None,
            }],
            false,
            false,
        );
        assert!(
            parsed_commit.is_err(),
            "Expected error when parsing with `skip: Some(true)`, but got Ok"
        );
    }

    #[test]
    fn field_name_regex() -> Result<()> {
        let mut commit = Commit::new(
            String::from("8f55e69eba6e6ce811ace32bd84cc82215673cb6"),
            String::from("feat: do something"),
        );
        commit.author = Signature {
            name: Some("John Doe".to_string()),
            email: None,
            timestamp: 0x0,
        };
        commit.remote = Some(crate::contributor::RemoteContributor {
            username: None,
            pr_author: None,
            pr_title: Some("feat: do something".to_string()),
            pr_number: None,
            pr_numbers: vec![],
            pr_labels: Vec::new(),
            is_first_time: true,
        });

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("author.name")),
                pattern: Regex::new("^John Doe$").ok(),
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("Test group")), parsed_commit.group);

        let parsed_commit = commit.clone().parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("remote.pr_title")),
                pattern: Regex::new("^feat(\\([^)]+\\))?").ok(),
            }],
            false,
            false,
        )?;
        assert_eq!(Some(String::from("Test group")), parsed_commit.group);

        let parse_result = commit.parse(
            &[CommitParser {
                sha: None,
                message: None,
                body: None,
                footer: None,
                group: Some(String::from("Test group")),
                default_scope: None,
                scope: None,
                skip: None,
                r#continue: None,
                field: Some(String::from("author.name")),
                pattern: Regex::new("Something else").ok(),
            }],
            false,
            true,
        );
        assert!(
            parse_result.is_err(),
            "Expected error because `author.name` did not match the given pattern, but got Ok"
        );

        Ok(())
    }
}