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