Skip to content

Commit cce18ed

Browse files
LoopThrough-i-jtimabbott
authored andcommitted
lint: Setup gitlint.
Setup gitlint for developers to write well formatted commit messages. Note: .gitlint, gitlint-rules.py and lint-commits are taken directly from zulip/zulip with minor changes.
1 parent f8cd424 commit cce18ed

File tree

5 files changed

+193
-0
lines changed

5 files changed

+193
-0
lines changed

.gitlint

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# This file is copied from the original .gitlint at zulip/zulip.
2+
# Please don't edit here; instead update the zulip/zulip copy and then resync this file.
3+
4+
[general]
5+
ignore=title-trailing-punctuation, body-min-length, body-is-missing
6+
extra-path=tools/gitlint-rules.py
7+
8+
[title-match-regex]
9+
regex=^(.+:\ )?[A-Z].+\.$
10+
11+
[title-max-length]
12+
line-length=76
13+
14+
[body-max-line-length]
15+
line-length=76

requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ pytest
99
-e ./zulip_botserver
1010
-e git+https://github.com/zulip/zulint@14e3974001bf8442a6a3486125865660f1f2eb68#egg=zulint==1.0.0
1111
mypy==0.790
12+
gitlint>=0.13.0

tools/gitlint-rules.py

+145
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
# This file is copied from the original at tools/lib/gitlint-rules.py in zulip/zulip.
2+
# Please don't edit here; instead update the zulip/zulip copy and then resync this file.
3+
4+
from typing import List
5+
6+
from gitlint.git import GitCommit
7+
from gitlint.rules import CommitMessageTitle, LineRule, RuleViolation
8+
9+
# Word list from https://github.com/m1foley/fit-commit
10+
# Copyright (c) 2015 Mike Foley
11+
# License: MIT
12+
# Ref: fit_commit/validators/tense.rb
13+
WORD_SET = {
14+
'adds', 'adding', 'added',
15+
'allows', 'allowing', 'allowed',
16+
'amends', 'amending', 'amended',
17+
'bumps', 'bumping', 'bumped',
18+
'calculates', 'calculating', 'calculated',
19+
'changes', 'changing', 'changed',
20+
'cleans', 'cleaning', 'cleaned',
21+
'commits', 'committing', 'committed',
22+
'corrects', 'correcting', 'corrected',
23+
'creates', 'creating', 'created',
24+
'darkens', 'darkening', 'darkened',
25+
'disables', 'disabling', 'disabled',
26+
'displays', 'displaying', 'displayed',
27+
'documents', 'documenting', 'documented',
28+
'drys', 'drying', 'dryed',
29+
'ends', 'ending', 'ended',
30+
'enforces', 'enforcing', 'enforced',
31+
'enqueues', 'enqueuing', 'enqueued',
32+
'extracts', 'extracting', 'extracted',
33+
'finishes', 'finishing', 'finished',
34+
'fixes', 'fixing', 'fixed',
35+
'formats', 'formatting', 'formatted',
36+
'guards', 'guarding', 'guarded',
37+
'handles', 'handling', 'handled',
38+
'hides', 'hiding', 'hid',
39+
'increases', 'increasing', 'increased',
40+
'ignores', 'ignoring', 'ignored',
41+
'implements', 'implementing', 'implemented',
42+
'improves', 'improving', 'improved',
43+
'keeps', 'keeping', 'kept',
44+
'kills', 'killing', 'killed',
45+
'makes', 'making', 'made',
46+
'merges', 'merging', 'merged',
47+
'moves', 'moving', 'moved',
48+
'permits', 'permitting', 'permitted',
49+
'prevents', 'preventing', 'prevented',
50+
'pushes', 'pushing', 'pushed',
51+
'rebases', 'rebasing', 'rebased',
52+
'refactors', 'refactoring', 'refactored',
53+
'removes', 'removing', 'removed',
54+
'renames', 'renaming', 'renamed',
55+
'reorders', 'reordering', 'reordered',
56+
'replaces', 'replacing', 'replaced',
57+
'requires', 'requiring', 'required',
58+
'restores', 'restoring', 'restored',
59+
'sends', 'sending', 'sent',
60+
'sets', 'setting',
61+
'separates', 'separating', 'separated',
62+
'shows', 'showing', 'showed',
63+
'simplifies', 'simplifying', 'simplified',
64+
'skips', 'skipping', 'skipped',
65+
'sorts', 'sorting',
66+
'speeds', 'speeding', 'sped',
67+
'starts', 'starting', 'started',
68+
'supports', 'supporting', 'supported',
69+
'takes', 'taking', 'took',
70+
'testing', 'tested', # 'tests' excluded to reduce false negative
71+
'truncates', 'truncating', 'truncated',
72+
'updates', 'updating', 'updated',
73+
'uses', 'using', 'used',
74+
}
75+
76+
imperative_forms = [
77+
'add', 'allow', 'amend', 'bump', 'calculate', 'change', 'clean', 'commit',
78+
'correct', 'create', 'darken', 'disable', 'display', 'document', 'dry',
79+
'end', 'enforce', 'enqueue', 'extract', 'finish', 'fix', 'format', 'guard',
80+
'handle', 'hide', 'ignore', 'implement', 'improve', 'increase', 'keep',
81+
'kill', 'make', 'merge', 'move', 'permit', 'prevent', 'push', 'rebase',
82+
'refactor', 'remove', 'rename', 'reorder', 'replace', 'require', 'restore',
83+
'send', 'separate', 'set', 'show', 'simplify', 'skip', 'sort', 'speed',
84+
'start', 'support', 'take', 'test', 'truncate', 'update', 'use',
85+
]
86+
imperative_forms.sort()
87+
88+
89+
def head_binary_search(key: str, words: List[str]) -> str:
90+
""" Find the imperative mood version of `word` by looking at the first
91+
3 characters. """
92+
93+
# Edge case: 'disable' and 'display' have the same 3 starting letters.
94+
if key in ['displays', 'displaying', 'displayed']:
95+
return 'display'
96+
97+
lower = 0
98+
upper = len(words) - 1
99+
100+
while True:
101+
if lower > upper:
102+
# Should not happen
103+
raise Exception(f"Cannot find imperative mood of {key}")
104+
105+
mid = (lower + upper) // 2
106+
imperative_form = words[mid]
107+
108+
if key[:3] == imperative_form[:3]:
109+
return imperative_form
110+
elif key < imperative_form:
111+
upper = mid - 1
112+
elif key > imperative_form:
113+
lower = mid + 1
114+
115+
116+
class ImperativeMood(LineRule):
117+
""" This rule will enforce that the commit message title uses imperative
118+
mood. This is done by checking if the first word is in `WORD_SET`, if so
119+
show the word in the correct mood. """
120+
121+
name = "title-imperative-mood"
122+
id = "Z1"
123+
target = CommitMessageTitle
124+
125+
error_msg = ('The first word in commit title should be in imperative mood '
126+
'("{word}" -> "{imperative}"): "{title}"')
127+
128+
def validate(self, line: str, commit: GitCommit) -> List[RuleViolation]:
129+
violations = []
130+
131+
# Ignore the section tag (ie `<section tag>: <message body>.`)
132+
words = line.split(': ', 1)[-1].split()
133+
first_word = words[0].lower()
134+
135+
if first_word in WORD_SET:
136+
imperative = head_binary_search(first_word, imperative_forms)
137+
violation = RuleViolation(self.id, self.error_msg.format(
138+
word=first_word,
139+
imperative=imperative,
140+
title=commit.message.title,
141+
))
142+
143+
violations.append(violation)
144+
145+
return violations

tools/lint

+5
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ EXCLUDED_FILES = [
1515
def run() -> None:
1616
parser = argparse.ArgumentParser()
1717
add_default_linter_arguments(parser)
18+
parser.add_argument('--no-gitlint', action='store_true', help='Disable gitlint')
1819
args = parser.parse_args()
1920

2021
linter_config = LinterConfig(args)
@@ -27,6 +28,10 @@ def run() -> None:
2728
linter_config.external_linter('flake8', ['flake8'], ['py'],
2829
description="Standard Python linter (config: .flake8)")
2930

31+
if not args.no_gitlint:
32+
linter_config.external_linter('gitlint', ['tools/lint-commits'],
33+
description="Git Lint for commit messages")
34+
3035
@linter_config.lint
3136
def custom_py() -> int:
3237
"""Runs custom checks for python files (config: tools/linter_lib/custom_check.py)"""

tools/lint-commits

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/bin/bash
2+
3+
# This file is copied from the original tools/commit-message-lint at zulip/zulip,
4+
# Edited at Line 14 Col 97 (zulip -> python-zulip-api)
5+
# Please don't edit here; instead update the zulip/zulip copy and then resync this file.
6+
7+
# Lint all commit messages that are newer than upstream/master if running
8+
# locally or the commits in the push or PR Gh-Actions.
9+
10+
# The rules can be found in /.gitlint
11+
12+
if [[ "
13+
$(git remote -v)
14+
" =~ '
15+
'([^[:space:]]*)[[:space:]]*(https://github\.com/|ssh://git@github\.com/|git@github\.com:)zulip/python-zulip-api(\.git|/)?\ \(fetch\)'
16+
' ]]; then
17+
range="${BASH_REMATCH[1]}/master..HEAD"
18+
else
19+
range="upstream/master..HEAD"
20+
fi
21+
22+
commits=$(git log "$range" | wc -l)
23+
if [ "$commits" -gt 0 ]; then
24+
# Only run gitlint with non-empty commit lists, to avoid a printed
25+
# warning.
26+
gitlint --commits "$range"
27+
fi

0 commit comments

Comments
 (0)