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