blob: f3eb379daac6cfb415caa6d3453e69137e64ff5d [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
239 (opt, args) = parser.parse_args(args)
240 for p in opt.params:
241 assert '=' in p, '--param is key=value, not "%s"' % p
242
243 result = gerrit_util.CreateChange(
244 urlparse.urlparse(opt.host).netloc,
245 opt.project,
246 branch=opt.branch,
247 subject=opt.subject,
248 params=list(tuple(p.split('=', 1)) for p in opt.params),
249 )
250 logging.info(result)
251 write_result(result, opt)
252
253
254@subcommand.usage('[args ...]')
255def CMDchangeedit(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000256 """Puts content of a file into a change edit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000257 parser.add_option('-c', '--change', type=int, help='change number')
258 parser.add_option('--path', help='path for file')
259 parser.add_option('--file', help='file to place at |path|')
260
261 (opt, args) = parser.parse_args(args)
262
263 with open(opt.file) as f:
264 data = f.read()
265 result = gerrit_util.ChangeEdit(
266 urlparse.urlparse(opt.host).netloc, opt.change, opt.path, data)
267 logging.info(result)
268 write_result(result, opt)
269
270
271@subcommand.usage('[args ...]')
272def CMDpublishchangeedit(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000273 """Publish a Gerrit change edit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000274 parser.add_option('-c', '--change', type=int, help='change number')
275 parser.add_option('--notify', help='whether to notify')
276
277 (opt, args) = parser.parse_args(args)
278
279 result = gerrit_util.PublishChangeEdit(
280 urlparse.urlparse(opt.host).netloc, opt.change, opt.notify)
281 logging.info(result)
282 write_result(result, opt)
283
284
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000285@subcommand.usage('[args ...]')
286def CMDsubmitchange(parser, args):
287 """Submit a Gerrit change."""
288 parser.add_option('-c', '--change', type=int, help='change number')
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000289 (opt, args) = parser.parse_args(args)
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000290 result = gerrit_util.SubmitChange(
291 urlparse.urlparse(opt.host).netloc, opt.change)
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000292 logging.info(result)
293 write_result(result, opt)
294
295
Xinan Linc2fb26a2021-07-27 18:01:55 +0000296@subcommand.usage('[args ...]')
Xinan Lin2b4ec952021-08-20 17:35:29 +0000297def CMDchangesubmittedtogether(parser, args):
298 """Get all changes submitted with the given one."""
299 parser.add_option('-c', '--change', type=int, help='change number')
300 (opt, args) = parser.parse_args(args)
301 result = gerrit_util.GetChangesSubmittedTogether(
302 urlparse.urlparse(opt.host).netloc, opt.change)
303 logging.info(result)
304 write_result(result, opt)
305
306
307@subcommand.usage('[args ...]')
Xinan Linc2fb26a2021-07-27 18:01:55 +0000308def CMDgetcommitincludedin(parser, args):
309 """Retrieves the branches and tags for a given commit."""
310 parser.add_option('--commit', dest='commit', help='commit hash')
311 (opt, args) = parser.parse_args(args)
312 result = gerrit_util.GetCommitIncludedIn(
313 urlparse.urlparse(opt.host).netloc, opt.project, opt.commit)
314 logging.info(result)
315 write_result(result, opt)
316
317
Xinan Lin0b0738d2021-07-27 19:13:49 +0000318@subcommand.usage('[args ...]')
319def CMDsetbotcommit(parser, args):
320 """Sets bot-commit+1 to a bot generated change."""
321 parser.add_option('-c', '--change', type=int, help='change number')
322 (opt, args) = parser.parse_args(args)
323 result = gerrit_util.SetReview(
324 urlparse.urlparse(opt.host).netloc,
325 opt.change,
326 labels={'Bot-Commit': 1},
327 ready=True)
328 logging.info(result)
329 write_result(result, opt)
330
331
Ben Pastene281edf72021-10-06 01:23:24 +0000332@subcommand.usage('[args ...]')
333def CMDsetlabel(parser, args):
334 """Sets a label to a specific value on a given change."""
335 parser.add_option('-c', '--change', type=int, help='change number')
336 parser.add_option('-l',
337 '--label',
338 nargs=2,
339 metavar=('label_name', 'label_value'))
340 (opt, args) = parser.parse_args(args)
341 result = gerrit_util.SetReview(urlparse.urlparse(opt.host).netloc,
342 opt.change,
343 labels={opt.label[0]: opt.label[1]})
344 logging.info(result)
345 write_result(result, opt)
346
347
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000348@subcommand.usage('')
349def CMDabandon(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000350 """Abandons a Gerrit change."""
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000351 parser.add_option('-c', '--change', type=int, help='change number')
352 parser.add_option('-m', '--message', default='', help='reason for abandoning')
353
354 (opt, args) = parser.parse_args(args)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000355 assert opt.change, "-c not defined"
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000356 result = gerrit_util.AbandonChange(
357 urlparse.urlparse(opt.host).netloc,
358 opt.change, opt.message)
359 logging.info(result)
360 write_result(result, opt)
361
362
Michael Moss5eebf6f2021-07-16 13:18:34 +0000363@subcommand.usage('')
Josip Sokcevice1a98942021-04-07 21:35:29 +0000364def CMDmass_abandon(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000365 """Mass abandon changes
366
367 Abandons CLs that match search criteria provided by user. Before any change is
368 actually abandoned, user is presented with a list of CLs that will be affected
369 if user confirms. User can skip confirmation by passing --force parameter.
370
371 The script can abandon up to 100 CLs per invocation.
372
373 Examples:
374 gerrit_client.py mass-abandon --host https://HOST -p 'project=repo2'
375 gerrit_client.py mass-abandon --host https://HOST -p 'message=testing'
376 gerrit_client.py mass-abandon --host https://HOST -p 'is=wip' -p 'age=1y'
377 """
Josip Sokcevice1a98942021-04-07 21:35:29 +0000378 parser.add_option('-p',
379 '--param',
380 dest='params',
381 action='append',
382 default=[],
383 help='repeatable query parameter, format: -p key=value')
384 parser.add_option('-m', '--message', default='', help='reason for abandoning')
385 parser.add_option('-f',
386 '--force',
387 action='store_true',
388 help='Don\'t prompt for confirmation')
389
390 opt, args = parser.parse_args(args)
391
392 for p in opt.params:
393 assert '=' in p, '--param is key=value, not "%s"' % p
394 search_query = list(tuple(p.split('=', 1)) for p in opt.params)
395 if not any(t for t in search_query if t[0] == 'owner'):
396 # owner should always be present when abandoning changes
397 search_query.append(('owner', 'me'))
398 search_query.append(('status', 'open'))
399 logging.info("Searching for: %s" % search_query)
400
401 host = urlparse.urlparse(opt.host).netloc
402
403 result = gerrit_util.QueryChanges(
404 host,
405 search_query,
406 # abandon at most 100 changes as not all Gerrit instances support
407 # unlimited results.
408 limit=100,
409 )
410 if len(result) == 0:
411 logging.warn("Nothing to abandon")
412 return
413
414 logging.warn("%s CLs match search query: " % len(result))
415 for change in result:
416 logging.warn("[ID: %d] %s" % (change['_number'], change['subject']))
417
418 if not opt.force:
Josip Sokcevic284fbdd2021-10-08 18:26:30 +0000419 q = input(
Josip Sokcevice1a98942021-04-07 21:35:29 +0000420 'Do you want to move forward with abandoning? [y to confirm] ').strip()
421 if q not in ['y', 'Y']:
422 logging.warn("Aborting...")
423 return
424
425 for change in result:
426 logging.warning("Abandoning: %s" % change['subject'])
427 gerrit_util.AbandonChange(host, change['id'], opt.message)
428
429 logging.warning("Done")
430
431
dimu833c94c2017-01-18 17:36:15 -0800432class OptionParser(optparse.OptionParser):
433 """Creates the option parse and add --verbose support."""
434 def __init__(self, *args, **kwargs):
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000435 optparse.OptionParser.__init__(self, *args, version=__version__, **kwargs)
dimu833c94c2017-01-18 17:36:15 -0800436 self.add_option(
437 '--verbose', action='count', default=0,
438 help='Use 2 times for more debugging info')
439 self.add_option('--host', dest='host', help='Url of host.')
440 self.add_option('--project', dest='project', help='project name')
441 self.add_option(
442 '--json_file', dest='json_file', help='output json filepath')
443
444 def parse_args(self, args=None, values=None):
445 options, args = optparse.OptionParser.parse_args(self, args, values)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000446 # Host is always required
447 assert options.host, "--host not defined."
dimu833c94c2017-01-18 17:36:15 -0800448 levels = [logging.WARNING, logging.INFO, logging.DEBUG]
449 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
450 return options, args
451
452
453def main(argv):
454 if sys.hexversion < 0x02060000:
455 print('\nYour python version %s is unsupported, please upgrade.\n'
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000456 % (sys.version.split(' ', 1)[0],),
dimu833c94c2017-01-18 17:36:15 -0800457 file=sys.stderr)
458 return 2
459 dispatcher = subcommand.CommandDispatcher(__name__)
460 return dispatcher.execute(OptionParser(), argv)
461
462
463if __name__ == '__main__':
464 # These affect sys.stdout so do it outside of main() to simplify mocks in
465 # unit testing.
466 fix_encoding.fix_encoding()
467 setup_color.init()
468 try:
469 sys.exit(main(sys.argv[1:]))
470 except KeyboardInterrupt:
471 sys.stderr.write('interrupted\n')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200472 sys.exit(1)