-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcommit_list_checks.py
More file actions
352 lines (296 loc) · 13.2 KB
/
commit_list_checks.py
File metadata and controls
352 lines (296 loc) · 13.2 KB
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
"""igcommit - Checks on Git commit lists
Copyright (c) 2021 InnoGames GmbH
Portions Copyright (c) 2021 Emre Hasegeli
"""
import re
from time import time
from os.path import exists
from os import remove
from igcommit.base_check import BaseCheck, Severity
from igcommit.git import Commit, CommitList, CommittedFile
class CommitListCheck(BaseCheck):
"""Parent class for all commit list checks"""
commit_list = None
def prepare(self, obj):
if not isinstance(obj, CommitList):
return super(CommitListCheck, self).prepare(obj)
new = self.clone()
new.commit_list = obj
return new
def __str__(self):
return '{} on {}'.format(type(self).__name__, self.commit_list)
class CheckDuplicateCommitSummaries(CommitListCheck):
"""Check repeated commit summaries on a single commit list
We are not exact matching the commit summaries, but searching summaries
on the beginning of other ones. This covers summaries like "Fix the bug"
and "Fix the bug really" which is common bad practice for some reason.
"""
def prepare(self, obj):
if isinstance(obj, CommitList) and len(obj) <= 1:
return None
return super(CheckDuplicateCommitSummaries, self).prepare(obj)
def get_problems(self):
duplicate_summaries = [()] # Nothing starts with an empty tuple.
for commit in sorted(self.commit_list, key=Commit.get_summary):
summary = commit.get_summary()
if summary.startswith(duplicate_summaries[0]):
duplicate_summaries.append(summary)
continue
if len(duplicate_summaries) > 1:
yield (
Severity.ERROR, 'summary "{}" duplicated {} times'.format(
min(duplicate_summaries, key=len),
len(duplicate_summaries),
)
)
duplicate_summaries = [summary]
class CheckMisleadingMergeCommit(CommitListCheck):
merge_template = "Merge branch '{}'"
def get_problems(self):
branch_name = self.commit_list.branch_name
for commit in self.commit_list:
summary = commit.get_summary()
if summary.startswith(self.merge_template.format(branch_name)):
yield Severity.WARNING, 'merge commit to itself'
elif summary.startswith(self.merge_template.format('master')):
yield Severity.WARNING, 'merge commit master'
class CheckTimestamps(CommitListCheck):
current_timestamp = time()
def get_problems(self):
previous_author_timestamp = 0
previous_committer_timestamp = 0
for commit in self.commit_list:
author_timestamp = commit.get_author().timestamp
committer_timestamp = commit.get_committer().timestamp
if author_timestamp > self.current_timestamp + 2:
yield (
Severity.ERROR,
'author timestamp of commit {} in future'
.format(commit),
)
if committer_timestamp > self.current_timestamp + 2:
yield (
Severity.ERROR,
'committer timestamp of commit {} in future'
.format(commit),
)
if author_timestamp > committer_timestamp:
yield (
Severity.ERROR,
'author timestamp of commit {} after committer'
.format(commit),
)
if previous_author_timestamp > author_timestamp:
yield (
Severity.NOTICE,
'author timestamp of commit {} before previous commit'
.format(commit),
)
if previous_committer_timestamp > committer_timestamp:
yield (
Severity.ERROR,
'committer timestamp of commit {} before previous commit'
.format(commit),
)
previous_author_timestamp = author_timestamp
previous_committer_timestamp = committer_timestamp
class CheckContributors(CommitListCheck):
"""Validate consistency of committer and author name and email addresses
We threat committers and authors the same way in this class. It is common
Git bad practice to commit with different combinations of names and
email addresses ruining useful statistics that can be made using the Git
history. There is not too much we can do about without having
the possible list of all users, and that is certainly not something we
would like.
In this class, we are searching and indexing the Git commits in the past
to find out the same names and email address, and cross check them with
the current commits. We are using the name together with the domain part
of the email address. It is common for some systems to commit changes
in behalf of the user with a different email address. Including
the domain on the index would let it happen.
"""
def prepare(self, obj):
new = super(CheckContributors, self).prepare(obj)
if new and isinstance(obj, CommitList):
new.email_index = {}
new.domain_index = {}
new.name_index = {}
return new
def get_problems(self):
old_contributors = self.get_old_contributors()
for commit in self.commit_list:
for contributor in commit.get_contributors():
found = self.index_contributors(old_contributors, contributor)
for problem in self.check_contributor(contributor, commit):
yield problem
# If there are any problems, evidently the contributor
# is not consistent with the indexes. We override
# the indexes after reporting problem to avoid the same
# ones to be reported again.
found = False
if not found:
self.index_contributor(contributor, override=True)
def get_old_commits(self):
"""Yield old commits in reverse order
We could call "git rev-list" here, but it is easy enough to implement
the same using the content we already need for other reasons. Though
"git rev-list" would order the commits nicer, we are not putting any
effort to the ordering in here as our caller is not sensitive.
"""
unused_commits = self.commit_list[0].get_parents()
commit_ids = {c.commit_id for c in unused_commits}
while unused_commits:
unused_commit = unused_commits.pop(0)
yield unused_commit
for commit in unused_commit.get_parents():
if commit.commit_id not in commit_ids:
unused_commits.append(commit)
commit_ids.add(commit.commit_id)
def get_old_contributors(self):
for commit in self.get_old_commits():
for contributor in commit.get_contributors():
yield contributor
def index_contributor(self, contributor, override=False, dry_run=False):
"""Index a single contributor
The function does nothing when the contributor is already indexed.
It returns true when if would add the contributor to any index.
The dry_run argument is used to test only, if the contributor is
indexed.
"""
found = False
if contributor.email not in self.email_index or override:
if not dry_run:
self.email_index[contributor.email] = contributor
found = True
domain = contributor.get_email_domain()
if domain not in self.domain_index or override:
if not dry_run:
self.domain_index[domain] = None
found = True
if (contributor.name, domain) not in self.name_index or override:
if not dry_run:
self.name_index[(contributor.name, domain)] = contributor
found = True
return found
def index_contributors(self, contributors, searched):
"""Index contributors until the searched one is found
The function stops when the searched one is found. We assume
the caller to pass the existing generator again to avoid starting over
to search the next one. It returns with true when the searched one
is found; returns with false when all of the items are indexes but
the searched one is not found.
"""
while self.index_contributor(searched, dry_run=True):
for contributor in contributors:
if self.index_contributor(contributor):
break
else:
return False
return True
def check_contributor(self, contributor, commit):
"""Check one contributor against the indexes"""
other = self.email_index.get(contributor.email)
if other and contributor.name != other.name:
yield (
Severity.ERROR,
'contributor of commit {} has a different name "{}" '
'than "{}" the contributor with the same email address'
.format(commit, contributor.name, other.name),
)
domain = contributor.get_email_domain()
if domain not in self.domain_index:
yield (
Severity.NOTICE,
'contributor of commit {} has a email address with a new '
'domain "{}" '
.format(commit, domain),
)
other = self.name_index.get((contributor.name, domain))
if other and contributor.email != other.email:
yield (
Severity.ERROR,
'contributor of commit {} has a different email address "{}" '
'with the same domain than "{}" from contributor with '
'the same name'
.format(commit, contributor.email, other.email),
)
class CheckBranchNameRegexp(CommitListCheck):
"""Check branch names against regular expressions
The configuration file can contain a list of regular expressions
(one per line). The branch names are checked against those,
and the commit is rejected if none of them match.
"""
config_files = []
def prepare(self, obj):
new = super(CheckBranchNameRegexp, self).prepare(obj)
config_exists = new._prepare_configs(obj)
if config_exists:
return new
def _prepare_configs(self, commitlist):
"""Update used configuration files, return true if any exist
This is copied from file_checks.py and slightly modified.
Please check the original file for explanation and
shortcomings.
"""
config_exists = False
for config_file in self.config_files:
prev_commit = config_file.commit
# We will check if the config file exists on the latest commit
config_file.commit = commitlist[-1]
if config_file.exists():
config_exists = True
# If the file is not changed on this commit, we can skip
# downloading.
if not prev_commit or config_file.changed():
with open(config_file.path, 'wb') as fd:
fd.write(config_file.get_content())
elif exists(config_file.path):
# Not found on the latest commit, but it exists on the
# workspace. Remove it.
remove(config_file.path)
return config_exists
def get_allowed_regexes(self):
for config_file in self.config_files:
with open(config_file.path) as f:
allowed_regexes = f.read().splitlines()
valid_list = []
failed_list = []
for regexline in allowed_regexes:
try:
if not regexline.strip():
continue
re.compile(regexline)
valid_list.append(regexline)
except re.error:
failed_list.append(regexline)
return valid_list, failed_list
def check_branch_name(self, regexp_list, branch_name):
"""Fails if the branch name does not match any regexp
It's enough to fit only one of the allowed patterns
"""
trimmed_branch_name = re.sub('refs/heads/', '', branch_name)
for pattern in regexp_list:
if re.match(pattern, trimmed_branch_name):
return True
return False
def get_problems(self):
branch_name = self.commit_list.branch_name
valid_regexes, broken_regexes = self.get_allowed_regexes()
if broken_regexes:
yield (
Severity.WARNING,
'following string is not a valid pattern '
'for branch name comparison:\n{}'
.format("\n".join(broken_regexes))
)
if not self.check_branch_name(valid_regexes, branch_name):
yield (
Severity.ERROR,
'{} is not an allowed branch name.\n'
'Branch names must match any of the following '
'list of regular expressions:\n{}'
.format(
branch_name,
'\n'.join(valid_regexes)
)
)