blob: f6006ff3921d0e39165df688a313078167cb0d9a [file] [log] [blame]
Anas Nashifa35378e2017-04-22 11:59:30 -04001from gitlint.rules import CommitRule, RuleViolation
2from gitlint.options import IntOption
Anas Nashif1338f492017-05-05 16:39:34 -04003import re
Anas Nashifa35378e2017-04-22 11:59:30 -04004
5"""
6The classes below are examples of user-defined CommitRules. Commit rules are gitlint rules that
7act on the entire commit at once. Once the rules are discovered, gitlint will automatically take care of applying them
8to the entire commit. This happens exactly once per commit.
9
10A CommitRule contrasts with a LineRule (see examples/my_line_rules.py) in that a commit rule is only applied once on
11an entire commit. This allows commit rules to implement more complex checks that span multiple lines and/or checks
12that should only be done once per gitlint run.
13
14While every LineRule can be implemented as a CommitRule, it's usually easier and more concise to go with a LineRule if
15that fits your needs.
16"""
17
18
19class BodyMaxLineCount(CommitRule):
20 # A rule MUST have a human friendly name
21 name = "body-max-line-count"
22
23 # A rule MUST have an *unique* id, we recommend starting with UC (for User-defined Commit-rule).
24 id = "UC1"
25
26 # A rule MAY have an option_spec if its behavior should be configurable.
27 options_spec = [IntOption('max-line-count', 3, "Maximum body line count")]
28
29 def validate(self, commit):
30 line_count = len(commit.message.body)
31 max_line_count = self.options['max-line-count'].value
32 if line_count > max_line_count:
33 message = "Body contains too many lines ({0} > {1})".format(line_count, max_line_count)
34 return [RuleViolation(self.id, message, line_nr=1)]
35
36
37class SignedOffBy(CommitRule):
38 """ This rule will enforce that each commit contains a "Signed-Off-By" line.
39 We keep things simple here and just check whether the commit body contains a line that starts with "Signed-Off-By".
40 """
41
42 # A rule MUST have a human friendly name
43 name = "body-requires-signed-off-by"
44
45 # A rule MUST have an *unique* id, we recommend starting with UC (for User-defined Commit-rule).
46 id = "UC2"
47
48 def validate(self, commit):
Anas Nashif1338f492017-05-05 16:39:34 -040049 flags = re.UNICODE
50 flags |= re.IGNORECASE
Anas Nashifa35378e2017-04-22 11:59:30 -040051 for line in commit.message.body:
52 if line.lower().startswith("signed-off-by"):
Anas Nashif1338f492017-05-05 16:39:34 -040053 if not re.search('(^)Signed-off-by: ([-\w.]+) ([-\w.]+) (.*)', line, flags=flags):
54 return [RuleViolation(self.id, "Signed-off-by: must have a full name", line_nr=1)]
55 else:
56 return
Anas Nashifa35378e2017-04-22 11:59:30 -040057 return [RuleViolation(self.id, "Body does not contain a 'Signed-Off-By' line", line_nr=1)]