blob: 5607b4032c83d84bf7d21716bd9ab9e5e4b037f7 [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 Paulba01d402011-05-05 11:36:23 -040036MIN_GIT_VERSION = [1, 7, 2, 0]
37
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]
101
102 m = re.match('(git version )(.*)\n', output)
103 if not m or not m.group(2):
104 _report_error('Failed to get git version, git output=' + output)
105
106 version = m.group(2).split('.')
107 version = map(lambda x: int(x), version)
108 for v, mv in zip(version, MIN_GIT_VERSION):
109 if v < mv:
110 _report_error('Invalid version of git (' + m.group(2) + '), you need '
111 + 'at least version '
112 + ''.join([`num` + '.' for num in MIN_GIT_VERSION]))
113 elif v > mv:
114 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700115
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700116def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700117 """Returns the diff for this commit."""
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700118 cmd = ['git', 'show', commit]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700119 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
120
Ryan Cuiec4d6332011-05-02 14:15:25 -0700121def _get_file_diff(file, commit):
122 """Returns a list of (linenum, lines) tuples that the commit touched."""
123 cmd = ['git', 'show', '-p', '--no-ext-diff', commit, file]
124 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
125
126 new_lines = []
127 line_num = 0
128 for line in output.splitlines():
129 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
130 if m:
131 line_num = int(m.groups(1)[0])
132 continue
133 if line.startswith('+') and not line.startswith('++'):
134 new_lines.append((line_num, line[1:]))
135 if not line.startswith('-'):
136 line_num += 1
137 return new_lines
138
139def _get_affected_files(commit):
140 """Returns list of absolute filepaths that were modified/added."""
141 cmd = ['git', 'diff', '--name-status', commit + '^!']
142 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
143 files = []
144 for statusline in output.splitlines():
145 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
146 # Ignore deleted files, and return absolute paths of files
147 if (m.group(1)[0] != 'D'):
148 pwd = os.getcwd()
149 files.append(os.path.join(pwd, m.group(2)))
150 return files
151
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700152def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700153 """Returns a list of commits for this review."""
154 cmd = ['git', 'log', 'm/master..', '--format=%H']
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700155 commits = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
156 return commits.split()
157
Ryan Cuiec4d6332011-05-02 14:15:25 -0700158def _get_commit_desc(commit):
159 """Returns the full commit message of a commit."""
160 cmd = ['git', 'log', '--format=%B', commit + '^!']
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700161 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700162
163
164# Common Hooks
165
166def _check_no_long_lines(project, commit):
167 """Checks that there aren't any lines longer than maxlen characters in any of
168 the text files to be submitted.
169 """
170 MAX_LEN = 80
171
172 errors = []
173 files = _filter_files(_get_affected_files(commit),
174 COMMON_INCLUDED_PATHS,
175 COMMON_EXCLUDED_PATHS)
176
177 for afile in files:
178 for line_num, line in _get_file_diff(afile, commit):
179 # Allow certain lines to exceed the maxlen rule.
180 if (len(line) > MAX_LEN and
181 not 'http://' in line and
182 not 'https://' in line and
183 not line.startswith('#define') and
184 not line.startswith('#include') and
185 not line.startswith('#import') and
186 not line.startswith('#pragma') and
187 not line.startswith('#if') and
188 not line.startswith('#endif')):
189 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
190 if len(errors) == 5: # Just show the first 5 errors.
191 break
192
193 if errors:
194 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
195 _report_error(msg, errors)
196
197def _check_no_stray_whitespace(project, commit):
198 """Checks that there is no stray whitespace at source lines end."""
199 errors = []
200 files = _filter_files(_get_affected_files(commit),
201 COMMON_INCLUDED_PATHS,
202 COMMON_EXCLUDED_PATHS)
203
204 for afile in files:
205 for line_num, line in _get_file_diff(afile, commit):
206 if line.rstrip() != line:
207 errors.append('%s, line %s' % (afile, line_num))
208 if errors:
209 _report_error('Found line ending with white space in:', errors)
210
211def _check_no_tabs(project, commit):
212 """Checks there are no unexpanded tabs."""
213 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700214 r"/src/third_party/u-boot/",
215 r"/src/third_party/u-boot-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700216 r".*\.ebuild$",
217 r".*\.eclass$",
218 r".*/[M|m]akefile$"
219 ]
220
221 errors = []
222 files = _filter_files(_get_affected_files(commit),
223 COMMON_INCLUDED_PATHS,
224 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
225
226 for afile in files:
227 for line_num, line in _get_file_diff(afile, commit):
228 if '\t' in line:
229 errors.append('%s, line %s' % (afile, line_num))
230 if errors:
231 _report_error('Found a tab character in:', errors)
232
233def _check_change_has_test_field(project, commit):
234 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700235 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700236
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700237 if not re.search(TEST_RE, _get_commit_desc(commit)):
238 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700239
240def _check_change_has_bug_field(project, commit):
241 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700242 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700243
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700244 if not re.search(BUG_RE, _get_commit_desc(commit)):
245 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700246
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700247def _check_change_has_proper_changeid(project, commit):
248 """Verify that Change-ID is present in last paragraph of commit message."""
249 desc = _get_commit_desc(commit)
250 loc = desc.rfind('\nChange-Id:')
251 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
252 _report_error('Change-Id must be in last paragraph of description.')
253
Ryan Cuiec4d6332011-05-02 14:15:25 -0700254def _check_license(project, commit):
255 """Verifies the license header."""
256 LICENSE_HEADER = (
257 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
258 r"reserved\." "\n"
259 r".*? Use of this source code is governed by a BSD-style license that can "
260 "be\n"
261 r".*? found in the LICENSE file\."
262 "\n"
263 )
264
265 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
266 bad_files = []
267 files = _filter_files(_get_affected_files(commit),
268 COMMON_INCLUDED_PATHS,
269 COMMON_EXCLUDED_PATHS)
270
271 for f in files:
272 contents = open(f).read()
273 if len(contents) == 0: continue # Ignore empty files
274 if not license_re.search(contents):
275 bad_files.append(f)
276 if bad_files:
277 _report_error('License must match:\n%s\n' % license_re.pattern +
278 'Found a bad license header in these files:',
279 bad_files)
280
281
282# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700283
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700284def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700285 """Runs checkpatch.pl on the given project"""
286 hooks_dir = _get_hooks_dir()
287 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
288 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700289 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700290 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700291 _report_error('checkpatch.pl errors/warnings\n\n' + output)
292
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700293
Dale Curtis2975c432011-05-03 17:25:20 -0700294def _run_json_check(project, commit):
295 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700296 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700297 try:
298 json.load(open(f))
299 except Exception, e:
300 _report_error('Invalid JSON in %s: %s' % (f, e))
301
302
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700303# Base
304
Ryan Cuie37fe1a2011-05-03 19:00:10 -0700305COMMON_HOOKS = [_check_change_has_bug_field,
306 _check_change_has_test_field,
307 _check_change_has_proper_changeid,
Ryan Cuiec4d6332011-05-02 14:15:25 -0700308 _check_no_stray_whitespace,
Ryan Cui31e0c172011-05-04 21:00:45 -0700309 _check_no_long_lines,
310 _check_license,
311 _check_no_tabs]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700312
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700313def _setup_project_hooks():
314 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
315 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700316 "chromiumos/third_party/kernel": [_run_checkpatch],
317 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700318 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700319 }
320
321def _run_project_hooks(project, hooks):
322 """For each project run its project specific hook from the hooks dictionary"""
323 cmd = ['repo', 'forall', project, '-c', 'pwd']
324 proj_dir = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
325 proj_dir = proj_dir.strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700326 pwd = os.getcwd()
327 # hooks assume they are run from the root of the project
328 os.chdir(proj_dir)
329
330 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700331 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700332 project_specific_hooks = hooks[project]
333
334 for commit in _get_commits():
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700335 try:
336 for hook in COMMON_HOOKS + project_specific_hooks:
337 hook(project, commit)
338 except:
339 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
340 project)
341 print >> sys.stderr, msg
342 raise
Ryan Cuiec4d6332011-05-02 14:15:25 -0700343 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700344
345# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700346
Anush Elangovan63afad72011-03-23 00:41:27 -0700347def main(project_list, **kwargs):
Sean Paulba01d402011-05-05 11:36:23 -0400348 _check_git_version()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700349 hooks = _setup_project_hooks()
350 for project in project_list:
351 _run_project_hooks(project, hooks)
Anush Elangovan63afad72011-03-23 00:41:27 -0700352
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700353if __name__ == '__main__':
354 main()