|
| 1 | +# (C) 2025 GoodData Corporation |
| 2 | +""" |
| 3 | +An extension of the CT1 rule from gitlint to enforce the conventional commit format. |
| 4 | +This version also allows specifying allowed scope values. |
| 5 | +""" |
| 6 | + |
| 7 | +import re |
| 8 | + |
| 9 | +from gitlint.options import ListOption |
| 10 | +from gitlint.rules import CommitMessageTitle, LineRule, RuleViolation |
| 11 | + |
| 12 | +RULE_REGEX = re.compile(r"([^(]+?)(?:\(([^)]+?)\))?!?: .+") |
| 13 | + |
| 14 | +DEFAULT_TYPES = [ |
| 15 | + "fix", |
| 16 | + "feat", |
| 17 | + "chore", |
| 18 | + "docs", |
| 19 | + "style", |
| 20 | + "refactor", |
| 21 | + "perf", |
| 22 | + "test", |
| 23 | + "revert", |
| 24 | + "ci", |
| 25 | + "build", |
| 26 | +] |
| 27 | +DEFAULT_SCOPES = [] |
| 28 | + |
| 29 | + |
| 30 | +class ConventionalCommit(LineRule): |
| 31 | + """This rule enforces the spec at https://www.conventionalcommits.org/.""" |
| 32 | + |
| 33 | + name = "gdc-title-conventional-commits" |
| 34 | + id = "GD1" |
| 35 | + target = CommitMessageTitle |
| 36 | + |
| 37 | + options_spec = [ |
| 38 | + ListOption( |
| 39 | + "types", |
| 40 | + DEFAULT_TYPES, |
| 41 | + "Comma separated list of allowed commit types.", |
| 42 | + ), |
| 43 | + ListOption( |
| 44 | + "scopes", |
| 45 | + DEFAULT_SCOPES, |
| 46 | + "Comma separated list of allowed commit scopes.", |
| 47 | + ), |
| 48 | + ] |
| 49 | + |
| 50 | + def validate(self, line, _commit): |
| 51 | + violations = [] |
| 52 | + match = RULE_REGEX.match(line) |
| 53 | + |
| 54 | + if not match: |
| 55 | + msg = "Title does not follow ConventionalCommits.org format 'type(optional-scope): description'" |
| 56 | + violations.append(RuleViolation(self.id, msg, line)) |
| 57 | + else: |
| 58 | + line_commit_type = match.group(1) |
| 59 | + line_commit_scope = match.group(2) |
| 60 | + if line_commit_type not in self.options["types"].value: |
| 61 | + opt_str = ", ".join(self.options["types"].value) |
| 62 | + violations.append(RuleViolation(self.id, f"Title does not start with one of {opt_str}", line)) |
| 63 | + if line_commit_scope and line_commit_scope not in self.options["scopes"].value: |
| 64 | + opt_str = ", ".join(self.options["scopes"].value) |
| 65 | + violations.append(RuleViolation(self.id, f"Scope is defined and is not one of {opt_str}", line)) |
| 66 | + |
| 67 | + return violations |
0 commit comments