blob: b9924896dee751a9abbc9edb9a3ed57439df14bc [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 = [
28 # avoid doing source file checks for kernel
29 r"/src/third_party/kernel/",
30 r"/src/third_party/kernel-next/",
31 r".*\bexperimental[\\\/].*",
32 r".*\b[A-Z0-9_]{2,}$",
33 r".*[\\\/]debian[\\\/]rules$",
34]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070035
36def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070037 """Returns the absolute path to the repohooks directory."""
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070038 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
39 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].strip()
40
Ryan Cuiec4d6332011-05-02 14:15:25 -070041def _match_regex_list(subject, expressions):
42 """Try to match a list of regular expressions to a string.
43
44 Args:
45 subject: The string to match regexes on
46 expressions: A list of regular expressions to check for matches with.
47
48 Returns:
49 Whether the passed in subject matches any of the passed in regexes.
50 """
51 for expr in expressions:
52 if (re.search(expr, subject)):
53 return True
54 return False
55
56def _filter_files(files, include_list, exclude_list=[]):
57 """Filter out files based on the conditions passed in.
58
59 Args:
60 files: list of filepaths to filter
61 include_list: list of regex that when matched with a file path will cause it
62 to be added to the output list unless the file is also matched with a
63 regex in the exclude_list.
64 exclude_list: list of regex that when matched with a file will prevent it
65 from being added to the output list, even if it is also matched with a
66 regex in the include_list.
67
68 Returns:
69 A list of filepaths that contain files matched in the include_list and not
70 in the exclude_list.
71 """
72 filtered = []
73 for f in files:
74 if (_match_regex_list(f, include_list) and
75 not _match_regex_list(f, exclude_list)):
76 filtered.append(f)
77 return filtered
78
79def _report_error(msg, items=None):
80 """Raises an exception with the passed in error message.
81
82 If extra error detail is passed in, it will be appended to the error message.
83
84 Args:
85 msg: Error message header.
86 items: A list of lines that follow the header that give extra error
87 information.
88 """
89 if items:
90 msg += '\n' + '\n'.join(items)
91 raise Exception(msg)
92
93
94# Git Helpers
95
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -070096def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -070097 """Returns the diff for this commit."""
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -070098 cmd = ['git', 'show', commit]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070099 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
100
Ryan Cuiec4d6332011-05-02 14:15:25 -0700101def _get_file_diff(file, commit):
102 """Returns a list of (linenum, lines) tuples that the commit touched."""
103 cmd = ['git', 'show', '-p', '--no-ext-diff', commit, file]
104 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
105
106 new_lines = []
107 line_num = 0
108 for line in output.splitlines():
109 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
110 if m:
111 line_num = int(m.groups(1)[0])
112 continue
113 if line.startswith('+') and not line.startswith('++'):
114 new_lines.append((line_num, line[1:]))
115 if not line.startswith('-'):
116 line_num += 1
117 return new_lines
118
119def _get_affected_files(commit):
120 """Returns list of absolute filepaths that were modified/added."""
121 cmd = ['git', 'diff', '--name-status', commit + '^!']
122 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
123 files = []
124 for statusline in output.splitlines():
125 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
126 # Ignore deleted files, and return absolute paths of files
127 if (m.group(1)[0] != 'D'):
128 pwd = os.getcwd()
129 files.append(os.path.join(pwd, m.group(2)))
130 return files
131
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700132def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700133 """Returns a list of commits for this review."""
134 cmd = ['git', 'log', 'm/master..', '--format=%H']
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700135 commits = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
136 return commits.split()
137
Ryan Cuiec4d6332011-05-02 14:15:25 -0700138def _get_commit_desc(commit):
139 """Returns the full commit message of a commit."""
140 cmd = ['git', 'log', '--format=%B', commit + '^!']
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700141 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700142
143
144# Common Hooks
145
146def _check_no_long_lines(project, commit):
147 """Checks that there aren't any lines longer than maxlen characters in any of
148 the text files to be submitted.
149 """
150 MAX_LEN = 80
151
152 errors = []
153 files = _filter_files(_get_affected_files(commit),
154 COMMON_INCLUDED_PATHS,
155 COMMON_EXCLUDED_PATHS)
156
157 for afile in files:
158 for line_num, line in _get_file_diff(afile, commit):
159 # Allow certain lines to exceed the maxlen rule.
160 if (len(line) > MAX_LEN and
161 not 'http://' in line and
162 not 'https://' in line and
163 not line.startswith('#define') and
164 not line.startswith('#include') and
165 not line.startswith('#import') and
166 not line.startswith('#pragma') and
167 not line.startswith('#if') and
168 not line.startswith('#endif')):
169 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
170 if len(errors) == 5: # Just show the first 5 errors.
171 break
172
173 if errors:
174 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
175 _report_error(msg, errors)
176
177def _check_no_stray_whitespace(project, commit):
178 """Checks that there is no stray whitespace at source lines end."""
179 errors = []
180 files = _filter_files(_get_affected_files(commit),
181 COMMON_INCLUDED_PATHS,
182 COMMON_EXCLUDED_PATHS)
183
184 for afile in files:
185 for line_num, line in _get_file_diff(afile, commit):
186 if line.rstrip() != line:
187 errors.append('%s, line %s' % (afile, line_num))
188 if errors:
189 _report_error('Found line ending with white space in:', errors)
190
191def _check_no_tabs(project, commit):
192 """Checks there are no unexpanded tabs."""
193 TAB_OK_PATHS = [
194 r"/src/third_party/u-boot/",
195 r"/src/third_party/u-boot-next/",
196 r".*\.ebuild$",
197 r".*\.eclass$",
198 r".*/[M|m]akefile$"
199 ]
200
201 errors = []
202 files = _filter_files(_get_affected_files(commit),
203 COMMON_INCLUDED_PATHS,
204 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
205
206 for afile in files:
207 for line_num, line in _get_file_diff(afile, commit):
208 if '\t' in line:
209 errors.append('%s, line %s' % (afile, line_num))
210 if errors:
211 _report_error('Found a tab character in:', errors)
212
213def _check_change_has_test_field(project, commit):
214 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700215 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700216
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700217 if not re.search(TEST_RE, _get_commit_desc(commit)):
218 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700219
220def _check_change_has_bug_field(project, commit):
221 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700222 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700223
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700224 if not re.search(BUG_RE, _get_commit_desc(commit)):
225 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700226
227def _check_license(project, commit):
228 """Verifies the license header."""
229 LICENSE_HEADER = (
230 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
231 r"reserved\." "\n"
232 r".*? Use of this source code is governed by a BSD-style license that can "
233 "be\n"
234 r".*? found in the LICENSE file\."
235 "\n"
236 )
237
238 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
239 bad_files = []
240 files = _filter_files(_get_affected_files(commit),
241 COMMON_INCLUDED_PATHS,
242 COMMON_EXCLUDED_PATHS)
243
244 for f in files:
245 contents = open(f).read()
246 if len(contents) == 0: continue # Ignore empty files
247 if not license_re.search(contents):
248 bad_files.append(f)
249 if bad_files:
250 _report_error('License must match:\n%s\n' % license_re.pattern +
251 'Found a bad license header in these files:',
252 bad_files)
253
254
255# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700256
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700257def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700258 """Runs checkpatch.pl on the given project"""
259 hooks_dir = _get_hooks_dir()
260 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
261 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700262 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700263 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700264 _report_error('checkpatch.pl errors/warnings\n\n' + output)
265
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700266
Dale Curtis2975c432011-05-03 17:25:20 -0700267def _run_json_check(project, commit):
268 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700269 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700270 try:
271 json.load(open(f))
272 except Exception, e:
273 _report_error('Invalid JSON in %s: %s' % (f, e))
274
275
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700276# Base
277
Ryan Cuiec4d6332011-05-02 14:15:25 -0700278COMMON_HOOKS = [_check_no_long_lines,
279 _check_no_stray_whitespace,
280 _check_no_tabs,
281 _check_change_has_test_field,
282 _check_change_has_bug_field,
283 _check_license]
284
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700285def _setup_project_hooks():
286 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
287 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700288 "chromiumos/third_party/kernel": [_run_checkpatch],
289 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700290 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700291 }
292
293def _run_project_hooks(project, hooks):
294 """For each project run its project specific hook from the hooks dictionary"""
295 cmd = ['repo', 'forall', project, '-c', 'pwd']
296 proj_dir = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
297 proj_dir = proj_dir.strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700298 pwd = os.getcwd()
299 # hooks assume they are run from the root of the project
300 os.chdir(proj_dir)
301
302 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700303 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700304 project_specific_hooks = hooks[project]
305
306 for commit in _get_commits():
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700307 try:
308 for hook in COMMON_HOOKS + project_specific_hooks:
309 hook(project, commit)
310 except:
311 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
312 project)
313 print >> sys.stderr, msg
314 raise
Ryan Cuiec4d6332011-05-02 14:15:25 -0700315 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700316
317# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700318
Anush Elangovan63afad72011-03-23 00:41:27 -0700319def main(project_list, **kwargs):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700320 hooks = _setup_project_hooks()
321 for project in project_list:
322 _run_project_hooks(project, hooks)
Anush Elangovan63afad72011-03-23 00:41:27 -0700323
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700324if __name__ == '__main__':
325 main()