blob: ce42dd16a094f393fa2060f418def6ec6218cfd8 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Mike Frysinger13f23a42013-05-13 17:32:01 -04002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Mike Frysinger08737512014-02-07 22:58:26 -05006"""A command line interface to Gerrit-on-borg instances.
Mike Frysinger13f23a42013-05-13 17:32:01 -04007
8Internal Note:
9To expose a function directly to the command line interface, name your function
10with the prefix "UserAct".
11"""
12
Mike Frysinger31ff6f92014-02-08 04:33:03 -050013from __future__ import print_function
14
Mike Frysinger8037f752020-02-29 20:47:09 -050015import argparse
Mike Frysinger65fc8632020-02-06 18:11:12 -050016import collections
Mike Frysinger2295d792021-03-08 15:55:23 -050017import configparser
Mike Frysingerc7796cf2020-02-06 23:55:15 -050018import functools
Mike Frysinger13f23a42013-05-13 17:32:01 -040019import inspect
Mike Frysinger87c74ce2017-04-04 16:12:31 -040020import json
Mike Frysinger2295d792021-03-08 15:55:23 -050021from pathlib import Path
Vadim Bendeburydcfe2322013-05-23 10:54:49 -070022import re
Mike Frysinger2295d792021-03-08 15:55:23 -050023import shlex
Mike Frysinger87c74ce2017-04-04 16:12:31 -040024import sys
Mike Frysinger13f23a42013-05-13 17:32:01 -040025
Mike Frysinger2295d792021-03-08 15:55:23 -050026from chromite.lib import chromite_config
Aviv Keshetb7519e12016-10-04 00:50:00 -070027from chromite.lib import config_lib
28from chromite.lib import constants
Mike Frysinger13f23a42013-05-13 17:32:01 -040029from chromite.lib import commandline
30from chromite.lib import cros_build_lib
Ralph Nathan446aee92015-03-23 14:44:56 -070031from chromite.lib import cros_logging as logging
Mike Frysinger13f23a42013-05-13 17:32:01 -040032from chromite.lib import gerrit
Mike Frysingerc85d8162014-02-08 00:45:21 -050033from chromite.lib import gob_util
Mike Frysinger254f33f2019-12-11 13:54:29 -050034from chromite.lib import parallel
Mike Frysinger7f2018d2021-02-04 00:10:58 -050035from chromite.lib import pformat
Mike Frysinger13f23a42013-05-13 17:32:01 -040036from chromite.lib import terminal
Mike Frysinger479f1192017-09-14 22:36:30 -040037from chromite.lib import uri_lib
Alex Klein337fee42019-07-08 11:38:26 -060038from chromite.utils import memoize
Mike Frysinger13f23a42013-05-13 17:32:01 -040039
40
Mike Frysinger1c76d4c2020-02-08 23:35:29 -050041assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
42
43
Mike Frysinger2295d792021-03-08 15:55:23 -050044class Config:
45 """Manage the user's gerrit config settings.
46
47 This is entirely unique to this gerrit command. Inspiration for naming and
48 layout is taken from ~/.gitconfig settings.
49 """
50
51 def __init__(self, path: Path = chromite_config.GERRIT_CONFIG):
52 self.cfg = configparser.ConfigParser(interpolation=None)
53 if path.exists():
54 self.cfg.read(chromite_config.GERRIT_CONFIG)
55
56 def expand_alias(self, action):
57 """Expand any aliases."""
58 alias = self.cfg.get('alias', action, fallback=None)
59 if alias is not None:
60 return shlex.split(alias)
61 return action
62
63
Mike Frysingerc7796cf2020-02-06 23:55:15 -050064class UserAction(object):
65 """Base class for all custom user actions."""
66
67 # The name of the command the user types in.
68 COMMAND = None
69
70 @staticmethod
71 def init_subparser(parser):
72 """Add arguments to this action's subparser."""
73
74 @staticmethod
75 def __call__(opts):
76 """Implement the action."""
Mike Frysinger62178ae2020-03-20 01:37:43 -040077 raise RuntimeError('Internal error: action missing __call__ implementation')
Mike Frysinger108eda22018-06-06 18:45:12 -040078
79
Mike Frysinger254f33f2019-12-11 13:54:29 -050080# How many connections we'll use in parallel. We don't want this to be too high
81# so we don't go over our per-user quota. Pick 10 somewhat arbitrarily as that
82# seems to be good enough for users.
83CONNECTION_LIMIT = 10
84
85
Mike Frysinger031ad0b2013-05-14 18:15:34 -040086COLOR = None
Mike Frysinger13f23a42013-05-13 17:32:01 -040087
88# Map the internal names to the ones we normally show on the web ui.
89GERRIT_APPROVAL_MAP = {
Vadim Bendebury50571832013-11-12 10:43:19 -080090 'COMR': ['CQ', 'Commit Queue ',],
91 'CRVW': ['CR', 'Code Review ',],
92 'SUBM': ['S ', 'Submitted ',],
Vadim Bendebury50571832013-11-12 10:43:19 -080093 'VRIF': ['V ', 'Verified ',],
Jason D. Clinton729f81f2019-05-02 20:24:33 -060094 'LCQ': ['L ', 'Legacy ',],
Mike Frysinger13f23a42013-05-13 17:32:01 -040095}
96
97# Order is important -- matches the web ui. This also controls the short
98# entries that we summarize in non-verbose mode.
99GERRIT_SUMMARY_CATS = ('CR', 'CQ', 'V',)
100
Mike Frysinger4aea5dc2019-07-17 13:39:56 -0400101# Shorter strings for CL status messages.
102GERRIT_SUMMARY_MAP = {
103 'ABANDONED': 'ABD',
104 'MERGED': 'MRG',
105 'NEW': 'NEW',
106 'WIP': 'WIP',
107}
108
Mike Frysinger13f23a42013-05-13 17:32:01 -0400109
110def red(s):
111 return COLOR.Color(terminal.Color.RED, s)
112
113
114def green(s):
115 return COLOR.Color(terminal.Color.GREEN, s)
116
117
118def blue(s):
119 return COLOR.Color(terminal.Color.BLUE, s)
120
121
Mike Frysinger254f33f2019-12-11 13:54:29 -0500122def _run_parallel_tasks(task, *args):
123 """Small wrapper around BackgroundTaskRunner to enforce job count."""
124 with parallel.BackgroundTaskRunner(task, processes=CONNECTION_LIMIT) as q:
125 for arg in args:
126 q.put([arg])
127
128
Mike Frysinger13f23a42013-05-13 17:32:01 -0400129def limits(cls):
130 """Given a dict of fields, calculate the longest string lengths
131
132 This allows you to easily format the output of many results so that the
133 various cols all line up correctly.
134 """
135 lims = {}
136 for cl in cls:
137 for k in cl.keys():
Mike Frysingerf16b8f02013-10-21 22:24:46 -0400138 # Use %s rather than str() to avoid codec issues.
139 # We also do this so we can format integers.
140 lims[k] = max(lims.get(k, 0), len('%s' % cl[k]))
Mike Frysinger13f23a42013-05-13 17:32:01 -0400141 return lims
142
143
Mike Frysinger88f27292014-06-17 09:40:45 -0700144# TODO: This func really needs to be merged into the core gerrit logic.
145def GetGerrit(opts, cl=None):
146 """Auto pick the right gerrit instance based on the |cl|
147
148 Args:
149 opts: The general options object.
150 cl: A CL taking one of the forms: 1234 *1234 chromium:1234
151
152 Returns:
153 A tuple of a gerrit object and a sanitized CL #.
154 """
155 gob = opts.gob
Paul Hobbs89765232015-06-24 14:07:49 -0700156 if cl is not None:
Jason D. Clintoneb1073d2019-04-13 02:33:20 -0600157 if cl.startswith('*') or cl.startswith('chrome-internal:'):
Alex Klein2ab29cc2018-07-19 12:01:00 -0600158 gob = config_lib.GetSiteParams().INTERNAL_GOB_INSTANCE
Jason D. Clintoneb1073d2019-04-13 02:33:20 -0600159 if cl.startswith('*'):
160 cl = cl[1:]
161 else:
162 cl = cl[16:]
Mike Frysinger88f27292014-06-17 09:40:45 -0700163 elif ':' in cl:
164 gob, cl = cl.split(':', 1)
165
166 if not gob in opts.gerrit:
167 opts.gerrit[gob] = gerrit.GetGerritHelper(gob=gob, print_cmd=opts.debug)
168
169 return (opts.gerrit[gob], cl)
170
171
Mike Frysinger13f23a42013-05-13 17:32:01 -0400172def GetApprovalSummary(_opts, cls):
173 """Return a dict of the most important approvals"""
174 approvs = dict([(x, '') for x in GERRIT_SUMMARY_CATS])
Aviv Keshetad30cec2018-09-27 18:12:15 -0700175 for approver in cls.get('currentPatchSet', {}).get('approvals', []):
176 cats = GERRIT_APPROVAL_MAP.get(approver['type'])
177 if not cats:
178 logging.warning('unknown gerrit approval type: %s', approver['type'])
179 continue
180 cat = cats[0].strip()
181 val = int(approver['value'])
182 if not cat in approvs:
183 # Ignore the extended categories in the summary view.
184 continue
185 elif approvs[cat] == '':
186 approvs[cat] = val
187 elif val < 0:
188 approvs[cat] = min(approvs[cat], val)
189 else:
190 approvs[cat] = max(approvs[cat], val)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400191 return approvs
192
193
Mike Frysingera1b4b272017-04-05 16:11:00 -0400194def PrettyPrintCl(opts, cl, lims=None, show_approvals=True):
Mike Frysinger13f23a42013-05-13 17:32:01 -0400195 """Pretty print a single result"""
Mike Frysingera1b4b272017-04-05 16:11:00 -0400196 if lims is None:
Mike Frysinger13f23a42013-05-13 17:32:01 -0400197 lims = {'url': 0, 'project': 0}
198
199 status = ''
Mike Frysinger4aea5dc2019-07-17 13:39:56 -0400200
201 if opts.verbose:
202 status += '%s ' % (cl['status'],)
203 else:
204 status += '%s ' % (GERRIT_SUMMARY_MAP.get(cl['status'], cl['status']),)
205
Mike Frysinger13f23a42013-05-13 17:32:01 -0400206 if show_approvals and not opts.verbose:
Mike Frysingerb4a3e3c2017-04-05 16:06:53 -0400207 approvs = GetApprovalSummary(opts, cl)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400208 for cat in GERRIT_SUMMARY_CATS:
Mike Frysingera0313d02017-07-10 16:44:43 -0400209 if approvs[cat] in ('', 0):
Mike Frysinger13f23a42013-05-13 17:32:01 -0400210 functor = lambda x: x
211 elif approvs[cat] < 0:
212 functor = red
213 else:
214 functor = green
215 status += functor('%s:%2s ' % (cat, approvs[cat]))
216
Mike Frysingerb4a3e3c2017-04-05 16:06:53 -0400217 print('%s %s%-*s %s' % (blue('%-*s' % (lims['url'], cl['url'])), status,
218 lims['project'], cl['project'], cl['subject']))
Mike Frysinger13f23a42013-05-13 17:32:01 -0400219
220 if show_approvals and opts.verbose:
Mike Frysingerb4a3e3c2017-04-05 16:06:53 -0400221 for approver in cl['currentPatchSet'].get('approvals', []):
Mike Frysinger13f23a42013-05-13 17:32:01 -0400222 functor = red if int(approver['value']) < 0 else green
223 n = functor('%2s' % approver['value'])
224 t = GERRIT_APPROVAL_MAP.get(approver['type'], [approver['type'],
225 approver['type']])[1]
Mike Frysinger31ff6f92014-02-08 04:33:03 -0500226 print(' %s %s %s' % (n, t, approver['by']['email']))
Mike Frysinger13f23a42013-05-13 17:32:01 -0400227
228
Mike Frysingera1b4b272017-04-05 16:11:00 -0400229def PrintCls(opts, cls, lims=None, show_approvals=True):
Mike Frysinger87c74ce2017-04-04 16:12:31 -0400230 """Print all results based on the requested format."""
Mike Frysingera1b4b272017-04-05 16:11:00 -0400231 if opts.raw:
Alex Klein2ab29cc2018-07-19 12:01:00 -0600232 site_params = config_lib.GetSiteParams()
Mike Frysingera1b4b272017-04-05 16:11:00 -0400233 pfx = ''
234 # Special case internal Chrome GoB as that is what most devs use.
235 # They can always redirect the list elsewhere via the -g option.
Alex Klein2ab29cc2018-07-19 12:01:00 -0600236 if opts.gob == site_params.INTERNAL_GOB_INSTANCE:
237 pfx = site_params.INTERNAL_CHANGE_PREFIX
Mike Frysingera1b4b272017-04-05 16:11:00 -0400238 for cl in cls:
239 print('%s%s' % (pfx, cl['number']))
240
Mike Frysinger87c74ce2017-04-04 16:12:31 -0400241 elif opts.json:
242 json.dump(cls, sys.stdout)
243
Mike Frysingera1b4b272017-04-05 16:11:00 -0400244 else:
245 if lims is None:
246 lims = limits(cls)
247
248 for cl in cls:
249 PrettyPrintCl(opts, cl, lims=lims, show_approvals=show_approvals)
250
251
Mike Frysinger5f938ca2017-07-19 18:29:02 -0400252def _Query(opts, query, raw=True, helper=None):
Paul Hobbs89765232015-06-24 14:07:49 -0700253 """Queries Gerrit with a query string built from the commandline options"""
Vadim Bendebury6e057b32014-12-29 09:41:36 -0800254 if opts.branch is not None:
255 query += ' branch:%s' % opts.branch
Mathieu Olivariedc45b82015-01-12 19:43:20 -0800256 if opts.project is not None:
257 query += ' project: %s' % opts.project
Mathieu Olivari14645a12015-01-16 15:41:32 -0800258 if opts.topic is not None:
259 query += ' topic: %s' % opts.topic
Vadim Bendebury6e057b32014-12-29 09:41:36 -0800260
Mike Frysinger5f938ca2017-07-19 18:29:02 -0400261 if helper is None:
262 helper, _ = GetGerrit(opts)
Paul Hobbs89765232015-06-24 14:07:49 -0700263 return helper.Query(query, raw=raw, bypass_cache=False)
264
265
Mike Frysinger5f938ca2017-07-19 18:29:02 -0400266def FilteredQuery(opts, query, helper=None):
Paul Hobbs89765232015-06-24 14:07:49 -0700267 """Query gerrit and filter/clean up the results"""
268 ret = []
269
Mike Frysinger2cd56022017-01-12 20:56:27 -0500270 logging.debug('Running query: %s', query)
Mike Frysinger5f938ca2017-07-19 18:29:02 -0400271 for cl in _Query(opts, query, raw=True, helper=helper):
Mike Frysinger13f23a42013-05-13 17:32:01 -0400272 # Gerrit likes to return a stats record too.
273 if not 'project' in cl:
274 continue
275
276 # Strip off common leading names since the result is still
277 # unique over the whole tree.
278 if not opts.verbose:
Mike Frysinger1d508282018-06-07 16:59:44 -0400279 for pfx in ('aosp', 'chromeos', 'chromiumos', 'external', 'overlays',
280 'platform', 'third_party'):
Mike Frysinger13f23a42013-05-13 17:32:01 -0400281 if cl['project'].startswith('%s/' % pfx):
282 cl['project'] = cl['project'][len(pfx) + 1:]
283
Mike Frysinger479f1192017-09-14 22:36:30 -0400284 cl['url'] = uri_lib.ShortenUri(cl['url'])
285
Mike Frysinger13f23a42013-05-13 17:32:01 -0400286 ret.append(cl)
287
Mike Frysingerb62313a2017-06-30 16:38:58 -0400288 if opts.sort == 'unsorted':
289 return ret
Paul Hobbs89765232015-06-24 14:07:49 -0700290 if opts.sort == 'number':
Mike Frysinger13f23a42013-05-13 17:32:01 -0400291 key = lambda x: int(x[opts.sort])
292 else:
293 key = lambda x: x[opts.sort]
294 return sorted(ret, key=key)
295
296
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500297class _ActionSearchQuery(UserAction):
298 """Base class for actions that perform searches."""
299
300 @staticmethod
301 def init_subparser(parser):
302 """Add arguments to this action's subparser."""
303 parser.add_argument('--sort', default='number',
304 help='Key to sort on (number, project); use "unsorted" '
305 'to disable')
306 parser.add_argument('-b', '--branch',
307 help='Limit output to the specific branch')
308 parser.add_argument('-p', '--project',
309 help='Limit output to the specific project')
310 parser.add_argument('-t', '--topic',
311 help='Limit output to the specific topic')
312
313
314class ActionTodo(_ActionSearchQuery):
Mike Frysinger13f23a42013-05-13 17:32:01 -0400315 """List CLs needing your review"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500316
317 COMMAND = 'todo'
318
319 @staticmethod
320 def __call__(opts):
321 """Implement the action."""
Mike Frysinger242d2922021-02-09 14:31:50 -0500322 cls = FilteredQuery(opts, 'attention:self')
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500323 PrintCls(opts, cls)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400324
325
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500326class ActionSearch(_ActionSearchQuery):
Harry Cutts26076b32019-02-26 15:01:29 -0800327 """List CLs matching the search query"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500328
329 COMMAND = 'search'
330
331 @staticmethod
332 def init_subparser(parser):
333 """Add arguments to this action's subparser."""
334 _ActionSearchQuery.init_subparser(parser)
335 parser.add_argument('query',
336 help='The search query')
337
338 @staticmethod
339 def __call__(opts):
340 """Implement the action."""
341 cls = FilteredQuery(opts, opts.query)
342 PrintCls(opts, cls)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400343
344
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500345class ActionMine(_ActionSearchQuery):
Mike Frysingera1db2c42014-06-15 00:42:48 -0700346 """List your CLs with review statuses"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500347
348 COMMAND = 'mine'
349
350 @staticmethod
351 def init_subparser(parser):
352 """Add arguments to this action's subparser."""
353 _ActionSearchQuery.init_subparser(parser)
354 parser.add_argument('--draft', default=False, action='store_true',
355 help='Show draft changes')
356
357 @staticmethod
358 def __call__(opts):
359 """Implement the action."""
360 if opts.draft:
361 rule = 'is:draft'
362 else:
363 rule = 'status:new'
364 cls = FilteredQuery(opts, 'owner:self %s' % (rule,))
365 PrintCls(opts, cls)
Mike Frysingera1db2c42014-06-15 00:42:48 -0700366
367
Paul Hobbs89765232015-06-24 14:07:49 -0700368def _BreadthFirstSearch(to_visit, children, visited_key=lambda x: x):
369 """Runs breadth first search starting from the nodes in |to_visit|
370
371 Args:
372 to_visit: the starting nodes
373 children: a function which takes a node and returns the nodes adjacent to it
374 visited_key: a function for deduplicating node visits. Defaults to the
375 identity function (lambda x: x)
376
377 Returns:
378 A list of nodes which are reachable from any node in |to_visit| by calling
379 |children| any number of times.
380 """
381 to_visit = list(to_visit)
Mike Frysinger66ce4132019-07-17 22:52:52 -0400382 seen = set(visited_key(x) for x in to_visit)
Paul Hobbs89765232015-06-24 14:07:49 -0700383 for node in to_visit:
384 for child in children(node):
385 key = visited_key(child)
386 if key not in seen:
387 seen.add(key)
388 to_visit.append(child)
389 return to_visit
390
391
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500392class ActionDeps(_ActionSearchQuery):
Paul Hobbs89765232015-06-24 14:07:49 -0700393 """List CLs matching a query, and all transitive dependencies of those CLs"""
Paul Hobbs89765232015-06-24 14:07:49 -0700394
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500395 COMMAND = 'deps'
Paul Hobbs89765232015-06-24 14:07:49 -0700396
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500397 @staticmethod
398 def init_subparser(parser):
399 """Add arguments to this action's subparser."""
400 _ActionSearchQuery.init_subparser(parser)
401 parser.add_argument('query',
402 help='The search query')
403
404 def __call__(self, opts):
405 """Implement the action."""
406 cls = _Query(opts, opts.query, raw=False)
407
408 @memoize.Memoize
409 def _QueryChange(cl, helper=None):
410 return _Query(opts, cl, raw=False, helper=helper)
411
412 transitives = _BreadthFirstSearch(
413 cls, functools.partial(self._Children, opts, _QueryChange),
Mike Frysingerdc407f52020-05-08 00:34:56 -0400414 visited_key=lambda cl: cl.PatchLink())
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500415
Mike Frysingerdc407f52020-05-08 00:34:56 -0400416 # This is a hack to avoid losing GoB host for each CL. The PrintCls
417 # function assumes the GoB host specified by the user is the only one
418 # that is ever used, but the deps command walks across hosts.
419 if opts.raw:
420 print('\n'.join(x.PatchLink() for x in transitives))
421 else:
422 transitives_raw = [cl.patch_dict for cl in transitives]
423 PrintCls(opts, transitives_raw)
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500424
425 @staticmethod
426 def _ProcessDeps(opts, querier, cl, deps, required):
Mike Frysinger5726da92017-09-20 22:14:25 -0400427 """Yields matching dependencies for a patch"""
Paul Hobbs89765232015-06-24 14:07:49 -0700428 # We need to query the change to guarantee that we have a .gerrit_number
Mike Frysinger5726da92017-09-20 22:14:25 -0400429 for dep in deps:
Mike Frysingerb3300c42017-07-20 01:41:17 -0400430 if not dep.remote in opts.gerrit:
431 opts.gerrit[dep.remote] = gerrit.GetGerritHelper(
432 remote=dep.remote, print_cmd=opts.debug)
433 helper = opts.gerrit[dep.remote]
434
Paul Hobbs89765232015-06-24 14:07:49 -0700435 # TODO(phobbs) this should maybe catch network errors.
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500436 changes = querier(dep.ToGerritQueryText(), helper=helper)
Mike Frysinger5726da92017-09-20 22:14:25 -0400437
438 # Handle empty results. If we found a commit that was pushed directly
439 # (e.g. a bot commit), then gerrit won't know about it.
440 if not changes:
441 if required:
442 logging.error('CL %s depends on %s which cannot be found',
443 cl, dep.ToGerritQueryText())
444 continue
445
446 # Our query might have matched more than one result. This can come up
447 # when CQ-DEPEND uses a Gerrit Change-Id, but that Change-Id shows up
448 # across multiple repos/branches. We blindly check all of them in the
449 # hopes that all open ones are what the user wants, but then again the
450 # CQ-DEPEND syntax itself is unable to differeniate. *shrug*
451 if len(changes) > 1:
452 logging.warning('CL %s has an ambiguous CQ dependency %s',
453 cl, dep.ToGerritQueryText())
454 for change in changes:
455 if change.status == 'NEW':
456 yield change
457
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500458 @classmethod
459 def _Children(cls, opts, querier, cl):
Mike Frysinger7cbd88c2021-02-12 03:52:25 -0500460 """Yields the Gerrit dependencies of a patch"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500461 for change in cls._ProcessDeps(
462 opts, querier, cl, cl.GerritDependencies(), False):
Mike Frysinger5726da92017-09-20 22:14:25 -0400463 yield change
Paul Hobbs89765232015-06-24 14:07:49 -0700464
Paul Hobbs89765232015-06-24 14:07:49 -0700465
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500466class ActionInspect(_ActionSearchQuery):
Harry Cutts26076b32019-02-26 15:01:29 -0800467 """Show the details of one or more CLs"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500468
469 COMMAND = 'inspect'
470
471 @staticmethod
472 def init_subparser(parser):
473 """Add arguments to this action's subparser."""
474 _ActionSearchQuery.init_subparser(parser)
475 parser.add_argument('cls', nargs='+', metavar='CL',
476 help='The CL(s) to update')
477
478 @staticmethod
479 def __call__(opts):
480 """Implement the action."""
481 cls = []
482 for arg in opts.cls:
483 helper, cl = GetGerrit(opts, arg)
484 change = FilteredQuery(opts, 'change:%s' % cl, helper=helper)
485 if change:
486 cls.extend(change)
487 else:
488 logging.warning('no results found for CL %s', arg)
489 PrintCls(opts, cls)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400490
491
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500492class _ActionLabeler(UserAction):
493 """Base helper for setting labels."""
494
495 LABEL = None
496 VALUES = None
497
498 @classmethod
499 def init_subparser(cls, parser):
500 """Add arguments to this action's subparser."""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500501 parser.add_argument('-m', '--msg', '--message', metavar='MESSAGE',
502 help='Optional message to include')
503 parser.add_argument('cls', nargs='+', metavar='CL',
504 help='The CL(s) to update')
505 parser.add_argument('value', nargs=1, metavar='value', choices=cls.VALUES,
506 help='The label value; one of [%(choices)s]')
507
508 @classmethod
509 def __call__(cls, opts):
510 """Implement the action."""
511 # Convert user friendly command line option into a gerrit parameter.
512 def task(arg):
513 helper, cl = GetGerrit(opts, arg)
514 helper.SetReview(cl, labels={cls.LABEL: opts.value[0]}, msg=opts.msg,
515 dryrun=opts.dryrun, notify=opts.notify)
516 _run_parallel_tasks(task, *opts.cls)
517
518
519class ActionLabelAutoSubmit(_ActionLabeler):
Mike Frysinger48b5e012020-02-06 17:04:12 -0500520 """Change the Auto-Submit label"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500521
522 COMMAND = 'label-as'
523 LABEL = 'Auto-Submit'
524 VALUES = ('0', '1')
Jack Rosenthal8a1fb542019-08-07 10:23:56 -0600525
526
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500527class ActionLabelCodeReview(_ActionLabeler):
Mike Frysinger48b5e012020-02-06 17:04:12 -0500528 """Change the Code-Review label (1=LGTM 2=LGTM+Approved)"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500529
530 COMMAND = 'label-cr'
531 LABEL = 'Code-Review'
532 VALUES = ('-2', '-1', '0', '1', '2')
Mike Frysinger13f23a42013-05-13 17:32:01 -0400533
534
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500535class ActionLabelVerified(_ActionLabeler):
Mike Frysinger48b5e012020-02-06 17:04:12 -0500536 """Change the Verified label"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500537
538 COMMAND = 'label-v'
539 LABEL = 'Verified'
540 VALUES = ('-1', '0', '1')
Mike Frysinger13f23a42013-05-13 17:32:01 -0400541
542
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500543class ActionLabelCommitQueue(_ActionLabeler):
Mike Frysinger48b5e012020-02-06 17:04:12 -0500544 """Change the Commit-Queue label (1=dry-run 2=commit)"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500545
546 COMMAND = 'label-cq'
547 LABEL = 'Commit-Queue'
548 VALUES = ('0', '1', '2')
Mike Frysinger15b23e42014-12-05 17:00:05 -0500549
550
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500551class _ActionSimpleParallelCLs(UserAction):
552 """Base helper for actions that only accept CLs."""
553
554 @staticmethod
555 def init_subparser(parser):
556 """Add arguments to this action's subparser."""
557 parser.add_argument('cls', nargs='+', metavar='CL',
558 help='The CL(s) to update')
559
560 def __call__(self, opts):
561 """Implement the action."""
562 def task(arg):
563 helper, cl = GetGerrit(opts, arg)
564 self._process_one(helper, cl, opts)
565 _run_parallel_tasks(task, *opts.cls)
566
567
568class ActionSubmit(_ActionSimpleParallelCLs):
Harry Cutts26076b32019-02-26 15:01:29 -0800569 """Submit CLs"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500570
571 COMMAND = 'submit'
572
573 @staticmethod
574 def _process_one(helper, cl, opts):
575 """Use |helper| to process the single |cl|."""
Mike Frysinger8674a112021-02-09 14:44:17 -0500576 helper.SubmitChange(cl, dryrun=opts.dryrun, notify=opts.notify)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400577
578
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500579class ActionAbandon(_ActionSimpleParallelCLs):
Harry Cutts26076b32019-02-26 15:01:29 -0800580 """Abandon CLs"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500581
582 COMMAND = 'abandon'
583
584 @staticmethod
585 def _process_one(helper, cl, opts):
586 """Use |helper| to process the single |cl|."""
Mike Frysinger8674a112021-02-09 14:44:17 -0500587 helper.AbandonChange(cl, dryrun=opts.dryrun, notify=opts.notify)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400588
589
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500590class ActionRestore(_ActionSimpleParallelCLs):
Harry Cutts26076b32019-02-26 15:01:29 -0800591 """Restore CLs that were abandoned"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500592
593 COMMAND = 'restore'
594
595 @staticmethod
596 def _process_one(helper, cl, opts):
597 """Use |helper| to process the single |cl|."""
Mike Frysinger88f27292014-06-17 09:40:45 -0700598 helper.RestoreChange(cl, dryrun=opts.dryrun)
Mike Frysinger13f23a42013-05-13 17:32:01 -0400599
600
Tomasz Figa54d70992021-01-20 13:48:59 +0900601class ActionWorkInProgress(_ActionSimpleParallelCLs):
602 """Mark CLs as work in progress"""
603
604 COMMAND = 'wip'
605
606 @staticmethod
607 def _process_one(helper, cl, opts):
608 """Use |helper| to process the single |cl|."""
609 helper.SetWorkInProgress(cl, True, dryrun=opts.dryrun)
610
611
612class ActionReadyForReview(_ActionSimpleParallelCLs):
613 """Mark CLs as ready for review"""
614
615 COMMAND = 'ready'
616
617 @staticmethod
618 def _process_one(helper, cl, opts):
619 """Use |helper| to process the single |cl|."""
620 helper.SetWorkInProgress(cl, False, dryrun=opts.dryrun)
621
622
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500623class ActionReviewers(UserAction):
Harry Cutts26076b32019-02-26 15:01:29 -0800624 """Add/remove reviewers' emails for a CL (prepend with '~' to remove)"""
Vadim Bendeburydcfe2322013-05-23 10:54:49 -0700625
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500626 COMMAND = 'reviewers'
Vadim Bendeburydcfe2322013-05-23 10:54:49 -0700627
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500628 @staticmethod
629 def init_subparser(parser):
630 """Add arguments to this action's subparser."""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500631 parser.add_argument('cl', metavar='CL',
632 help='The CL to update')
633 parser.add_argument('reviewers', nargs='+',
634 help='The reviewers to add/remove')
Vadim Bendeburydcfe2322013-05-23 10:54:49 -0700635
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500636 @staticmethod
637 def __call__(opts):
638 """Implement the action."""
639 # Allow for optional leading '~'.
640 email_validator = re.compile(r'^[~]?%s$' % constants.EMAIL_REGEX)
641 add_list, remove_list, invalid_list = [], [], []
642
643 for email in opts.reviewers:
644 if not email_validator.match(email):
645 invalid_list.append(email)
646 elif email[0] == '~':
647 remove_list.append(email[1:])
648 else:
649 add_list.append(email)
650
651 if invalid_list:
652 cros_build_lib.Die(
653 'Invalid email address(es): %s' % ', '.join(invalid_list))
654
655 if add_list or remove_list:
656 helper, cl = GetGerrit(opts, opts.cl)
657 helper.SetReviewers(cl, add=add_list, remove=remove_list,
658 dryrun=opts.dryrun, notify=opts.notify)
Vadim Bendeburydcfe2322013-05-23 10:54:49 -0700659
660
Mike Frysinger62178ae2020-03-20 01:37:43 -0400661class ActionMessage(_ActionSimpleParallelCLs):
Harry Cutts26076b32019-02-26 15:01:29 -0800662 """Add a message to a CL"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500663
664 COMMAND = 'message'
665
666 @staticmethod
667 def init_subparser(parser):
668 """Add arguments to this action's subparser."""
Mike Frysinger62178ae2020-03-20 01:37:43 -0400669 _ActionSimpleParallelCLs.init_subparser(parser)
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500670 parser.add_argument('message',
671 help='The message to post')
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500672
673 @staticmethod
674 def _process_one(helper, cl, opts):
675 """Use |helper| to process the single |cl|."""
676 helper.SetReview(cl, msg=opts.message, dryrun=opts.dryrun)
Doug Anderson8119df02013-07-20 21:00:24 +0530677
678
Mike Frysinger62178ae2020-03-20 01:37:43 -0400679class ActionTopic(_ActionSimpleParallelCLs):
Harry Cutts26076b32019-02-26 15:01:29 -0800680 """Set a topic for one or more CLs"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500681
682 COMMAND = 'topic'
683
684 @staticmethod
685 def init_subparser(parser):
686 """Add arguments to this action's subparser."""
Mike Frysinger62178ae2020-03-20 01:37:43 -0400687 _ActionSimpleParallelCLs.init_subparser(parser)
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500688 parser.add_argument('topic',
689 help='The topic to set')
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500690
691 @staticmethod
692 def _process_one(helper, cl, opts):
693 """Use |helper| to process the single |cl|."""
694 helper.SetTopic(cl, opts.topic, dryrun=opts.dryrun)
Harry Cutts26076b32019-02-26 15:01:29 -0800695
Mathieu Olivari02f89b32015-01-09 13:53:38 -0800696
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500697class ActionPrivate(_ActionSimpleParallelCLs):
698 """Mark CLs private"""
Prathmesh Prabhu871e7772018-03-28 17:11:29 -0700699
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500700 COMMAND = 'private'
701
702 @staticmethod
703 def _process_one(helper, cl, opts):
704 """Use |helper| to process the single |cl|."""
705 helper.SetPrivate(cl, True, dryrun=opts.dryrun)
Prathmesh Prabhu871e7772018-03-28 17:11:29 -0700706
Mathieu Olivari02f89b32015-01-09 13:53:38 -0800707
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500708class ActionPublic(_ActionSimpleParallelCLs):
709 """Mark CLs public"""
710
711 COMMAND = 'public'
712
713 @staticmethod
714 def _process_one(helper, cl, opts):
715 """Use |helper| to process the single |cl|."""
716 helper.SetPrivate(cl, False, dryrun=opts.dryrun)
717
718
719class ActionSethashtags(UserAction):
Harry Cutts26076b32019-02-26 15:01:29 -0800720 """Add/remove hashtags on a CL (prepend with '~' to remove)"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500721
722 COMMAND = 'hashtags'
723
724 @staticmethod
725 def init_subparser(parser):
726 """Add arguments to this action's subparser."""
727 parser.add_argument('cl', metavar='CL',
728 help='The CL to update')
729 parser.add_argument('hashtags', nargs='+',
730 help='The hashtags to add/remove')
731
732 @staticmethod
733 def __call__(opts):
734 """Implement the action."""
735 add = []
736 remove = []
737 for hashtag in opts.hashtags:
738 if hashtag.startswith('~'):
739 remove.append(hashtag[1:])
740 else:
741 add.append(hashtag)
742 helper, cl = GetGerrit(opts, opts.cl)
743 helper.SetHashtags(cl, add, remove, dryrun=opts.dryrun)
Wei-Han Chenb4c9af52017-02-09 14:43:22 +0800744
745
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500746class ActionDeletedraft(_ActionSimpleParallelCLs):
Harry Cutts26076b32019-02-26 15:01:29 -0800747 """Delete draft CLs"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500748
749 COMMAND = 'deletedraft'
750
751 @staticmethod
752 def _process_one(helper, cl, opts):
753 """Use |helper| to process the single |cl|."""
Mike Frysinger88f27292014-06-17 09:40:45 -0700754 helper.DeleteDraft(cl, dryrun=opts.dryrun)
Jon Salza427fb02014-03-07 18:13:17 +0800755
756
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500757class ActionReviewed(_ActionSimpleParallelCLs):
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500758 """Mark CLs as reviewed"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500759
760 COMMAND = 'reviewed'
761
762 @staticmethod
763 def _process_one(helper, cl, opts):
764 """Use |helper| to process the single |cl|."""
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500765 helper.ReviewedChange(cl, dryrun=opts.dryrun)
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500766
767
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500768class ActionUnreviewed(_ActionSimpleParallelCLs):
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500769 """Mark CLs as unreviewed"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500770
771 COMMAND = 'unreviewed'
772
773 @staticmethod
774 def _process_one(helper, cl, opts):
775 """Use |helper| to process the single |cl|."""
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500776 helper.UnreviewedChange(cl, dryrun=opts.dryrun)
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500777
778
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500779class ActionIgnore(_ActionSimpleParallelCLs):
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500780 """Ignore CLs (suppress notifications/dashboard/etc...)"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500781
782 COMMAND = 'ignore'
783
784 @staticmethod
785 def _process_one(helper, cl, opts):
786 """Use |helper| to process the single |cl|."""
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500787 helper.IgnoreChange(cl, dryrun=opts.dryrun)
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500788
789
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500790class ActionUnignore(_ActionSimpleParallelCLs):
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500791 """Unignore CLs (enable notifications/dashboard/etc...)"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500792
793 COMMAND = 'unignore'
794
795 @staticmethod
796 def _process_one(helper, cl, opts):
797 """Use |helper| to process the single |cl|."""
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500798 helper.UnignoreChange(cl, dryrun=opts.dryrun)
Mike Frysinger6f04dd42020-02-06 16:48:18 -0500799
800
Mike Frysinger5dab15e2020-08-06 10:11:03 -0400801class ActionCherryPick(UserAction):
802 """Cherry pick CLs to branches."""
803
804 COMMAND = 'cherry-pick'
805
806 @staticmethod
807 def init_subparser(parser):
808 """Add arguments to this action's subparser."""
809 # Should we add an option to walk Cq-Depend and try to cherry-pick them?
810 parser.add_argument('--rev', '--revision', default='current',
811 help='A specific revision or patchset')
812 parser.add_argument('-m', '--msg', '--message', metavar='MESSAGE',
813 help='Include a message')
814 parser.add_argument('--branches', '--branch', '--br', action='split_extend',
815 default=[], required=True,
816 help='The destination branches')
817 parser.add_argument('cls', nargs='+', metavar='CL',
818 help='The CLs to cherry-pick')
819
820 @staticmethod
821 def __call__(opts):
822 """Implement the action."""
823 # Process branches in parallel, but CLs in serial in case of CL stacks.
824 def task(branch):
825 for arg in opts.cls:
826 helper, cl = GetGerrit(opts, arg)
827 ret = helper.CherryPick(cl, branch, rev=opts.rev, msg=opts.msg,
Mike Frysinger8674a112021-02-09 14:44:17 -0500828 dryrun=opts.dryrun, notify=opts.notify)
Mike Frysinger5dab15e2020-08-06 10:11:03 -0400829 logging.debug('Response: %s', ret)
830 if opts.raw:
831 print(ret['_number'])
832 else:
833 uri = f'https://{helper.host}/c/{ret["_number"]}'
834 print(uri_lib.ShortenUri(uri))
835
836 _run_parallel_tasks(task, *opts.branches)
837
838
Mike Frysinger8037f752020-02-29 20:47:09 -0500839class ActionReview(_ActionSimpleParallelCLs):
840 """Review CLs with multiple settings
841
842 The label option supports extended/multiple syntax for easy use. The --label
843 option may be specified multiple times (as settings are merges), and multiple
844 labels are allowed in a single argument. Each label has the form:
845 <long or short name><=+-><value>
846
847 Common arguments:
848 Commit-Queue=0 Commit-Queue-1 Commit-Queue+2 CQ+2
849 'V+1 CQ+2'
850 'AS=1 V=1'
851 """
852
853 COMMAND = 'review'
854
855 class _SetLabel(argparse.Action):
856 """Argparse action for setting labels."""
857
858 LABEL_MAP = {
859 'AS': 'Auto-Submit',
860 'CQ': 'Commit-Queue',
861 'CR': 'Code-Review',
862 'V': 'Verified',
863 }
864
865 def __call__(self, parser, namespace, values, option_string=None):
866 labels = getattr(namespace, self.dest)
867 for request in values.split():
868 if '=' in request:
869 # Handle Verified=1 form.
870 short, value = request.split('=', 1)
871 elif '+' in request:
872 # Handle Verified+1 form.
873 short, value = request.split('+', 1)
874 elif '-' in request:
875 # Handle Verified-1 form.
876 short, value = request.split('-', 1)
877 value = '-%s' % (value,)
878 else:
879 parser.error('Invalid label setting "%s". Must be Commit-Queue=1 or '
880 'CQ+1 or CR-1.' % (request,))
881
882 # Convert possible short label names like "V" to "Verified".
883 label = self.LABEL_MAP.get(short)
884 if not label:
885 label = short
886
887 # We allow existing label requests to be overridden.
888 labels[label] = value
889
890 @classmethod
891 def init_subparser(cls, parser):
892 """Add arguments to this action's subparser."""
893 parser.add_argument('-m', '--msg', '--message', metavar='MESSAGE',
894 help='Include a message')
895 parser.add_argument('-l', '--label', dest='labels',
896 action=cls._SetLabel, default={},
897 help='Set a label with a value')
898 parser.add_argument('--ready', default=None, action='store_true',
899 help='Set CL status to ready-for-review')
900 parser.add_argument('--wip', default=None, action='store_true',
901 help='Set CL status to WIP')
902 parser.add_argument('--reviewers', '--re', action='append', default=[],
903 help='Add reviewers')
904 parser.add_argument('--cc', action='append', default=[],
905 help='Add people to CC')
906 _ActionSimpleParallelCLs.init_subparser(parser)
907
908 @staticmethod
909 def _process_one(helper, cl, opts):
910 """Use |helper| to process the single |cl|."""
911 helper.SetReview(cl, msg=opts.msg, labels=opts.labels, dryrun=opts.dryrun,
912 notify=opts.notify, reviewers=opts.reviewers, cc=opts.cc,
913 ready=opts.ready, wip=opts.wip)
914
915
Mike Frysinger7f2018d2021-02-04 00:10:58 -0500916class ActionAccount(_ActionSimpleParallelCLs):
917 """Get user account information"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500918
919 COMMAND = 'account'
920
921 @staticmethod
Mike Frysinger7f2018d2021-02-04 00:10:58 -0500922 def init_subparser(parser):
923 """Add arguments to this action's subparser."""
924 parser.add_argument('accounts', nargs='*', default=['self'],
925 help='The accounts to query')
926
927 @classmethod
928 def __call__(cls, opts):
Mike Frysingerc7796cf2020-02-06 23:55:15 -0500929 """Implement the action."""
930 helper, _ = GetGerrit(opts)
Mike Frysinger7f2018d2021-02-04 00:10:58 -0500931
932 def print_one(header, data):
933 print(f'### {header}')
934 print(pformat.json(data, compact=opts.json).rstrip())
935
936 def task(arg):
937 detail = gob_util.FetchUrlJson(helper.host, f'accounts/{arg}/detail')
938 if not detail:
939 print(f'{arg}: account not found')
940 else:
941 print_one('detail', detail)
942 for field in ('groups', 'capabilities', 'preferences', 'sshkeys',
943 'gpgkeys'):
944 data = gob_util.FetchUrlJson(helper.host, f'accounts/{arg}/{field}')
945 print_one(field, data)
946
947 _run_parallel_tasks(task, *opts.accounts)
Yu-Ju Hongc20d7b32014-11-18 07:51:11 -0800948
949
Mike Frysinger2295d792021-03-08 15:55:23 -0500950class ActionConfig(UserAction):
951 """Manage the gerrit tool's own config file
952
953 Gerrit may be customized via ~/.config/chromite/gerrit.cfg.
954 It is an ini file like ~/.gitconfig. See `man git-config` for basic format.
955
956 # Set up subcommand aliases.
957 [alias]
958 common-search = search 'is:open project:something/i/care/about'
959 """
960
961 COMMAND = 'config'
962
963 @staticmethod
964 def __call__(opts):
965 """Implement the action."""
966 # For now, this is a place holder for raising visibility for the config file
967 # and its associated help text documentation.
968 opts.parser.parse_args(['config', '--help'])
969
970
Mike Frysingere5450602021-03-08 15:34:17 -0500971class ActionHelp(UserAction):
972 """An alias to --help for CLI symmetry"""
973
974 COMMAND = 'help'
975
976 @staticmethod
977 def init_subparser(parser):
978 """Add arguments to this action's subparser."""
979 parser.add_argument('command', nargs='?',
980 help='The command to display.')
981
982 @staticmethod
983 def __call__(opts):
984 """Implement the action."""
985 # Show global help.
986 if not opts.command:
987 opts.parser.print_help()
988 return
989
990 opts.parser.parse_args([opts.command, '--help'])
991
992
Mike Frysinger484e2f82020-03-20 01:41:10 -0400993class ActionHelpAll(UserAction):
994 """Show all actions help output at once."""
995
996 COMMAND = 'help-all'
997
998 @staticmethod
999 def __call__(opts):
1000 """Implement the action."""
1001 first = True
1002 for action in _GetActions():
1003 if first:
1004 first = False
1005 else:
1006 print('\n\n')
1007
1008 try:
1009 opts.parser.parse_args([action, '--help'])
1010 except SystemExit:
1011 pass
1012
1013
Mike Frysinger65fc8632020-02-06 18:11:12 -05001014@memoize.Memoize
1015def _GetActions():
1016 """Get all the possible actions we support.
1017
1018 Returns:
1019 An ordered dictionary mapping the user subcommand (e.g. "foo") to the
1020 function that implements that command (e.g. UserActFoo).
1021 """
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001022 VALID_NAME = re.compile(r'^[a-z][a-z-]*[a-z]$')
1023
1024 actions = {}
1025 for cls in globals().values():
1026 if (not inspect.isclass(cls) or
1027 not issubclass(cls, UserAction) or
1028 not getattr(cls, 'COMMAND', None)):
Mike Frysinger65fc8632020-02-06 18:11:12 -05001029 continue
1030
Mike Frysinger65fc8632020-02-06 18:11:12 -05001031 # Sanity check names for devs adding new commands. Should be quick.
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001032 cmd = cls.COMMAND
1033 assert VALID_NAME.match(cmd), '"%s" must match [a-z-]+' % (cmd,)
1034 assert cmd not in actions, 'multiple "%s" commands found' % (cmd,)
Mike Frysinger65fc8632020-02-06 18:11:12 -05001035
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001036 actions[cmd] = cls
Mike Frysinger65fc8632020-02-06 18:11:12 -05001037
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001038 return collections.OrderedDict(sorted(actions.items()))
Mike Frysinger65fc8632020-02-06 18:11:12 -05001039
1040
Harry Cutts26076b32019-02-26 15:01:29 -08001041def _GetActionUsages():
1042 """Formats a one-line usage and doc message for each action."""
Mike Frysinger65fc8632020-02-06 18:11:12 -05001043 actions = _GetActions()
Harry Cutts26076b32019-02-26 15:01:29 -08001044
Mike Frysinger65fc8632020-02-06 18:11:12 -05001045 cmds = list(actions.keys())
1046 functions = list(actions.values())
Harry Cutts26076b32019-02-26 15:01:29 -08001047 usages = [getattr(x, 'usage', '') for x in functions]
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001048 docs = [x.__doc__.splitlines()[0] for x in functions]
Harry Cutts26076b32019-02-26 15:01:29 -08001049
Harry Cutts26076b32019-02-26 15:01:29 -08001050 cmd_indent = len(max(cmds, key=len))
1051 usage_indent = len(max(usages, key=len))
Mike Frysinger65fc8632020-02-06 18:11:12 -05001052 return '\n'.join(
1053 ' %-*s %-*s : %s' % (cmd_indent, cmd, usage_indent, usage, doc)
1054 for cmd, usage, doc in zip(cmds, usages, docs)
1055 )
Harry Cutts26076b32019-02-26 15:01:29 -08001056
1057
Mike Frysinger2295d792021-03-08 15:55:23 -05001058def _AddCommonOptions(parser, subparser):
1059 """Add options that should work before & after the subcommand.
1060
1061 Make it easy to do `gerrit --dry-run foo` and `gerrit foo --dry-run`.
1062 """
1063 parser.add_common_argument_to_group(
1064 subparser, '--ne', '--no-emails', dest='notify',
1065 default='ALL', action='store_const', const='NONE',
1066 help='Do not send e-mail notifications')
1067 parser.add_common_argument_to_group(
1068 subparser, '-n', '--dry-run', dest='dryrun',
1069 default=False, action='store_true',
1070 help='Show what would be done, but do not make changes')
1071
1072
1073def GetBaseParser() -> commandline.ArgumentParser:
1074 """Returns the common parser (i.e. no subparsers added)."""
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001075 description = """\
Mike Frysinger13f23a42013-05-13 17:32:01 -04001076There is no support for doing line-by-line code review via the command line.
1077This helps you manage various bits and CL status.
1078
Mike Frysingera1db2c42014-06-15 00:42:48 -07001079For general Gerrit documentation, see:
1080 https://gerrit-review.googlesource.com/Documentation/
1081The Searching Changes page covers the search query syntax:
1082 https://gerrit-review.googlesource.com/Documentation/user-search.html
1083
Mike Frysinger13f23a42013-05-13 17:32:01 -04001084Example:
Mike Frysinger48b5e012020-02-06 17:04:12 -05001085 $ gerrit todo # List all the CLs that await your review.
1086 $ gerrit mine # List all of your open CLs.
1087 $ gerrit inspect 28123 # Inspect CL 28123 on the public gerrit.
1088 $ gerrit inspect *28123 # Inspect CL 28123 on the internal gerrit.
1089 $ gerrit label-v 28123 1 # Mark CL 28123 as verified (+1).
Harry Cuttsde9b32c2019-02-21 15:25:35 -08001090 $ gerrit reviewers 28123 foo@chromium.org # Add foo@ as a reviewer on CL \
109128123.
1092 $ gerrit reviewers 28123 ~foo@chromium.org # Remove foo@ as a reviewer on \
1093CL 28123.
Mike Frysingerd8f841c2014-06-15 00:48:26 -07001094Scripting:
Mike Frysinger48b5e012020-02-06 17:04:12 -05001095 $ gerrit label-cq `gerrit --raw mine` 1 # Mark *ALL* of your public CLs \
1096with Commit-Queue=1.
1097 $ gerrit label-cq `gerrit --raw -i mine` 1 # Mark *ALL* of your internal \
1098CLs with Commit-Queue=1.
Mike Frysingerd7f10792021-03-08 13:11:38 -05001099 $ gerrit --json search 'attention:self' # Dump all pending CLs in JSON.
Mike Frysinger13f23a42013-05-13 17:32:01 -04001100
Harry Cutts26076b32019-02-26 15:01:29 -08001101Actions:
1102"""
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001103 description += _GetActionUsages()
Mike Frysinger13f23a42013-05-13 17:32:01 -04001104
Alex Klein2ab29cc2018-07-19 12:01:00 -06001105 site_params = config_lib.GetSiteParams()
Mike Frysinger3f257c82020-06-16 01:42:29 -04001106 parser = commandline.ArgumentParser(
1107 description=description, default_log_level='notice')
Mike Frysinger8674a112021-02-09 14:44:17 -05001108
1109 group = parser.add_argument_group('Server options')
1110 group.add_argument('-i', '--internal', dest='gob', action='store_const',
1111 default=site_params.EXTERNAL_GOB_INSTANCE,
1112 const=site_params.INTERNAL_GOB_INSTANCE,
1113 help='Query internal Chrome Gerrit instance')
1114 group.add_argument('-g', '--gob',
1115 default=site_params.EXTERNAL_GOB_INSTANCE,
1116 help='Gerrit (on borg) instance to query (default: %s)' %
1117 (site_params.EXTERNAL_GOB_INSTANCE))
1118
Mike Frysinger8674a112021-02-09 14:44:17 -05001119 group = parser.add_argument_group('CL options')
Mike Frysinger2295d792021-03-08 15:55:23 -05001120 _AddCommonOptions(parser, group)
Mike Frysinger8674a112021-02-09 14:44:17 -05001121
Mike Frysingerf70bdc72014-06-15 00:44:06 -07001122 parser.add_argument('--raw', default=False, action='store_true',
1123 help='Return raw results (suitable for scripting)')
Mike Frysinger87c74ce2017-04-04 16:12:31 -04001124 parser.add_argument('--json', default=False, action='store_true',
1125 help='Return results in JSON (suitable for scripting)')
Mike Frysinger2295d792021-03-08 15:55:23 -05001126 return parser
1127
1128
1129def GetParser(parser: commandline.ArgumentParser = None) -> (
1130 commandline.ArgumentParser):
1131 """Returns the full parser to use for this module."""
1132 if parser is None:
1133 parser = GetBaseParser()
1134
1135 actions = _GetActions()
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001136
1137 # Subparsers are required by default under Python 2. Python 3 changed to
1138 # not required, but didn't include a required option until 3.7. Setting
1139 # the required member works in all versions (and setting dest name).
1140 subparsers = parser.add_subparsers(dest='action')
1141 subparsers.required = True
1142 for cmd, cls in actions.items():
1143 # Format the full docstring by removing the file level indentation.
1144 description = re.sub(r'^ ', '', cls.__doc__, flags=re.M)
1145 subparser = subparsers.add_parser(cmd, description=description)
Mike Frysinger2295d792021-03-08 15:55:23 -05001146 _AddCommonOptions(parser, subparser)
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001147 cls.init_subparser(subparser)
Mike Frysinger108eda22018-06-06 18:45:12 -04001148
1149 return parser
1150
1151
1152def main(argv):
Mike Frysinger2295d792021-03-08 15:55:23 -05001153 base_parser = GetBaseParser()
1154 opts, subargs = base_parser.parse_known_args(argv)
1155
1156 config = Config()
1157 if subargs:
1158 # If the action is an alias to an expanded value, we need to mutate the argv
1159 # and reparse things.
1160 action = config.expand_alias(subargs[0])
1161 if action != subargs[0]:
1162 pos = argv.index(subargs[0])
1163 argv = argv[:pos] + action + argv[pos + 1:]
1164
1165 parser = GetParser(parser=base_parser)
Mike Frysingerddf86eb2014-02-07 22:51:41 -05001166 opts = parser.parse_args(argv)
Mike Frysinger13f23a42013-05-13 17:32:01 -04001167
Mike Frysinger484e2f82020-03-20 01:41:10 -04001168 # In case the action wants to throw a parser error.
1169 opts.parser = parser
1170
Mike Frysinger88f27292014-06-17 09:40:45 -07001171 # A cache of gerrit helpers we'll load on demand.
1172 opts.gerrit = {}
Vadim Bendebury2e3f82d2019-02-11 17:53:03 -08001173
Mike Frysinger88f27292014-06-17 09:40:45 -07001174 opts.Freeze()
1175
Mike Frysinger27e21b72018-07-12 14:20:21 -04001176 # pylint: disable=global-statement
Mike Frysinger031ad0b2013-05-14 18:15:34 -04001177 global COLOR
1178 COLOR = terminal.Color(enabled=opts.color)
1179
Mike Frysinger13f23a42013-05-13 17:32:01 -04001180 # Now look up the requested user action and run it.
Mike Frysinger65fc8632020-02-06 18:11:12 -05001181 actions = _GetActions()
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001182 obj = actions[opts.action]()
Mike Frysinger65fc8632020-02-06 18:11:12 -05001183 try:
Mike Frysingerc7796cf2020-02-06 23:55:15 -05001184 obj(opts)
Mike Frysinger65fc8632020-02-06 18:11:12 -05001185 except (cros_build_lib.RunCommandError, gerrit.GerritException,
1186 gob_util.GOBError) as e:
1187 cros_build_lib.Die(e)