estade@chromium.org | ae7af92 | 2012-01-27 14:51:13 +0000 | [diff] [blame] | 1 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """Generic presubmit checks that can be reused by other presubmit checks.""" |
| 6 | |
maruel@chromium.org | ff9a217 | 2012-04-24 16:55:32 +0000 | [diff] [blame] | 7 | import os as _os |
| 8 | _HERE = _os.path.dirname(_os.path.abspath(__file__)) |
| 9 | |
tfarina@chromium.org | b679564 | 2014-12-12 00:03:49 +0000 | [diff] [blame] | 10 | # Justifications for each filter: |
| 11 | # |
| 12 | # - build/include : Too many; fix in the future. |
| 13 | # - build/include_order : Not happening; #ifdefed includes. |
| 14 | # - build/namespace : I'm surprised by how often we violate this rule. |
| 15 | # - readability/casting : Mistakes a whole bunch of function pointer. |
| 16 | # - runtime/int : Can be fixed long term; volume of errors too high |
| 17 | # - runtime/virtual : Broken now, but can be fixed in the future? |
| 18 | # - whitespace/braces : We have a lot of explicit scoping in chrome code. |
tfarina@chromium.org | b679564 | 2014-12-12 00:03:49 +0000 | [diff] [blame] | 19 | DEFAULT_LINT_FILTERS = [ |
| 20 | '-build/include', |
| 21 | '-build/include_order', |
| 22 | '-build/namespace', |
| 23 | '-readability/casting', |
| 24 | '-runtime/int', |
| 25 | '-runtime/virtual', |
| 26 | '-whitespace/braces', |
tfarina@chromium.org | b679564 | 2014-12-12 00:03:49 +0000 | [diff] [blame] | 27 | ] |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 28 | |
danakj@chromium.org | 0ae7122 | 2016-01-11 19:37:11 +0000 | [diff] [blame] | 29 | # These filters will always be removed, even if the caller specifies a filter |
| 30 | # set, as they are problematic or broken in some way. |
| 31 | # |
| 32 | # Justifications for each filter: |
| 33 | # - build/c++11 : Rvalue ref checks are unreliable (false positives), |
| 34 | # include file and feature blacklists are |
| 35 | # google3-specific. |
| 36 | BLACKLIST_LINT_FILTERS = [ |
| 37 | '-build/c++11', |
| 38 | ] |
| 39 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 40 | ### Description checks |
| 41 | |
kuchhal@chromium.org | 00c41e4 | 2009-05-12 21:43:13 +0000 | [diff] [blame] | 42 | def CheckChangeHasBugField(input_api, output_api): |
Aaron Gable | fc03e67 | 2017-05-15 14:09:42 -0700 | [diff] [blame] | 43 | """Requires that the changelist have a Bug: field.""" |
| 44 | if input_api.change.BugsFromDescription(): |
kuchhal@chromium.org | 00c41e4 | 2009-05-12 21:43:13 +0000 | [diff] [blame] | 45 | return [] |
| 46 | else: |
| 47 | return [output_api.PresubmitNotifyResult( |
Aaron Gable | fc03e67 | 2017-05-15 14:09:42 -0700 | [diff] [blame] | 48 | 'If this change has an associated bug, add Bug: [bug number].')] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 49 | |
| 50 | |
| 51 | def CheckDoNotSubmitInDescription(input_api, output_api): |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 52 | """Checks that the user didn't add 'DO NOT ''SUBMIT' to the CL description. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 53 | """ |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 54 | keyword = 'DO NOT ''SUBMIT' |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 55 | if keyword in input_api.change.DescriptionText(): |
| 56 | return [output_api.PresubmitError( |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 57 | keyword + ' is present in the changelist description.')] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 58 | else: |
| 59 | return [] |
| 60 | |
| 61 | |
maruel@chromium.org | bc50eb4 | 2009-06-10 18:22:47 +0000 | [diff] [blame] | 62 | def CheckChangeHasDescription(input_api, output_api): |
| 63 | """Checks the CL description is not empty.""" |
| 64 | text = input_api.change.DescriptionText() |
| 65 | if text.strip() == '': |
| 66 | if input_api.is_committing: |
pgervais@chromium.org | bc3b3b5 | 2014-06-03 00:53:48 +0000 | [diff] [blame] | 67 | return [output_api.PresubmitError('Add a description to the CL.')] |
maruel@chromium.org | bc50eb4 | 2009-06-10 18:22:47 +0000 | [diff] [blame] | 68 | else: |
pgervais@chromium.org | bc3b3b5 | 2014-06-03 00:53:48 +0000 | [diff] [blame] | 69 | return [output_api.PresubmitNotifyResult('Add a description to the CL.')] |
maruel@chromium.org | bc50eb4 | 2009-06-10 18:22:47 +0000 | [diff] [blame] | 70 | return [] |
| 71 | |
maruel@chromium.org | cc73ad6 | 2011-07-06 17:39:26 +0000 | [diff] [blame] | 72 | |
| 73 | def CheckChangeWasUploaded(input_api, output_api): |
| 74 | """Checks that the issue was uploaded before committing.""" |
maruel@chromium.org | d587f39 | 2011-07-26 00:41:18 +0000 | [diff] [blame] | 75 | if input_api.is_committing and not input_api.change.issue: |
maruel@chromium.org | cc73ad6 | 2011-07-06 17:39:26 +0000 | [diff] [blame] | 76 | return [output_api.PresubmitError( |
| 77 | 'Issue wasn\'t uploaded. Please upload first.')] |
| 78 | return [] |
| 79 | |
| 80 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 81 | ### Content checks |
| 82 | |
Sergiy Byelozyorov | 621fe6f | 2018-05-25 17:38:46 -0700 | [diff] [blame^] | 83 | def CheckAuthorizedAuthor(input_api, output_api, bot_whitelist=None): |
Michael Achenbach | c850b96 | 2016-12-05 15:40:17 +0100 | [diff] [blame] | 84 | """For non-googler/chromites committers, verify the author's email address is |
| 85 | in AUTHORS. |
| 86 | """ |
Michael Achenbach | 590420d | 2017-10-18 12:35:37 +0200 | [diff] [blame] | 87 | if input_api.is_committing: |
| 88 | error_type = output_api.PresubmitError |
| 89 | else: |
| 90 | error_type = output_api.PresubmitPromptWarning |
| 91 | |
Michael Achenbach | c850b96 | 2016-12-05 15:40:17 +0100 | [diff] [blame] | 92 | author = input_api.change.author_email |
| 93 | if not author: |
| 94 | input_api.logging.info('No author, skipping AUTHOR check') |
| 95 | return [] |
Sergiy Byelozyorov | 621fe6f | 2018-05-25 17:38:46 -0700 | [diff] [blame^] | 96 | |
| 97 | # This is used for CLs created by trusted robot accounts. |
| 98 | if bot_whitelist and author in bot_whitelist: |
| 99 | return [] |
| 100 | |
Michael Achenbach | c850b96 | 2016-12-05 15:40:17 +0100 | [diff] [blame] | 101 | authors_path = input_api.os_path.join( |
| 102 | input_api.PresubmitLocalPath(), 'AUTHORS') |
| 103 | valid_authors = ( |
| 104 | input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line) |
| 105 | for line in open(authors_path)) |
| 106 | valid_authors = [item.group(1).lower() for item in valid_authors if item] |
| 107 | if not any(input_api.fnmatch.fnmatch(author.lower(), valid) |
| 108 | for valid in valid_authors): |
| 109 | input_api.logging.info('Valid authors are %s', ', '.join(valid_authors)) |
Michael Achenbach | 590420d | 2017-10-18 12:35:37 +0200 | [diff] [blame] | 110 | return [error_type( |
Michael Achenbach | c850b96 | 2016-12-05 15:40:17 +0100 | [diff] [blame] | 111 | ('%s is not in AUTHORS file. If you are a new contributor, please visit' |
| 112 | '\n' |
Xiaoyin Liu | b580797 | 2017-10-04 22:07:24 -0400 | [diff] [blame] | 113 | 'https://www.chromium.org/developers/contributing-code and read the ' |
Michael Achenbach | c850b96 | 2016-12-05 15:40:17 +0100 | [diff] [blame] | 114 | '"Legal" section\n' |
| 115 | 'If you are a chromite, verify the contributor signed the CLA.') % |
| 116 | author)] |
| 117 | return [] |
| 118 | |
| 119 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 120 | def CheckDoNotSubmitInFiles(input_api, output_api): |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 121 | """Checks that the user didn't add 'DO NOT ''SUBMIT' to any files.""" |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 122 | # We want to check every text file, not just source files. |
| 123 | file_filter = lambda x : x |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 124 | keyword = 'DO NOT ''SUBMIT' |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 125 | errors = _FindNewViolationsOfRule(lambda _, line : keyword not in line, |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 126 | input_api, file_filter) |
| 127 | text = '\n'.join('Found %s in %s' % (keyword, loc) for loc in errors) |
| 128 | if text: |
| 129 | return [output_api.PresubmitError(text)] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 130 | return [] |
| 131 | |
| 132 | |
tfarina@chromium.org | b679564 | 2014-12-12 00:03:49 +0000 | [diff] [blame] | 133 | def CheckChangeLintsClean(input_api, output_api, source_file_filter=None, |
tfarina@chromium.org | a62208f | 2015-02-25 03:23:11 +0000 | [diff] [blame] | 134 | lint_filters=None, verbose_level=None): |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 135 | """Checks that all '.cc' and '.h' files pass cpplint.py.""" |
erg@google.com | 26970fa | 2009-11-17 18:07:32 +0000 | [diff] [blame] | 136 | _RE_IS_TEST = input_api.re.compile(r'.*tests?.(cc|h)$') |
| 137 | result = [] |
| 138 | |
enne@chromium.org | e72c5f5 | 2013-04-16 00:36:40 +0000 | [diff] [blame] | 139 | cpplint = input_api.cpplint |
maruel@chromium.org | b17b55b | 2010-11-03 14:42:37 +0000 | [diff] [blame] | 140 | # Access to a protected member _XX of a client class |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 141 | # pylint: disable=protected-access |
erg@google.com | 26970fa | 2009-11-17 18:07:32 +0000 | [diff] [blame] | 142 | cpplint._cpplint_state.ResetErrorCounts() |
| 143 | |
tfarina@chromium.org | b679564 | 2014-12-12 00:03:49 +0000 | [diff] [blame] | 144 | lint_filters = lint_filters or DEFAULT_LINT_FILTERS |
danakj@chromium.org | 0ae7122 | 2016-01-11 19:37:11 +0000 | [diff] [blame] | 145 | lint_filters.extend(BLACKLIST_LINT_FILTERS) |
tfarina@chromium.org | b679564 | 2014-12-12 00:03:49 +0000 | [diff] [blame] | 146 | cpplint._SetFilters(','.join(lint_filters)) |
erg@google.com | 26970fa | 2009-11-17 18:07:32 +0000 | [diff] [blame] | 147 | |
| 148 | # We currently are more strict with normal code than unit tests; 4 and 5 are |
| 149 | # the verbosity level that would normally be passed to cpplint.py through |
| 150 | # --verbose=#. Hopefully, in the future, we can be more verbose. |
| 151 | files = [f.AbsoluteLocalPath() for f in |
| 152 | input_api.AffectedSourceFiles(source_file_filter)] |
| 153 | for file_name in files: |
| 154 | if _RE_IS_TEST.match(file_name): |
| 155 | level = 5 |
| 156 | else: |
| 157 | level = 4 |
| 158 | |
tfarina@chromium.org | a62208f | 2015-02-25 03:23:11 +0000 | [diff] [blame] | 159 | verbose_level = verbose_level or level |
| 160 | cpplint.ProcessFile(file_name, verbose_level) |
erg@google.com | 26970fa | 2009-11-17 18:07:32 +0000 | [diff] [blame] | 161 | |
| 162 | if cpplint._cpplint_state.error_count > 0: |
| 163 | if input_api.is_committing: |
| 164 | res_type = output_api.PresubmitError |
| 165 | else: |
| 166 | res_type = output_api.PresubmitPromptWarning |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 167 | result = [res_type('Changelist failed cpplint.py check.')] |
erg@google.com | 26970fa | 2009-11-17 18:07:32 +0000 | [diff] [blame] | 168 | |
| 169 | return result |
| 170 | |
| 171 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 172 | def CheckChangeHasNoCR(input_api, output_api, source_file_filter=None): |
maruel@chromium.org | e9b71c9 | 2009-06-10 18:10:01 +0000 | [diff] [blame] | 173 | """Checks no '\r' (CR) character is in any source files.""" |
| 174 | cr_files = [] |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 175 | for f in input_api.AffectedSourceFiles(source_file_filter): |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 176 | if '\r' in input_api.ReadFile(f, 'rb'): |
maruel@chromium.org | e9b71c9 | 2009-06-10 18:10:01 +0000 | [diff] [blame] | 177 | cr_files.append(f.LocalPath()) |
| 178 | if cr_files: |
| 179 | return [output_api.PresubmitPromptWarning( |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 180 | 'Found a CR character in these files:', items=cr_files)] |
maruel@chromium.org | e9b71c9 | 2009-06-10 18:10:01 +0000 | [diff] [blame] | 181 | return [] |
| 182 | |
| 183 | |
| 184 | def CheckChangeHasOnlyOneEol(input_api, output_api, source_file_filter=None): |
| 185 | """Checks the files ends with one and only one \n (LF).""" |
| 186 | eof_files = [] |
| 187 | for f in input_api.AffectedSourceFiles(source_file_filter): |
| 188 | contents = input_api.ReadFile(f, 'rb') |
| 189 | # Check that the file ends in one and only one newline character. |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 190 | if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'): |
maruel@chromium.org | e9b71c9 | 2009-06-10 18:10:01 +0000 | [diff] [blame] | 191 | eof_files.append(f.LocalPath()) |
| 192 | |
| 193 | if eof_files: |
| 194 | return [output_api.PresubmitPromptWarning( |
| 195 | 'These files should end in one (and only one) newline character:', |
| 196 | items=eof_files)] |
| 197 | return [] |
| 198 | |
| 199 | |
| 200 | def CheckChangeHasNoCrAndHasOnlyOneEol(input_api, output_api, |
| 201 | source_file_filter=None): |
| 202 | """Runs both CheckChangeHasNoCR and CheckChangeHasOnlyOneEOL in one pass. |
| 203 | |
| 204 | It is faster because it is reading the file only once. |
| 205 | """ |
| 206 | cr_files = [] |
| 207 | eof_files = [] |
| 208 | for f in input_api.AffectedSourceFiles(source_file_filter): |
| 209 | contents = input_api.ReadFile(f, 'rb') |
| 210 | if '\r' in contents: |
| 211 | cr_files.append(f.LocalPath()) |
| 212 | # Check that the file ends in one and only one newline character. |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 213 | if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'): |
maruel@chromium.org | e9b71c9 | 2009-06-10 18:10:01 +0000 | [diff] [blame] | 214 | eof_files.append(f.LocalPath()) |
| 215 | outputs = [] |
| 216 | if cr_files: |
| 217 | outputs.append(output_api.PresubmitPromptWarning( |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 218 | 'Found a CR character in these files:', items=cr_files)) |
maruel@chromium.org | e9b71c9 | 2009-06-10 18:10:01 +0000 | [diff] [blame] | 219 | if eof_files: |
| 220 | outputs.append(output_api.PresubmitPromptWarning( |
| 221 | 'These files should end in one (and only one) newline character:', |
| 222 | items=eof_files)) |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 223 | return outputs |
| 224 | |
seanmccullough | 0b67044 | 2016-06-07 10:45:58 -0700 | [diff] [blame] | 225 | def CheckGenderNeutral(input_api, output_api, source_file_filter=None): |
| 226 | """Checks that there are no gendered pronouns in any of the text files to be |
| 227 | submitted. |
| 228 | """ |
| 229 | gendered_re = input_api.re.compile( |
| 230 | '(^|\s|\(|\[)([Hh]e|[Hh]is|[Hh]ers?|[Hh]im|[Ss]he|[Gg]uys?)\\b') |
| 231 | |
| 232 | errors = [] |
| 233 | for f in input_api.AffectedFiles(include_deletes=False, |
| 234 | file_filter=source_file_filter): |
| 235 | for line_num, line in f.ChangedContents(): |
| 236 | if gendered_re.search(line): |
| 237 | errors.append('%s (%d): %s' % (f.LocalPath(), line_num, line)) |
| 238 | |
| 239 | if len(errors): |
| 240 | return [output_api.PresubmitPromptWarning('Found a gendered pronoun in:', |
| 241 | long_text='\n'.join(errors))] |
| 242 | return [] |
| 243 | |
| 244 | |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 245 | |
chrisha@google.com | 267d659 | 2012-06-19 19:23:31 +0000 | [diff] [blame] | 246 | def _ReportErrorFileAndLine(filename, line_num, dummy_line): |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 247 | """Default error formatter for _FindNewViolationsOfRule.""" |
danakj@chromium.org | c5965ba | 2013-08-14 00:27:24 +0000 | [diff] [blame] | 248 | return '%s:%s' % (filename, line_num) |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 249 | |
| 250 | |
| 251 | def _FindNewViolationsOfRule(callable_rule, input_api, source_file_filter=None, |
| 252 | error_formatter=_ReportErrorFileAndLine): |
| 253 | """Find all newly introduced violations of a per-line rule (a callable). |
| 254 | |
| 255 | Arguments: |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 256 | callable_rule: a callable taking a file extension and line of input and |
| 257 | returning True if the rule is satisfied and False if there was a problem. |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 258 | input_api: object to enumerate the affected files. |
| 259 | source_file_filter: a filter to be passed to the input api. |
| 260 | error_formatter: a callable taking (filename, line_number, line) and |
| 261 | returning a formatted error string. |
| 262 | |
| 263 | Returns: |
| 264 | A list of the newly-introduced violations reported by the rule. |
| 265 | """ |
| 266 | errors = [] |
sail@chromium.org | 5538e02 | 2011-05-12 17:53:16 +0000 | [diff] [blame] | 267 | for f in input_api.AffectedFiles(include_deletes=False, |
| 268 | file_filter=source_file_filter): |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 269 | # For speed, we do two passes, checking first the full file. Shelling out |
| 270 | # to the SCM to determine the changed region can be quite expensive on |
| 271 | # Win32. Assuming that most files will be kept problem-free, we can |
| 272 | # skip the SCM operations most of the time. |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 273 | extension = str(f.LocalPath()).rsplit('.', 1)[-1] |
| 274 | if all(callable_rule(extension, line) for line in f.NewContents()): |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 275 | continue # No violation found in full text: can skip considering diff. |
| 276 | |
| 277 | for line_num, line in f.ChangedContents(): |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 278 | if not callable_rule(extension, line): |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 279 | errors.append(error_formatter(f.LocalPath(), line_num, line)) |
| 280 | |
| 281 | return errors |
| 282 | |
| 283 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 284 | def CheckChangeHasNoTabs(input_api, output_api, source_file_filter=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 285 | """Checks that there are no tab characters in any of the text files to be |
| 286 | submitted. |
| 287 | """ |
maruel@chromium.org | 115ae6c | 2010-06-18 17:11:43 +0000 | [diff] [blame] | 288 | # In addition to the filter, make sure that makefiles are blacklisted. |
| 289 | if not source_file_filter: |
| 290 | # It's the default filter. |
| 291 | source_file_filter = input_api.FilterSourceFile |
| 292 | def filter_more(affected_file): |
cmp@chromium.org | cb5e57c | 2012-04-06 19:50:15 +0000 | [diff] [blame] | 293 | basename = input_api.os_path.basename(affected_file.LocalPath()) |
| 294 | return (not (basename in ('Makefile', 'makefile') or |
| 295 | basename.endswith('.mk')) and |
maruel@chromium.org | 115ae6c | 2010-06-18 17:11:43 +0000 | [diff] [blame] | 296 | source_file_filter(affected_file)) |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 297 | |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 298 | tabs = _FindNewViolationsOfRule(lambda _, line : '\t' not in line, |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 299 | input_api, filter_more) |
| 300 | |
maruel@chromium.org | e9b71c9 | 2009-06-10 18:10:01 +0000 | [diff] [blame] | 301 | if tabs: |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 302 | return [output_api.PresubmitPromptWarning('Found a tab character in:', |
| 303 | long_text='\n'.join(tabs))] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 304 | return [] |
| 305 | |
| 306 | |
estade@chromium.org | fdcc9f7 | 2011-02-07 22:25:07 +0000 | [diff] [blame] | 307 | def CheckChangeTodoHasOwner(input_api, output_api, source_file_filter=None): |
| 308 | """Checks that the user didn't add TODO(name) without an owner.""" |
| 309 | |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 310 | unowned_todo = input_api.re.compile('TO''DO[^(]') |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 311 | errors = _FindNewViolationsOfRule(lambda _, x : not unowned_todo.search(x), |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 312 | input_api, source_file_filter) |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 313 | errors = ['Found TO''DO with no owner in ' + x for x in errors] |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 314 | if errors: |
| 315 | return [output_api.PresubmitPromptWarning('\n'.join(errors))] |
estade@chromium.org | fdcc9f7 | 2011-02-07 22:25:07 +0000 | [diff] [blame] | 316 | return [] |
| 317 | |
| 318 | |
maruel@chromium.org | f5888bb | 2009-06-10 20:26:37 +0000 | [diff] [blame] | 319 | def CheckChangeHasNoStrayWhitespace(input_api, output_api, |
| 320 | source_file_filter=None): |
| 321 | """Checks that there is no stray whitespace at source lines end.""" |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 322 | errors = _FindNewViolationsOfRule(lambda _, line : line.rstrip() == line, |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 323 | input_api, source_file_filter) |
maruel@chromium.org | f5888bb | 2009-06-10 20:26:37 +0000 | [diff] [blame] | 324 | if errors: |
| 325 | return [output_api.PresubmitPromptWarning( |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 326 | 'Found line ending with white spaces in:', |
| 327 | long_text='\n'.join(errors))] |
maruel@chromium.org | f5888bb | 2009-06-10 20:26:37 +0000 | [diff] [blame] | 328 | return [] |
| 329 | |
| 330 | |
jamesr@chromium.org | af27f46 | 2013-04-04 21:44:22 +0000 | [diff] [blame] | 331 | def CheckLongLines(input_api, output_api, maxlen, source_file_filter=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 332 | """Checks that there aren't any lines longer than maxlen characters in any of |
| 333 | the text files to be submitted. |
| 334 | """ |
dpranke@chromium.org | e3b1c3d | 2012-10-20 22:28:14 +0000 | [diff] [blame] | 335 | maxlens = { |
| 336 | 'java': 100, |
torne@chromium.org | 0ecad9c | 2013-02-15 16:35:16 +0000 | [diff] [blame] | 337 | # This is specifically for Android's handwritten makefiles (Android.mk). |
| 338 | 'mk': 200, |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 339 | '': maxlen, |
| 340 | } |
maruel@chromium.org | eba6462 | 2011-06-20 18:26:48 +0000 | [diff] [blame] | 341 | |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 342 | # Language specific exceptions to max line length. |
| 343 | # '.h' is considered an obj-c file extension, since OBJC_EXCEPTIONS are a |
| 344 | # superset of CPP_EXCEPTIONS. |
| 345 | CPP_FILE_EXTS = ('c', 'cc') |
| 346 | CPP_EXCEPTIONS = ('#define', '#endif', '#if', '#include', '#pragma') |
Dave Schuyler | 6eea7c2 | 2017-03-03 18:46:25 -0800 | [diff] [blame] | 347 | HTML_FILE_EXTS = ('html',) |
Dave Schuyler | 9b9b94c | 2017-04-13 15:28:41 -0700 | [diff] [blame] | 348 | HTML_EXCEPTIONS = ('<g ', '<link ', '<path ',) |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 349 | JAVA_FILE_EXTS = ('java',) |
| 350 | JAVA_EXCEPTIONS = ('import ', 'package ') |
dbeam@chromium.org | 5a2af6d | 2015-10-08 17:52:29 +0000 | [diff] [blame] | 351 | JS_FILE_EXTS = ('js',) |
| 352 | JS_EXCEPTIONS = ("GEN('#include",) |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 353 | OBJC_FILE_EXTS = ('h', 'm', 'mm') |
| 354 | OBJC_EXCEPTIONS = ('#define', '#endif', '#if', '#import', '#include', |
| 355 | '#pragma') |
dbeam@chromium.org | 5a2af6d | 2015-10-08 17:52:29 +0000 | [diff] [blame] | 356 | PY_FILE_EXTS = ('py',) |
aiolos@chromium.org | 84033cc | 2015-07-16 01:27:15 +0000 | [diff] [blame] | 357 | PY_EXCEPTIONS = ('import', 'from') |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 358 | |
| 359 | LANGUAGE_EXCEPTIONS = [ |
| 360 | (CPP_FILE_EXTS, CPP_EXCEPTIONS), |
Dave Schuyler | 6eea7c2 | 2017-03-03 18:46:25 -0800 | [diff] [blame] | 361 | (HTML_FILE_EXTS, HTML_EXCEPTIONS), |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 362 | (JAVA_FILE_EXTS, JAVA_EXCEPTIONS), |
dbeam@chromium.org | 5a2af6d | 2015-10-08 17:52:29 +0000 | [diff] [blame] | 363 | (JS_FILE_EXTS, JS_EXCEPTIONS), |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 364 | (OBJC_FILE_EXTS, OBJC_EXCEPTIONS), |
aiolos@chromium.org | 84033cc | 2015-07-16 01:27:15 +0000 | [diff] [blame] | 365 | (PY_FILE_EXTS, PY_EXCEPTIONS), |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 366 | ] |
sivachandra@chromium.org | 270db5c | 2012-10-09 22:38:44 +0000 | [diff] [blame] | 367 | |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 368 | def no_long_lines(file_extension, line): |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 369 | # Check for language specific exceptions. |
Dave Schuyler | 9b9b94c | 2017-04-13 15:28:41 -0700 | [diff] [blame] | 370 | if any(file_extension in exts and line.lstrip().startswith(exceptions) |
erikchen@google.com | 1281608 | 2013-12-03 02:04:20 +0000 | [diff] [blame] | 371 | for exts, exceptions in LANGUAGE_EXCEPTIONS): |
sivachandra@chromium.org | 270db5c | 2012-10-09 22:38:44 +0000 | [diff] [blame] | 372 | return True |
| 373 | |
bulach@chromium.org | bfffd45 | 2012-02-22 01:13:29 +0000 | [diff] [blame] | 374 | file_maxlen = maxlens.get(file_extension, maxlens['']) |
| 375 | # Stupidly long symbols that needs to be worked around if takes 66% of line. |
| 376 | long_symbol = file_maxlen * 2 / 3 |
| 377 | # Hard line length limit at 50% more. |
| 378 | extra_maxlen = file_maxlen * 3 / 2 |
| 379 | |
| 380 | line_len = len(line) |
| 381 | if line_len <= file_maxlen: |
maruel@chromium.org | eba6462 | 2011-06-20 18:26:48 +0000 | [diff] [blame] | 382 | return True |
| 383 | |
dtu@chromium.org | 03f0c53 | 2015-03-27 22:22:07 +0000 | [diff] [blame] | 384 | # Allow long URLs of any length. |
treib@chromium.org | de3ee90 | 2014-07-28 14:23:11 +0000 | [diff] [blame] | 385 | if any((url in line) for url in ('file://', 'http://', 'https://')): |
| 386 | return True |
| 387 | |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 388 | # If 'line-too-long' is explicitly suppressed for the line, any length is |
nednguyen@google.com | 6df90f3 | 2015-12-01 20:14:33 +0000 | [diff] [blame] | 389 | # acceptable. |
| 390 | if 'pylint: disable=line-too-long' in line and file_extension == 'py': |
| 391 | return True |
| 392 | |
dtu@chromium.org | 03f0c53 | 2015-03-27 22:22:07 +0000 | [diff] [blame] | 393 | if line_len > extra_maxlen: |
| 394 | return False |
| 395 | |
treib@chromium.org | de3ee90 | 2014-07-28 14:23:11 +0000 | [diff] [blame] | 396 | if 'url(' in line and file_extension == 'css': |
| 397 | return True |
| 398 | |
dbeam@chromium.org | b5ccc9b | 2014-09-23 00:42:22 +0000 | [diff] [blame] | 399 | if '<include' in line and file_extension in ('css', 'html', 'js'): |
| 400 | return True |
| 401 | |
treib@chromium.org | de3ee90 | 2014-07-28 14:23:11 +0000 | [diff] [blame] | 402 | return input_api.re.match( |
| 403 | r'.*[A-Za-z][A-Za-z_0-9]{%d,}.*' % long_symbol, line) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 404 | |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 405 | def format_error(filename, line_num, line): |
| 406 | return '%s, line %s, %s chars' % (filename, line_num, len(line)) |
| 407 | |
| 408 | errors = _FindNewViolationsOfRule(no_long_lines, input_api, |
| 409 | source_file_filter, |
| 410 | error_formatter=format_error) |
| 411 | if errors: |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 412 | msg = 'Found lines longer than %s characters (first 5 shown).' % maxlen |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 413 | return [output_api.PresubmitPromptWarning(msg, items=errors[:5])] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 414 | else: |
| 415 | return [] |
| 416 | |
| 417 | |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 418 | def CheckLicense(input_api, output_api, license_re, source_file_filter=None, |
maruel@chromium.org | 7162685 | 2010-11-03 13:14:25 +0000 | [diff] [blame] | 419 | accept_empty_files=True): |
maruel@chromium.org | b9e7ada | 2010-01-27 23:12:39 +0000 | [diff] [blame] | 420 | """Verifies the license header. |
| 421 | """ |
maruel@chromium.org | cb2985f | 2010-11-03 14:08:31 +0000 | [diff] [blame] | 422 | license_re = input_api.re.compile(license_re, input_api.re.MULTILINE) |
maruel@chromium.org | b9e7ada | 2010-01-27 23:12:39 +0000 | [diff] [blame] | 423 | bad_files = [] |
| 424 | for f in input_api.AffectedSourceFiles(source_file_filter): |
| 425 | contents = input_api.ReadFile(f, 'rb') |
maruel@chromium.org | 7162685 | 2010-11-03 13:14:25 +0000 | [diff] [blame] | 426 | if accept_empty_files and not contents: |
| 427 | continue |
maruel@chromium.org | b9e7ada | 2010-01-27 23:12:39 +0000 | [diff] [blame] | 428 | if not license_re.search(contents): |
| 429 | bad_files.append(f.LocalPath()) |
| 430 | if bad_files: |
phajdan.jr@chromium.org | e27eb7e | 2015-11-16 12:47:53 +0000 | [diff] [blame] | 431 | return [output_api.PresubmitPromptWarning( |
bradnelson@google.com | 393460b | 2011-03-29 01:20:26 +0000 | [diff] [blame] | 432 | 'License must match:\n%s\n' % license_re.pattern + |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 433 | 'Found a bad license header in these files:', items=bad_files)] |
maruel@chromium.org | b9e7ada | 2010-01-27 23:12:39 +0000 | [diff] [blame] | 434 | return [] |
| 435 | |
| 436 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 437 | ### Other checks |
| 438 | |
| 439 | def CheckDoNotSubmit(input_api, output_api): |
| 440 | return ( |
| 441 | CheckDoNotSubmitInDescription(input_api, output_api) + |
| 442 | CheckDoNotSubmitInFiles(input_api, output_api) |
| 443 | ) |
| 444 | |
| 445 | |
bradnelson@google.com | c0b332a | 2010-08-26 00:30:37 +0000 | [diff] [blame] | 446 | def CheckTreeIsOpen(input_api, output_api, |
| 447 | url=None, closed=None, json_url=None): |
| 448 | """Check whether to allow commit without prompt. |
| 449 | |
| 450 | Supports two styles: |
| 451 | 1. Checks that an url's content doesn't match a regexp that would mean that |
| 452 | the tree is closed. (old) |
| 453 | 2. Check the json_url to decide whether to allow commit without prompt. |
| 454 | Args: |
| 455 | input_api: input related apis. |
| 456 | output_api: output related apis. |
| 457 | url: url to use for regex based tree status. |
| 458 | closed: regex to match for closed status. |
| 459 | json_url: url to download json style status. |
| 460 | """ |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 461 | if not input_api.is_committing: |
| 462 | return [] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 463 | try: |
bradnelson@google.com | c0b332a | 2010-08-26 00:30:37 +0000 | [diff] [blame] | 464 | if json_url: |
| 465 | connection = input_api.urllib2.urlopen(json_url) |
| 466 | status = input_api.json.loads(connection.read()) |
| 467 | connection.close() |
| 468 | if not status['can_commit_freely']: |
| 469 | short_text = 'Tree state is: ' + status['general_state'] |
| 470 | long_text = status['message'] + '\n' + json_url |
| 471 | return [output_api.PresubmitError(short_text, long_text=long_text)] |
| 472 | else: |
| 473 | # TODO(bradnelson): drop this once all users are gone. |
| 474 | connection = input_api.urllib2.urlopen(url) |
| 475 | status = connection.read() |
| 476 | connection.close() |
| 477 | if input_api.re.match(closed, status): |
| 478 | long_text = status + '\n' + url |
| 479 | return [output_api.PresubmitError('The tree is closed.', |
| 480 | long_text=long_text)] |
rohitrao@chromium.org | d490ee8 | 2012-02-06 19:31:33 +0000 | [diff] [blame] | 481 | except IOError as e: |
| 482 | return [output_api.PresubmitError('Error fetching tree status.', |
| 483 | long_text=str(e))] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 484 | return [] |
maruel@chromium.org | 7b305e8 | 2009-05-19 18:24:20 +0000 | [diff] [blame] | 485 | |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 486 | def GetUnitTestsInDirectory( |
smut@google.com | ac29620 | 2014-04-24 21:47:17 +0000 | [diff] [blame] | 487 | input_api, output_api, directory, whitelist=None, blacklist=None, env=None): |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 488 | """Lists all files in a directory and runs them. Doesn't recurse. |
| 489 | |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 490 | It's mainly a wrapper for RunUnitTests. Use whitelist and blacklist to filter |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 491 | tests accordingly. |
| 492 | """ |
| 493 | unit_tests = [] |
| 494 | test_path = input_api.os_path.abspath( |
| 495 | input_api.os_path.join(input_api.PresubmitLocalPath(), directory)) |
| 496 | |
| 497 | def check(filename, filters): |
| 498 | return any(True for i in filters if input_api.re.match(i, filename)) |
| 499 | |
maruel@chromium.org | fae707b | 2011-09-15 18:57:58 +0000 | [diff] [blame] | 500 | to_run = found = 0 |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 501 | for filename in input_api.os_listdir(test_path): |
maruel@chromium.org | fae707b | 2011-09-15 18:57:58 +0000 | [diff] [blame] | 502 | found += 1 |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 503 | fullpath = input_api.os_path.join(test_path, filename) |
| 504 | if not input_api.os_path.isfile(fullpath): |
| 505 | continue |
| 506 | if whitelist and not check(filename, whitelist): |
| 507 | continue |
| 508 | if blacklist and check(filename, blacklist): |
| 509 | continue |
| 510 | unit_tests.append(input_api.os_path.join(directory, filename)) |
maruel@chromium.org | fae707b | 2011-09-15 18:57:58 +0000 | [diff] [blame] | 511 | to_run += 1 |
anatoly techtonik | bdcdc59 | 2017-03-29 17:00:13 +0300 | [diff] [blame] | 512 | input_api.logging.debug('Found %d files, running %d unit tests' |
| 513 | % (found, to_run)) |
maruel@chromium.org | fae707b | 2011-09-15 18:57:58 +0000 | [diff] [blame] | 514 | if not to_run: |
| 515 | return [ |
| 516 | output_api.PresubmitPromptWarning( |
| 517 | 'Out of %d files, found none that matched w=%r, b=%r in directory %s' |
| 518 | % (found, whitelist, blacklist, directory)) |
| 519 | ] |
smut@google.com | ac29620 | 2014-04-24 21:47:17 +0000 | [diff] [blame] | 520 | return GetUnitTests(input_api, output_api, unit_tests, env) |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 521 | |
| 522 | |
smut@google.com | ac29620 | 2014-04-24 21:47:17 +0000 | [diff] [blame] | 523 | def GetUnitTests(input_api, output_api, unit_tests, env=None): |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 524 | """Runs all unit tests in a directory. |
| 525 | |
| 526 | On Windows, sys.executable is used for unit tests ending with ".py". |
| 527 | """ |
| 528 | # We don't want to hinder users from uploading incomplete patches. |
| 529 | if input_api.is_committing: |
| 530 | message_type = output_api.PresubmitError |
| 531 | else: |
| 532 | message_type = output_api.PresubmitPromptWarning |
| 533 | |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 534 | results = [] |
| 535 | for unit_test in unit_tests: |
Robert Iannucci | 5025893 | 2018-03-19 10:30:59 -0700 | [diff] [blame] | 536 | cmd = [unit_test] |
maruel@chromium.org | 899e1c1 | 2011-04-07 17:03:18 +0000 | [diff] [blame] | 537 | if input_api.verbose: |
maruel@chromium.org | 6c7723e | 2011-04-12 19:04:55 +0000 | [diff] [blame] | 538 | cmd.append('--verbose') |
smut@google.com | ac29620 | 2014-04-24 21:47:17 +0000 | [diff] [blame] | 539 | kwargs = {'cwd': input_api.PresubmitLocalPath()} |
| 540 | if env: |
| 541 | kwargs['env'] = env |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 542 | results.append(input_api.Command( |
| 543 | name=unit_test, |
| 544 | cmd=cmd, |
smut@google.com | ac29620 | 2014-04-24 21:47:17 +0000 | [diff] [blame] | 545 | kwargs=kwargs, |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 546 | message=message_type)) |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 547 | return results |
| 548 | |
nick@chromium.org | ff52619 | 2013-06-10 19:30:26 +0000 | [diff] [blame] | 549 | |
agable@chromium.org | 40a3d0b | 2014-05-15 01:59:16 +0000 | [diff] [blame] | 550 | def GetUnitTestsRecursively(input_api, output_api, directory, |
| 551 | whitelist, blacklist): |
| 552 | """Gets all files in the directory tree (git repo) that match the whitelist. |
| 553 | |
| 554 | Restricts itself to only find files within the Change's source repo, not |
| 555 | dependencies. |
| 556 | """ |
| 557 | def check(filename): |
| 558 | return (any(input_api.re.match(f, filename) for f in whitelist) and |
| 559 | not any(input_api.re.match(f, filename) for f in blacklist)) |
| 560 | |
| 561 | tests = [] |
| 562 | |
| 563 | to_run = found = 0 |
| 564 | for filepath in input_api.change.AllFiles(directory): |
| 565 | found += 1 |
| 566 | if check(filepath): |
| 567 | to_run += 1 |
| 568 | tests.append(filepath) |
| 569 | input_api.logging.debug('Found %d files, running %d' % (found, to_run)) |
| 570 | if not to_run: |
| 571 | return [ |
| 572 | output_api.PresubmitPromptWarning( |
| 573 | 'Out of %d files, found none that matched w=%r, b=%r in directory %s' |
| 574 | % (found, whitelist, blacklist, directory)) |
| 575 | ] |
| 576 | |
| 577 | return GetUnitTests(input_api, output_api, tests) |
| 578 | |
| 579 | |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 580 | def GetPythonUnitTests(input_api, output_api, unit_tests): |
maruel@chromium.org | c0b2297 | 2009-06-25 16:19:14 +0000 | [diff] [blame] | 581 | """Run the unit tests out of process, capture the output and use the result |
| 582 | code to determine success. |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 583 | |
| 584 | DEPRECATED. |
maruel@chromium.org | c0b2297 | 2009-06-25 16:19:14 +0000 | [diff] [blame] | 585 | """ |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 586 | # We don't want to hinder users from uploading incomplete patches. |
| 587 | if input_api.is_committing: |
| 588 | message_type = output_api.PresubmitError |
| 589 | else: |
| 590 | message_type = output_api.PresubmitNotifyResult |
maruel@chromium.org | 0e76605 | 2011-04-06 13:32:51 +0000 | [diff] [blame] | 591 | results = [] |
maruel@chromium.org | 7b305e8 | 2009-05-19 18:24:20 +0000 | [diff] [blame] | 592 | for unit_test in unit_tests: |
maruel@chromium.org | c0b2297 | 2009-06-25 16:19:14 +0000 | [diff] [blame] | 593 | # Run the unit tests out of process. This is because some unit tests |
| 594 | # stub out base libraries and don't clean up their mess. It's too easy to |
| 595 | # get subtle bugs. |
| 596 | cwd = None |
| 597 | env = None |
| 598 | unit_test_name = unit_test |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 599 | # 'python -m test.unit_test' doesn't work. We need to change to the right |
maruel@chromium.org | c0b2297 | 2009-06-25 16:19:14 +0000 | [diff] [blame] | 600 | # directory instead. |
| 601 | if '.' in unit_test: |
| 602 | # Tests imported in submodules (subdirectories) assume that the current |
| 603 | # directory is in the PYTHONPATH. Manually fix that. |
| 604 | unit_test = unit_test.replace('.', '/') |
| 605 | cwd = input_api.os_path.dirname(unit_test) |
| 606 | unit_test = input_api.os_path.basename(unit_test) |
| 607 | env = input_api.environ.copy() |
kbr@google.com | ab31859 | 2009-09-04 00:54:55 +0000 | [diff] [blame] | 608 | # At least on Windows, it seems '.' must explicitly be in PYTHONPATH |
| 609 | backpath = [ |
| 610 | '.', input_api.os_path.pathsep.join(['..'] * (cwd.count('/') + 1)) |
| 611 | ] |
maruel@chromium.org | c0b2297 | 2009-06-25 16:19:14 +0000 | [diff] [blame] | 612 | if env.get('PYTHONPATH'): |
| 613 | backpath.append(env.get('PYTHONPATH')) |
ukai@chromium.org | a301f1f | 2009-08-05 10:37:33 +0000 | [diff] [blame] | 614 | env['PYTHONPATH'] = input_api.os_path.pathsep.join((backpath)) |
Robert Iannucci | 23bd735 | 2018-03-23 11:51:40 -0700 | [diff] [blame] | 615 | env.pop('VPYTHON_CLEAR_PYTHONPATH', None) |
maruel@chromium.org | 0e76605 | 2011-04-06 13:32:51 +0000 | [diff] [blame] | 616 | cmd = [input_api.python_executable, '-m', '%s' % unit_test] |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 617 | results.append(input_api.Command( |
| 618 | name=unit_test_name, |
| 619 | cmd=cmd, |
| 620 | kwargs={'env': env, 'cwd': cwd}, |
| 621 | message=message_type)) |
maruel@chromium.org | 0e76605 | 2011-04-06 13:32:51 +0000 | [diff] [blame] | 622 | return results |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 623 | |
| 624 | |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 625 | def RunUnitTestsInDirectory(input_api, *args, **kwargs): |
| 626 | """Run tests in a directory serially. |
| 627 | |
| 628 | For better performance, use GetUnitTestsInDirectory and then |
| 629 | pass to input_api.RunTests. |
| 630 | """ |
| 631 | return input_api.RunTests( |
| 632 | GetUnitTestsInDirectory(input_api, *args, **kwargs), False) |
| 633 | |
| 634 | |
| 635 | def RunUnitTests(input_api, *args, **kwargs): |
| 636 | """Run tests serially. |
| 637 | |
| 638 | For better performance, use GetUnitTests and then pass to |
| 639 | input_api.RunTests. |
| 640 | """ |
| 641 | return input_api.RunTests(GetUnitTests(input_api, *args, **kwargs), False) |
| 642 | |
| 643 | |
| 644 | def RunPythonUnitTests(input_api, *args, **kwargs): |
| 645 | """Run python tests in a directory serially. |
| 646 | |
| 647 | DEPRECATED |
| 648 | """ |
| 649 | return input_api.RunTests( |
| 650 | GetPythonUnitTests(input_api, *args, **kwargs), False) |
| 651 | |
| 652 | |
maruel@chromium.org | 5d0dc43 | 2011-01-03 02:40:37 +0000 | [diff] [blame] | 653 | def _FetchAllFiles(input_api, white_list, black_list): |
| 654 | """Hack to fetch all files.""" |
| 655 | # We cannot use AffectedFiles here because we want to test every python |
| 656 | # file on each single python change. It's because a change in a python file |
| 657 | # can break another unmodified file. |
| 658 | # Use code similar to InputApi.FilterSourceFile() |
| 659 | def Find(filepath, filters): |
anatoly techtonik | bdcdc59 | 2017-03-29 17:00:13 +0300 | [diff] [blame] | 660 | if input_api.platform == 'win32': |
| 661 | filepath = filepath.replace('\\', '/') |
| 662 | |
maruel@chromium.org | 5d0dc43 | 2011-01-03 02:40:37 +0000 | [diff] [blame] | 663 | for item in filters: |
| 664 | if input_api.re.match(item, filepath): |
| 665 | return True |
| 666 | return False |
| 667 | |
maruel@chromium.org | 5d0dc43 | 2011-01-03 02:40:37 +0000 | [diff] [blame] | 668 | files = [] |
| 669 | path_len = len(input_api.PresubmitLocalPath()) |
maruel@chromium.org | 2b5ce56 | 2011-03-31 16:15:44 +0000 | [diff] [blame] | 670 | for dirpath, dirnames, filenames in input_api.os_walk( |
| 671 | input_api.PresubmitLocalPath()): |
maruel@chromium.org | 5d0dc43 | 2011-01-03 02:40:37 +0000 | [diff] [blame] | 672 | # Passes dirnames in black list to speed up search. |
| 673 | for item in dirnames[:]: |
| 674 | filepath = input_api.os_path.join(dirpath, item)[path_len + 1:] |
| 675 | if Find(filepath, black_list): |
| 676 | dirnames.remove(item) |
| 677 | for item in filenames: |
| 678 | filepath = input_api.os_path.join(dirpath, item)[path_len + 1:] |
| 679 | if Find(filepath, white_list) and not Find(filepath, black_list): |
| 680 | files.append(filepath) |
| 681 | return files |
| 682 | |
| 683 | |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 684 | def GetPylint(input_api, output_api, white_list=None, black_list=None, |
dtu@chromium.org | f23524d | 2016-01-27 20:08:49 +0000 | [diff] [blame] | 685 | disabled_warnings=None, extra_paths_list=None, pylintrc=None): |
maruel@chromium.org | bf38a7e | 2010-12-14 18:15:54 +0000 | [diff] [blame] | 686 | """Run pylint on python files. |
| 687 | |
chrisha@google.com | 267d659 | 2012-06-19 19:23:31 +0000 | [diff] [blame] | 688 | The default white_list enforces looking only at *.py files. |
maruel@chromium.org | bf38a7e | 2010-12-14 18:15:54 +0000 | [diff] [blame] | 689 | """ |
maruel@chromium.org | 69eaecb | 2011-06-14 13:09:13 +0000 | [diff] [blame] | 690 | white_list = tuple(white_list or ('.*\.py$',)) |
| 691 | black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST) |
ilevy@chromium.org | 7b677f7 | 2013-01-07 18:49:26 +0000 | [diff] [blame] | 692 | extra_paths_list = extra_paths_list or [] |
| 693 | |
maruel@chromium.org | ade9c59 | 2011-04-07 15:59:11 +0000 | [diff] [blame] | 694 | if input_api.is_committing: |
| 695 | error_type = output_api.PresubmitError |
| 696 | else: |
| 697 | error_type = output_api.PresubmitPromptWarning |
maruel@chromium.org | bf38a7e | 2010-12-14 18:15:54 +0000 | [diff] [blame] | 698 | |
| 699 | # Only trigger if there is at least one python file affected. |
ilevy@chromium.org | 3657633 | 2013-01-08 03:16:15 +0000 | [diff] [blame] | 700 | def rel_path(regex): |
| 701 | """Modifies a regex for a subject to accept paths relative to root.""" |
chrisha@chromium.org | 40e5d3d | 2013-01-18 17:46:57 +0000 | [diff] [blame] | 702 | def samefile(a, b): |
| 703 | # Default implementation for platforms lacking os.path.samefile |
| 704 | # (like Windows). |
| 705 | return input_api.os_path.abspath(a) == input_api.os_path.abspath(b) |
| 706 | samefile = getattr(input_api.os_path, 'samefile', samefile) |
| 707 | if samefile(input_api.PresubmitLocalPath(), |
| 708 | input_api.change.RepositoryRoot()): |
ilevy@chromium.org | dd4e931 | 2013-01-15 03:22:04 +0000 | [diff] [blame] | 709 | return regex |
chrisha@chromium.org | 40e5d3d | 2013-01-18 17:46:57 +0000 | [diff] [blame] | 710 | |
ilevy@chromium.org | 3657633 | 2013-01-08 03:16:15 +0000 | [diff] [blame] | 711 | prefix = input_api.os_path.join(input_api.os_path.relpath( |
| 712 | input_api.PresubmitLocalPath(), input_api.change.RepositoryRoot()), '') |
| 713 | return input_api.re.escape(prefix) + regex |
ilevy@chromium.org | 7b677f7 | 2013-01-07 18:49:26 +0000 | [diff] [blame] | 714 | src_filter = lambda x: input_api.FilterSourceFile( |
| 715 | x, map(rel_path, white_list), map(rel_path, black_list)) |
maruel@chromium.org | bf38a7e | 2010-12-14 18:15:54 +0000 | [diff] [blame] | 716 | if not input_api.AffectedSourceFiles(src_filter): |
ilevy@chromium.org | 7b677f7 | 2013-01-07 18:49:26 +0000 | [diff] [blame] | 717 | input_api.logging.info('Skipping pylint: no matching changes.') |
maruel@chromium.org | bf38a7e | 2010-12-14 18:15:54 +0000 | [diff] [blame] | 718 | return [] |
| 719 | |
agable@chromium.org | 327d72b | 2015-04-21 20:22:50 +0000 | [diff] [blame] | 720 | if pylintrc is not None: |
| 721 | pylintrc = input_api.os_path.join(input_api.PresubmitLocalPath(), pylintrc) |
| 722 | else: |
| 723 | pylintrc = input_api.os_path.join(_HERE, 'pylintrc') |
dtu@chromium.org | f23524d | 2016-01-27 20:08:49 +0000 | [diff] [blame] | 724 | extra_args = ['--rcfile=%s' % pylintrc] |
maruel@chromium.org | ff9a217 | 2012-04-24 16:55:32 +0000 | [diff] [blame] | 725 | if disabled_warnings: |
| 726 | extra_args.extend(['-d', ','.join(disabled_warnings)]) |
| 727 | |
chrisha@google.com | 267d659 | 2012-06-19 19:23:31 +0000 | [diff] [blame] | 728 | files = _FetchAllFiles(input_api, white_list, black_list) |
| 729 | if not files: |
maruel@chromium.org | fca5339 | 2010-12-21 18:42:57 +0000 | [diff] [blame] | 730 | return [] |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 731 | files.sort() |
chrisha@google.com | 267d659 | 2012-06-19 19:23:31 +0000 | [diff] [blame] | 732 | |
csharp@chromium.org | 4039534 | 2013-02-21 14:57:23 +0000 | [diff] [blame] | 733 | input_api.logging.info('Running pylint on %d files', len(files)) |
| 734 | input_api.logging.debug('Running pylint on: %s', files) |
chrisha@google.com | 267d659 | 2012-06-19 19:23:31 +0000 | [diff] [blame] | 735 | env = input_api.environ.copy() |
ilevy@chromium.org | 7b677f7 | 2013-01-07 18:49:26 +0000 | [diff] [blame] | 736 | env['PYTHONPATH'] = input_api.os_path.pathsep.join( |
Robert Iannucci | 82a6480 | 2018-03-23 16:40:16 -0700 | [diff] [blame] | 737 | extra_paths_list).encode('utf8') |
Robert Iannucci | 23bd735 | 2018-03-23 11:51:40 -0700 | [diff] [blame] | 738 | env.pop('VPYTHON_CLEAR_PYTHONPATH', None) |
Robert Iannucci | 82a6480 | 2018-03-23 16:40:16 -0700 | [diff] [blame] | 739 | input_api.logging.debug(' with extra PYTHONPATH: %r', extra_paths_list) |
chrisha@google.com | 267d659 | 2012-06-19 19:23:31 +0000 | [diff] [blame] | 740 | |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 741 | def GetPylintCmd(flist, extra, parallel): |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 742 | # Windows needs help running python files so we explicitly specify |
| 743 | # the interpreter to use. It also has limitations on the size of |
| 744 | # the command-line, so we pass arguments via a pipe. |
iannucci@chromium.org | 0af3bb3 | 2015-06-12 20:44:35 +0000 | [diff] [blame] | 745 | cmd = [input_api.python_executable, |
| 746 | input_api.os_path.join(_HERE, 'third_party', 'pylint.py'), |
| 747 | '--args-on-stdin'] |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 748 | if len(flist) == 1: |
| 749 | description = flist[0] |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 750 | else: |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 751 | description = '%s files' % len(flist) |
chrisha@chromium.org | 1b129e5 | 2012-06-22 17:08:11 +0000 | [diff] [blame] | 752 | |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 753 | args = extra_args[:] |
iannucci@chromium.org | 0af3bb3 | 2015-06-12 20:44:35 +0000 | [diff] [blame] | 754 | if extra: |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 755 | args.extend(extra) |
iannucci@chromium.org | 0af3bb3 | 2015-06-12 20:44:35 +0000 | [diff] [blame] | 756 | description += ' using %s' % (extra,) |
| 757 | if parallel: |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 758 | args.append('--jobs=%s' % input_api.cpu_count) |
iannucci@chromium.org | 0af3bb3 | 2015-06-12 20:44:35 +0000 | [diff] [blame] | 759 | description += ' on %d cores' % input_api.cpu_count |
| 760 | |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 761 | return input_api.Command( |
| 762 | name='Pylint (%s)' % description, |
iannucci@chromium.org | 0af3bb3 | 2015-06-12 20:44:35 +0000 | [diff] [blame] | 763 | cmd=cmd, |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 764 | kwargs={'env': env, 'stdin': '\n'.join(args + flist)}, |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 765 | message=error_type) |
chrisha@chromium.org | 1b129e5 | 2012-06-22 17:08:11 +0000 | [diff] [blame] | 766 | |
sbc@chromium.org | 7fc75ca | 2012-09-21 20:14:21 +0000 | [diff] [blame] | 767 | # Always run pylint and pass it all the py files at once. |
| 768 | # Passing py files one at time is slower and can produce |
| 769 | # different results. input_api.verbose used to be used |
| 770 | # to enable this behaviour but differing behaviour in |
| 771 | # verbose mode is not desirable. |
ilevy@chromium.org | 7b677f7 | 2013-01-07 18:49:26 +0000 | [diff] [blame] | 772 | # Leave this unreachable code in here so users can make |
| 773 | # a quick local edit to diagnose pylint issues more |
| 774 | # easily. |
sbc@chromium.org | 7fc75ca | 2012-09-21 20:14:21 +0000 | [diff] [blame] | 775 | if True: |
iannucci@chromium.org | 0af3bb3 | 2015-06-12 20:44:35 +0000 | [diff] [blame] | 776 | # pylint's cycle detection doesn't work in parallel, so spawn a second, |
| 777 | # single-threaded job for just that check. |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 778 | |
| 779 | # Some PRESUBMITs explicitly mention cycle detection. |
| 780 | if not any('R0401' in a or 'cyclic-import' in a for a in extra_args): |
| 781 | return [ |
| 782 | GetPylintCmd(files, ["--disable=cyclic-import"], True), |
| 783 | GetPylintCmd(files, ["--disable=all", "--enable=cyclic-import"], False) |
| 784 | ] |
| 785 | else: |
| 786 | return [ GetPylintCmd(files, [], True) ] |
| 787 | |
chrisha@google.com | 267d659 | 2012-06-19 19:23:31 +0000 | [diff] [blame] | 788 | else: |
iannucci@chromium.org | d61a495 | 2015-07-01 23:21:26 +0000 | [diff] [blame] | 789 | return map(lambda x: GetPylintCmd([x], [], 1), files) |
ilevy@chromium.org | bc11731 | 2013-04-20 03:57:56 +0000 | [diff] [blame] | 790 | |
| 791 | |
| 792 | def RunPylint(input_api, *args, **kwargs): |
| 793 | """Legacy presubmit function. |
| 794 | |
| 795 | For better performance, get all tests and then pass to |
| 796 | input_api.RunTests. |
| 797 | """ |
| 798 | return input_api.RunTests(GetPylint(input_api, *args, **kwargs), False) |
maruel@chromium.org | e94aedc | 2010-12-13 21:11:30 +0000 | [diff] [blame] | 799 | |
maruel@chromium.org | ade9c59 | 2011-04-07 15:59:11 +0000 | [diff] [blame] | 800 | |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 801 | def CheckBuildbotPendingBuilds(input_api, output_api, url, max_pendings, |
| 802 | ignored): |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 803 | try: |
| 804 | connection = input_api.urllib2.urlopen(url) |
| 805 | raw_data = connection.read() |
| 806 | connection.close() |
| 807 | except IOError: |
| 808 | return [output_api.PresubmitNotifyResult('%s is not accessible' % url)] |
| 809 | |
| 810 | try: |
| 811 | data = input_api.json.loads(raw_data) |
| 812 | except ValueError: |
| 813 | return [output_api.PresubmitNotifyResult('Received malformed json while ' |
| 814 | 'looking up buildbot status')] |
| 815 | |
| 816 | out = [] |
| 817 | for (builder_name, builder) in data.iteritems(): |
| 818 | if builder_name in ignored: |
| 819 | continue |
maruel@chromium.org | cf1982c | 2010-10-04 15:08:28 +0000 | [diff] [blame] | 820 | if builder.get('state', '') == 'offline': |
| 821 | continue |
maruel@chromium.org | 3fbcb08 | 2010-03-19 14:03:28 +0000 | [diff] [blame] | 822 | pending_builds_len = len(builder.get('pending_builds', [])) |
| 823 | if pending_builds_len > max_pendings: |
| 824 | out.append('%s has %d build(s) pending' % |
| 825 | (builder_name, pending_builds_len)) |
| 826 | if out: |
| 827 | return [output_api.PresubmitPromptWarning( |
| 828 | 'Build(s) pending. It is suggested to wait that no more than %d ' |
| 829 | 'builds are pending.' % max_pendings, |
| 830 | long_text='\n'.join(out))] |
| 831 | return [] |
dpranke@chromium.org | 2a00962 | 2011-03-01 02:43:31 +0000 | [diff] [blame] | 832 | |
| 833 | |
Edward Lesmes | 067ef5d | 2018-04-19 17:54:45 -0400 | [diff] [blame] | 834 | def CheckOwnersFormat(input_api, output_api): |
| 835 | affected_files = set([ |
| 836 | f.LocalPath() |
| 837 | for f in input_api.change.AffectedFiles() |
| 838 | if 'OWNERS' in f.LocalPath() and f.Action() != 'D' |
| 839 | ]) |
| 840 | if not affected_files: |
| 841 | return [] |
| 842 | try: |
| 843 | input_api.owners_db.load_data_needed_for(affected_files) |
| 844 | return [] |
| 845 | except Exception as e: |
| 846 | return [output_api.PresubmitError( |
| 847 | 'Error parsing OWNERS files:\n%s' % e)] |
| 848 | |
| 849 | |
dpranke@chromium.org | bce925d | 2015-01-16 22:38:38 +0000 | [diff] [blame] | 850 | def CheckOwners(input_api, output_api, source_file_filter=None): |
Aaron Gable | 8678d32 | 2018-04-02 13:28:19 -0700 | [diff] [blame] | 851 | affected_files = set([f.LocalPath() for f in |
| 852 | input_api.change.AffectedFiles(file_filter=source_file_filter)]) |
Jeremy Roman | 5ae86d2 | 2018-04-26 15:36:02 -0400 | [diff] [blame] | 853 | affects_owners = any('OWNERS' in name for name in affected_files) |
Aaron Gable | 8678d32 | 2018-04-02 13:28:19 -0700 | [diff] [blame] | 854 | |
pam@chromium.org | f46aed9 | 2012-03-08 09:18:17 +0000 | [diff] [blame] | 855 | if input_api.is_committing: |
Jeremy Roman | 5ae86d2 | 2018-04-26 15:36:02 -0400 | [diff] [blame] | 856 | if input_api.tbr and not affects_owners: |
pam@chromium.org | f46aed9 | 2012-03-08 09:18:17 +0000 | [diff] [blame] | 857 | return [output_api.PresubmitNotifyResult( |
| 858 | '--tbr was specified, skipping OWNERS check')] |
Clemens Hammacher | d0c226a | 2017-01-16 14:09:52 +0100 | [diff] [blame] | 859 | needed = 'LGTM from an OWNER' |
| 860 | output_fn = output_api.PresubmitError |
rmistry@google.com | 5fc6c8c | 2015-04-16 16:38:43 +0000 | [diff] [blame] | 861 | if input_api.change.issue: |
tandrii@chromium.org | 9dea2ac | 2016-04-28 06:26:20 +0000 | [diff] [blame] | 862 | if input_api.dry_run: |
Clemens Hammacher | d0c226a | 2017-01-16 14:09:52 +0100 | [diff] [blame] | 863 | output_fn = lambda text: output_api.PresubmitNotifyResult( |
| 864 | 'This is a dry run, but these failures would be reported on ' + |
| 865 | 'commit:\n' + text) |
rmistry@google.com | 5fc6c8c | 2015-04-16 16:38:43 +0000 | [diff] [blame] | 866 | else: |
Andrii Shyshkalov | 63560ad | 2018-02-09 19:09:54 -0800 | [diff] [blame] | 867 | return [output_api.PresubmitError( |
| 868 | 'OWNERS check failed: this CL has no Gerrit change number, ' |
| 869 | 'so we can\'t check it for approvals.')] |
pam@chromium.org | f46aed9 | 2012-03-08 09:18:17 +0000 | [diff] [blame] | 870 | else: |
| 871 | needed = 'OWNER reviewers' |
Clemens Hammacher | d0c226a | 2017-01-16 14:09:52 +0100 | [diff] [blame] | 872 | output_fn = output_api.PresubmitNotifyResult |
dpranke@chromium.org | 3e331bd | 2011-03-24 23:13:04 +0000 | [diff] [blame] | 873 | |
dpranke@chromium.org | 2a00962 | 2011-03-01 02:43:31 +0000 | [diff] [blame] | 874 | owners_db = input_api.owners_db |
Jochen Eisinger | d0573ec | 2017-04-13 10:55:06 +0200 | [diff] [blame] | 875 | owners_db.override_files = input_api.change.OriginalOwnersFiles() |
tandrii@chromium.org | 830dc0b | 2016-05-09 06:26:34 +0000 | [diff] [blame] | 876 | owner_email, reviewers = GetCodereviewOwnerAndReviewers( |
pam@chromium.org | f46aed9 | 2012-03-08 09:18:17 +0000 | [diff] [blame] | 877 | input_api, |
| 878 | owners_db.email_regexp, |
| 879 | approval_needed=input_api.is_committing) |
| 880 | |
dpranke@chromium.org | f6ddfa4 | 2013-03-05 21:06:03 +0000 | [diff] [blame] | 881 | owner_email = owner_email or input_api.change.author_email |
| 882 | |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 883 | finder = input_api.owners_finder( |
| 884 | affected_files, input_api.change.RepositoryRoot(), |
| 885 | owner_email, reviewers, fopen=file, os_path=input_api.os_path, |
| 886 | email_postfix='', disable_color=True, |
| 887 | override_files=input_api.change.OriginalOwnersFiles()) |
| 888 | missing_files = finder.unreviewed_files |
maruel@chromium.org | e4067ab | 2011-06-03 01:07:35 +0000 | [diff] [blame] | 889 | |
dpranke@chromium.org | 6b1e3ee | 2013-02-23 00:06:38 +0000 | [diff] [blame] | 890 | if missing_files: |
zork@chromium.org | 046e175 | 2012-05-07 05:56:12 +0000 | [diff] [blame] | 891 | output_list = [ |
Clemens Hammacher | d0c226a | 2017-01-16 14:09:52 +0100 | [diff] [blame] | 892 | output_fn('Missing %s for these files:\n %s' % |
| 893 | (needed, '\n '.join(sorted(missing_files))))] |
Jeremy Roman | 5ae86d2 | 2018-04-26 15:36:02 -0400 | [diff] [blame] | 894 | if input_api.tbr and affects_owners: |
| 895 | output_list.append(output_fn('Note that TBR does not apply to changes ' |
| 896 | 'that affect OWNERS files.')) |
zork@chromium.org | 046e175 | 2012-05-07 05:56:12 +0000 | [diff] [blame] | 897 | if not input_api.is_committing: |
dpranke@chromium.org | 31b42c0 | 2013-09-19 19:24:15 +0000 | [diff] [blame] | 898 | suggested_owners = owners_db.reviewers_for(missing_files, owner_email) |
Jochen Eisinger | 76f5fc6 | 2017-04-07 16:27:46 +0200 | [diff] [blame] | 899 | owners_with_comments = [] |
| 900 | def RecordComments(text): |
| 901 | owners_with_comments.append(finder.print_indent() + text) |
| 902 | finder.writeln = RecordComments |
| 903 | for owner in suggested_owners: |
| 904 | finder.print_comments(owner) |
Clemens Hammacher | d0c226a | 2017-01-16 14:09:52 +0100 | [diff] [blame] | 905 | output_list.append(output_fn('Suggested OWNERS: ' + |
scheib@chromium.org | 93276ab | 2013-10-14 23:55:32 +0000 | [diff] [blame] | 906 | '(Use "git-cl owners" to interactively select owners.)\n %s' % |
Jochen Eisinger | 76f5fc6 | 2017-04-07 16:27:46 +0200 | [diff] [blame] | 907 | ('\n '.join(owners_with_comments)))) |
zork@chromium.org | 046e175 | 2012-05-07 05:56:12 +0000 | [diff] [blame] | 908 | return output_list |
dpranke@chromium.org | 2a00962 | 2011-03-01 02:43:31 +0000 | [diff] [blame] | 909 | |
pam@chromium.org | f46aed9 | 2012-03-08 09:18:17 +0000 | [diff] [blame] | 910 | if input_api.is_committing and not reviewers: |
Clemens Hammacher | d0c226a | 2017-01-16 14:09:52 +0100 | [diff] [blame] | 911 | return [output_fn('Missing LGTM from someone other than %s' % owner_email)] |
dpranke@chromium.org | 3e331bd | 2011-03-24 23:13:04 +0000 | [diff] [blame] | 912 | return [] |
dpranke@chromium.org | 627ea67 | 2011-03-11 23:29:03 +0000 | [diff] [blame] | 913 | |
Aaron Gable | 668c1d8 | 2018-04-03 10:19:16 -0700 | [diff] [blame] | 914 | |
tandrii@chromium.org | 830dc0b | 2016-05-09 06:26:34 +0000 | [diff] [blame] | 915 | def GetCodereviewOwnerAndReviewers(input_api, email_regexp, approval_needed): |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 916 | """Return the owner and reviewers of a change, if any. |
| 917 | |
| 918 | If approval_needed is True, only reviewers who have approved the change |
| 919 | will be returned. |
| 920 | """ |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 921 | issue = input_api.change.issue |
| 922 | if not issue: |
tandrii@chromium.org | 830dc0b | 2016-05-09 06:26:34 +0000 | [diff] [blame] | 923 | return None, (set() if approval_needed else |
| 924 | _ReviewersFromChange(input_api.change)) |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 925 | |
| 926 | owner_email = input_api.gerrit.GetChangeOwner(issue) |
| 927 | reviewers = set( |
| 928 | r for r in input_api.gerrit.GetChangeReviewers(issue, approval_needed) |
| 929 | if _match_reviewer_email(r, owner_email, email_regexp)) |
tandrii | 81665dc | 2016-08-29 09:16:19 -0700 | [diff] [blame] | 930 | input_api.logging.debug('owner: %s; approvals given by: %s', |
| 931 | owner_email, ', '.join(sorted(reviewers))) |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 932 | return owner_email, reviewers |
| 933 | |
| 934 | |
Aaron Gable | 668c1d8 | 2018-04-03 10:19:16 -0700 | [diff] [blame] | 935 | def _ReviewersFromChange(change): |
| 936 | """Return the reviewers specified in the |change|, if any.""" |
| 937 | reviewers = set() |
| 938 | reviewers.update(change.ReviewersFromDescription()) |
| 939 | reviewers.update(change.TBRsFromDescription()) |
| 940 | |
| 941 | # Drop reviewers that aren't specified in email address format. |
| 942 | return set(reviewer for reviewer in reviewers if '@' in reviewer) |
| 943 | |
| 944 | |
| 945 | def _match_reviewer_email(r, owner_email, email_regexp): |
| 946 | return email_regexp.match(r) and r != owner_email |
| 947 | |
| 948 | |
bauerb@chromium.org | 4cea01e | 2012-03-20 19:49:05 +0000 | [diff] [blame] | 949 | def CheckSingletonInHeaders(input_api, output_api, source_file_filter=None): |
glider@chromium.org | c3617f3 | 2015-02-19 16:33:33 +0000 | [diff] [blame] | 950 | """Deprecated, must be removed.""" |
| 951 | return [ |
| 952 | output_api.PresubmitNotifyResult( |
| 953 | 'CheckSingletonInHeaders is deprecated, please remove it.') |
| 954 | ] |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 955 | |
| 956 | |
| 957 | def PanProjectChecks(input_api, output_api, |
| 958 | excluded_paths=None, text_files=None, |
bradnelson@google.com | d57771d | 2011-03-31 19:18:32 +0000 | [diff] [blame] | 959 | license_header=None, project_name=None, |
jamesr@chromium.org | af27f46 | 2013-04-04 21:44:22 +0000 | [diff] [blame] | 960 | owners_check=True, maxlen=80): |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 961 | """Checks that ALL chromium orbit projects should use. |
| 962 | |
| 963 | These are checks to be run on all Chromium orbit project, including: |
| 964 | Chromium |
| 965 | Native Client |
| 966 | V8 |
| 967 | When you update this function, please take this broad scope into account. |
| 968 | Args: |
| 969 | input_api: Bag of input related interfaces. |
| 970 | output_api: Bag of output related interfaces. |
| 971 | excluded_paths: Don't include these paths in common checks. |
| 972 | text_files: Which file are to be treated as documentation text files. |
| 973 | license_header: What license header should be on files. |
| 974 | project_name: What is the name of the project as it appears in the license. |
| 975 | Returns: |
| 976 | A list of warning or error objects. |
| 977 | """ |
maruel@chromium.org | 69eaecb | 2011-06-14 13:09:13 +0000 | [diff] [blame] | 978 | excluded_paths = tuple(excluded_paths or []) |
| 979 | text_files = tuple(text_files or ( |
maruel@chromium.org | fe1211a | 2011-05-28 18:54:17 +0000 | [diff] [blame] | 980 | r'.+\.txt$', |
| 981 | r'.+\.json$', |
maruel@chromium.org | 69eaecb | 2011-06-14 13:09:13 +0000 | [diff] [blame] | 982 | )) |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 983 | project_name = project_name or 'Chromium' |
mark@chromium.org | 2cc6642 | 2012-08-07 21:22:32 +0000 | [diff] [blame] | 984 | |
| 985 | # Accept any year number from 2006 to the current year, or the special |
rvargas@chromium.org | 0265260 | 2014-03-14 19:43:20 +0000 | [diff] [blame] | 986 | # 2006-20xx string used on the oldest files. 2006-20xx is deprecated, but |
| 987 | # tolerated on old files. |
mark@chromium.org | 2cc6642 | 2012-08-07 21:22:32 +0000 | [diff] [blame] | 988 | current_year = int(input_api.time.strftime('%Y')) |
| 989 | allowed_years = (str(s) for s in reversed(xrange(2006, current_year + 1))) |
rvargas@chromium.org | 0265260 | 2014-03-14 19:43:20 +0000 | [diff] [blame] | 990 | years_re = '(' + '|'.join(allowed_years) + '|2006-2008|2006-2009|2006-2010)' |
mark@chromium.org | 2cc6642 | 2012-08-07 21:22:32 +0000 | [diff] [blame] | 991 | |
| 992 | # The (c) is deprecated, but tolerate it until it's removed from all files. |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 993 | license_header = license_header or ( |
mark@chromium.org | 2cc6642 | 2012-08-07 21:22:32 +0000 | [diff] [blame] | 994 | r'.*? Copyright (\(c\) )?%(year)s The %(project)s Authors\. ' |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 995 | r'All rights reserved\.\n' |
| 996 | r'.*? Use of this source code is governed by a BSD-style license that ' |
| 997 | r'can be\n' |
dbeam@chromium.org | b231210 | 2012-02-15 02:01:55 +0000 | [diff] [blame] | 998 | r'.*? found in the LICENSE file\.(?: \*/)?\n' |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 999 | ) % { |
mark@chromium.org | 2cc6642 | 2012-08-07 21:22:32 +0000 | [diff] [blame] | 1000 | 'year': years_re, |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 1001 | 'project': project_name, |
| 1002 | } |
| 1003 | |
| 1004 | results = [] |
| 1005 | # This code loads the default black list (e.g. third_party, experimental, etc) |
| 1006 | # and add our black list (breakpad, skia and v8 are still not following |
| 1007 | # google style and are not really living this repository). |
| 1008 | # See presubmit_support.py InputApi.FilterSourceFile for the (simple) usage. |
| 1009 | black_list = input_api.DEFAULT_BLACK_LIST + excluded_paths |
| 1010 | white_list = input_api.DEFAULT_WHITE_LIST + text_files |
| 1011 | sources = lambda x: input_api.FilterSourceFile(x, black_list=black_list) |
maruel@chromium.org | fe1211a | 2011-05-28 18:54:17 +0000 | [diff] [blame] | 1012 | text_files = lambda x: input_api.FilterSourceFile( |
| 1013 | x, black_list=black_list, white_list=white_list) |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 1014 | |
| 1015 | snapshot_memory = [] |
| 1016 | def snapshot(msg): |
| 1017 | """Measures & prints performance warning if a rule is running slow.""" |
| 1018 | dt2 = input_api.time.clock() |
| 1019 | if snapshot_memory: |
| 1020 | delta_ms = int(1000*(dt2 - snapshot_memory[0])) |
| 1021 | if delta_ms > 500: |
| 1022 | print " %s took a long time: %dms" % (snapshot_memory[1], delta_ms) |
| 1023 | snapshot_memory[:] = (dt2, msg) |
| 1024 | |
Edward Lesmes | cb62e48 | 2018-04-19 18:29:35 -0400 | [diff] [blame] | 1025 | snapshot("checking owners files format") |
| 1026 | results.extend(input_api.canned_checks.CheckOwnersFormat( |
| 1027 | input_api, output_api)) |
| 1028 | |
bradnelson@google.com | d57771d | 2011-03-31 19:18:32 +0000 | [diff] [blame] | 1029 | if owners_check: |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 1030 | snapshot("checking owners") |
bradnelson@google.com | d57771d | 2011-03-31 19:18:32 +0000 | [diff] [blame] | 1031 | results.extend(input_api.canned_checks.CheckOwners( |
Dirk Pranke | 3c86cee | 2017-01-23 22:02:06 -0800 | [diff] [blame] | 1032 | input_api, output_api, source_file_filter=None)) |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 1033 | |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 1034 | snapshot("checking long lines") |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 1035 | results.extend(input_api.canned_checks.CheckLongLines( |
jamesr@chromium.org | af27f46 | 2013-04-04 21:44:22 +0000 | [diff] [blame] | 1036 | input_api, output_api, maxlen, source_file_filter=sources)) |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 1037 | snapshot( "checking tabs") |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 1038 | results.extend(input_api.canned_checks.CheckChangeHasNoTabs( |
| 1039 | input_api, output_api, source_file_filter=sources)) |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 1040 | snapshot( "checking stray whitespace") |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 1041 | results.extend(input_api.canned_checks.CheckChangeHasNoStrayWhitespace( |
| 1042 | input_api, output_api, source_file_filter=sources)) |
phajdan.jr@chromium.org | d965db3 | 2015-11-16 09:46:56 +0000 | [diff] [blame] | 1043 | snapshot("checking license") |
| 1044 | results.extend(input_api.canned_checks.CheckLicense( |
| 1045 | input_api, output_api, license_header, source_file_filter=sources)) |
maruel@chromium.org | b1ce775 | 2011-05-08 13:50:16 +0000 | [diff] [blame] | 1046 | |
maruel@chromium.org | b1ce775 | 2011-05-08 13:50:16 +0000 | [diff] [blame] | 1047 | if input_api.is_committing: |
maruel@chromium.org | cc73ad6 | 2011-07-06 17:39:26 +0000 | [diff] [blame] | 1048 | snapshot("checking was uploaded") |
| 1049 | results.extend(input_api.canned_checks.CheckChangeWasUploaded( |
| 1050 | input_api, output_api)) |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 1051 | snapshot("checking description") |
| 1052 | results.extend(input_api.canned_checks.CheckChangeHasDescription( |
| 1053 | input_api, output_api)) |
| 1054 | results.extend(input_api.canned_checks.CheckDoNotSubmitInDescription( |
| 1055 | input_api, output_api)) |
ilevy@chromium.org | c50d761 | 2012-12-05 04:25:14 +0000 | [diff] [blame] | 1056 | snapshot("checking do not submit in files") |
| 1057 | results.extend(input_api.canned_checks.CheckDoNotSubmitInFiles( |
| 1058 | input_api, output_api)) |
nick@chromium.org | e06cb4e | 2011-04-23 01:20:38 +0000 | [diff] [blame] | 1059 | snapshot("done") |
bradnelson@google.com | 56e48bc | 2011-03-24 20:51:21 +0000 | [diff] [blame] | 1060 | return results |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 1061 | |
| 1062 | |
Nodir Turakulov | 0ae14e9 | 2018-05-31 14:53:53 -0700 | [diff] [blame] | 1063 | def CheckPatchFormatted( |
| 1064 | input_api, output_api, check_js=False, check_python=False): |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 1065 | import git_cl |
Nodir Turakulov | 0ae14e9 | 2018-05-31 14:53:53 -0700 | [diff] [blame] | 1066 | |
| 1067 | display_args = [] |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 1068 | if check_js: |
Nodir Turakulov | 0ae14e9 | 2018-05-31 14:53:53 -0700 | [diff] [blame] | 1069 | display_args.append('--js') |
| 1070 | if check_python: |
| 1071 | # --python requires --full |
| 1072 | display_args.extend(['--python', '--full']) |
| 1073 | |
| 1074 | cmd = ['-C', input_api.change.RepositoryRoot(), |
| 1075 | 'cl', 'format', '--dry-run', '--presubmit'] + display_args |
Andrew Grieve | d86c803 | 2017-09-26 14:40:36 -0400 | [diff] [blame] | 1076 | presubmit_subdir = input_api.os_path.relpath( |
| 1077 | input_api.PresubmitLocalPath(), input_api.change.RepositoryRoot()) |
| 1078 | if presubmit_subdir.startswith('..') or presubmit_subdir == '.': |
| 1079 | presubmit_subdir = '' |
| 1080 | # If the PRESUBMIT.py is in a parent repository, then format the entire |
| 1081 | # subrepository. Otherwise, format only the code in the directory that |
| 1082 | # contains the PRESUBMIT.py. |
| 1083 | if presubmit_subdir: |
| 1084 | cmd.append(input_api.PresubmitLocalPath()) |
enne@chromium.org | 555cfe4 | 2014-01-29 18:21:39 +0000 | [diff] [blame] | 1085 | code, _ = git_cl.RunGitWithCode(cmd, suppress_stderr=True) |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 1086 | if code == 2: |
Andrew Grieve | d3b2548 | 2017-10-13 16:06:25 -0400 | [diff] [blame] | 1087 | if presubmit_subdir: |
| 1088 | short_path = presubmit_subdir |
| 1089 | else: |
| 1090 | short_path = input_api.basename(input_api.change.RepositoryRoot()) |
Nodir Turakulov | 0ae14e9 | 2018-05-31 14:53:53 -0700 | [diff] [blame] | 1091 | display_args.append(presubmit_subdir) |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 1092 | return [output_api.PresubmitPromptWarning( |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 1093 | 'The %s directory requires source formatting. ' |
Nodir Turakulov | 0ae14e9 | 2018-05-31 14:53:53 -0700 | [diff] [blame] | 1094 | 'Please run: git cl format %s' % |
| 1095 | (short_path, ' '.join(display_args)))] |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 1096 | # As this is just a warning, ignore all other errors if the user |
| 1097 | # happens to have a broken clang-format, doesn't use git, etc etc. |
| 1098 | return [] |
scottmg@chromium.org | d05ab35 | 2014-12-05 17:24:26 +0000 | [diff] [blame] | 1099 | |
| 1100 | |
| 1101 | def CheckGNFormatted(input_api, output_api): |
| 1102 | import gn |
| 1103 | affected_files = input_api.AffectedFiles( |
| 1104 | include_deletes=False, |
| 1105 | file_filter=lambda x: x.LocalPath().endswith('.gn') or |
kylechar | 58edce2 | 2016-06-17 06:07:51 -0700 | [diff] [blame] | 1106 | x.LocalPath().endswith('.gni') or |
| 1107 | x.LocalPath().endswith('.typemap')) |
scottmg@chromium.org | d05ab35 | 2014-12-05 17:24:26 +0000 | [diff] [blame] | 1108 | warnings = [] |
| 1109 | for f in affected_files: |
| 1110 | cmd = ['gn', 'format', '--dry-run', f.AbsoluteLocalPath()] |
| 1111 | rc = gn.main(cmd) |
| 1112 | if rc == 2: |
| 1113 | warnings.append(output_api.PresubmitPromptWarning( |
brettw | 4b8ed59 | 2016-08-05 16:19:12 -0700 | [diff] [blame] | 1114 | '%s requires formatting. Please run:\n gn format %s' % ( |
scottmg@chromium.org | d05ab35 | 2014-12-05 17:24:26 +0000 | [diff] [blame] | 1115 | f.AbsoluteLocalPath(), f.LocalPath()))) |
| 1116 | # It's just a warning, so ignore other types of failures assuming they'll be |
| 1117 | # caught elsewhere. |
| 1118 | return warnings |
Dan Jacques | 94652a3 | 2017-10-09 23:18:46 -0400 | [diff] [blame] | 1119 | |
| 1120 | |
| 1121 | def CheckCIPDManifest(input_api, output_api, path=None, content=None): |
| 1122 | """Verifies that a CIPD ensure file manifest is valid against all platforms. |
| 1123 | |
| 1124 | Exactly one of "path" or "content" must be provided. An assertion will occur |
| 1125 | if neither or both are provided. |
| 1126 | |
| 1127 | Args: |
| 1128 | path (str): If provided, the filesystem path to the manifest to verify. |
| 1129 | content (str): If provided, the raw content of the manifest to veirfy. |
| 1130 | """ |
| 1131 | cipd_bin = 'cipd' if not input_api.is_windows else 'cipd.bat' |
| 1132 | cmd = [cipd_bin, 'ensure-file-verify'] |
| 1133 | kwargs = {} |
| 1134 | |
| 1135 | if input_api.is_windows: |
| 1136 | # Needs to be able to resolve "cipd.bat". |
| 1137 | kwargs['shell'] = True |
| 1138 | |
| 1139 | if input_api.verbose: |
| 1140 | cmd += ['-log-level', 'debug'] |
| 1141 | |
| 1142 | if path: |
| 1143 | assert content is None, 'Cannot provide both "path" and "content".' |
| 1144 | cmd += ['-ensure-file', path] |
Robert Iannucci | 7d47eb5 | 2017-12-06 12:18:18 -0800 | [diff] [blame] | 1145 | name = 'Check CIPD manifest %r' % path |
Dan Jacques | 94652a3 | 2017-10-09 23:18:46 -0400 | [diff] [blame] | 1146 | elif content: |
| 1147 | assert path is None, 'Cannot provide both "path" and "content".' |
| 1148 | cmd += ['-ensure-file=-'] |
| 1149 | kwargs['stdin'] = content |
Robert Iannucci | 7d47eb5 | 2017-12-06 12:18:18 -0800 | [diff] [blame] | 1150 | # quick and dirty parser to extract checked packages. |
| 1151 | packages = [ |
| 1152 | l.split()[0] for l in (ll.strip() for ll in content.splitlines()) |
| 1153 | if ' ' in l and not l.startswith('$') |
| 1154 | ] |
| 1155 | name = 'Check CIPD packages from string: %r' % (packages,) |
Dan Jacques | 94652a3 | 2017-10-09 23:18:46 -0400 | [diff] [blame] | 1156 | else: |
| 1157 | raise Exception('Exactly one of "path" or "content" must be provided.') |
| 1158 | |
| 1159 | return input_api.Command( |
Robert Iannucci | 7d47eb5 | 2017-12-06 12:18:18 -0800 | [diff] [blame] | 1160 | name, |
Dan Jacques | 94652a3 | 2017-10-09 23:18:46 -0400 | [diff] [blame] | 1161 | cmd, |
| 1162 | kwargs, |
| 1163 | output_api.PresubmitError) |
| 1164 | |
| 1165 | |
| 1166 | def CheckCIPDPackages(input_api, output_api, platforms, packages): |
| 1167 | """Verifies that all named CIPD packages can be resolved against all supplied |
| 1168 | platforms. |
| 1169 | |
| 1170 | Args: |
| 1171 | platforms (list): List of CIPD platforms to verify. |
| 1172 | packages (dict): Mapping of package name to version. |
| 1173 | """ |
| 1174 | manifest = [] |
| 1175 | for p in platforms: |
| 1176 | manifest.append('$VerifiedPlatform %s' % (p,)) |
| 1177 | for k, v in packages.iteritems(): |
| 1178 | manifest.append('%s %s' % (k, v)) |
| 1179 | return CheckCIPDManifest(input_api, output_api, content='\n'.join(manifest)) |
Sergiy Byelozyorov | eba8347 | 2017-10-27 02:08:21 +0200 | [diff] [blame] | 1180 | |
| 1181 | |
| 1182 | def CheckVPythonSpec(input_api, output_api, file_filter=None): |
| 1183 | """Validates any changed .vpython files with vpython verification tool. |
| 1184 | |
| 1185 | Args: |
| 1186 | input_api: Bag of input related interfaces. |
| 1187 | output_api: Bag of output related interfaces. |
| 1188 | file_filter: Custom function that takes a path (relative to client root) and |
| 1189 | returns boolean, which is used to filter files for which to apply the |
| 1190 | verification to. Defaults to any path ending with .vpython, which captures |
| 1191 | both global .vpython and <script>.vpython files. |
| 1192 | |
| 1193 | Returns: |
| 1194 | A list of input_api.Command objects containing verification commands. |
| 1195 | """ |
| 1196 | file_filter = file_filter or (lambda f: f.LocalPath().endswith('.vpython')) |
John Budorick | 1616237 | 2018-04-18 10:39:53 -0700 | [diff] [blame] | 1197 | affected_files = input_api.AffectedTestableFiles(file_filter=file_filter) |
Sergiy Byelozyorov | eba8347 | 2017-10-27 02:08:21 +0200 | [diff] [blame] | 1198 | affected_files = map(lambda f: f.AbsoluteLocalPath(), affected_files) |
| 1199 | |
| 1200 | commands = [] |
| 1201 | for f in affected_files: |
| 1202 | commands.append(input_api.Command( |
| 1203 | 'Verify %s' % f, |
| 1204 | ['vpython', '-vpython-spec', f, '-vpython-tool', 'verify'], |
| 1205 | {'stderr': input_api.subprocess.STDOUT}, |
| 1206 | output_api.PresubmitError)) |
| 1207 | |
| 1208 | return commands |
Mun Yong Jang | 17995a9 | 2017-12-01 16:00:31 -0800 | [diff] [blame] | 1209 | |
| 1210 | |
| 1211 | def CheckChangedLUCIConfigs(input_api, output_api): |
| 1212 | import collections |
| 1213 | import base64 |
| 1214 | import json |
Mun Yong Jang | cfb9a23 | 2017-12-18 10:39:34 -0800 | [diff] [blame] | 1215 | import logging |
Mun Yong Jang | 17995a9 | 2017-12-01 16:00:31 -0800 | [diff] [blame] | 1216 | import urllib2 |
| 1217 | |
| 1218 | import auth |
| 1219 | import git_cl |
| 1220 | |
| 1221 | LUCI_CONFIG_HOST_NAME = 'luci-config.appspot.com' |
| 1222 | |
| 1223 | cl = git_cl.Changelist() |
Mun Yong Jang | 603d01e | 2017-12-19 16:38:30 -0800 | [diff] [blame] | 1224 | if input_api.change.issue and input_api.gerrit: |
| 1225 | remote_branch = input_api.gerrit.GetDestRef(input_api.change.issue) |
| 1226 | else: |
| 1227 | remote, remote_branch = cl.GetRemoteBranch() |
| 1228 | if remote_branch.startswith('refs/remotes/%s/' % remote): |
| 1229 | remote_branch = remote_branch.replace( |
| 1230 | 'refs/remotes/%s/' % remote, 'refs/heads/', 1) |
| 1231 | if remote_branch.startswith('refs/remotes/branch-heads/'): |
| 1232 | remote_branch = remote_branch.replace( |
| 1233 | 'refs/remotes/branch-heads/', 'refs/branch-heads/', 1) |
Mun Yong Jang | 17995a9 | 2017-12-01 16:00:31 -0800 | [diff] [blame] | 1234 | |
| 1235 | remote_host_url = cl.GetRemoteUrl() |
| 1236 | if not remote_host_url: |
| 1237 | return [output_api.PresubmitError( |
| 1238 | 'Remote host url for git has not been defined')] |
| 1239 | remote_host_url = remote_host_url.rstrip('/') |
| 1240 | if remote_host_url.endswith('.git'): |
| 1241 | remote_host_url = remote_host_url[:-len('.git')] |
| 1242 | |
| 1243 | # authentication |
| 1244 | try: |
| 1245 | authenticator = auth.get_authenticator_for_host( |
| 1246 | LUCI_CONFIG_HOST_NAME, auth.make_auth_config()) |
| 1247 | acc_tkn = authenticator.get_access_token() |
| 1248 | except auth.AuthenticationError as e: |
| 1249 | return [output_api.PresubmitError( |
| 1250 | 'Error in authenticating user.', long_text=str(e))] |
| 1251 | |
| 1252 | def request(endpoint, body=None): |
| 1253 | api_url = ('https://%s/_ah/api/config/v1/%s' |
| 1254 | % (LUCI_CONFIG_HOST_NAME, endpoint)) |
| 1255 | req = urllib2.Request(api_url) |
| 1256 | req.add_header('Authorization', 'Bearer %s' % acc_tkn.token) |
| 1257 | if body is not None: |
| 1258 | req.add_header('Content-Type', 'application/json') |
| 1259 | req.add_data(json.dumps(body)) |
| 1260 | return json.load(urllib2.urlopen(req)) |
| 1261 | |
| 1262 | try: |
| 1263 | config_sets = request('config-sets').get('config_sets') |
| 1264 | except urllib2.HTTPError as e: |
| 1265 | return [output_api.PresubmitError( |
| 1266 | 'Config set request to luci-config failed', long_text=str(e))] |
| 1267 | if not config_sets: |
| 1268 | return [output_api.PresubmitWarning('No config_sets were returned')] |
| 1269 | loc_pref = '%s/+/%s/' % (remote_host_url, remote_branch) |
Mun Yong Jang | cfb9a23 | 2017-12-18 10:39:34 -0800 | [diff] [blame] | 1270 | logging.debug('Derived location prefix: %s', loc_pref) |
Mun Yong Jang | 17995a9 | 2017-12-01 16:00:31 -0800 | [diff] [blame] | 1271 | dir_to_config_set = { |
| 1272 | '%s/' % cs['location'][len(loc_pref):].rstrip('/'): cs['config_set'] |
| 1273 | for cs in config_sets |
| 1274 | if cs['location'].startswith(loc_pref) or |
| 1275 | ('%s/' % cs['location']) == loc_pref |
| 1276 | } |
| 1277 | cs_to_files = collections.defaultdict(list) |
| 1278 | for f in input_api.AffectedFiles(): |
| 1279 | # windows |
| 1280 | file_path = f.LocalPath().replace(_os.sep, '/') |
Mun Yong Jang | cfb9a23 | 2017-12-18 10:39:34 -0800 | [diff] [blame] | 1281 | logging.debug('Affected file path: %s', file_path) |
Mun Yong Jang | 17995a9 | 2017-12-01 16:00:31 -0800 | [diff] [blame] | 1282 | for dr, cs in dir_to_config_set.iteritems(): |
| 1283 | if dr == '/' or file_path.startswith(dr): |
| 1284 | cs_to_files[cs].append({ |
| 1285 | 'path': file_path[len(dr):] if dr != '/' else file_path, |
| 1286 | 'content': base64.b64encode( |
| 1287 | '\n'.join(f.NewContents()).encode('utf-8')) |
| 1288 | }) |
| 1289 | outputs = [] |
| 1290 | for cs, f in cs_to_files.iteritems(): |
| 1291 | try: |
| 1292 | # TODO(myjang): parallelize |
| 1293 | res = request( |
| 1294 | 'validate-config', body={'config_set': cs, 'files': f}) |
| 1295 | except urllib2.HTTPError as e: |
| 1296 | return [output_api.PresubmitError( |
| 1297 | 'Validation request to luci-config failed', long_text=str(e))] |
| 1298 | for msg in res.get('messages', []): |
| 1299 | sev = msg['severity'] |
| 1300 | if sev == 'WARNING': |
| 1301 | out_f = output_api.PresubmitPromptWarning |
| 1302 | elif sev == 'ERROR' or sev == 'CRITICAL': |
| 1303 | out_f = output_api.PresubmitError |
| 1304 | else: |
| 1305 | out_f = output_api.PresubmitNotifyResult |
| 1306 | outputs.append(out_f('Config validation: %s' % msg['text'])) |
| 1307 | return outputs |