blob: b12c89f29412e8c469e0fab35b06cd68a0909add [file] [log] [blame]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Dale Curtis2975c432011-05-03 17:25:20 -07005import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07006import os
Ryan Cuiec4d6332011-05-02 14:15:25 -07007import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -07008import sys
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07009import subprocess
10
Ryan Cuiec4d6332011-05-02 14:15:25 -070011
12# General Helpers
13
14COMMON_INCLUDED_PATHS = [
15 # C++ and friends
16 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
17 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
18 # Scripts
19 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
20 # No extension at all, note that ALL CAPS files are black listed in
21 # COMMON_EXCLUDED_LIST below.
22 r"(^|.*?[\\\/])[^.]+$",
23 # Other
24 r".*\.java$", r".*\.mk$", r".*\.am$",
25]
26
27COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070028 # avoid doing source file checks for kernel
29 r"/src/third_party/kernel/",
30 r"/src/third_party/kernel-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070031 r".*\bexperimental[\\\/].*",
32 r".*\b[A-Z0-9_]{2,}$",
33 r".*[\\\/]debian[\\\/]rules$",
34]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070035
Sean Paul19baef02011-05-05 17:10:31 -040036MIN_GIT_VERSION = [1, 7, 2]
Sean Paulba01d402011-05-05 11:36:23 -040037
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070038def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070039 """Returns the absolute path to the repohooks directory."""
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070040 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
41 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].strip()
42
Ryan Cuiec4d6332011-05-02 14:15:25 -070043def _match_regex_list(subject, expressions):
44 """Try to match a list of regular expressions to a string.
45
46 Args:
47 subject: The string to match regexes on
48 expressions: A list of regular expressions to check for matches with.
49
50 Returns:
51 Whether the passed in subject matches any of the passed in regexes.
52 """
53 for expr in expressions:
54 if (re.search(expr, subject)):
55 return True
56 return False
57
58def _filter_files(files, include_list, exclude_list=[]):
59 """Filter out files based on the conditions passed in.
60
61 Args:
62 files: list of filepaths to filter
63 include_list: list of regex that when matched with a file path will cause it
64 to be added to the output list unless the file is also matched with a
65 regex in the exclude_list.
66 exclude_list: list of regex that when matched with a file will prevent it
67 from being added to the output list, even if it is also matched with a
68 regex in the include_list.
69
70 Returns:
71 A list of filepaths that contain files matched in the include_list and not
72 in the exclude_list.
73 """
74 filtered = []
75 for f in files:
76 if (_match_regex_list(f, include_list) and
77 not _match_regex_list(f, exclude_list)):
78 filtered.append(f)
79 return filtered
80
81def _report_error(msg, items=None):
82 """Raises an exception with the passed in error message.
83
84 If extra error detail is passed in, it will be appended to the error message.
85
86 Args:
87 msg: Error message header.
88 items: A list of lines that follow the header that give extra error
89 information.
90 """
91 if items:
92 msg += '\n' + '\n'.join(items)
93 raise Exception(msg)
94
95
96# Git Helpers
Sean Paulba01d402011-05-05 11:36:23 -040097def _check_git_version():
98 """Checks the git version installed, dies if it is insufficient"""
99 cmd = ['git', '--version']
100 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
Sean Paul19baef02011-05-05 17:10:31 -0400101 m = re.match('(git version )([0-9]+\.[0-9]+\.[0-9]+).*\n', output)
Sean Paulba01d402011-05-05 11:36:23 -0400102 if not m or not m.group(2):
103 _report_error('Failed to get git version, git output=' + output)
104
105 version = m.group(2).split('.')
106 version = map(lambda x: int(x), version)
107 for v, mv in zip(version, MIN_GIT_VERSION):
108 if v < mv:
109 _report_error('Invalid version of git (' + m.group(2) + '), you need '
110 + 'at least version '
111 + ''.join([`num` + '.' for num in MIN_GIT_VERSION]))
112 elif v > mv:
113 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700114
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700115def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700116 """Returns the diff for this commit."""
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700117 cmd = ['git', 'show', commit]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700118 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
119
Ryan Cuiec4d6332011-05-02 14:15:25 -0700120def _get_file_diff(file, commit):
121 """Returns a list of (linenum, lines) tuples that the commit touched."""
122 cmd = ['git', 'show', '-p', '--no-ext-diff', commit, file]
123 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
124
125 new_lines = []
126 line_num = 0
127 for line in output.splitlines():
128 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
129 if m:
130 line_num = int(m.groups(1)[0])
131 continue
132 if line.startswith('+') and not line.startswith('++'):
133 new_lines.append((line_num, line[1:]))
134 if not line.startswith('-'):
135 line_num += 1
136 return new_lines
137
138def _get_affected_files(commit):
139 """Returns list of absolute filepaths that were modified/added."""
140 cmd = ['git', 'diff', '--name-status', commit + '^!']
141 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
142 files = []
143 for statusline in output.splitlines():
144 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
145 # Ignore deleted files, and return absolute paths of files
146 if (m.group(1)[0] != 'D'):
147 pwd = os.getcwd()
148 files.append(os.path.join(pwd, m.group(2)))
149 return files
150
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700151def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700152 """Returns a list of commits for this review."""
153 cmd = ['git', 'log', 'm/master..', '--format=%H']
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700154 commits = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
155 return commits.split()
156
Ryan Cuiec4d6332011-05-02 14:15:25 -0700157def _get_commit_desc(commit):
158 """Returns the full commit message of a commit."""
159 cmd = ['git', 'log', '--format=%B', commit + '^!']
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700160 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700161
162
163# Common Hooks
164
165def _check_no_long_lines(project, commit):
166 """Checks that there aren't any lines longer than maxlen characters in any of
167 the text files to be submitted.
168 """
169 MAX_LEN = 80
170
171 errors = []
172 files = _filter_files(_get_affected_files(commit),
173 COMMON_INCLUDED_PATHS,
174 COMMON_EXCLUDED_PATHS)
175
176 for afile in files:
177 for line_num, line in _get_file_diff(afile, commit):
178 # Allow certain lines to exceed the maxlen rule.
179 if (len(line) > MAX_LEN and
180 not 'http://' in line and
181 not 'https://' in line and
182 not line.startswith('#define') and
183 not line.startswith('#include') and
184 not line.startswith('#import') and
185 not line.startswith('#pragma') and
186 not line.startswith('#if') and
187 not line.startswith('#endif')):
188 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
189 if len(errors) == 5: # Just show the first 5 errors.
190 break
191
192 if errors:
193 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
194 _report_error(msg, errors)
195
196def _check_no_stray_whitespace(project, commit):
197 """Checks that there is no stray whitespace at source lines end."""
198 errors = []
199 files = _filter_files(_get_affected_files(commit),
200 COMMON_INCLUDED_PATHS,
201 COMMON_EXCLUDED_PATHS)
202
203 for afile in files:
204 for line_num, line in _get_file_diff(afile, commit):
205 if line.rstrip() != line:
206 errors.append('%s, line %s' % (afile, line_num))
207 if errors:
208 _report_error('Found line ending with white space in:', errors)
209
210def _check_no_tabs(project, commit):
211 """Checks there are no unexpanded tabs."""
212 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700213 r"/src/third_party/u-boot/",
214 r"/src/third_party/u-boot-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700215 r".*\.ebuild$",
216 r".*\.eclass$",
217 r".*/[M|m]akefile$"
218 ]
219
220 errors = []
221 files = _filter_files(_get_affected_files(commit),
222 COMMON_INCLUDED_PATHS,
223 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
224
225 for afile in files:
226 for line_num, line in _get_file_diff(afile, commit):
227 if '\t' in line:
228 errors.append('%s, line %s' % (afile, line_num))
229 if errors:
230 _report_error('Found a tab character in:', errors)
231
232def _check_change_has_test_field(project, commit):
233 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700234 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700235
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700236 if not re.search(TEST_RE, _get_commit_desc(commit)):
237 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700238
239def _check_change_has_bug_field(project, commit):
240 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700241 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700242
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700243 if not re.search(BUG_RE, _get_commit_desc(commit)):
244 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700245
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700246def _check_change_has_proper_changeid(project, commit):
247 """Verify that Change-ID is present in last paragraph of commit message."""
248 desc = _get_commit_desc(commit)
249 loc = desc.rfind('\nChange-Id:')
250 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
251 _report_error('Change-Id must be in last paragraph of description.')
252
Ryan Cuiec4d6332011-05-02 14:15:25 -0700253def _check_license(project, commit):
254 """Verifies the license header."""
255 LICENSE_HEADER = (
256 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
257 r"reserved\." "\n"
258 r".*? Use of this source code is governed by a BSD-style license that can "
259 "be\n"
260 r".*? found in the LICENSE file\."
261 "\n"
262 )
263
264 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
265 bad_files = []
266 files = _filter_files(_get_affected_files(commit),
267 COMMON_INCLUDED_PATHS,
268 COMMON_EXCLUDED_PATHS)
269
270 for f in files:
271 contents = open(f).read()
272 if len(contents) == 0: continue # Ignore empty files
273 if not license_re.search(contents):
274 bad_files.append(f)
275 if bad_files:
276 _report_error('License must match:\n%s\n' % license_re.pattern +
277 'Found a bad license header in these files:',
278 bad_files)
279
280
281# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700282
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700283def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700284 """Runs checkpatch.pl on the given project"""
285 hooks_dir = _get_hooks_dir()
286 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
287 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700288 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700289 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700290 _report_error('checkpatch.pl errors/warnings\n\n' + output)
291
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700292
Dale Curtis2975c432011-05-03 17:25:20 -0700293def _run_json_check(project, commit):
294 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700295 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700296 try:
297 json.load(open(f))
298 except Exception, e:
299 _report_error('Invalid JSON in %s: %s' % (f, e))
300
301
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700302# Base
303
Ryan Cuie37fe1a2011-05-03 19:00:10 -0700304COMMON_HOOKS = [_check_change_has_bug_field,
305 _check_change_has_test_field,
306 _check_change_has_proper_changeid,
Ryan Cuiec4d6332011-05-02 14:15:25 -0700307 _check_no_stray_whitespace,
Ryan Cui31e0c172011-05-04 21:00:45 -0700308 _check_no_long_lines,
309 _check_license,
310 _check_no_tabs]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700311
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700312def _setup_project_hooks():
313 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
314 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700315 "chromiumos/third_party/kernel": [_run_checkpatch],
316 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700317 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700318 }
319
320def _run_project_hooks(project, hooks):
321 """For each project run its project specific hook from the hooks dictionary"""
322 cmd = ['repo', 'forall', project, '-c', 'pwd']
323 proj_dir = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
324 proj_dir = proj_dir.strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700325 pwd = os.getcwd()
326 # hooks assume they are run from the root of the project
327 os.chdir(proj_dir)
328
329 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700330 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700331 project_specific_hooks = hooks[project]
332
333 for commit in _get_commits():
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700334 try:
335 for hook in COMMON_HOOKS + project_specific_hooks:
336 hook(project, commit)
337 except:
338 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
339 project)
340 print >> sys.stderr, msg
341 raise
Ryan Cuiec4d6332011-05-02 14:15:25 -0700342 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700343
344# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700345
Anush Elangovan63afad72011-03-23 00:41:27 -0700346def main(project_list, **kwargs):
Sean Paulba01d402011-05-05 11:36:23 -0400347 _check_git_version()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700348 hooks = _setup_project_hooks()
349 for project in project_list:
350 _run_project_hooks(project, hooks)
Anush Elangovan63afad72011-03-23 00:41:27 -0700351
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700352if __name__ == '__main__':
353 main()