lintje 0.3.1

Lintje is an opinionated linter for Git.
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
use crate::rule::{rule_by_name, Rule, Violation};
use regex::Regex;

lazy_static! {
    pub static ref SUBJECT_WITH_MERGE_REMOTE_BRANCH: Regex = Regex::new(r"^Merge branch '.+' of .+ into .+").unwrap();
    static ref SUBJECT_STARTS_WITH_PREFIX: Regex = Regex::new(r"^([\w\(\)/!]+:)\s.*").unwrap();
    static ref SUBJECT_STARTS_WITH_EMOJI: Regex = Regex::new(r"^\p{Emoji}").unwrap();
    static ref SUBJECT_WITH_TICKET: Regex = Regex::new(r"[A-Z]+-\d+").unwrap();
    // Match all GitHub and GitLab keywords
    static ref SUBJECT_WITH_FIX_TICKET: Regex =
        Regex::new(r"([fF]ix(es|ed|ing)?|[cC]los(e|es|ed|ing)|[rR]esolv(e|es|ed|ing)|[iI]mplement(s|ed|ing)?):? ([^\s]*[\w\-_/]+)?[#!]{1}\d+").unwrap();
    static ref URL_REGEX: Regex = Regex::new(r"https?://\w+").unwrap();
    static ref CODE_BLOCK_LINE_WITH_LANGUAGE: Regex = Regex::new(r"^\s*```\s*([\w]+)?$").unwrap();
    static ref CODE_BLOCK_LINE_END: Regex = Regex::new(r"^\s*```$").unwrap();
    static ref OTHER_PUNCTUATION: Vec<char> = vec![
        '',
        '',
    ];
    static ref MOOD_WORDS: Vec<&'static str> = vec![
        "fixed",
        "fixes",
        "fixing",
        "solved",
        "solves",
        "solving",
        "resolved",
        "resolves",
        "resolving",
        "closed",
        "closes",
        "closing",
        "added",
        "adding",
        "updated",
        "updates",
        "updating",
        "removed",
        "removes",
        "removing",
        "deleted",
        "deletes",
        "deleting",
        "changed",
        "changes",
        "changing",
        "moved",
        "moves",
        "moving",
        "refactored",
        "refactors",
        "refactoring",
        "checked",
        "checks",
        "checking",
        "adjusted",
        "adjusts",
        "adjusting",
        "tests",
        "tested",
        "testing",
    ];
    static ref BUILD_TAGS: Vec<&'static str> = vec![
        // General
        "[ci skip]",
        "[skip ci]",
        "[no ci]",
        // AppVeyor
        "[skip appveyor]",
        // Azure
        "[azurepipelines skip]",
        "[skip azurepipelines]",
        "[azpipelines skip]",
        "[skip azpipelines]",
        "[azp skip]",
        "[skip azp]",
        "***NO_CI***",
        // GitHub Actions
        "[actions skip]",
        "[skip actions]",
        // Travis
        "[travis skip]",
        "[skip travis]",
        "[travis ci skip]",
        "[skip travis ci]",
        "[travis-ci skip]",
        "[skip travis-ci]",
        "[travisci skip]",
        "[skip travisci]",
    ];
}

#[derive(Debug)]
pub struct Commit {
    pub long_sha: Option<String>,
    pub short_sha: Option<String>,
    pub subject: String,
    pub message: String,
    pub violations: Vec<Violation>,
    pub ignored_rules: Vec<Rule>,
}

impl Commit {
    pub fn new(long_sha: Option<String>, subject: String, message: String) -> Self {
        // Get first 7 characters of the commit SHA to get the short SHA.
        let short_sha = match &long_sha {
            Some(long) => match long.get(0..7) {
                Some(sha) => Some(sha.to_string()),
                None => {
                    debug!("Could not determine abbreviated SHA from SHA");
                    None
                }
            },
            None => None,
        };
        let ignored_rules = Self::find_ignored_rules(&message);
        Self {
            long_sha,
            short_sha,
            subject: subject.trim_end().to_string(),
            message,
            ignored_rules,
            violations: Vec::<Violation>::new(),
        }
    }

    pub fn find_ignored_rules(message: &str) -> Vec<Rule> {
        let disable_prefix = "lintje:disable ";
        let mut ignored = vec![];
        for line in message.lines().into_iter() {
            if let Some(name) = line.strip_prefix(disable_prefix) {
                match rule_by_name(name) {
                    Some(rule) => ignored.push(rule),
                    None => warn!("Attempted to ignore unknown rule: {}", name),
                }
            }
        }
        ignored
    }

    fn rule_ignored(&self, rule: Rule) -> bool {
        self.ignored_rules.contains(&rule)
    }

    pub fn is_valid(&self) -> bool {
        self.violations.is_empty()
    }

    pub fn validate(&mut self) {
        self.validate_merge_commit();
        self.validate_needs_rebase();
        self.validate_subject_line_length();
        self.validate_subject_mood();
        self.validate_subject_whitespace();
        self.validate_subject_capitalization();
        self.validate_subject_punctuation();
        self.validate_subject_ticket_numbers();
        self.validate_subject_prefix();
        self.validate_subject_build_tags();
        self.validate_subject_cliches();
        self.validate_message_second_line_empty();
        self.validate_message_presence();
        self.validate_message_line_length();
    }

    // Note: Some merge commits are ignored in git.rs and won't be validated here, because they are
    // Pull/Merge Requests, which are valid.
    fn validate_merge_commit(&mut self) {
        if self.rule_ignored(Rule::MergeCommit) {
            return;
        }

        let subject = &self.subject;
        if SUBJECT_WITH_MERGE_REMOTE_BRANCH.is_match(subject) {
            self.add_violation(
                Rule::MergeCommit,
                "Rebase branches on the remote branch, rather than merging the remote branch into the local branch.".to_string()
            )
        }
    }

    fn validate_needs_rebase(&mut self) {
        if self.rule_ignored(Rule::NeedsRebase) {
            return;
        }

        let subject = &self.subject;
        if subject.starts_with("fixup! ") {
            self.add_violation(
                Rule::NeedsRebase,
                "Rebase fixup commits before merging.".to_string(),
            )
        } else if subject.starts_with("squash! ") {
            self.add_violation(
                Rule::NeedsRebase,
                "Rebase squash commits before merging.".to_string(),
            )
        }
    }

    fn validate_subject_line_length(&mut self) {
        let length = self.subject.chars().count();
        if length > 50 {
            if self.rule_ignored(Rule::SubjectLength) {
                return;
            }

            self.add_violation(
                Rule::SubjectLength,
                format!(
                    "Subject is too long: {} characters. Shorten the subject to max 50 characters.",
                    length
                ),
            )
        }
        if length < 5 {
            if self.rule_ignored(Rule::SubjectLength) {
                return;
            }

            self.add_violation(
                Rule::SubjectLength,
                format!(
                    "Subject is too short: {} characters. Describe the change in more detail.",
                    length
                ),
            )
        }
    }

    fn validate_subject_mood(&mut self) {
        if self.rule_ignored(Rule::SubjectMood) {
            return;
        }

        match self.subject.split(' ').next() {
            Some(raw_word) => {
                let word = raw_word.to_lowercase();
                if MOOD_WORDS.contains(&word.as_str()) {
                    self.add_violation(
                        Rule::SubjectMood,
                        "Use the imperative mood for the commit subject.".to_string(),
                    )
                }
            }
            None => {
                error!("SubjectMood validation failure: No first word found of commit subject.")
            }
        }
    }

    fn validate_subject_whitespace(&mut self) {
        if self.rule_ignored(Rule::SubjectWhitespace) {
            return;
        }

        match self.subject.chars().next() {
            Some(character) => {
                if character.is_whitespace() {
                    self.add_violation(
                        Rule::SubjectWhitespace,
                        "Remove leading whitespace from the commit subject.".to_string(),
                    )
                }
            }
            None => {
                error!("SubjectWhitespace validation failure: No first character found of subject.")
            }
        }
    }

    fn validate_subject_capitalization(&mut self) {
        if self.rule_ignored(Rule::SubjectCapitalization) {
            return;
        }

        match self.subject.chars().next() {
            Some(character) => {
                if character.is_lowercase() {
                    self.add_violation(
                        Rule::SubjectCapitalization,
                        "Start the commit subject a capital letter.".to_string(),
                    )
                }
            }
            None => {
                error!("SubjectCapitalization validation failure: No first character found of subject.")
            }
        }
    }

    fn validate_subject_punctuation(&mut self) {
        if self.rule_ignored(Rule::SubjectPunctuation) {
            return;
        }

        if SUBJECT_STARTS_WITH_EMOJI.is_match(&self.subject) {
            self.add_violation(
                Rule::SubjectPunctuation,
                format!(
                    "Remove emoji from the start of the commit subject: {}",
                    self.subject
                ),
            )
        }

        match self.subject.chars().next() {
            Some(character) => {
                if is_punctuation(&character) {
                    self.add_violation(
                        Rule::SubjectPunctuation,
                        format!(
                            "Remove punctuation from the start of the commit subject: {}",
                            character
                        ),
                    )
                }
            }
            None => {
                error!(
                    "SubjectPunctuation validation failure: No first character found of subject."
                )
            }
        }

        match self.subject.chars().last() {
            Some(character) => {
                if is_punctuation(&character) {
                    self.add_violation(
                        Rule::SubjectPunctuation,
                        format!(
                            "Remove punctuation from the end of the commit subject: {}",
                            character
                        ),
                    )
                }
            }
            None => {
                error!("SubjectPunctuation validation failure: No last character found of subject.")
            }
        }
    }

    fn validate_subject_ticket_numbers(&mut self) {
        if self.rule_ignored(Rule::SubjectTicketNumber) {
            return;
        }

        let subject = &self.subject;
        if SUBJECT_WITH_TICKET.is_match(subject) || SUBJECT_WITH_FIX_TICKET.is_match(subject) {
            self.add_violation(
                Rule::SubjectTicketNumber,
                "Remove the ticket number from the commit subject. Move it to the message body."
                    .to_string(),
            )
        }
    }

    fn validate_subject_prefix(&mut self) {
        if self.rule_ignored(Rule::SubjectPrefix) {
            return;
        }

        let subject = &self.subject.to_string();
        if let Some(captures) = SUBJECT_STARTS_WITH_PREFIX.captures(subject) {
            // Get first match from captures, the prefix
            match captures.get(1) {
                Some(capture) => self.add_violation(
                    Rule::SubjectPrefix,
                    format!(
                        "Remove the prefix from the commit subject: \"{}\"",
                        capture.as_str()
                    ),
                ),
                None => error!("SubjectPrefix: Unable to fetch prefix capture from subject."),
            }
        }
    }

    fn validate_subject_build_tags(&mut self) {
        if self.rule_ignored(Rule::SubjectBuildTag) {
            return;
        }

        let subject = &self.subject.to_string();
        for tag in BUILD_TAGS.iter() {
            if subject.contains(tag) {
                self.add_violation(
                    Rule::SubjectBuildTag,
                    format!("Move the build tag `{}` to the message body.", tag),
                )
            }
        }
    }

    fn validate_subject_cliches(&mut self) {
        if self.rule_ignored(Rule::SubjectCliche) {
            return;
        }

        let subject = &self.subject.to_lowercase();
        let wip_commit = subject.starts_with("wip ") || subject == &"wip".to_string();
        if wip_commit {
            self.add_violation(
                Rule::SubjectCliche,
                "Reword the subject to describe the change in more detail.".to_string(),
            )
        } else if subject == &"fix test".to_string() {
            self.add_violation(
                Rule::SubjectCliche,
                "Reword the subject to explain which test was fixed.".to_string(),
            )
        } else if subject == &"fix bug".to_string() {
            self.add_violation(
                Rule::SubjectCliche,
                "Reword the subject to explain what bug was fixed.".to_string(),
            )
        } else if subject == &"fix".to_string() {
            self.add_violation(
                Rule::SubjectCliche,
                "Reword the subject to explain what was fixed.".to_string(),
            )
        }
    }

    fn validate_message_second_line_empty(&mut self) {
        if self.rule_ignored(Rule::MessageEmptyFirstLine) {
            return;
        }

        if let Some(line) = self.message.lines().next() {
            if !line.is_empty() {
                self.add_violation(
                    Rule::MessageEmptyFirstLine,
                    "Add an empty line below the subject line.".to_string(),
                );
            }
        }
    }

    fn validate_message_presence(&mut self) {
        if self.rule_ignored(Rule::MessagePresence) {
            return;
        }

        let length = self.message.chars().count();
        if length == 0 {
            self.add_violation(
                Rule::MessagePresence,
                "Add a message body to provide more context about the change and why it was made."
                    .to_string(),
            )
        } else if length < 10 {
            self.add_violation(
                Rule::MessagePresence,
                "Add a longer message body to provide more context about the change and why it was made.".to_string(),
            )
        }
    }

    fn validate_message_line_length(&mut self) {
        if self.rule_ignored(Rule::MessageLineLength) {
            return;
        }

        let mut code_block_style = CodeBlockStyle::None;
        let mut previous_line_was_empty_line = false;
        let mut violations = vec![];
        for (index, raw_line) in self.message.lines().enumerate() {
            let line = raw_line.trim_end();
            let length = line.chars().count();
            match code_block_style {
                CodeBlockStyle::Fenced => {
                    if CODE_BLOCK_LINE_END.is_match(line) {
                        code_block_style = CodeBlockStyle::None
                    }
                }
                CodeBlockStyle::Indenting => {
                    if !line.starts_with("    ") {
                        code_block_style = CodeBlockStyle::None;
                    }
                }
                CodeBlockStyle::None => {
                    if CODE_BLOCK_LINE_WITH_LANGUAGE.is_match(line) {
                        code_block_style = CodeBlockStyle::Fenced
                    } else if line.starts_with("    ") && previous_line_was_empty_line {
                        code_block_style = CodeBlockStyle::Indenting
                    }
                }
            }
            if code_block_style != CodeBlockStyle::None {
                // When in a code block, skip line length validation
                continue;
            }
            if length > 72 {
                if URL_REGEX.is_match(line) {
                    continue;
                }
                violations.push((
                    Rule::MessageLineLength,
                    format!("Line {} of the message body is too long. Shorten the line to maximum 72 characters.", index + 1),
                ))
            }
            previous_line_was_empty_line = line.trim() == "";
        }

        for (rule, message) in violations {
            self.add_violation(rule, message);
        }
    }

    fn add_violation(&mut self, rule: Rule, message: String) {
        self.violations.push(Violation { rule, message })
    }
}

fn is_punctuation(character: &char) -> bool {
    character.is_ascii_punctuation() || OTHER_PUNCTUATION.contains(&character)
}

#[derive(PartialEq)]
enum CodeBlockStyle {
    None,
    Fenced,
    Indenting,
}

#[cfg(test)]
mod tests {
    use super::{Commit, Rule, Violation, BUILD_TAGS, MOOD_WORDS};

    fn commit_with_sha(sha: Option<String>, subject: String, message: String) -> Commit {
        Commit::new(sha, subject, message)
    }

    fn commit(subject: String, message: String) -> Commit {
        commit_with_sha(
            Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()),
            subject,
            message,
        )
    }

    fn validated_commit(subject: String, message: String) -> Commit {
        let mut commit = commit(subject, message);
        commit.validate();
        commit
    }

    fn assert_commit_valid_for(commit: Commit, rule: &Rule) {
        assert!(
            !has_violation(&commit.violations, rule),
            "Commit was not considered valid: {:?}",
            commit
        );
    }

    fn assert_commit_invalid_for(commit: Commit, rule: &Rule) {
        assert!(
            has_violation(&commit.violations, rule),
            "Commit was not considered invalid: {:?}",
            commit
        );
    }

    fn assert_commit_subject_as_valid(subject: &str, rule: &Rule) {
        let commit = validated_commit(subject.to_string(), "".to_string());
        assert_commit_valid_for(commit, rule);
    }

    fn assert_commit_subjects_as_valid(subjects: Vec<&str>, rule: &Rule) {
        for subject in subjects {
            assert_commit_subject_as_valid(subject, rule)
        }
    }

    fn assert_commit_subject_as_invalid<S: AsRef<str>>(subject: S, rule: &Rule) {
        let commit = validated_commit(subject.as_ref().to_string(), "".to_string());
        assert_commit_invalid_for(commit, rule);
    }

    fn assert_commit_subjects_as_invalid<S: AsRef<str>>(subjects: Vec<S>, rule: &Rule) {
        for subject in subjects {
            assert_commit_subject_as_invalid(subject, rule)
        }
    }

    fn has_violation(violations: &Vec<Violation>, rule: &Rule) -> bool {
        violations.iter().any(|v| &v.rule == rule)
    }

    fn assert_has_violation<S: AsRef<str>>(commit: &Commit, rule: Rule, message: S) {
        let violation = commit
            .violations
            .iter()
            .find(|v| v.rule == rule)
            .unwrap_or_else(|| panic!("Could not find violation"));
        assert_eq!(message.as_ref().to_string(), violation.message);
    }

    #[test]
    fn test_create_short_sha() {
        let long_sha = Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string());
        let with_long_sha = commit_with_sha(long_sha, "Subject".to_string(), "Message".to_string());
        assert_eq!(
            with_long_sha.long_sha,
            Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string())
        );
        assert_eq!(with_long_sha.short_sha, Some("aaaaaaa".to_string()));

        let long_sha = Some("a".to_string());
        let without_long_sha =
            commit_with_sha(long_sha, "Subject".to_string(), "Message".to_string());
        assert_eq!(without_long_sha.long_sha, Some("a".to_string()));
        assert_eq!(without_long_sha.short_sha, None);
    }

    #[test]
    fn test_validate_subject_merge_commit() {
        assert_commit_subject_as_valid("I am not a merge commit", &Rule::MergeCommit);
        assert_commit_subject_as_valid("Merge pull request #123 from repo", &Rule::MergeCommit);
        // Merge into the project's defaultBranch branch
        assert_commit_subject_as_valid("Merge branch 'develop'", &Rule::MergeCommit);
        // Merge a local branch into another local branch
        assert_commit_subject_as_valid(
            "Merge branch 'develop' into feature-branch",
            &Rule::MergeCommit,
        );
        // Merge a remote branch into a local branch
        let remote_merge_commit = validated_commit(
            "Merge branch 'develop' of github.com/org/repo into develop".to_string(),
            "".to_string(),
        );
        assert_has_violation(
            &remote_merge_commit,
            Rule::MergeCommit,
            "Rebase branches on the remote branch, rather than merging the remote branch into the local branch.",
        );

        let ignore_commit = validated_commit(
            "Merge branch 'develop' of github.com/org/repo into develop".to_string(),
            "lintje:disable MergeCommit".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::MergeCommit);
    }

    #[test]
    fn test_validate_needs_rebase() {
        assert_commit_subject_as_valid("I don't need a rebase", &Rule::NeedsRebase);
        assert_commit_subject_as_invalid("fixup! I don't need a rebase", &Rule::NeedsRebase);
        assert_commit_subject_as_invalid("squash! I don't need a rebase", &Rule::NeedsRebase);

        let ignore_commit = validated_commit(
            "fixup! I don't need to be rebased".to_string(),
            "lintje:disable NeedsRebase".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::NeedsRebase);
    }

    #[test]
    fn test_validate_subject_line_length() {
        let subject = "a".repeat(50);
        assert_commit_subject_as_valid(subject.as_str(), &Rule::SubjectLength);

        assert_commit_subject_as_invalid("", &Rule::SubjectLength);

        let short_subject = "a".repeat(4);
        assert_commit_subject_as_invalid(short_subject.as_str(), &Rule::SubjectLength);

        let long_subject = "a".repeat(51);
        assert_commit_subject_as_invalid(long_subject.as_str(), &Rule::SubjectLength);

        let emoji_subject = "".repeat(50);
        assert_commit_subject_as_valid(emoji_subject.as_str(), &Rule::SubjectLength);

        let hiragana_short_subject = "".repeat(50);
        assert_commit_subject_as_valid(hiragana_short_subject.as_str(), &Rule::SubjectLength);

        let hiragana_long_subject = "".repeat(51);
        assert_commit_subject_as_invalid(hiragana_long_subject.as_str(), &Rule::SubjectLength);

        let ignore_commit = validated_commit(
            "a".repeat(51).to_string(),
            "lintje:disable SubjectLength".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectLength);
    }

    #[test]
    fn test_validate_subject_mood() {
        let subjects = vec!["Fix test"];
        assert_commit_subjects_as_valid(subjects, &Rule::SubjectMood);

        let mut invalid_subjects = vec![];
        for word in MOOD_WORDS.iter() {
            invalid_subjects.push(format!("{} test", word));
            let mut chars = word.chars();
            let capitalized_word = match chars.next() {
                None => panic!("Could not capitalize word: {}", word),
                Some(letter) => letter.to_uppercase().collect::<String>() + chars.as_str(),
            };
            invalid_subjects.push(format!("{} test", capitalized_word));
        }
        for subject in invalid_subjects {
            assert_commit_subject_as_invalid(subject.as_str(), &Rule::SubjectMood);
        }

        let ignore_commit = validated_commit(
            "Fixed test".to_string(),
            "lintje:disable SubjectMood".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectMood);
    }

    #[test]
    fn test_validate_subject_whitespace() {
        let subjects = vec!["Fix test"];
        assert_commit_subjects_as_valid(subjects, &Rule::SubjectWhitespace);

        let invalid_subjects = vec![" Fix test", "\tFix test", "\x20Fix test"];
        assert_commit_subjects_as_invalid(invalid_subjects, &Rule::SubjectWhitespace);

        let ignore_commit = validated_commit(
            " Fix test".to_string(),
            "lintje:disable SubjectWhitespace".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectWhitespace);
    }

    #[test]
    fn test_validate_subject_capitalization() {
        let subjects = vec!["Fix test"];
        assert_commit_subjects_as_valid(subjects, &Rule::SubjectCapitalization);

        let invalid_subjects = vec!["fix test"];
        assert_commit_subjects_as_invalid(invalid_subjects, &Rule::SubjectCapitalization);

        let ignore_commit = validated_commit(
            "fix test".to_string(),
            "lintje:disable SubjectCapitalization".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectCapitalization);
    }

    #[test]
    fn test_validate_subject_punctuation() {
        let subjects = vec!["Fix test", "あ commit"];
        assert_commit_subjects_as_valid(subjects, &Rule::SubjectPunctuation);

        let invalid_subjects = vec![
            "Fix test.",
            "Fix test!",
            "Fix test?",
            "Fix test:",
            "Fix test\'",
            "Fix test\"",
            "Fix test…",
            "Fix test⋯",
            ".Fix test",
            "!Fix test",
            "?Fix test",
            ":Fix test",
            "…Fix test",
            "⋯Fix test",
            "📺Fix test",
            "👍Fix test",
            "👍🏻Fix test",
            "[JIRA-123] Fix test",
            "[Bug] Fix test",
            "[chore] Fix test",
            "[feat] Fix test",
            "(feat) Fix test",
            "{fix} Fix test",
            "|fix| Fix test",
            "-fix- Fix test",
            "+fix+ Fix test",
            "*fix* Fix test",
            "%fix% Fix test",
            "@fix Fix test",
        ];
        assert_commit_subjects_as_invalid(invalid_subjects, &Rule::SubjectPunctuation);

        let ignore_commit = validated_commit(
            "Fix test.".to_string(),
            "lintje:disable SubjectPunctuation".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectPunctuation);
    }

    #[test]
    fn test_validate_subject_ticket() {
        let valid_ticket_subjects = vec![
            "This is a normal commit",
            "Fix #", // Not really good subjects, but won't fail on this rule
            "Fix ##123",
            "Fix #a123",
            "Fix !",
            "Fix !!123",
            "Fix !a123",
        ];
        assert_commit_subjects_as_valid(valid_ticket_subjects, &Rule::SubjectTicketNumber);

        let invalid_ticket_subjects = vec!["JIRA-1234", "Fix JIRA-1234 lorem"];
        assert_commit_subjects_as_invalid(invalid_ticket_subjects, &Rule::SubjectTicketNumber);

        let invalid_subjects = vec![
            "Fix {}1234",
            "Fixed {}1234",
            "Fixes {}1234",
            "Fixing {}1234",
            "Fix {}1234 lorem",
            "Fix: {}1234 lorem",
            "Fix my-org/repo{}1234 lorem",
            "Fix https://examplegithosting.com/my-org/repo{}1234 lorem",
            "Commit fixes {}1234",
            "Close {}1234",
            "Closed {}1234",
            "Closes {}1234",
            "Closing {}1234",
            "Close {}1234 lorem",
            "Close: {}1234 lorem",
            "Commit closes {}1234",
            "Resolve {}1234",
            "Resolved {}1234",
            "Resolves {}1234",
            "Resolving {}1234",
            "Resolve {}1234 lorem",
            "Resolve: {}1234 lorem",
            "Commit resolves {}1234",
            "Implement {}1234",
            "Implemented {}1234",
            "Implements {}1234",
            "Implementing {}1234",
            "Implement {}1234 lorem",
            "Implement: {}1234 lorem",
            "Commit implements {}1234",
        ];
        let invalid_issue_subjects = invalid_subjects
            .iter()
            .map(|s| s.replace("{}", "#"))
            .collect();
        assert_commit_subjects_as_invalid(invalid_issue_subjects, &Rule::SubjectTicketNumber);
        let invalid_merge_request_subjects = invalid_subjects
            .iter()
            .map(|s| s.replace("{}", "!"))
            .collect();
        assert_commit_subjects_as_invalid(
            invalid_merge_request_subjects,
            &Rule::SubjectTicketNumber,
        );

        let ignore_ticket_number = validated_commit(
            "Fix bug with 'JIRA-1234' type commits".to_string(),
            "lintje:disable SubjectTicketNumber".to_string(),
        );
        assert_commit_valid_for(ignore_ticket_number, &Rule::SubjectTicketNumber);

        let ignore_issue_number = validated_commit(
            "Fix bug with 'Fix #1234' type commits".to_string(),
            "lintje:disable SubjectTicketNumber".to_string(),
        );
        assert_commit_valid_for(ignore_issue_number, &Rule::SubjectTicketNumber);

        let ignore_merge_request_number = validated_commit(
            "Fix bug with 'Fix !1234' type commits".to_string(),
            "lintje:disable SubjectTicketNumber".to_string(),
        );
        assert_commit_valid_for(ignore_merge_request_number, &Rule::SubjectTicketNumber);
    }

    #[test]
    fn test_validate_subject_prefix() {
        let subjects = vec!["This is a commit without prefix"];
        assert_commit_subjects_as_valid(subjects, &Rule::SubjectPrefix);

        let invalid_subjects = vec![
            "fix: bug",
            "fix!: bug",
            "Fix: bug",
            "Fix!: bug",
            "fix(scope): bug",
            "fix(scope)!: bug",
            "Fix(scope123)!: bug",
            "fix(scope/scope): bug",
            "fix(scope/scope)!: bug",
        ];
        assert_commit_subjects_as_invalid(invalid_subjects, &Rule::SubjectPrefix);

        assert_has_violation(
            &validated_commit("fix: bug".to_string(), "".to_string()),
            Rule::SubjectPrefix,
            "Remove the prefix from the commit subject: \"fix:\"",
        );

        let ignore_commit = validated_commit(
            "fix: bug".to_string(),
            "lintje:disable SubjectPrefix".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectPrefix);
    }

    #[test]
    fn test_validate_subject_build_tags() {
        let subjects = vec!["Add exception for no ci build tag"];
        assert_commit_subjects_as_valid(subjects, &Rule::SubjectBuildTag);

        let mut invalid_subjects = vec![];
        for tag in BUILD_TAGS.iter() {
            invalid_subjects.push(format!("Update README {}", tag))
        }
        assert_commit_subjects_as_invalid(invalid_subjects, &Rule::SubjectBuildTag);

        let ignore_commit = validated_commit(
            "Update README [ci skip]".to_string(),
            "lintje:disable SubjectBuildTag".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectBuildTag);
    }

    #[test]
    fn test_validate_subject_cliches() {
        let subjects = vec![
            "I am not a cliche",
            "Fix test for some feature",
            "Fix bug for some feature",
        ];
        assert_commit_subjects_as_valid(subjects, &Rule::SubjectCliche);

        let invalid_subjects = vec![
            "WIP something",
            "wip something",
            "Wip something",
            "WIP",
            "wip",
            "Fix test",
            "fix test",
            "Fix bug",
            "fix bug",
            "Fix",
            "fix",
            "FIX",
        ];
        assert_commit_subjects_as_invalid(invalid_subjects, &Rule::SubjectCliche);

        let ignore_commit = validated_commit(
            "WIP".to_string(),
            "lintje:disable SubjectCliche".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::SubjectCliche);
    }

    #[test]
    fn test_validate_message_first_line_empty() {
        let with_empty_line = validated_commit(
            "Subject".to_string(),
            "\nEmpty line after subject.".to_string(),
        );
        assert_commit_valid_for(with_empty_line, &Rule::MessageEmptyFirstLine);

        let without_empty_line = validated_commit(
            "Subject".to_string(),
            "No empty line after subject.".to_string(),
        );
        assert_commit_invalid_for(without_empty_line, &Rule::MessageEmptyFirstLine);

        let ignore_commit = validated_commit(
            "Subject".to_string(),
            "No empty line after subject\nlintje:disable MessageEmptyFirstLine".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::MessageEmptyFirstLine);
    }

    #[test]
    fn test_validate_message_presence() {
        let commit1 = validated_commit("Subject".to_string(), "Hello I am a message.".to_string());
        assert_commit_valid_for(commit1, &Rule::MessagePresence);

        let commit2 = validated_commit("Subject".to_string(), "".to_string());
        assert_commit_invalid_for(commit2, &Rule::MessagePresence);

        let commit3 = validated_commit("Subject".to_string(), "Short.".to_string());
        assert_commit_invalid_for(commit3, &Rule::MessagePresence);

        let commit4 = validated_commit("Subject".to_string(), "...".to_string());
        assert_commit_invalid_for(commit4, &Rule::MessagePresence);

        let ignore_commit = validated_commit(
            "Subject".to_string(),
            "lintje:disable MessagePresence".to_string(),
        );
        assert_commit_valid_for(ignore_commit, &Rule::MessagePresence);
    }

    #[test]
    fn test_validate_message_line_length() {
        let message1 = ["Hello I am a message.", "Line 2.", &"a".repeat(72)].join("\n");
        let commit1 = validated_commit("Subject".to_string(), message1);
        assert_commit_valid_for(commit1, &Rule::MessageLineLength);

        let message2 = ["a".repeat(72), "a".repeat(73)].join("\n");
        let commit2 = validated_commit("Subject".to_string(), message2);
        assert_commit_invalid_for(commit2, &Rule::MessageLineLength);

        let message3 = [
            "This message is accepted.".to_string(),
            "This a long line with a link https://tomdebruijn.com/posts/git-is-about-communication/".to_string()
        ].join("\n");
        let commit3 = validated_commit("Subject".to_string(), message3);
        assert_commit_valid_for(commit3, &Rule::MessageLineLength);

        let message4 = [
            "This message is accepted.".to_string(),
            "This a long line with a link http://tomdebruijn.com/posts/git-is-about-communication/"
                .to_string(),
        ]
        .join("\n");
        let commit4 = validated_commit("Subject".to_string(), message4);
        assert_commit_valid_for(commit4, &Rule::MessageLineLength);

        let message5 = [
            "This a too long line with only protocols http:// https:// which is not accepted."
                .to_string(),
        ]
        .join("\n");
        let commit5 = validated_commit("Subject".to_string(), message5);
        assert_commit_invalid_for(commit5, &Rule::MessageLineLength);

        let hiragana_short_message = ["".repeat(72)].join("\n");
        let hiragana_short_commit = validated_commit("Subject".to_string(), hiragana_short_message);
        assert_commit_valid_for(hiragana_short_commit, &Rule::MessageLineLength);

        let hiragana_long_message = ["".repeat(73)].join("\n");
        let hiragana_long_commit = validated_commit("Subject".to_string(), hiragana_long_message);
        assert_commit_invalid_for(hiragana_long_commit, &Rule::MessageLineLength);

        let ignore_message = [
            "a".repeat(72),
            "a".repeat(73),
            "lintje:disable MessageLineLength".to_string(),
        ]
        .join("\n");
        let ignore_commit = validated_commit("Subject".to_string(), ignore_message);
        assert_commit_valid_for(ignore_commit, &Rule::MessageLineLength);
    }

    #[test]
    fn test_validate_message_line_length_in_code_block() {
        let valid_fenced_code_blocks = [
            "Beginning of message.",
            "```",
            &"a".repeat(73), // Valid, inside code block
            &"b".repeat(73),
            &"c".repeat(73),
            "```",
            "Normal line",
            "```md",
            "I am markdown",
            &"d".repeat(73), // Valid, inside code block
            "```",
            "Normal line",
            "``` yaml",
            "I am yaml",
            &"d".repeat(73), // Valid, inside code block
            "```",
            "Normal line",
            "```  elixir ",
            "I am elixir",
            &"d".repeat(73), // Valid, inside code block
            "```",
            "",
            "  ```",
            "  I am elixir",
            &"  d".repeat(73), // Valid, inside fenced indented code block
            "  ```",
            "End of message",
        ]
        .join("\n");
        assert_commit_valid_for(
            validated_commit("Subject".to_string(), valid_fenced_code_blocks),
            &Rule::MessageLineLength,
        );

        let invalid_long_line_outside_fenced_code_block = [
            "Beginning of message.",
            "```",
            &"a".repeat(73),
            "```",
            &"a".repeat(73), // Long line outside code block is invalid
            "End of message",
        ]
        .join("\n");
        assert_commit_invalid_for(
            validated_commit(
                "Subject".to_string(),
                invalid_long_line_outside_fenced_code_block,
            ),
            &Rule::MessageLineLength,
        );

        let invalid_fenced_code_block_language_identifier = [
            "Beginning of message.",
            "``` m d", // Invald language identifier
            &"a".repeat(73),
            "```",
            "End of message",
        ]
        .join("\n");
        assert_commit_invalid_for(
            validated_commit(
                "Subject".to_string(),
                invalid_fenced_code_block_language_identifier,
            ),
            &Rule::MessageLineLength,
        );

        let valid_indented_code_blocks = [
            "Beginning of message.",
            "",
            "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
            "",
            "    ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
            "    ",
            "    ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
            "",
            "End of message",
        ]
        .join("\n");
        assert_commit_valid_for(
            validated_commit("Subject".to_string(), valid_indented_code_blocks),
            &Rule::MessageLineLength,
        );

        let invalid_long_ling_outside_indended_code_block = [
            "Beginning of message.",
            "",
            "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
            "",
            "    ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
            "",
            "End of message",
            &"a".repeat(73), // Long line outside code block is invalid
        ]
        .join("\n");
        assert_commit_invalid_for(
            validated_commit(
                "Subject".to_string(),
                invalid_long_ling_outside_indended_code_block,
            ),
            &Rule::MessageLineLength,
        );
    }
}