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