Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. |
| 4 | # Use of this source code is governed by a BSD-style license that can be |
| 5 | # found in the LICENSE file. |
| 6 | |
| 7 | """A command line interface to the ChromeOS gerrit instances |
| 8 | |
| 9 | Internal Note: |
| 10 | To expose a function directly to the command line interface, name your function |
| 11 | with the prefix "UserAct". |
| 12 | """ |
| 13 | |
Mike Frysinger | 31ff6f9 | 2014-02-08 04:33:03 -0500 | [diff] [blame^] | 14 | from __future__ import print_function |
| 15 | |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 16 | import inspect |
| 17 | import os |
Vadim Bendebury | dcfe232 | 2013-05-23 10:54:49 -0700 | [diff] [blame] | 18 | import re |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 19 | |
| 20 | from chromite.buildbot import constants |
| 21 | from chromite.lib import commandline |
| 22 | from chromite.lib import cros_build_lib |
| 23 | from chromite.lib import gerrit |
| 24 | from chromite.lib import terminal |
| 25 | |
| 26 | |
Mike Frysinger | 031ad0b | 2013-05-14 18:15:34 -0400 | [diff] [blame] | 27 | COLOR = None |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 28 | |
| 29 | # Map the internal names to the ones we normally show on the web ui. |
| 30 | GERRIT_APPROVAL_MAP = { |
Vadim Bendebury | 5057183 | 2013-11-12 10:43:19 -0800 | [diff] [blame] | 31 | 'COMR': ['CQ', 'Commit Queue ',], |
| 32 | 'CRVW': ['CR', 'Code Review ',], |
| 33 | 'SUBM': ['S ', 'Submitted ',], |
| 34 | 'TBVF': ['TV', 'Trybot Verified',], |
| 35 | 'VRIF': ['V ', 'Verified ',], |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 36 | } |
| 37 | |
| 38 | # Order is important -- matches the web ui. This also controls the short |
| 39 | # entries that we summarize in non-verbose mode. |
| 40 | GERRIT_SUMMARY_CATS = ('CR', 'CQ', 'V',) |
| 41 | |
| 42 | |
| 43 | def red(s): |
| 44 | return COLOR.Color(terminal.Color.RED, s) |
| 45 | |
| 46 | |
| 47 | def green(s): |
| 48 | return COLOR.Color(terminal.Color.GREEN, s) |
| 49 | |
| 50 | |
| 51 | def blue(s): |
| 52 | return COLOR.Color(terminal.Color.BLUE, s) |
| 53 | |
| 54 | |
| 55 | def limits(cls): |
| 56 | """Given a dict of fields, calculate the longest string lengths |
| 57 | |
| 58 | This allows you to easily format the output of many results so that the |
| 59 | various cols all line up correctly. |
| 60 | """ |
| 61 | lims = {} |
| 62 | for cl in cls: |
| 63 | for k in cl.keys(): |
Mike Frysinger | f16b8f0 | 2013-10-21 22:24:46 -0400 | [diff] [blame] | 64 | # Use %s rather than str() to avoid codec issues. |
| 65 | # We also do this so we can format integers. |
| 66 | lims[k] = max(lims.get(k, 0), len('%s' % cl[k])) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 67 | return lims |
| 68 | |
| 69 | |
| 70 | def GetApprovalSummary(_opts, cls): |
| 71 | """Return a dict of the most important approvals""" |
| 72 | approvs = dict([(x, '') for x in GERRIT_SUMMARY_CATS]) |
| 73 | if 'approvals' in cls['currentPatchSet']: |
| 74 | for approver in cls['currentPatchSet']['approvals']: |
| 75 | cats = GERRIT_APPROVAL_MAP.get(approver['type']) |
| 76 | if not cats: |
| 77 | cros_build_lib.Warning('unknown gerrit approval type: %s', |
| 78 | approver['type']) |
| 79 | continue |
| 80 | cat = cats[0].strip() |
| 81 | val = int(approver['value']) |
| 82 | if not cat in approvs: |
| 83 | # Ignore the extended categories in the summary view. |
| 84 | continue |
| 85 | elif approvs[cat] is '': |
| 86 | approvs[cat] = val |
| 87 | elif val < 0: |
| 88 | approvs[cat] = min(approvs[cat], val) |
| 89 | else: |
| 90 | approvs[cat] = max(approvs[cat], val) |
| 91 | return approvs |
| 92 | |
| 93 | |
| 94 | def PrintCl(opts, cls, lims, show_approvals=True): |
| 95 | """Pretty print a single result""" |
| 96 | if not lims: |
| 97 | lims = {'url': 0, 'project': 0} |
| 98 | |
| 99 | status = '' |
| 100 | if show_approvals and not opts.verbose: |
| 101 | approvs = GetApprovalSummary(opts, cls) |
| 102 | for cat in GERRIT_SUMMARY_CATS: |
| 103 | if approvs[cat] is '': |
| 104 | functor = lambda x: x |
| 105 | elif approvs[cat] < 0: |
| 106 | functor = red |
| 107 | else: |
| 108 | functor = green |
| 109 | status += functor('%s:%2s ' % (cat, approvs[cat])) |
| 110 | |
Mike Frysinger | 31ff6f9 | 2014-02-08 04:33:03 -0500 | [diff] [blame^] | 111 | print('%s %s%-*s %s' % (blue('%-*s' % (lims['url'], cls['url'])), status, |
| 112 | lims['project'], cls['project'], cls['subject'])) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 113 | |
| 114 | if show_approvals and opts.verbose: |
| 115 | for approver in cls['currentPatchSet'].get('approvals', []): |
| 116 | functor = red if int(approver['value']) < 0 else green |
| 117 | n = functor('%2s' % approver['value']) |
| 118 | t = GERRIT_APPROVAL_MAP.get(approver['type'], [approver['type'], |
| 119 | approver['type']])[1] |
Mike Frysinger | 31ff6f9 | 2014-02-08 04:33:03 -0500 | [diff] [blame^] | 120 | print(' %s %s %s' % (n, t, approver['by']['email'])) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 121 | |
| 122 | |
| 123 | def _MyUserInfo(): |
| 124 | username = os.environ['USER'] |
| 125 | emails = ['%s@%s' % (username, domain) |
| 126 | for domain in ('google.com', 'chromium.org')] |
| 127 | reviewers = ['reviewer:%s' % x for x in emails] |
| 128 | owners = ['owner:%s' % x for x in emails] |
| 129 | return emails, reviewers, owners |
| 130 | |
| 131 | |
| 132 | def FilteredQuery(opts, query): |
| 133 | """Query gerrit and filter/clean up the results""" |
| 134 | ret = [] |
| 135 | |
| 136 | for cl in opts.gerrit.Query(query, raw=True): |
| 137 | # Gerrit likes to return a stats record too. |
| 138 | if not 'project' in cl: |
| 139 | continue |
| 140 | |
| 141 | # Strip off common leading names since the result is still |
| 142 | # unique over the whole tree. |
| 143 | if not opts.verbose: |
| 144 | for pfx in ('chromeos', 'chromiumos', 'overlays', 'platform'): |
| 145 | if cl['project'].startswith('%s/' % pfx): |
| 146 | cl['project'] = cl['project'][len(pfx) + 1:] |
| 147 | |
| 148 | ret.append(cl) |
| 149 | |
| 150 | if opts.sort in ('number',): |
| 151 | key = lambda x: int(x[opts.sort]) |
| 152 | else: |
| 153 | key = lambda x: x[opts.sort] |
| 154 | return sorted(ret, key=key) |
| 155 | |
| 156 | |
| 157 | def ChangeNumberToCommit(opts, idx): |
| 158 | """Given a gerrit CL #, return the revision info |
| 159 | |
| 160 | This is the form that the gerrit ssh interface expects. |
| 161 | """ |
| 162 | cl = opts.gerrit.QuerySingleRecord(idx, raw=True) |
| 163 | return cl['currentPatchSet']['revision'] |
| 164 | |
| 165 | |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 166 | def IsApprover(cl, users): |
| 167 | """See if the approvers in |cl| is listed in |users|""" |
| 168 | # See if we are listed in the approvals list. We have to parse |
| 169 | # this by hand as the gerrit query system doesn't support it :( |
| 170 | # http://code.google.com/p/gerrit/issues/detail?id=1235 |
| 171 | if 'approvals' not in cl['currentPatchSet']: |
| 172 | return False |
| 173 | |
| 174 | if isinstance(users, basestring): |
| 175 | users = (users,) |
| 176 | |
| 177 | for approver in cl['currentPatchSet']['approvals']: |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 178 | if (approver['by']['email'] in users and |
| 179 | approver['type'] == 'CRVW' and |
| 180 | int(approver['value']) != 0): |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 181 | return True |
| 182 | |
| 183 | return False |
| 184 | |
| 185 | |
| 186 | def UserActTodo(opts): |
| 187 | """List CLs needing your review""" |
| 188 | emails, reviewers, owners = _MyUserInfo() |
| 189 | cls = FilteredQuery(opts, '( %s ) status:open NOT ( %s )' % |
| 190 | (' OR '.join(reviewers), ' OR '.join(owners))) |
| 191 | cls = [x for x in cls if not IsApprover(x, emails)] |
| 192 | lims = limits(cls) |
| 193 | for cl in cls: |
| 194 | PrintCl(opts, cl, lims) |
| 195 | |
| 196 | |
| 197 | def UserActMine(opts): |
| 198 | """List your CLs with review statuses""" |
| 199 | _, _, owners = _MyUserInfo() |
| 200 | cls = FilteredQuery(opts, '( %s ) status:new' % (' OR '.join(owners),)) |
| 201 | lims = limits(cls) |
| 202 | for cl in cls: |
| 203 | PrintCl(opts, cl, lims) |
| 204 | |
| 205 | |
| 206 | def UserActInspect(opts, idx): |
| 207 | """Inspect CL number <n>""" |
| 208 | PrintCl(opts, FilteredQuery(opts, idx)[0], None) |
| 209 | |
| 210 | |
| 211 | def UserActReview(opts, idx, num): |
| 212 | """Mark CL <n> with code review status [-2,-1,0,1,2]""" |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 213 | opts.gerrit.SetReview(idx, labels={'Code-Review': num}) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 214 | |
| 215 | |
| 216 | def UserActVerify(opts, idx, num): |
| 217 | """Mark CL <n> with verify status [-1,0,1]""" |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 218 | opts.gerrit.SetReview(idx, labels={'Verified': num}) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 219 | |
| 220 | |
| 221 | def UserActReady(opts, idx, num): |
| 222 | """Mark CL <n> with ready status [-1,0,1]""" |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 223 | opts.gerrit.SetReview(idx, labels={'Commit-Queue': num}) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 224 | |
| 225 | |
| 226 | def UserActSubmit(opts, idx): |
| 227 | """Submit CL <n>""" |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 228 | opts.gerrit.SubmitChange(idx) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 229 | |
| 230 | |
| 231 | def UserActAbandon(opts, idx): |
| 232 | """Abandon CL <n>""" |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 233 | opts.gerrit.AbandonChange(idx) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 234 | |
| 235 | |
| 236 | def UserActRestore(opts, idx): |
| 237 | """Restore CL <n> that was abandoned""" |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 238 | opts.gerrit.RestoreChange(idx) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 239 | |
| 240 | |
Mike Frysinger | c15efa5 | 2013-12-12 01:13:56 -0500 | [diff] [blame] | 241 | def UserActReviewers(opts, idx, *args): |
Vadim Bendebury | dcfe232 | 2013-05-23 10:54:49 -0700 | [diff] [blame] | 242 | """Add/remove reviewers' emails for CL <n> (prepend with '~' to remove)""" |
Mike Frysinger | c15efa5 | 2013-12-12 01:13:56 -0500 | [diff] [blame] | 243 | emails = args |
Vadim Bendebury | dcfe232 | 2013-05-23 10:54:49 -0700 | [diff] [blame] | 244 | # Allow for optional leading '~'. |
| 245 | email_validator = re.compile(r'^[~]?%s$' % constants.EMAIL_REGEX) |
| 246 | add_list, remove_list, invalid_list = [], [], [] |
| 247 | |
| 248 | for x in emails: |
| 249 | if not email_validator.match(x): |
| 250 | invalid_list.append(x) |
| 251 | elif x[0] == '~': |
| 252 | remove_list.append(x[1:]) |
| 253 | else: |
| 254 | add_list.append(x) |
| 255 | |
| 256 | if invalid_list: |
| 257 | cros_build_lib.Die( |
| 258 | 'Invalid email address(es): %s' % ', '.join(invalid_list)) |
| 259 | |
| 260 | if add_list or remove_list: |
| 261 | opts.gerrit.SetReviewers(idx, add=add_list, remove=remove_list) |
| 262 | |
| 263 | |
Doug Anderson | 8119df0 | 2013-07-20 21:00:24 +0530 | [diff] [blame] | 264 | def UserActMessage(opts, idx, message): |
| 265 | """Add a message to CL <n>""" |
Stefan Zager | 2956030 | 2013-09-06 14:30:54 -0700 | [diff] [blame] | 266 | opts.gerrit.SetReview(idx, msg=message) |
Doug Anderson | 8119df0 | 2013-07-20 21:00:24 +0530 | [diff] [blame] | 267 | |
| 268 | |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 269 | def main(argv): |
| 270 | # Locate actions that are exposed to the user. All functions that start |
| 271 | # with "UserAct" are fair game. |
| 272 | act_pfx = 'UserAct' |
| 273 | actions = [x for x in globals() if x.startswith(act_pfx)] |
| 274 | |
| 275 | usage = """%prog [options] <action> [action args] |
| 276 | |
| 277 | There is no support for doing line-by-line code review via the command line. |
| 278 | This helps you manage various bits and CL status. |
| 279 | |
| 280 | Example: |
| 281 | $ gerrit todo # List all the CLs that await your review. |
| 282 | $ gerrit mine # List all of your open CLs. |
| 283 | $ gerrit inspect 28123 # Inspect CL 28123 on the public gerrit. |
| 284 | $ gerrit inspect *28123 # Inspect CL 28123 on the internal gerrit. |
| 285 | $ gerrit verify 28123 1 # Mark CL 28123 as verified (+1). |
| 286 | |
| 287 | Actions:""" |
| 288 | indent = max([len(x) - len(act_pfx) for x in actions]) |
| 289 | for a in sorted(actions): |
| 290 | usage += '\n %-*s: %s' % (indent, a[len(act_pfx):].lower(), |
| 291 | globals()[a].__doc__) |
| 292 | |
| 293 | parser = commandline.OptionParser(usage=usage) |
| 294 | parser.add_option('-i', '--internal', default=None, action='store_true', |
| 295 | help='Query gerrit-int') |
| 296 | parser.add_option('-e', '--external', dest='internal', action='store_false', |
| 297 | help='Query gerrit (default)') |
| 298 | parser.add_option('--sort', default='number', help='Key to sort on ' |
| 299 | '(number, project)') |
| 300 | parser.add_option('-v', '--verbose', default=False, action='store_true', |
| 301 | help='Be more verbose in output') |
| 302 | opts, args = parser.parse_args(argv) |
| 303 | if not args: |
| 304 | parser.error('missing action') |
| 305 | |
Mike Frysinger | 031ad0b | 2013-05-14 18:15:34 -0400 | [diff] [blame] | 306 | # pylint: disable=W0603 |
| 307 | global COLOR |
| 308 | COLOR = terminal.Color(enabled=opts.color) |
| 309 | |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 310 | # TODO: This sucks. We assume that all actions which take an argument are |
| 311 | # a CL #. Or at least, there's no other reason for it to start with a *. |
| 312 | # We do this to automatically select internal vs external gerrit as this |
| 313 | # convention is encoded in much of our system. However, the rest of this |
| 314 | # script doesn't expect (or want) the leading *. |
| 315 | if len(args) > 1: |
| 316 | if args[1][0] == '*': |
| 317 | if opts.internal is None: |
| 318 | opts.internal = True |
| 319 | args[1] = args[1][1:] |
| 320 | |
Stefan Zager | af6c614 | 2013-05-28 17:25:41 -0700 | [diff] [blame] | 321 | opts.gerrit = gerrit.GetGerritHelper( |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 322 | constants.INTERNAL_REMOTE if opts.internal else constants.EXTERNAL_REMOTE, |
| 323 | print_cmd=opts.debug) |
| 324 | |
| 325 | # Now look up the requested user action and run it. |
| 326 | cmd = args[0].lower() |
| 327 | args = args[1:] |
| 328 | functor = globals().get(act_pfx + cmd.capitalize()) |
| 329 | if functor: |
| 330 | argspec = inspect.getargspec(functor) |
Vadim Bendebury | dcfe232 | 2013-05-23 10:54:49 -0700 | [diff] [blame] | 331 | if argspec.varargs: |
| 332 | if len(args) < len(argspec.args): |
| 333 | parser.error('incorrect number of args: %s expects at least %s' % |
| 334 | (cmd, len(argspec.args))) |
| 335 | elif len(argspec.args) - 1 != len(args): |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 336 | parser.error('incorrect number of args: %s expects %s' % |
| 337 | (cmd, len(argspec.args) - 1)) |
Vadim Bendebury | 614f868 | 2013-05-23 10:33:35 -0700 | [diff] [blame] | 338 | try: |
| 339 | functor(opts, *args) |
Vadim Bendebury | dcfe232 | 2013-05-23 10:54:49 -0700 | [diff] [blame] | 340 | except (cros_build_lib.RunCommandError, gerrit.GerritException) as e: |
| 341 | cros_build_lib.Die(e.message) |
Mike Frysinger | 13f23a4 | 2013-05-13 17:32:01 -0400 | [diff] [blame] | 342 | else: |
| 343 | parser.error('unknown action: %s' % (cmd,)) |