Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
David James | 28766e6 | 2012-08-06 17:30:15 -0700 | [diff] [blame] | 2 | # Copyright (c) 2011 The Chromium OS Authors. All rights reserved. |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 6 | import ConfigParser |
Dale Curtis | 2975c43 | 2011-05-03 17:25:20 -0700 | [diff] [blame] | 7 | import json |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 8 | import optparse |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 9 | import os |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 10 | import re |
Mandeep Singh Baines | a7ffa4b | 2011-05-03 11:37:02 -0700 | [diff] [blame] | 11 | import sys |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 12 | import subprocess |
| 13 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 14 | from errors import (VerifyException, HookFailure, PrintErrorForProject, |
| 15 | PrintErrorsForCommit) |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 16 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 17 | |
| 18 | COMMON_INCLUDED_PATHS = [ |
| 19 | # C++ and friends |
| 20 | r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$", |
| 21 | r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$", |
| 22 | # Scripts |
| 23 | r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$", |
| 24 | # No extension at all, note that ALL CAPS files are black listed in |
| 25 | # COMMON_EXCLUDED_LIST below. |
| 26 | r"(^|.*?[\\\/])[^.]+$", |
| 27 | # Other |
| 28 | r".*\.java$", r".*\.mk$", r".*\.am$", |
| 29 | ] |
| 30 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 31 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 32 | COMMON_EXCLUDED_PATHS = [ |
Ryan Cui | 31e0c17 | 2011-05-04 21:00:45 -0700 | [diff] [blame] | 33 | # avoid doing source file checks for kernel |
| 34 | r"/src/third_party/kernel/", |
| 35 | r"/src/third_party/kernel-next/", |
Paul Taysom | f8b6e01 | 2011-05-09 14:32:42 -0700 | [diff] [blame] | 36 | r"/src/third_party/ktop/", |
| 37 | r"/src/third_party/punybench/", |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 38 | r".*\bexperimental[\\\/].*", |
| 39 | r".*\b[A-Z0-9_]{2,}$", |
| 40 | r".*[\\\/]debian[\\\/]rules$", |
Brian Harring | d780d60 | 2011-10-18 16:48:08 -0700 | [diff] [blame] | 41 | # for ebuild trees, ignore any caches and manifest data |
| 42 | r".*/Manifest$", |
| 43 | r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$", |
Doug Anderson | 5bfb679 | 2011-10-25 16:45:41 -0700 | [diff] [blame] | 44 | |
| 45 | # ignore profiles data (like overlay-tegra2/profiles) |
| 46 | r".*/overlay-.*/profiles/.*", |
Andrew de los Reyes | 0e67992 | 2012-05-02 11:42:54 -0700 | [diff] [blame] | 47 | # ignore minified js and jquery |
| 48 | r".*\.min\.js", |
| 49 | r".*jquery.*\.js", |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 50 | ] |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 51 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 52 | |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 53 | _CONFIG_FILE = 'PRESUBMIT.cfg' |
| 54 | |
| 55 | |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 56 | # Exceptions |
| 57 | |
| 58 | |
| 59 | class BadInvocation(Exception): |
| 60 | """An Exception indicating a bad invocation of the program.""" |
| 61 | pass |
| 62 | |
| 63 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 64 | # General Helpers |
| 65 | |
Sean Paul | ba01d40 | 2011-05-05 11:36:23 -0400 | [diff] [blame] | 66 | |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 67 | def _run_command(cmd, cwd=None, stderr=None): |
| 68 | """Executes the passed in command and returns raw stdout output. |
| 69 | |
| 70 | Args: |
| 71 | cmd: The command to run; should be a list of strings. |
| 72 | cwd: The directory to switch to for running the command. |
| 73 | stderr: Can be one of None (print stderr to console), subprocess.STDOUT |
| 74 | (combine stderr with stdout), or subprocess.PIPE (ignore stderr). |
| 75 | |
| 76 | Returns: |
| 77 | The standard out from the process. |
| 78 | """ |
| 79 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd) |
| 80 | return p.communicate()[0] |
Ryan Cui | 72834d1 | 2011-05-05 14:51:33 -0700 | [diff] [blame] | 81 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 82 | |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 83 | def _get_hooks_dir(): |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 84 | """Returns the absolute path to the repohooks directory.""" |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 85 | if __name__ == '__main__': |
| 86 | # Works when file is run on its own (__file__ is defined)... |
| 87 | return os.path.abspath(os.path.dirname(__file__)) |
| 88 | else: |
| 89 | # We need to do this when we're run through repo. Since repo executes |
| 90 | # us with execfile(), we don't get __file__ defined. |
| 91 | cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd'] |
| 92 | return _run_command(cmd).strip() |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 93 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 94 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 95 | def _match_regex_list(subject, expressions): |
| 96 | """Try to match a list of regular expressions to a string. |
| 97 | |
| 98 | Args: |
| 99 | subject: The string to match regexes on |
| 100 | expressions: A list of regular expressions to check for matches with. |
| 101 | |
| 102 | Returns: |
| 103 | Whether the passed in subject matches any of the passed in regexes. |
| 104 | """ |
| 105 | for expr in expressions: |
| 106 | if (re.search(expr, subject)): |
| 107 | return True |
| 108 | return False |
| 109 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 110 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 111 | def _filter_files(files, include_list, exclude_list=[]): |
| 112 | """Filter out files based on the conditions passed in. |
| 113 | |
| 114 | Args: |
| 115 | files: list of filepaths to filter |
| 116 | include_list: list of regex that when matched with a file path will cause it |
| 117 | to be added to the output list unless the file is also matched with a |
| 118 | regex in the exclude_list. |
| 119 | exclude_list: list of regex that when matched with a file will prevent it |
| 120 | from being added to the output list, even if it is also matched with a |
| 121 | regex in the include_list. |
| 122 | |
| 123 | Returns: |
| 124 | A list of filepaths that contain files matched in the include_list and not |
| 125 | in the exclude_list. |
| 126 | """ |
| 127 | filtered = [] |
| 128 | for f in files: |
| 129 | if (_match_regex_list(f, include_list) and |
| 130 | not _match_regex_list(f, exclude_list)): |
| 131 | filtered.append(f) |
| 132 | return filtered |
| 133 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 134 | |
| 135 | # Git Helpers |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 136 | |
| 137 | |
Ryan Cui | 4725d95 | 2011-05-05 15:41:19 -0700 | [diff] [blame] | 138 | def _get_upstream_branch(): |
| 139 | """Returns the upstream tracking branch of the current branch. |
| 140 | |
| 141 | Raises: |
| 142 | Error if there is no tracking branch |
| 143 | """ |
| 144 | current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip() |
| 145 | current_branch = current_branch.replace('refs/heads/', '') |
| 146 | if not current_branch: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 147 | raise VerifyException('Need to be on a tracking branch') |
Ryan Cui | 4725d95 | 2011-05-05 15:41:19 -0700 | [diff] [blame] | 148 | |
| 149 | cfg_option = 'branch.' + current_branch + '.%s' |
| 150 | full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip() |
| 151 | remote = _run_command(['git', 'config', cfg_option % 'remote']).strip() |
| 152 | if not remote or not full_upstream: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 153 | raise VerifyException('Need to be on a tracking branch') |
Ryan Cui | 4725d95 | 2011-05-05 15:41:19 -0700 | [diff] [blame] | 154 | |
| 155 | return full_upstream.replace('heads', 'remotes/' + remote) |
| 156 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 157 | |
Mandeep Singh Baines | b9ed140 | 2011-04-29 15:32:06 -0700 | [diff] [blame] | 158 | def _get_diff(commit): |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 159 | """Returns the diff for this commit.""" |
Ryan Cui | 72834d1 | 2011-05-05 14:51:33 -0700 | [diff] [blame] | 160 | return _run_command(['git', 'show', commit]) |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 161 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 162 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 163 | def _get_file_diff(file, commit): |
| 164 | """Returns a list of (linenum, lines) tuples that the commit touched.""" |
Ryan Cui | 72834d1 | 2011-05-05 14:51:33 -0700 | [diff] [blame] | 165 | output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file]) |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 166 | |
| 167 | new_lines = [] |
| 168 | line_num = 0 |
| 169 | for line in output.splitlines(): |
| 170 | m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line) |
| 171 | if m: |
| 172 | line_num = int(m.groups(1)[0]) |
| 173 | continue |
| 174 | if line.startswith('+') and not line.startswith('++'): |
| 175 | new_lines.append((line_num, line[1:])) |
| 176 | if not line.startswith('-'): |
| 177 | line_num += 1 |
| 178 | return new_lines |
| 179 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 180 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 181 | def _get_affected_files(commit): |
| 182 | """Returns list of absolute filepaths that were modified/added.""" |
Ryan Cui | 72834d1 | 2011-05-05 14:51:33 -0700 | [diff] [blame] | 183 | output = _run_command(['git', 'diff', '--name-status', commit + '^!']) |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 184 | files = [] |
| 185 | for statusline in output.splitlines(): |
| 186 | m = re.match('^(\w)+\t(.+)$', statusline.rstrip()) |
| 187 | # Ignore deleted files, and return absolute paths of files |
| 188 | if (m.group(1)[0] != 'D'): |
| 189 | pwd = os.getcwd() |
| 190 | files.append(os.path.join(pwd, m.group(2))) |
| 191 | return files |
| 192 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 193 | |
Mandeep Singh Baines | b9ed140 | 2011-04-29 15:32:06 -0700 | [diff] [blame] | 194 | def _get_commits(): |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 195 | """Returns a list of commits for this review.""" |
Ryan Cui | 4725d95 | 2011-05-05 15:41:19 -0700 | [diff] [blame] | 196 | cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H'] |
Ryan Cui | 72834d1 | 2011-05-05 14:51:33 -0700 | [diff] [blame] | 197 | return _run_command(cmd).split() |
Mandeep Singh Baines | b9ed140 | 2011-04-29 15:32:06 -0700 | [diff] [blame] | 198 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 199 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 200 | def _get_commit_desc(commit): |
| 201 | """Returns the full commit message of a commit.""" |
Sean Paul | 23a2c58 | 2011-05-06 13:10:44 -0400 | [diff] [blame] | 202 | return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!']) |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 203 | |
| 204 | |
| 205 | # Common Hooks |
| 206 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 207 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 208 | def _check_no_long_lines(project, commit): |
| 209 | """Checks that there aren't any lines longer than maxlen characters in any of |
| 210 | the text files to be submitted. |
| 211 | """ |
| 212 | MAX_LEN = 80 |
| 213 | |
| 214 | errors = [] |
| 215 | files = _filter_files(_get_affected_files(commit), |
| 216 | COMMON_INCLUDED_PATHS, |
| 217 | COMMON_EXCLUDED_PATHS) |
| 218 | |
| 219 | for afile in files: |
| 220 | for line_num, line in _get_file_diff(afile, commit): |
| 221 | # Allow certain lines to exceed the maxlen rule. |
| 222 | if (len(line) > MAX_LEN and |
| 223 | not 'http://' in line and |
| 224 | not 'https://' in line and |
| 225 | not line.startswith('#define') and |
| 226 | not line.startswith('#include') and |
| 227 | not line.startswith('#import') and |
| 228 | not line.startswith('#pragma') and |
| 229 | not line.startswith('#if') and |
| 230 | not line.startswith('#endif')): |
| 231 | errors.append('%s, line %s, %s chars' % (afile, line_num, len(line))) |
| 232 | if len(errors) == 5: # Just show the first 5 errors. |
| 233 | break |
| 234 | |
| 235 | if errors: |
| 236 | msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 237 | return HookFailure(msg, errors) |
| 238 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 239 | |
| 240 | def _check_no_stray_whitespace(project, commit): |
| 241 | """Checks that there is no stray whitespace at source lines end.""" |
| 242 | errors = [] |
| 243 | files = _filter_files(_get_affected_files(commit), |
| 244 | COMMON_INCLUDED_PATHS, |
| 245 | COMMON_EXCLUDED_PATHS) |
| 246 | |
| 247 | for afile in files: |
| 248 | for line_num, line in _get_file_diff(afile, commit): |
| 249 | if line.rstrip() != line: |
| 250 | errors.append('%s, line %s' % (afile, line_num)) |
| 251 | if errors: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 252 | return HookFailure('Found line ending with white space in:', errors) |
| 253 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 254 | |
| 255 | def _check_no_tabs(project, commit): |
| 256 | """Checks there are no unexpanded tabs.""" |
| 257 | TAB_OK_PATHS = [ |
Ryan Cui | 31e0c17 | 2011-05-04 21:00:45 -0700 | [diff] [blame] | 258 | r"/src/third_party/u-boot/", |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 259 | r".*\.ebuild$", |
| 260 | r".*\.eclass$", |
Elly Jones | 5ab3419 | 2011-11-15 14:57:06 -0500 | [diff] [blame] | 261 | r".*/[M|m]akefile$", |
| 262 | r".*\.mk$" |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 263 | ] |
| 264 | |
| 265 | errors = [] |
| 266 | files = _filter_files(_get_affected_files(commit), |
| 267 | COMMON_INCLUDED_PATHS, |
| 268 | COMMON_EXCLUDED_PATHS + TAB_OK_PATHS) |
| 269 | |
| 270 | for afile in files: |
| 271 | for line_num, line in _get_file_diff(afile, commit): |
| 272 | if '\t' in line: |
| 273 | errors.append('%s, line %s' % (afile, line_num)) |
| 274 | if errors: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 275 | return HookFailure('Found a tab character in:', errors) |
| 276 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 277 | |
| 278 | def _check_change_has_test_field(project, commit): |
| 279 | """Check for a non-empty 'TEST=' field in the commit message.""" |
David McMahon | 8f6553e | 2011-06-10 15:46:36 -0700 | [diff] [blame] | 280 | TEST_RE = r'\nTEST=\S+' |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 281 | |
Mandeep Singh Baines | 96a53be | 2011-05-03 11:10:25 -0700 | [diff] [blame] | 282 | if not re.search(TEST_RE, _get_commit_desc(commit)): |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 283 | msg = 'Changelist description needs TEST field (after first line)' |
| 284 | return HookFailure(msg) |
| 285 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 286 | |
| 287 | def _check_change_has_bug_field(project, commit): |
David McMahon | 8f6553e | 2011-06-10 15:46:36 -0700 | [diff] [blame] | 288 | """Check for a correctly formatted 'BUG=' field in the commit message.""" |
Daniel Erat | 1f06464 | 2012-01-10 09:48:20 -0800 | [diff] [blame] | 289 | BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|chromium-os):\d+)' |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 290 | |
Mandeep Singh Baines | 96a53be | 2011-05-03 11:10:25 -0700 | [diff] [blame] | 291 | if not re.search(BUG_RE, _get_commit_desc(commit)): |
David McMahon | 8f6553e | 2011-06-10 15:46:36 -0700 | [diff] [blame] | 292 | msg = ('Changelist description needs BUG field (after first line):\n' |
Daniel Erat | 1f06464 | 2012-01-10 09:48:20 -0800 | [diff] [blame] | 293 | 'BUG=chromium-os:9999 (for public tracker)\n' |
David McMahon | 8f6553e | 2011-06-10 15:46:36 -0700 | [diff] [blame] | 294 | 'BUG=chrome-os-partner:9999 (for partner tracker)\n' |
Daniel Erat | 1f06464 | 2012-01-10 09:48:20 -0800 | [diff] [blame] | 295 | 'BUG=chromium:9999 (for browser tracker)\n' |
David McMahon | 8f6553e | 2011-06-10 15:46:36 -0700 | [diff] [blame] | 296 | 'BUG=None') |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 297 | return HookFailure(msg) |
| 298 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 299 | |
Mandeep Singh Baines | a23eb5f | 2011-05-04 13:43:25 -0700 | [diff] [blame] | 300 | def _check_change_has_proper_changeid(project, commit): |
| 301 | """Verify that Change-ID is present in last paragraph of commit message.""" |
| 302 | desc = _get_commit_desc(commit) |
| 303 | loc = desc.rfind('\nChange-Id:') |
| 304 | if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]): |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 305 | return HookFailure('Change-Id must be in last paragraph of description.') |
| 306 | |
Mandeep Singh Baines | a23eb5f | 2011-05-04 13:43:25 -0700 | [diff] [blame] | 307 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 308 | def _check_license(project, commit): |
| 309 | """Verifies the license header.""" |
| 310 | LICENSE_HEADER = ( |
David James | 28766e6 | 2012-08-06 17:30:15 -0700 | [diff] [blame] | 311 | r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights " |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 312 | r"reserved\." "\n" |
| 313 | r".*? Use of this source code is governed by a BSD-style license that can " |
| 314 | "be\n" |
| 315 | r".*? found in the LICENSE file\." |
| 316 | "\n" |
| 317 | ) |
| 318 | |
| 319 | license_re = re.compile(LICENSE_HEADER, re.MULTILINE) |
| 320 | bad_files = [] |
| 321 | files = _filter_files(_get_affected_files(commit), |
| 322 | COMMON_INCLUDED_PATHS, |
| 323 | COMMON_EXCLUDED_PATHS) |
| 324 | |
| 325 | for f in files: |
| 326 | contents = open(f).read() |
| 327 | if len(contents) == 0: continue # Ignore empty files |
| 328 | if not license_re.search(contents): |
| 329 | bad_files.append(f) |
| 330 | if bad_files: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 331 | return HookFailure('License must match:\n%s\n' % license_re.pattern + |
| 332 | 'Found a bad license header in these files:', |
| 333 | bad_files) |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 334 | |
| 335 | |
| 336 | # Project-specific hooks |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 337 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 338 | |
Anton Staaf | 815d685 | 2011-08-22 10:08:45 -0700 | [diff] [blame] | 339 | def _run_checkpatch(project, commit, options=[]): |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 340 | """Runs checkpatch.pl on the given project""" |
| 341 | hooks_dir = _get_hooks_dir() |
Anton Staaf | 815d685 | 2011-08-22 10:08:45 -0700 | [diff] [blame] | 342 | cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-'] |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 343 | p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
Mandeep Singh Baines | b9ed140 | 2011-04-29 15:32:06 -0700 | [diff] [blame] | 344 | output = p.communicate(_get_diff(commit))[0] |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 345 | if p.returncode: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 346 | return HookFailure('checkpatch.pl errors/warnings\n\n' + output) |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 347 | |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 348 | |
Anton Staaf | 815d685 | 2011-08-22 10:08:45 -0700 | [diff] [blame] | 349 | def _run_checkpatch_no_tree(project, commit): |
| 350 | return _run_checkpatch(project, commit, ['--no-tree']) |
| 351 | |
| 352 | |
Dale Curtis | 2975c43 | 2011-05-03 17:25:20 -0700 | [diff] [blame] | 353 | def _run_json_check(project, commit): |
| 354 | """Checks that all JSON files are syntactically valid.""" |
Dale Curtis | a039cfd | 2011-05-04 12:01:05 -0700 | [diff] [blame] | 355 | for f in _filter_files(_get_affected_files(commit), [r'.*\.json']): |
Dale Curtis | 2975c43 | 2011-05-03 17:25:20 -0700 | [diff] [blame] | 356 | try: |
| 357 | json.load(open(f)) |
| 358 | except Exception, e: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 359 | return HookFailure('Invalid JSON in %s: %s' % (f, e)) |
Dale Curtis | 2975c43 | 2011-05-03 17:25:20 -0700 | [diff] [blame] | 360 | |
| 361 | |
Puneet Kumar | c80e3f6 | 2012-08-13 19:01:18 -0700 | [diff] [blame] | 362 | def _check_change_has_branch_field(project, commit): |
| 363 | """Check for a non-empty 'BRANCH=' field in the commit message.""" |
| 364 | BRANCH_RE = r'\nBRANCH=\S+' |
| 365 | |
| 366 | if not re.search(BRANCH_RE, _get_commit_desc(commit)): |
| 367 | msg = ('Changelist description needs BRANCH field (after first line)\n' |
| 368 | 'E.g. BRANCH=none or BRANCH=link,snow') |
| 369 | return HookFailure(msg) |
| 370 | |
| 371 | |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 372 | # Base |
| 373 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 374 | |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 375 | # A list of hooks that are not project-specific |
| 376 | _COMMON_HOOKS = [ |
| 377 | _check_change_has_bug_field, |
| 378 | _check_change_has_test_field, |
| 379 | _check_change_has_proper_changeid, |
| 380 | _check_no_stray_whitespace, |
| 381 | _check_no_long_lines, |
| 382 | _check_license, |
| 383 | _check_no_tabs, |
| 384 | ] |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 385 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 386 | |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 387 | # A dictionary of project-specific hooks(callbacks), indexed by project name. |
| 388 | # dict[project] = [callback1, callback2] |
| 389 | _PROJECT_SPECIFIC_HOOKS = { |
Doug Anderson | 830216f | 2011-05-02 10:08:37 -0700 | [diff] [blame] | 390 | "chromiumos/third_party/kernel": [_run_checkpatch], |
| 391 | "chromiumos/third_party/kernel-next": [_run_checkpatch], |
Puneet Kumar | c80e3f6 | 2012-08-13 19:01:18 -0700 | [diff] [blame] | 392 | "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree, |
| 393 | _check_change_has_branch_field], |
| 394 | "chromiumos/platform/ec": [_run_checkpatch_no_tree, |
| 395 | _check_change_has_branch_field], |
| 396 | "chromeos/platform/ec-private": [_run_checkpatch_no_tree, |
| 397 | _check_change_has_branch_field], |
| 398 | "chromeos/third_party/coreboot": [_check_change_has_branch_field], |
Puneet Kumar | 57b9c09 | 2012-08-14 18:58:29 -0700 | [diff] [blame^] | 399 | "chromeos/third_party/intel-framework": [_check_change_has_branch_field], |
Puneet Kumar | c80e3f6 | 2012-08-13 19:01:18 -0700 | [diff] [blame] | 400 | "chromiumos/platform/vboot_reference": [_check_change_has_branch_field], |
| 401 | "chromiumos/platform/mosys": [_check_change_has_branch_field], |
| 402 | "chromiumos/third_party/flashrom": [_check_change_has_branch_field], |
Dale Curtis | 2975c43 | 2011-05-03 17:25:20 -0700 | [diff] [blame] | 403 | "chromeos/autotest-tools": [_run_json_check], |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 404 | } |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 405 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 406 | |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 407 | # A dictionary of flags (keys) that can appear in the config file, and the hook |
| 408 | # that the flag disables (value) |
| 409 | _DISABLE_FLAGS = { |
| 410 | 'stray_whitespace_check': _check_no_stray_whitespace, |
| 411 | 'long_line_check': _check_no_long_lines, |
| 412 | 'cros_license_check': _check_license, |
| 413 | 'tab_check': _check_no_tabs, |
Puneet Kumar | c80e3f6 | 2012-08-13 19:01:18 -0700 | [diff] [blame] | 414 | 'branch_check': _check_change_has_branch_field, |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 415 | } |
| 416 | |
| 417 | |
| 418 | def _get_disabled_hooks(): |
| 419 | """Returns a set of hooks disabled by the current project's config file. |
| 420 | |
| 421 | Expects to be called within the project root. |
| 422 | """ |
| 423 | SECTION = 'Hook Overrides' |
| 424 | config = ConfigParser.RawConfigParser() |
| 425 | try: |
| 426 | config.read(_CONFIG_FILE) |
| 427 | flags = config.options(SECTION) |
| 428 | except ConfigParser.Error: |
| 429 | return set([]) |
| 430 | |
| 431 | disable_flags = [] |
| 432 | for flag in flags: |
| 433 | try: |
| 434 | if not config.getboolean(SECTION, flag): disable_flags.append(flag) |
| 435 | except ValueError as e: |
| 436 | msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE) |
| 437 | print msg + str(e) |
| 438 | |
| 439 | disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags) |
| 440 | return set([_DISABLE_FLAGS[key] for key in disabled_keys]) |
| 441 | |
| 442 | |
| 443 | def _get_project_hooks(project): |
| 444 | """Returns a list of hooks that need to be run for a project. |
| 445 | |
| 446 | Expects to be called from within the project root. |
| 447 | """ |
| 448 | disabled_hooks = _get_disabled_hooks() |
| 449 | hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks] |
| 450 | |
| 451 | if project in _PROJECT_SPECIFIC_HOOKS: |
Puneet Kumar | c80e3f6 | 2012-08-13 19:01:18 -0700 | [diff] [blame] | 452 | hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project] |
| 453 | if hook not in disabled_hooks) |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 454 | |
| 455 | return hooks |
| 456 | |
| 457 | |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 458 | def _run_project_hooks(project, proj_dir=None): |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 459 | """For each project run its project specific hook from the hooks dictionary. |
| 460 | |
| 461 | Args: |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 462 | project: The name of project to run hooks for. |
| 463 | proj_dir: If non-None, this is the directory the project is in. If None, |
| 464 | we'll ask repo. |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 465 | |
| 466 | Returns: |
| 467 | Boolean value of whether any errors were ecountered while running the hooks. |
| 468 | """ |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 469 | if proj_dir is None: |
| 470 | proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip() |
| 471 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 472 | pwd = os.getcwd() |
| 473 | # hooks assume they are run from the root of the project |
| 474 | os.chdir(proj_dir) |
| 475 | |
Ryan Cui | fa55df5 | 2011-05-06 11:16:55 -0700 | [diff] [blame] | 476 | try: |
| 477 | commit_list = _get_commits() |
Don Garrett | dba548a | 2011-05-05 15:17:14 -0700 | [diff] [blame] | 478 | except VerifyException as e: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 479 | PrintErrorForProject(project, HookFailure(str(e))) |
| 480 | os.chdir(pwd) |
| 481 | return True |
Ryan Cui | fa55df5 | 2011-05-06 11:16:55 -0700 | [diff] [blame] | 482 | |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 483 | hooks = _get_project_hooks(project) |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 484 | error_found = False |
Ryan Cui | fa55df5 | 2011-05-06 11:16:55 -0700 | [diff] [blame] | 485 | for commit in commit_list: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 486 | error_list = [] |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 487 | for hook in hooks: |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 488 | hook_error = hook(project, commit) |
| 489 | if hook_error: |
| 490 | error_list.append(hook_error) |
| 491 | error_found = True |
| 492 | if error_list: |
| 493 | PrintErrorsForCommit(project, commit, _get_commit_desc(commit), |
| 494 | error_list) |
Don Garrett | dba548a | 2011-05-05 15:17:14 -0700 | [diff] [blame] | 495 | |
Ryan Cui | ec4d633 | 2011-05-02 14:15:25 -0700 | [diff] [blame] | 496 | os.chdir(pwd) |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 497 | return error_found |
Mandeep Singh Baines | 116ad10 | 2011-04-27 15:16:37 -0700 | [diff] [blame] | 498 | |
| 499 | # Main |
Mandeep Singh Baines | 69e470e | 2011-04-06 10:34:52 -0700 | [diff] [blame] | 500 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 501 | |
Anush Elangovan | 63afad7 | 2011-03-23 00:41:27 -0700 | [diff] [blame] | 502 | def main(project_list, **kwargs): |
Doug Anderson | 0645663 | 2012-01-05 11:02:14 -0800 | [diff] [blame] | 503 | """Main function invoked directly by repo. |
| 504 | |
| 505 | This function will exit directly upon error so that repo doesn't print some |
| 506 | obscure error message. |
| 507 | |
| 508 | Args: |
| 509 | project_list: List of projects to run on. |
| 510 | kwargs: Leave this here for forward-compatibility. |
| 511 | """ |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 512 | found_error = False |
| 513 | for project in project_list: |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 514 | if _run_project_hooks(project): |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 515 | found_error = True |
| 516 | |
| 517 | if (found_error): |
| 518 | msg = ('Preupload failed due to errors in project(s). HINTS:\n' |
Ryan Cui | 9b65163 | 2011-05-11 11:38:58 -0700 | [diff] [blame] | 519 | '- To disable some source style checks, and for other hints, see ' |
| 520 | '<checkout_dir>/src/repohooks/README\n' |
| 521 | '- To upload only current project, run \'repo upload .\'') |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 522 | print >> sys.stderr, msg |
Don Garrett | dba548a | 2011-05-05 15:17:14 -0700 | [diff] [blame] | 523 | sys.exit(1) |
Anush Elangovan | 63afad7 | 2011-03-23 00:41:27 -0700 | [diff] [blame] | 524 | |
Ryan Cui | 1562fb8 | 2011-05-09 11:01:31 -0700 | [diff] [blame] | 525 | |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 526 | def _identify_project(path): |
| 527 | """Identify the repo project associated with the given path. |
| 528 | |
| 529 | Returns: |
| 530 | A string indicating what project is associated with the path passed in or |
| 531 | a blank string upon failure. |
| 532 | """ |
| 533 | return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'], |
| 534 | stderr=subprocess.PIPE, cwd=path).strip() |
| 535 | |
| 536 | |
| 537 | def direct_main(args, verbose=False): |
| 538 | """Run hooks directly (outside of the context of repo). |
| 539 | |
| 540 | # Setup for doctests below. |
| 541 | # ...note that some tests assume that running pre-upload on this CWD is fine. |
| 542 | # TODO: Use mock and actually mock out _run_project_hooks() for tests. |
| 543 | >>> mydir = os.path.dirname(os.path.abspath(__file__)) |
| 544 | >>> olddir = os.getcwd() |
| 545 | |
| 546 | # OK to run w/ no arugments; will run with CWD. |
| 547 | >>> os.chdir(mydir) |
| 548 | >>> direct_main(['prog_name'], verbose=True) |
| 549 | Running hooks on chromiumos/repohooks |
| 550 | 0 |
| 551 | >>> os.chdir(olddir) |
| 552 | |
| 553 | # Run specifying a dir |
| 554 | >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True) |
| 555 | Running hooks on chromiumos/repohooks |
| 556 | 0 |
| 557 | |
| 558 | # Not a problem to use a bogus project; we'll just get default settings. |
| 559 | >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True) |
| 560 | Running hooks on X |
| 561 | 0 |
| 562 | |
| 563 | # Run with project but no dir |
| 564 | >>> os.chdir(mydir) |
| 565 | >>> direct_main(['prog_name', '--project=X'], verbose=True) |
| 566 | Running hooks on X |
| 567 | 0 |
| 568 | >>> os.chdir(olddir) |
| 569 | |
| 570 | # Try with a non-git CWD |
| 571 | >>> os.chdir('/tmp') |
| 572 | >>> direct_main(['prog_name']) |
| 573 | Traceback (most recent call last): |
| 574 | ... |
| 575 | BadInvocation: The current directory is not part of a git project. |
| 576 | |
| 577 | # Check various bad arguments... |
| 578 | >>> direct_main(['prog_name', 'bogus']) |
| 579 | Traceback (most recent call last): |
| 580 | ... |
| 581 | BadInvocation: Unexpected arguments: bogus |
| 582 | >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir']) |
| 583 | Traceback (most recent call last): |
| 584 | ... |
| 585 | BadInvocation: Invalid dir: bogusdir |
| 586 | >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp']) |
| 587 | Traceback (most recent call last): |
| 588 | ... |
| 589 | BadInvocation: Not a git directory: /tmp |
| 590 | |
| 591 | Args: |
| 592 | args: The value of sys.argv |
| 593 | |
| 594 | Returns: |
| 595 | 0 if no pre-upload failures, 1 if failures. |
| 596 | |
| 597 | Raises: |
| 598 | BadInvocation: On some types of invocation errors. |
| 599 | """ |
| 600 | desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.' |
| 601 | parser = optparse.OptionParser(description=desc) |
| 602 | |
| 603 | parser.add_option('--dir', default=None, |
| 604 | help='The directory that the project lives in. If not ' |
| 605 | 'specified, use the git project root based on the cwd.') |
| 606 | parser.add_option('--project', default=None, |
| 607 | help='The project repo path; this can affect how the hooks ' |
| 608 | 'get run, since some hooks are project-specific. For ' |
| 609 | 'chromite this is chromiumos/chromite. If not specified, ' |
| 610 | 'the repo tool will be used to figure this out based on ' |
| 611 | 'the dir.') |
| 612 | |
| 613 | opts, args = parser.parse_args(args[1:]) |
| 614 | |
| 615 | if args: |
| 616 | raise BadInvocation('Unexpected arguments: %s' % ' '.join(args)) |
| 617 | |
| 618 | # Check/normlaize git dir; if unspecified, we'll use the root of the git |
| 619 | # project from CWD |
| 620 | if opts.dir is None: |
| 621 | git_dir = _run_command(['git', 'rev-parse', '--git-dir'], |
| 622 | stderr=subprocess.PIPE).strip() |
| 623 | if not git_dir: |
| 624 | raise BadInvocation('The current directory is not part of a git project.') |
| 625 | opts.dir = os.path.dirname(os.path.abspath(git_dir)) |
| 626 | elif not os.path.isdir(opts.dir): |
| 627 | raise BadInvocation('Invalid dir: %s' % opts.dir) |
| 628 | elif not os.path.isdir(os.path.join(opts.dir, '.git')): |
| 629 | raise BadInvocation('Not a git directory: %s' % opts.dir) |
| 630 | |
| 631 | # Identify the project if it wasn't specified; this _requires_ the repo |
| 632 | # tool to be installed and for the project to be part of a repo checkout. |
| 633 | if not opts.project: |
| 634 | opts.project = _identify_project(opts.dir) |
| 635 | if not opts.project: |
| 636 | raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir) |
| 637 | |
| 638 | if verbose: |
| 639 | print "Running hooks on %s" % (opts.project) |
| 640 | |
| 641 | found_error = _run_project_hooks(opts.project, proj_dir=opts.dir) |
| 642 | if found_error: |
| 643 | return 1 |
| 644 | return 0 |
| 645 | |
| 646 | |
| 647 | def _test(): |
| 648 | """Run any built-in tests.""" |
| 649 | import doctest |
| 650 | doctest.testmod() |
| 651 | |
| 652 | |
Mandeep Singh Baines | 69e470e | 2011-04-06 10:34:52 -0700 | [diff] [blame] | 653 | if __name__ == '__main__': |
Doug Anderson | 44a644f | 2011-11-02 10:37:37 -0700 | [diff] [blame] | 654 | if sys.argv[1:2] == ["--test"]: |
| 655 | _test() |
| 656 | exit_code = 0 |
| 657 | else: |
| 658 | prog_name = os.path.basename(sys.argv[0]) |
| 659 | try: |
| 660 | exit_code = direct_main(sys.argv) |
| 661 | except BadInvocation, e: |
| 662 | print >>sys.stderr, "%s: %s" % (prog_name, str(e)) |
| 663 | exit_code = 1 |
| 664 | sys.exit(exit_code) |