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
// Copyright Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use derive_builder::Builder;
use git_checks_core::impl_prelude::*;
use itertools::Itertools;
use lazy_static::lazy_static;
use regex::Regex;

/// Check commit message subjects for invalid patterns.
///
/// Patterns which are checked for:
///   - overly long or short summary lines;
///   - work-in-progress messages;
///   - `fixup!` and `squash!` messages; and
///   - custom prefixes.
///
/// Commit messages which appear to have been auto generated by actions such as merging or
/// reverting commits will skip the summary line length limit (if enforced).
#[derive(Builder, Debug, Clone)]
#[builder(field(private))]
pub struct CommitSubject {
    /// The minimum length allowed for the summary line.
    ///
    /// Configuration: Optional
    /// Default: `8`
    #[builder(default = "8")]
    min_summary: usize,
    /// The maximum length allowed for the summary line.
    ///
    /// Configuration: Optional
    /// Default: `78`
    #[builder(default = "78")]
    max_summary: usize,

    /// Whether to deny work-in-progress commits or not.
    ///
    /// Commit messages which mention `WIP`, `wip`, or a few variants of `Draft` at the beginning
    /// of their commit messages are rejected since they are (nominally) incomplete.
    ///
    /// Configuration: Optional
    /// Default: `true`
    #[builder(default = "true")]
    check_work_in_progress: bool,

    /// Check for rebase commands
    ///
    /// Rebase commands include commits which begin with `fixup! `, `squash! `, or `amend! `. These
    /// subjects are used to indicate that the commit belongs somewhere else in the branch and
    /// should be completed before merging.
    ///
    /// Configuration: Optional
    /// Default: `true`
    #[builder(default = "true")]
    check_rebase_commands: bool,

    /// Check for suggestions applied through a hosting facility
    ///
    /// Some hosting services support applying suggestions for changes to a topic as a new commit.
    /// Enabling this option detects these subjects and rejects the commit as the code suggestion
    /// should be squashed back into the relevant commit.
    ///
    /// Configuration: Optional
    /// Default: `false`
    #[builder(default = "false")]
    check_suggestion_subjects: bool,

    #[builder(private)]
    #[builder(setter(name = "_tolerated_prefixes"))]
    #[builder(default)]
    tolerated_prefixes: Vec<Regex>,
    #[builder(private)]
    #[builder(setter(name = "_allowed_prefixes"))]
    #[builder(default)]
    allowed_prefixes: Vec<String>,
    #[builder(private)]
    #[builder(setter(name = "_disallowed_prefixes"))]
    #[builder(default)]
    disallowed_prefixes: Vec<String>,
}

lazy_static! {
    static ref SUGGESTION_SUBJECTS: Vec<Regex> = vec![
        // GitLab
        Regex::new(r#"Apply \d* suggestion\(s\) to \d* file\(s\)"#).unwrap(),
        // GitHub. Developers are asked for commit information, but this is the default for a
        // "batch" of suggestions.
        Regex::new("Apply suggestions from code review").unwrap(),
    ];
}

impl CommitSubjectBuilder {
    /// Tolerated prefixes for commits.
    ///
    /// The specified prefix patterns will be tolerated regardless of any configured
    /// allowed or disallowed prefixes.
    ///
    /// Configuration: Optional
    /// Default: `Vec::new()`
    pub fn tolerated_prefixes<I, P>(&mut self, patterns: I) -> &mut Self
    where
        I: IntoIterator<Item = P>,
        P: Into<Regex>,
    {
        self.tolerated_prefixes = Some(patterns.into_iter().map(Into::into).collect());
        self
    }

    /// Required prefixes for commits.
    ///
    /// The specified prefixes will be the only allowed prefixes on commit message subjects
    /// that do not match a tolerated pattern.
    ///
    /// Configuration: Optional
    /// Default: `Vec::new()`
    pub fn allowed_prefixes<I, P>(&mut self, prefixes: I) -> &mut Self
    where
        I: IntoIterator<Item = P>,
        P: Into<String>,
    {
        self.allowed_prefixes = Some(prefixes.into_iter().map(Into::into).collect());
        self
    }

    /// Forbidden prefixes for commits.
    ///
    /// The specified prefixes will be rejected on commit message subjects that do not
    /// also match a tolerated pattern.
    ///
    /// Configuration: Optional
    /// Default: `Vec::new()`
    pub fn disallowed_prefixes<I, P>(&mut self, prefixes: I) -> &mut Self
    where
        I: IntoIterator<Item = P>,
        P: Into<String>,
    {
        self.disallowed_prefixes = Some(prefixes.into_iter().map(Into::into).collect());
        self
    }
}

impl CommitSubject {
    /// Create a new builder.
    pub fn builder() -> CommitSubjectBuilder {
        CommitSubjectBuilder::default()
    }

    /// Whether the summary is generated or not.
    ///
    /// The commit summaries generated by `git merge` and `git revert` can be long, but since they
    /// are auto-generated, allow them.
    fn is_generated_subject(summary: &str) -> bool {
        summary.starts_with("Merge ") || summary.starts_with("Revert ")
    }
}

impl Default for CommitSubject {
    fn default() -> Self {
        CommitSubject {
            min_summary: 8,
            max_summary: 78,
            check_work_in_progress: true,
            check_rebase_commands: true,
            check_suggestion_subjects: false,
            tolerated_prefixes: Vec::new(),
            allowed_prefixes: Vec::new(),
            disallowed_prefixes: Vec::new(),
        }
    }
}

impl Check for CommitSubject {
    fn name(&self) -> &str {
        "commit-subject"
    }

    fn check(&self, _: &CheckGitContext, commit: &Commit) -> Result<CheckResult, Box<dyn Error>> {
        let mut result = CheckResult::new();
        let lines = commit.message.trim().lines().collect::<Vec<_>>();

        if lines.is_empty() {
            result.add_error(format!(
                "commit {} has an invalid commit subject; it is empty.",
                commit.sha1,
            ));
            return Ok(result);
        }

        let summary = &lines[0];
        let summary_len = summary.len();

        if summary_len < self.min_summary {
            result.add_error(format!(
                "commit {} has an invalid commit subject; the first line must be at least {} \
                 characters.",
                commit.sha1, self.min_summary,
            ));
        }

        let is_generated = Self::is_generated_subject(summary);
        if !is_generated && self.max_summary < summary_len {
            result.add_error(format!(
                "commit {} has an invalid commit subject; the first line must be no longer than \
                 {} characters.",
                commit.sha1, self.max_summary,
            ));
        }

        if lines.len() >= 2 {
            if lines.len() >= 2 && !lines[1].is_empty() {
                result.add_error(format!(
                    "commit {} has an invalid commit subject; the second line must be empty.",
                    commit.sha1,
                ));
            }

            if lines.len() == 2 {
                result.add_error(format!(
                    "commit {} has an invalid commit subject; it cannot be exactly two lines.",
                    commit.sha1,
                ));
            } else if lines[2].is_empty() {
                result.add_error(format!(
                    "commit {} has an invalid commit subject; the third line must not be empty.",
                    commit.sha1,
                ));
            }
        }

        const WIP_PREFIXES: &[&str] = &[
            "WIP", "wip", "Draft:", "draft:", "[Draft]", "[draft]", "(Draft)", "(draft)",
        ];

        if self.check_work_in_progress
            && WIP_PREFIXES
                .iter()
                .any(|prefix| summary.starts_with(prefix))
        {
            result.add_error(format!(
                "commit {} cannot be merged; it is marked as a work-in-progress (WIP).",
                commit.sha1,
            ));
        }

        if self.check_rebase_commands {
            if summary.starts_with("fixup! ") {
                result.add_error(format!(
                    "commit {} cannot be merged; it is marked as a fixup commit.",
                    commit.sha1,
                ));
            } else if summary.starts_with("squash! ") {
                result.add_error(format!(
                    "commit {} cannot be merged; it is marked as a commit to be squashed.",
                    commit.sha1,
                ));
            } else if summary.starts_with("amend! ") {
                result.add_error(format!(
                    "commit {} cannot be merged; it is marked as an amending commit.",
                    commit.sha1,
                ));
            }
        }

        if self.check_suggestion_subjects {
            for subject in SUGGESTION_SUBJECTS.iter() {
                if subject.is_match(summary) {
                    result.add_error(format!(
                        "commit {} cannot be merged; its commit summary appears to have been \
                         automatically generated by a suggestion application mechanism. Please \
                         squash the suggestion(s) into the relevant commit(s) using `git rebase`.",
                        commit.sha1,
                    ));
                }
            }
        }

        if !is_generated {
            let is_tolerated = self.tolerated_prefixes.iter().any(|regex| {
                regex
                    .find(summary)
                    .map(|found| found.start() == 0)
                    .unwrap_or(false)
            });
            if !is_tolerated {
                if !self.allowed_prefixes.is_empty() {
                    let is_ok = self
                        .allowed_prefixes
                        .iter()
                        .any(|prefix| summary.starts_with(prefix));
                    if !is_ok {
                        result.add_error(format!(
                            "commit {} cannot be merged; it must start with one of the following \
                             prefixes: `{}`.",
                            commit.sha1,
                            self.allowed_prefixes.iter().format("`, `"),
                        ));
                    }
                }

                let is_ok = self
                    .disallowed_prefixes
                    .iter()
                    .all(|prefix| !summary.starts_with(prefix));
                if !is_ok {
                    result.add_error(format!(
                        "commit {} cannot be merged; it cannot start with any of the following \
                         prefixes: `{}`.",
                        commit.sha1,
                        self.disallowed_prefixes.iter().format("`, `"),
                    ));
                }
            }
        }

        Ok(result)
    }
}

#[cfg(feature = "config")]
pub(crate) mod config {
    use git_checks_config::{register_checks, CommitCheckConfig, IntoCheck};
    use regex::Regex;
    use serde::de::{Deserializer, Error as SerdeError};
    use serde::Deserialize;
    #[cfg(test)]
    use serde_json::json;

    use crate::CommitSubject;

    #[derive(Debug)]
    struct RegexConfig(Regex);

    impl<'de> Deserialize<'de> for RegexConfig {
        fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let regex_str = <String as Deserialize>::deserialize(deserializer)?;
            let regex = Regex::new(&regex_str)
                .map_err(|err| D::Error::custom(format!("'{}': {}", regex_str, err)))?;
            Ok(RegexConfig(regex))
        }
    }

    impl From<RegexConfig> for Regex {
        fn from(regex_config: RegexConfig) -> Self {
            regex_config.0
        }
    }

    /// Configuration for the `CommitSubject` check.
    ///
    /// No configuration is necessary. The defaults are guided by common commit message guidelines.
    ///
    /// | Field | Type | Default |
    /// | ----- | ---- | ------- |
    /// | `min_summary` | positive integer | 8 |
    /// | `max_summary` | positive integer | 78 |
    /// | `check_work_in_progress` | boolean | true |
    /// | `check_rebase_commands` | boolean | true |
    /// | `check_suggestion_subjects` | boolean | false |
    ///
    /// The prefix configurations are lists of strings that are by default empty lists. The
    /// `tolerated_prefixes` key is interpreted as a list of regular expressions.
    ///
    /// This check is registered as a commit check with the name `"commit_subject".
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///     "min_summary": 8,
    ///     "max_summary": 78,
    ///
    ///     "check_work_in_progress": true,
    ///     "check_rebase_commands": true,
    ///     "check_suggestion_subjects": true,
    ///
    ///     "tolerated_prefixes": [
    ///         "regex"
    ///     ],
    ///     "allowed_prefixes": [
    ///         "literal"
    ///     ],
    ///     "disallowed_prefixes": [
    ///         "literal"
    ///     ]
    /// }
    /// ```
    #[derive(Deserialize, Debug)]
    pub struct CommitSubjectConfig {
        #[serde(default)]
        min_summary: Option<usize>,
        #[serde(default)]
        max_summary: Option<usize>,

        #[serde(default)]
        check_work_in_progress: Option<bool>,
        #[serde(default)]
        check_rebase_commands: Option<bool>,
        #[serde(default)]
        check_suggestion_subjects: Option<bool>,

        #[serde(default)]
        tolerated_prefixes: Option<Vec<RegexConfig>>,
        #[serde(default)]
        allowed_prefixes: Option<Vec<String>>,
        #[serde(default)]
        disallowed_prefixes: Option<Vec<String>>,
    }

    impl IntoCheck for CommitSubjectConfig {
        type Check = CommitSubject;

        fn into_check(self) -> Self::Check {
            let mut builder = CommitSubject::builder();

            if let Some(min_summary) = self.min_summary {
                builder.min_summary(min_summary);
            }

            if let Some(max_summary) = self.max_summary {
                builder.max_summary(max_summary);
            }

            if let Some(check_work_in_progress) = self.check_work_in_progress {
                builder.check_work_in_progress(check_work_in_progress);
            }

            if let Some(check_rebase_commands) = self.check_rebase_commands {
                builder.check_rebase_commands(check_rebase_commands);
            }

            if let Some(check_suggestion_subjects) = self.check_suggestion_subjects {
                builder.check_suggestion_subjects(check_suggestion_subjects);
            }

            if let Some(tolerated_prefixes) = self.tolerated_prefixes {
                builder.tolerated_prefixes(tolerated_prefixes);
            }

            if let Some(allowed_prefixes) = self.allowed_prefixes {
                builder.allowed_prefixes(allowed_prefixes);
            }

            if let Some(disallowed_prefixes) = self.disallowed_prefixes {
                builder.disallowed_prefixes(disallowed_prefixes);
            }

            builder
                .build()
                .expect("configuration mismatch for `CommitSubject`")
        }
    }

    register_checks! {
        CommitSubjectConfig {
            "commit_subject" => CommitCheckConfig,
        },
    }

    #[test]
    fn test_commit_subject_config_empty() {
        let json = json!({});
        let check: CommitSubjectConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.min_summary, None);
        assert_eq!(check.max_summary, None);
        assert_eq!(check.check_work_in_progress, None);
        assert_eq!(check.check_rebase_commands, None);
        assert_eq!(check.check_suggestion_subjects, None);
        assert!(check.tolerated_prefixes.is_none());
        assert_eq!(check.allowed_prefixes, None);
        assert_eq!(check.disallowed_prefixes, None);

        let check = check.into_check();

        assert_eq!(check.min_summary, 8);
        assert_eq!(check.max_summary, 78);
        assert!(check.check_work_in_progress);
        assert!(check.check_rebase_commands);
        assert!(!check.check_suggestion_subjects);
        assert!(check.tolerated_prefixes.is_empty());
        itertools::assert_equal(&check.allowed_prefixes, &[] as &[&str]);
        itertools::assert_equal(&check.disallowed_prefixes, &[] as &[&str]);
    }

    #[test]
    fn test_commit_subject_config_all_fields() {
        let exp_tprefix: String = "tolerated".into();
        let exp_aprefix: String = "allowed".into();
        let exp_dprefix: String = "disallowed".into();
        let json = json!({
            "min_summary": 1,
            "max_summary": 100,
            "check_work_in_progress": false,
            "check_rebase_commands": false,
            "check_suggestion_subjects": true,
            "tolerated_prefixes": [exp_tprefix],
            "allowed_prefixes": [exp_aprefix],
            "disallowed_prefixes": [exp_dprefix],
        });
        let check: CommitSubjectConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.min_summary, Some(1));
        assert_eq!(check.max_summary, Some(100));
        assert_eq!(check.check_work_in_progress, Some(false));
        assert_eq!(check.check_rebase_commands, Some(false));
        assert_eq!(check.check_suggestion_subjects, Some(true));
        itertools::assert_equal(
            check
                .tolerated_prefixes
                .as_ref()
                .unwrap()
                .iter()
                .map(|re| re.0.as_str()),
            &[exp_tprefix.clone()],
        );
        itertools::assert_equal(&check.allowed_prefixes, &Some([exp_aprefix.clone()]));
        itertools::assert_equal(&check.disallowed_prefixes, &Some([exp_dprefix.clone()]));

        let check = check.into_check();

        assert_eq!(check.min_summary, 1);
        assert_eq!(check.max_summary, 100);
        assert!(!check.check_work_in_progress);
        assert!(!check.check_rebase_commands);
        assert!(check.check_suggestion_subjects);
        itertools::assert_equal(
            check.tolerated_prefixes.iter().map(|re| re.as_str()),
            &[exp_tprefix],
        );
        itertools::assert_equal(&check.allowed_prefixes, &[exp_aprefix]);
        itertools::assert_equal(&check.disallowed_prefixes, &[exp_dprefix]);
    }
}

#[cfg(test)]
mod tests {
    use git_checks_core::Check;
    use regex::Regex;

    use crate::test::*;
    use crate::CommitSubject;

    const BAD_TOPIC: &str = "891db15952303d4f18ca23070c1bf054bc51a15c";

    #[test]
    fn test_commit_subject_builder_default() {
        assert!(CommitSubject::builder().build().is_ok());
    }

    #[test]
    fn test_commit_subject_name_commit() {
        let check = CommitSubject::default();
        assert_eq!(Check::name(&check), "commit-subject");
    }

    #[test]
    fn test_commit_subject() {
        let check = CommitSubject::default();
        let result = run_check("test_commit_subject", BAD_TOPIC, check);
        test_result_errors(result, &[
            "commit 234de3c3f17ab29f0b7644ae96242e31a3dd634c has an invalid commit subject; the \
             first line must be at least 8 characters.",
            "commit 1afc6b3584580488917fc61aa5e5298e98583805 has an invalid commit subject; the \
             first line must be no longer than 78 characters.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; the \
             second line must be empty.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; it \
             cannot be exactly two lines.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             second line must be empty.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             third line must not be empty.",
            "commit e478f630b586e331753477eba88059d644927be8 cannot be merged; it is marked as a \
             work-in-progress (WIP).",
            "commit 9039b9a4813fa019229e960033fe1ae8514a0c8e cannot be merged; it is marked as a \
             work-in-progress (WIP).",
            "commit 11dbbbff3f32445d74d1a8d96df0a49381c81ba0 cannot be merged; it is marked as a \
             work-in-progress (WIP).",
            "commit 54d673ff559a72ce6343bd9526a950d79034b24e cannot be merged; it is marked as a \
             fixup commit.",
            "commit 5f7284fe1599265c90550b681a4bf0763bc1de21 cannot be merged; it is marked as a \
             commit to be squashed.",
            "commit c4a9d2f34a687134e0d5d47ff576d34966381f56 has an invalid commit subject; it is \
             empty.",
            "commit 12b564db852a80190950caf5b363a4939b822730 cannot be merged; it is marked as an \
             amending commit.",
        ]);
    }

    #[test]
    fn test_commit_subject_with_suggestions() {
        let check = CommitSubject::builder()
            .check_work_in_progress(false)
            .check_rebase_commands(false)
            .check_suggestion_subjects(true)
            .build()
            .unwrap();
        let result = run_check("test_commit_subject_with_suggestions", BAD_TOPIC, check);
        test_result_errors(result, &[
            "commit 234de3c3f17ab29f0b7644ae96242e31a3dd634c has an invalid commit subject; the \
             first line must be at least 8 characters.",
            "commit 1afc6b3584580488917fc61aa5e5298e98583805 has an invalid commit subject; the \
             first line must be no longer than 78 characters.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; the \
             second line must be empty.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; it \
             cannot be exactly two lines.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             second line must be empty.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             third line must not be empty.",
            "commit c4a9d2f34a687134e0d5d47ff576d34966381f56 has an invalid commit subject; it is \
             empty.",
            "commit c52a84631f35561043cb7cca6c136f94bd9fc757 cannot be merged; its commit summary \
             appears to have been automatically generated by a suggestion application mechanism. \
             Please squash the suggestion(s) into the relevant commit(s) using `git rebase`.",
            "commit 891db15952303d4f18ca23070c1bf054bc51a15c cannot be merged; its commit summary \
             appears to have been automatically generated by a suggestion application mechanism. \
             Please squash the suggestion(s) into the relevant commit(s) using `git rebase`.",
        ]);
    }

    #[test]
    fn test_commit_subject_allowed_prefixes() {
        let check = CommitSubject::builder()
            .check_work_in_progress(false)
            .check_rebase_commands(false)
            .allowed_prefixes(["commit message "].iter().cloned())
            .build()
            .unwrap();
        let result = run_check("test_commit_subject_allowed_prefixes", BAD_TOPIC, check);
        test_result_errors(result, &[
            "commit 234de3c3f17ab29f0b7644ae96242e31a3dd634c has an invalid commit subject; the \
             first line must be at least 8 characters.",
            "commit 234de3c3f17ab29f0b7644ae96242e31a3dd634c cannot be merged; it must start with one of the following prefixes: `commit message `.",
            "commit 1afc6b3584580488917fc61aa5e5298e98583805 has an invalid commit subject; the \
             first line must be no longer than 78 characters.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; the \
             second line must be empty.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; it \
             cannot be exactly two lines.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             second line must be empty.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             third line must not be empty.",
            "commit e478f630b586e331753477eba88059d644927be8 cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
            "commit 9039b9a4813fa019229e960033fe1ae8514a0c8e cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
            "commit 11dbbbff3f32445d74d1a8d96df0a49381c81ba0 cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
            "commit 54d673ff559a72ce6343bd9526a950d79034b24e cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
            "commit 5f7284fe1599265c90550b681a4bf0763bc1de21 cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
            "commit c4a9d2f34a687134e0d5d47ff576d34966381f56 has an invalid commit subject; it is \
             empty.",
            "commit 12b564db852a80190950caf5b363a4939b822730 cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
            "commit c52a84631f35561043cb7cca6c136f94bd9fc757 cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
            "commit 891db15952303d4f18ca23070c1bf054bc51a15c cannot be merged; it must start with \
             one of the following prefixes: `commit message `.",
        ]);
    }

    #[test]
    fn test_commit_subject_disallowed_prefixes() {
        let check = CommitSubject::builder()
            .check_work_in_progress(false)
            .check_rebase_commands(false)
            .disallowed_prefixes(["commit message "].iter().cloned())
            .build()
            .unwrap();
        let result = run_check("test_commit_subject_disallowed_prefixes", BAD_TOPIC, check);
        test_result_errors(result, &[
            "commit 234de3c3f17ab29f0b7644ae96242e31a3dd634c has an invalid commit subject; the \
             first line must be at least 8 characters.",
            "commit 1afc6b3584580488917fc61aa5e5298e98583805 has an invalid commit subject; the \
             first line must be no longer than 78 characters.",
            "commit 1afc6b3584580488917fc61aa5e5298e98583805 cannot be merged; it cannot start \
             with any of the following prefixes: `commit message `.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; the \
             second line must be empty.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; it \
             cannot be exactly two lines.",
            "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 cannot be merged; it cannot start \
             with any of the following prefixes: `commit message `.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             second line must be empty.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; the \
             third line must not be empty.",
            "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 cannot be merged; it cannot start \
             with any of the following prefixes: `commit message `.",
            "commit c4a9d2f34a687134e0d5d47ff576d34966381f56 has an invalid commit subject; it is \
             empty.",
        ]);
    }

    #[test]
    fn test_commit_subject_tolerated_prefixes() {
        let check = CommitSubject::builder()
            .check_work_in_progress(false)
            .check_rebase_commands(false)
            .tolerated_prefixes(
                [
                    "^(commit message )",
                    "^([Ww][Ii][Pp]|fixup|squash|amend)",
                    "Apply",
                    // Intentionally match the middle of commit 234de3c3f's subject line
                    // to verify that the line "short" is not a tolerated prefix.
                    "hort",
                ]
                .iter()
                .map(|patt| Regex::new(patt).unwrap()),
            )
            .allowed_prefixes(["allowed prefix "].iter().cloned())
            .disallowed_prefixes(["commit message "].iter().cloned())
            .build()
            .unwrap();
        let result = run_check("test_commit_subject_tolerated_prefixes", BAD_TOPIC, check);
        test_result_errors(
            result,
            &[
                "commit 234de3c3f17ab29f0b7644ae96242e31a3dd634c has an invalid commit subject; \
                 the first line must be at least 8 characters.",
                "commit 234de3c3f17ab29f0b7644ae96242e31a3dd634c cannot be merged; it must start \
                 with one of the following prefixes: `allowed prefix `.",
                "commit 1afc6b3584580488917fc61aa5e5298e98583805 has an invalid commit subject; \
                 the first line must be no longer than 78 characters.",
                "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; \
                 the second line must be empty.",
                "commit b1ca628043ed78625551420e2dbbd8cf74fde2c4 has an invalid commit subject; \
                 it cannot be exactly two lines.",
                "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; \
                 the second line must be empty.",
                "commit 3a6fe6d56fbf11c667b6c88bdd7d851a8dcac0b1 has an invalid commit subject; \
                 the third line must not be empty.",
                "commit c4a9d2f34a687134e0d5d47ff576d34966381f56 has an invalid commit subject; \
                 it is empty.",
            ],
        );
    }
}