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