blob: 2afb6bc213f9f7e37f0e31c89734a5ce6b03d779 [file] [log] [blame]
Josip Sokcevic84434e82021-06-09 22:48:43 +00001#!/usr/bin/env vpython3
dimu833c94c2017-01-18 17:36:15 -08002# Copyright 2017 The Chromium 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
6"""Simple client for the Gerrit REST API.
7
8Example usage:
Michael Moss5eebf6f2021-07-16 13:18:34 +00009 ./gerrit_client.py [command] [args]
dimu833c94c2017-01-18 17:36:15 -080010"""
11
12from __future__ import print_function
13
14import json
15import logging
16import optparse
17import subcommand
18import sys
Josip Sokcevicc99efb22020-03-17 00:35:34 +000019
20if sys.version_info.major == 2:
21 import urlparse
22 from urllib import quote_plus
23else:
24 from urllib.parse import quote_plus
25 import urllib.parse as urlparse
dimu833c94c2017-01-18 17:36:15 -080026
dimu833c94c2017-01-18 17:36:15 -080027import fix_encoding
28import gerrit_util
29import setup_color
30
31__version__ = '0.1'
dimu833c94c2017-01-18 17:36:15 -080032
33
34def write_result(result, opt):
35 if opt.json_file:
36 with open(opt.json_file, 'w') as json_file:
37 json_file.write(json.dumps(result))
38
39
40@subcommand.usage('[args ...]')
Josip Sokcevicc39ab992020-09-24 20:09:15 +000041def CMDmovechanges(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +000042 """Move changes to a different destination branch."""
Josip Sokcevicc39ab992020-09-24 20:09:15 +000043 parser.add_option('-p', '--param', dest='params', action='append',
44 help='repeatable query parameter, format: -p key=value')
45 parser.add_option('--destination_branch', dest='destination_branch',
46 help='where to move changes to')
47
48 (opt, args) = parser.parse_args(args)
49 assert opt.destination_branch, "--destination_branch not defined"
Mike Frysinger8820ab82020-11-25 00:52:31 +000050 for p in opt.params:
51 assert '=' in p, '--param is key=value, not "%s"' % p
Josip Sokcevicc39ab992020-09-24 20:09:15 +000052 host = urlparse.urlparse(opt.host).netloc
53
54 limit = 100
55 while True:
56 result = gerrit_util.QueryChanges(
57 host,
58 list(tuple(p.split('=', 1)) for p in opt.params),
59 limit=limit,
60 )
61 for change in result:
62 gerrit_util.MoveChange(host, change['id'], opt.destination_branch)
63
64 if len(result) < limit:
65 break
66 logging.info("Done")
67
68
69@subcommand.usage('[args ...]')
dimu833c94c2017-01-18 17:36:15 -080070def CMDbranchinfo(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +000071 """Get information on a gerrit branch."""
dimu833c94c2017-01-18 17:36:15 -080072 parser.add_option('--branch', dest='branch', help='branch name')
73
74 (opt, args) = parser.parse_args(args)
75 host = urlparse.urlparse(opt.host).netloc
Josip Sokcevicc99efb22020-03-17 00:35:34 +000076 project = quote_plus(opt.project)
77 branch = quote_plus(opt.branch)
dimu833c94c2017-01-18 17:36:15 -080078 result = gerrit_util.GetGerritBranch(host, project, branch)
79 logging.info(result)
80 write_result(result, opt)
81
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000082
dimu833c94c2017-01-18 17:36:15 -080083@subcommand.usage('[args ...]')
Michael Moss9c28af42021-10-25 16:59:05 +000084def CMDrawapi(parser, args):
85 """Call an arbitrary Gerrit REST API endpoint."""
86 parser.add_option('--path', dest='path', help='HTTP path of the API endpoint')
87 parser.add_option('--method', dest='method',
88 help='HTTP method for the API (default: GET)')
89 parser.add_option('--body', dest='body', help='API JSON body contents')
90 parser.add_option('--accept_status',
91 dest='accept_status',
92 help='Comma-delimited list of status codes for success.')
93
94 (opt, args) = parser.parse_args(args)
95 assert opt.path, "--path not defined"
96
97 host = urlparse.urlparse(opt.host).netloc
98 kwargs = {}
99 if opt.method:
100 kwargs['reqtype'] = opt.method.upper()
101 if opt.body:
102 kwargs['body'] = json.loads(opt.body)
103 if opt.accept_status:
104 kwargs['accept_statuses'] = [int(x) for x in opt.accept_status.split(',')]
105 result = gerrit_util.CallGerritApi(host, opt.path, **kwargs)
106 logging.info(result)
107 write_result(result, opt)
108
109
110@subcommand.usage('[args ...]')
dimu833c94c2017-01-18 17:36:15 -0800111def CMDbranch(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000112 """Create a branch in a gerrit project."""
dimu833c94c2017-01-18 17:36:15 -0800113 parser.add_option('--branch', dest='branch', help='branch name')
114 parser.add_option('--commit', dest='commit', help='commit hash')
115
116 (opt, args) = parser.parse_args(args)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000117 assert opt.project, "--project not defined"
118 assert opt.branch, "--branch not defined"
119 assert opt.commit, "--commit not defined"
dimu833c94c2017-01-18 17:36:15 -0800120
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000121 project = quote_plus(opt.project)
dimu833c94c2017-01-18 17:36:15 -0800122 host = urlparse.urlparse(opt.host).netloc
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000123 branch = quote_plus(opt.branch)
Michael Moss5c9e8b42021-10-26 16:54:16 +0000124 result = gerrit_util.CreateGerritBranch(host, project, branch, opt.commit)
dimu833c94c2017-01-18 17:36:15 -0800125 logging.info(result)
126 write_result(result, opt)
127
128
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200129@subcommand.usage('[args ...]')
Michael Mossb6ce2442021-10-20 04:36:24 +0000130def CMDtag(parser, args):
131 """Create a tag in a gerrit project."""
132 parser.add_option('--tag', dest='tag', help='tag name')
133 parser.add_option('--commit', dest='commit', help='commit hash')
134
135 (opt, args) = parser.parse_args(args)
136 assert opt.project, "--project not defined"
137 assert opt.tag, "--tag not defined"
138 assert opt.commit, "--commit not defined"
139
140 project = quote_plus(opt.project)
141 host = urlparse.urlparse(opt.host).netloc
142 tag = quote_plus(opt.tag)
Michael Moss5c9e8b42021-10-26 16:54:16 +0000143 result = gerrit_util.CreateGerritTag(host, project, tag, opt.commit)
Michael Mossb6ce2442021-10-20 04:36:24 +0000144 logging.info(result)
145 write_result(result, opt)
146
147
148@subcommand.usage('[args ...]')
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000149def CMDhead(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000150 """Update which branch the project HEAD points to."""
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000151 parser.add_option('--branch', dest='branch', help='branch name')
152
153 (opt, args) = parser.parse_args(args)
154 assert opt.project, "--project not defined"
155 assert opt.branch, "--branch not defined"
156
157 project = quote_plus(opt.project)
158 host = urlparse.urlparse(opt.host).netloc
159 branch = quote_plus(opt.branch)
160 result = gerrit_util.UpdateHead(host, project, branch)
161 logging.info(result)
162 write_result(result, opt)
163
164
165@subcommand.usage('[args ...]')
166def CMDheadinfo(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000167 """Retrieves the current HEAD of the project."""
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000168
169 (opt, args) = parser.parse_args(args)
170 assert opt.project, "--project not defined"
171
172 project = quote_plus(opt.project)
173 host = urlparse.urlparse(opt.host).netloc
174 result = gerrit_util.GetHead(host, project)
175 logging.info(result)
176 write_result(result, opt)
177
178
179@subcommand.usage('[args ...]')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200180def CMDchanges(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000181 """Queries gerrit for matching changes."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200182 parser.add_option('-p', '--param', dest='params', action='append',
183 help='repeatable query parameter, format: -p key=value')
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +0200184 parser.add_option('-o', '--o-param', dest='o_params', action='append',
185 help='gerrit output parameters, e.g. ALL_REVISIONS')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200186 parser.add_option('--limit', dest='limit', type=int,
187 help='maximum number of results to return')
188 parser.add_option('--start', dest='start', type=int,
189 help='how many changes to skip '
190 '(starting with the most recent)')
191
192 (opt, args) = parser.parse_args(args)
Mike Frysinger8820ab82020-11-25 00:52:31 +0000193 for p in opt.params:
194 assert '=' in p, '--param is key=value, not "%s"' % p
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200195
196 result = gerrit_util.QueryChanges(
197 urlparse.urlparse(opt.host).netloc,
198 list(tuple(p.split('=', 1)) for p in opt.params),
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +0200199 start=opt.start, # Default: None
200 limit=opt.limit, # Default: None
201 o_params=opt.o_params, # Default: None
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200202 )
203 logging.info('Change query returned %d changes.', len(result))
204 write_result(result, opt)
205
206
LaMont Jones9eed4232021-04-02 16:29:49 +0000207@subcommand.usage('[args ...]')
Marco Georgaklis85557a02021-06-03 15:56:54 +0000208def CMDrelatedchanges(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000209 """Gets related changes for a given change and revision."""
Marco Georgaklis85557a02021-06-03 15:56:54 +0000210 parser.add_option('-c', '--change', type=str, help='change id')
211 parser.add_option('-r', '--revision', type=str, help='revision id')
212
213 (opt, args) = parser.parse_args(args)
214
215 result = gerrit_util.GetRelatedChanges(
216 urlparse.urlparse(opt.host).netloc,
217 change=opt.change,
218 revision=opt.revision,
219 )
220 logging.info(result)
221 write_result(result, opt)
222
223
224@subcommand.usage('[args ...]')
LaMont Jones9eed4232021-04-02 16:29:49 +0000225def CMDcreatechange(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000226 """Create a new change in gerrit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000227 parser.add_option('-s', '--subject', help='subject for change')
228 parser.add_option('-b',
229 '--branch',
230 default='main',
231 help='target branch for change')
232 parser.add_option(
233 '-p',
234 '--param',
235 dest='params',
236 action='append',
237 help='repeatable field value parameter, format: -p key=value')
238
Xinan Lin91d2a5d2022-02-04 21:18:32 +0000239 parser.add_option('--cc',
240 dest='cc_list',
241 action='append',
242 help='CC address to notify, format: --cc foo@example.com')
243
LaMont Jones9eed4232021-04-02 16:29:49 +0000244 (opt, args) = parser.parse_args(args)
245 for p in opt.params:
246 assert '=' in p, '--param is key=value, not "%s"' % p
247
Xinan Lin91d2a5d2022-02-04 21:18:32 +0000248 params = list(tuple(p.split('=', 1)) for p in opt.params)
249
250 if opt.cc_list:
251 params.append(('notify_details', {'CC': {'accounts': opt.cc_list}}))
252
LaMont Jones9eed4232021-04-02 16:29:49 +0000253 result = gerrit_util.CreateChange(
254 urlparse.urlparse(opt.host).netloc,
255 opt.project,
256 branch=opt.branch,
257 subject=opt.subject,
Xinan Lin91d2a5d2022-02-04 21:18:32 +0000258 params=params,
LaMont Jones9eed4232021-04-02 16:29:49 +0000259 )
260 logging.info(result)
261 write_result(result, opt)
262
263
264@subcommand.usage('[args ...]')
265def CMDchangeedit(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000266 """Puts content of a file into a change edit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000267 parser.add_option('-c', '--change', type=int, help='change number')
268 parser.add_option('--path', help='path for file')
269 parser.add_option('--file', help='file to place at |path|')
270
271 (opt, args) = parser.parse_args(args)
272
273 with open(opt.file) as f:
274 data = f.read()
275 result = gerrit_util.ChangeEdit(
276 urlparse.urlparse(opt.host).netloc, opt.change, opt.path, data)
277 logging.info(result)
278 write_result(result, opt)
279
280
281@subcommand.usage('[args ...]')
282def CMDpublishchangeedit(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000283 """Publish a Gerrit change edit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000284 parser.add_option('-c', '--change', type=int, help='change number')
285 parser.add_option('--notify', help='whether to notify')
286
287 (opt, args) = parser.parse_args(args)
288
289 result = gerrit_util.PublishChangeEdit(
290 urlparse.urlparse(opt.host).netloc, opt.change, opt.notify)
291 logging.info(result)
292 write_result(result, opt)
293
294
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000295@subcommand.usage('[args ...]')
296def CMDsubmitchange(parser, args):
297 """Submit a Gerrit change."""
298 parser.add_option('-c', '--change', type=int, help='change number')
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000299 (opt, args) = parser.parse_args(args)
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000300 result = gerrit_util.SubmitChange(
301 urlparse.urlparse(opt.host).netloc, opt.change)
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000302 logging.info(result)
303 write_result(result, opt)
304
305
Xinan Linc2fb26a2021-07-27 18:01:55 +0000306@subcommand.usage('[args ...]')
Xinan Lin2b4ec952021-08-20 17:35:29 +0000307def CMDchangesubmittedtogether(parser, args):
308 """Get all changes submitted with the given one."""
309 parser.add_option('-c', '--change', type=int, help='change number')
310 (opt, args) = parser.parse_args(args)
311 result = gerrit_util.GetChangesSubmittedTogether(
312 urlparse.urlparse(opt.host).netloc, opt.change)
313 logging.info(result)
314 write_result(result, opt)
315
316
317@subcommand.usage('[args ...]')
Xinan Linc2fb26a2021-07-27 18:01:55 +0000318def CMDgetcommitincludedin(parser, args):
319 """Retrieves the branches and tags for a given commit."""
320 parser.add_option('--commit', dest='commit', help='commit hash')
321 (opt, args) = parser.parse_args(args)
322 result = gerrit_util.GetCommitIncludedIn(
323 urlparse.urlparse(opt.host).netloc, opt.project, opt.commit)
324 logging.info(result)
325 write_result(result, opt)
326
327
Xinan Lin0b0738d2021-07-27 19:13:49 +0000328@subcommand.usage('[args ...]')
329def CMDsetbotcommit(parser, args):
330 """Sets bot-commit+1 to a bot generated change."""
331 parser.add_option('-c', '--change', type=int, help='change number')
332 (opt, args) = parser.parse_args(args)
333 result = gerrit_util.SetReview(
334 urlparse.urlparse(opt.host).netloc,
335 opt.change,
336 labels={'Bot-Commit': 1},
337 ready=True)
338 logging.info(result)
339 write_result(result, opt)
340
341
Ben Pastene281edf72021-10-06 01:23:24 +0000342@subcommand.usage('[args ...]')
343def CMDsetlabel(parser, args):
344 """Sets a label to a specific value on a given change."""
345 parser.add_option('-c', '--change', type=int, help='change number')
346 parser.add_option('-l',
347 '--label',
348 nargs=2,
349 metavar=('label_name', 'label_value'))
350 (opt, args) = parser.parse_args(args)
351 result = gerrit_util.SetReview(urlparse.urlparse(opt.host).netloc,
352 opt.change,
353 labels={opt.label[0]: opt.label[1]})
354 logging.info(result)
355 write_result(result, opt)
356
357
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000358@subcommand.usage('')
359def CMDabandon(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000360 """Abandons a Gerrit change."""
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000361 parser.add_option('-c', '--change', type=int, help='change number')
362 parser.add_option('-m', '--message', default='', help='reason for abandoning')
363
364 (opt, args) = parser.parse_args(args)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000365 assert opt.change, "-c not defined"
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000366 result = gerrit_util.AbandonChange(
367 urlparse.urlparse(opt.host).netloc,
368 opt.change, opt.message)
369 logging.info(result)
370 write_result(result, opt)
371
372
Michael Moss5eebf6f2021-07-16 13:18:34 +0000373@subcommand.usage('')
Josip Sokcevice1a98942021-04-07 21:35:29 +0000374def CMDmass_abandon(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000375 """Mass abandon changes
376
377 Abandons CLs that match search criteria provided by user. Before any change is
378 actually abandoned, user is presented with a list of CLs that will be affected
379 if user confirms. User can skip confirmation by passing --force parameter.
380
381 The script can abandon up to 100 CLs per invocation.
382
383 Examples:
384 gerrit_client.py mass-abandon --host https://HOST -p 'project=repo2'
385 gerrit_client.py mass-abandon --host https://HOST -p 'message=testing'
386 gerrit_client.py mass-abandon --host https://HOST -p 'is=wip' -p 'age=1y'
387 """
Josip Sokcevice1a98942021-04-07 21:35:29 +0000388 parser.add_option('-p',
389 '--param',
390 dest='params',
391 action='append',
392 default=[],
393 help='repeatable query parameter, format: -p key=value')
394 parser.add_option('-m', '--message', default='', help='reason for abandoning')
395 parser.add_option('-f',
396 '--force',
397 action='store_true',
398 help='Don\'t prompt for confirmation')
399
400 opt, args = parser.parse_args(args)
401
402 for p in opt.params:
403 assert '=' in p, '--param is key=value, not "%s"' % p
404 search_query = list(tuple(p.split('=', 1)) for p in opt.params)
405 if not any(t for t in search_query if t[0] == 'owner'):
406 # owner should always be present when abandoning changes
407 search_query.append(('owner', 'me'))
408 search_query.append(('status', 'open'))
409 logging.info("Searching for: %s" % search_query)
410
411 host = urlparse.urlparse(opt.host).netloc
412
413 result = gerrit_util.QueryChanges(
414 host,
415 search_query,
416 # abandon at most 100 changes as not all Gerrit instances support
417 # unlimited results.
418 limit=100,
419 )
420 if len(result) == 0:
421 logging.warn("Nothing to abandon")
422 return
423
424 logging.warn("%s CLs match search query: " % len(result))
425 for change in result:
426 logging.warn("[ID: %d] %s" % (change['_number'], change['subject']))
427
428 if not opt.force:
Josip Sokcevic284fbdd2021-10-08 18:26:30 +0000429 q = input(
Josip Sokcevice1a98942021-04-07 21:35:29 +0000430 'Do you want to move forward with abandoning? [y to confirm] ').strip()
431 if q not in ['y', 'Y']:
432 logging.warn("Aborting...")
433 return
434
435 for change in result:
436 logging.warning("Abandoning: %s" % change['subject'])
437 gerrit_util.AbandonChange(host, change['id'], opt.message)
438
439 logging.warning("Done")
440
441
dimu833c94c2017-01-18 17:36:15 -0800442class OptionParser(optparse.OptionParser):
443 """Creates the option parse and add --verbose support."""
444 def __init__(self, *args, **kwargs):
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000445 optparse.OptionParser.__init__(self, *args, version=__version__, **kwargs)
dimu833c94c2017-01-18 17:36:15 -0800446 self.add_option(
447 '--verbose', action='count', default=0,
448 help='Use 2 times for more debugging info')
449 self.add_option('--host', dest='host', help='Url of host.')
450 self.add_option('--project', dest='project', help='project name')
451 self.add_option(
452 '--json_file', dest='json_file', help='output json filepath')
453
454 def parse_args(self, args=None, values=None):
455 options, args = optparse.OptionParser.parse_args(self, args, values)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000456 # Host is always required
457 assert options.host, "--host not defined."
dimu833c94c2017-01-18 17:36:15 -0800458 levels = [logging.WARNING, logging.INFO, logging.DEBUG]
459 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
460 return options, args
461
462
463def main(argv):
464 if sys.hexversion < 0x02060000:
465 print('\nYour python version %s is unsupported, please upgrade.\n'
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000466 % (sys.version.split(' ', 1)[0],),
dimu833c94c2017-01-18 17:36:15 -0800467 file=sys.stderr)
468 return 2
469 dispatcher = subcommand.CommandDispatcher(__name__)
470 return dispatcher.execute(OptionParser(), argv)
471
472
473if __name__ == '__main__':
474 # These affect sys.stdout so do it outside of main() to simplify mocks in
475 # unit testing.
476 fix_encoding.fix_encoding()
477 setup_color.init()
478 try:
479 sys.exit(main(sys.argv[1:]))
480 except KeyboardInterrupt:
481 sys.stderr.write('interrupted\n')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200482 sys.exit(1)