blob: 2a26eaa42623a7f6a5ea897a1eeddcf811e0064e [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)
124 commit = quote_plus(opt.commit)
dimu833c94c2017-01-18 17:36:15 -0800125 result = gerrit_util.CreateGerritBranch(host, project, branch, commit)
126 logging.info(result)
127 write_result(result, opt)
128
129
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200130@subcommand.usage('[args ...]')
Michael Mossb6ce2442021-10-20 04:36:24 +0000131def CMDtag(parser, args):
132 """Create a tag in a gerrit project."""
133 parser.add_option('--tag', dest='tag', help='tag name')
134 parser.add_option('--commit', dest='commit', help='commit hash')
135
136 (opt, args) = parser.parse_args(args)
137 assert opt.project, "--project not defined"
138 assert opt.tag, "--tag not defined"
139 assert opt.commit, "--commit not defined"
140
141 project = quote_plus(opt.project)
142 host = urlparse.urlparse(opt.host).netloc
143 tag = quote_plus(opt.tag)
144 commit = quote_plus(opt.commit)
145 result = gerrit_util.CreateGerritTag(host, project, tag, commit)
146 logging.info(result)
147 write_result(result, opt)
148
149
150@subcommand.usage('[args ...]')
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000151def CMDhead(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000152 """Update which branch the project HEAD points to."""
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000153 parser.add_option('--branch', dest='branch', help='branch name')
154
155 (opt, args) = parser.parse_args(args)
156 assert opt.project, "--project not defined"
157 assert opt.branch, "--branch not defined"
158
159 project = quote_plus(opt.project)
160 host = urlparse.urlparse(opt.host).netloc
161 branch = quote_plus(opt.branch)
162 result = gerrit_util.UpdateHead(host, project, branch)
163 logging.info(result)
164 write_result(result, opt)
165
166
167@subcommand.usage('[args ...]')
168def CMDheadinfo(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000169 """Retrieves the current HEAD of the project."""
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000170
171 (opt, args) = parser.parse_args(args)
172 assert opt.project, "--project not defined"
173
174 project = quote_plus(opt.project)
175 host = urlparse.urlparse(opt.host).netloc
176 result = gerrit_util.GetHead(host, project)
177 logging.info(result)
178 write_result(result, opt)
179
180
181@subcommand.usage('[args ...]')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200182def CMDchanges(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000183 """Queries gerrit for matching changes."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200184 parser.add_option('-p', '--param', dest='params', action='append',
185 help='repeatable query parameter, format: -p key=value')
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +0200186 parser.add_option('-o', '--o-param', dest='o_params', action='append',
187 help='gerrit output parameters, e.g. ALL_REVISIONS')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200188 parser.add_option('--limit', dest='limit', type=int,
189 help='maximum number of results to return')
190 parser.add_option('--start', dest='start', type=int,
191 help='how many changes to skip '
192 '(starting with the most recent)')
193
194 (opt, args) = parser.parse_args(args)
Mike Frysinger8820ab82020-11-25 00:52:31 +0000195 for p in opt.params:
196 assert '=' in p, '--param is key=value, not "%s"' % p
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200197
198 result = gerrit_util.QueryChanges(
199 urlparse.urlparse(opt.host).netloc,
200 list(tuple(p.split('=', 1)) for p in opt.params),
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +0200201 start=opt.start, # Default: None
202 limit=opt.limit, # Default: None
203 o_params=opt.o_params, # Default: None
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200204 )
205 logging.info('Change query returned %d changes.', len(result))
206 write_result(result, opt)
207
208
LaMont Jones9eed4232021-04-02 16:29:49 +0000209@subcommand.usage('[args ...]')
Marco Georgaklis85557a02021-06-03 15:56:54 +0000210def CMDrelatedchanges(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000211 """Gets related changes for a given change and revision."""
Marco Georgaklis85557a02021-06-03 15:56:54 +0000212 parser.add_option('-c', '--change', type=str, help='change id')
213 parser.add_option('-r', '--revision', type=str, help='revision id')
214
215 (opt, args) = parser.parse_args(args)
216
217 result = gerrit_util.GetRelatedChanges(
218 urlparse.urlparse(opt.host).netloc,
219 change=opt.change,
220 revision=opt.revision,
221 )
222 logging.info(result)
223 write_result(result, opt)
224
225
226@subcommand.usage('[args ...]')
LaMont Jones9eed4232021-04-02 16:29:49 +0000227def CMDcreatechange(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000228 """Create a new change in gerrit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000229 parser.add_option('-s', '--subject', help='subject for change')
230 parser.add_option('-b',
231 '--branch',
232 default='main',
233 help='target branch for change')
234 parser.add_option(
235 '-p',
236 '--param',
237 dest='params',
238 action='append',
239 help='repeatable field value parameter, format: -p key=value')
240
241 (opt, args) = parser.parse_args(args)
242 for p in opt.params:
243 assert '=' in p, '--param is key=value, not "%s"' % p
244
245 result = gerrit_util.CreateChange(
246 urlparse.urlparse(opt.host).netloc,
247 opt.project,
248 branch=opt.branch,
249 subject=opt.subject,
250 params=list(tuple(p.split('=', 1)) for p in opt.params),
251 )
252 logging.info(result)
253 write_result(result, opt)
254
255
256@subcommand.usage('[args ...]')
257def CMDchangeedit(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000258 """Puts content of a file into a change edit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000259 parser.add_option('-c', '--change', type=int, help='change number')
260 parser.add_option('--path', help='path for file')
261 parser.add_option('--file', help='file to place at |path|')
262
263 (opt, args) = parser.parse_args(args)
264
265 with open(opt.file) as f:
266 data = f.read()
267 result = gerrit_util.ChangeEdit(
268 urlparse.urlparse(opt.host).netloc, opt.change, opt.path, data)
269 logging.info(result)
270 write_result(result, opt)
271
272
273@subcommand.usage('[args ...]')
274def CMDpublishchangeedit(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000275 """Publish a Gerrit change edit."""
LaMont Jones9eed4232021-04-02 16:29:49 +0000276 parser.add_option('-c', '--change', type=int, help='change number')
277 parser.add_option('--notify', help='whether to notify')
278
279 (opt, args) = parser.parse_args(args)
280
281 result = gerrit_util.PublishChangeEdit(
282 urlparse.urlparse(opt.host).netloc, opt.change, opt.notify)
283 logging.info(result)
284 write_result(result, opt)
285
286
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000287@subcommand.usage('[args ...]')
288def CMDsubmitchange(parser, args):
289 """Submit a Gerrit change."""
290 parser.add_option('-c', '--change', type=int, help='change number')
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000291 (opt, args) = parser.parse_args(args)
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000292 result = gerrit_util.SubmitChange(
293 urlparse.urlparse(opt.host).netloc, opt.change)
Xinan Lin6ec7cd82021-07-21 00:53:42 +0000294 logging.info(result)
295 write_result(result, opt)
296
297
Xinan Linc2fb26a2021-07-27 18:01:55 +0000298@subcommand.usage('[args ...]')
Xinan Lin2b4ec952021-08-20 17:35:29 +0000299def CMDchangesubmittedtogether(parser, args):
300 """Get all changes submitted with the given one."""
301 parser.add_option('-c', '--change', type=int, help='change number')
302 (opt, args) = parser.parse_args(args)
303 result = gerrit_util.GetChangesSubmittedTogether(
304 urlparse.urlparse(opt.host).netloc, opt.change)
305 logging.info(result)
306 write_result(result, opt)
307
308
309@subcommand.usage('[args ...]')
Xinan Linc2fb26a2021-07-27 18:01:55 +0000310def CMDgetcommitincludedin(parser, args):
311 """Retrieves the branches and tags for a given commit."""
312 parser.add_option('--commit', dest='commit', help='commit hash')
313 (opt, args) = parser.parse_args(args)
314 result = gerrit_util.GetCommitIncludedIn(
315 urlparse.urlparse(opt.host).netloc, opt.project, opt.commit)
316 logging.info(result)
317 write_result(result, opt)
318
319
Xinan Lin0b0738d2021-07-27 19:13:49 +0000320@subcommand.usage('[args ...]')
321def CMDsetbotcommit(parser, args):
322 """Sets bot-commit+1 to a bot generated change."""
323 parser.add_option('-c', '--change', type=int, help='change number')
324 (opt, args) = parser.parse_args(args)
325 result = gerrit_util.SetReview(
326 urlparse.urlparse(opt.host).netloc,
327 opt.change,
328 labels={'Bot-Commit': 1},
329 ready=True)
330 logging.info(result)
331 write_result(result, opt)
332
333
Ben Pastene281edf72021-10-06 01:23:24 +0000334@subcommand.usage('[args ...]')
335def CMDsetlabel(parser, args):
336 """Sets a label to a specific value on a given change."""
337 parser.add_option('-c', '--change', type=int, help='change number')
338 parser.add_option('-l',
339 '--label',
340 nargs=2,
341 metavar=('label_name', 'label_value'))
342 (opt, args) = parser.parse_args(args)
343 result = gerrit_util.SetReview(urlparse.urlparse(opt.host).netloc,
344 opt.change,
345 labels={opt.label[0]: opt.label[1]})
346 logging.info(result)
347 write_result(result, opt)
348
349
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000350@subcommand.usage('')
351def CMDabandon(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000352 """Abandons a Gerrit change."""
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000353 parser.add_option('-c', '--change', type=int, help='change number')
354 parser.add_option('-m', '--message', default='', help='reason for abandoning')
355
356 (opt, args) = parser.parse_args(args)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000357 assert opt.change, "-c not defined"
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000358 result = gerrit_util.AbandonChange(
359 urlparse.urlparse(opt.host).netloc,
360 opt.change, opt.message)
361 logging.info(result)
362 write_result(result, opt)
363
364
Michael Moss5eebf6f2021-07-16 13:18:34 +0000365@subcommand.usage('')
Josip Sokcevice1a98942021-04-07 21:35:29 +0000366def CMDmass_abandon(parser, args):
Michael Moss5eebf6f2021-07-16 13:18:34 +0000367 """Mass abandon changes
368
369 Abandons CLs that match search criteria provided by user. Before any change is
370 actually abandoned, user is presented with a list of CLs that will be affected
371 if user confirms. User can skip confirmation by passing --force parameter.
372
373 The script can abandon up to 100 CLs per invocation.
374
375 Examples:
376 gerrit_client.py mass-abandon --host https://HOST -p 'project=repo2'
377 gerrit_client.py mass-abandon --host https://HOST -p 'message=testing'
378 gerrit_client.py mass-abandon --host https://HOST -p 'is=wip' -p 'age=1y'
379 """
Josip Sokcevice1a98942021-04-07 21:35:29 +0000380 parser.add_option('-p',
381 '--param',
382 dest='params',
383 action='append',
384 default=[],
385 help='repeatable query parameter, format: -p key=value')
386 parser.add_option('-m', '--message', default='', help='reason for abandoning')
387 parser.add_option('-f',
388 '--force',
389 action='store_true',
390 help='Don\'t prompt for confirmation')
391
392 opt, args = parser.parse_args(args)
393
394 for p in opt.params:
395 assert '=' in p, '--param is key=value, not "%s"' % p
396 search_query = list(tuple(p.split('=', 1)) for p in opt.params)
397 if not any(t for t in search_query if t[0] == 'owner'):
398 # owner should always be present when abandoning changes
399 search_query.append(('owner', 'me'))
400 search_query.append(('status', 'open'))
401 logging.info("Searching for: %s" % search_query)
402
403 host = urlparse.urlparse(opt.host).netloc
404
405 result = gerrit_util.QueryChanges(
406 host,
407 search_query,
408 # abandon at most 100 changes as not all Gerrit instances support
409 # unlimited results.
410 limit=100,
411 )
412 if len(result) == 0:
413 logging.warn("Nothing to abandon")
414 return
415
416 logging.warn("%s CLs match search query: " % len(result))
417 for change in result:
418 logging.warn("[ID: %d] %s" % (change['_number'], change['subject']))
419
420 if not opt.force:
Josip Sokcevic284fbdd2021-10-08 18:26:30 +0000421 q = input(
Josip Sokcevice1a98942021-04-07 21:35:29 +0000422 'Do you want to move forward with abandoning? [y to confirm] ').strip()
423 if q not in ['y', 'Y']:
424 logging.warn("Aborting...")
425 return
426
427 for change in result:
428 logging.warning("Abandoning: %s" % change['subject'])
429 gerrit_util.AbandonChange(host, change['id'], opt.message)
430
431 logging.warning("Done")
432
433
dimu833c94c2017-01-18 17:36:15 -0800434class OptionParser(optparse.OptionParser):
435 """Creates the option parse and add --verbose support."""
436 def __init__(self, *args, **kwargs):
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000437 optparse.OptionParser.__init__(self, *args, version=__version__, **kwargs)
dimu833c94c2017-01-18 17:36:15 -0800438 self.add_option(
439 '--verbose', action='count', default=0,
440 help='Use 2 times for more debugging info')
441 self.add_option('--host', dest='host', help='Url of host.')
442 self.add_option('--project', dest='project', help='project name')
443 self.add_option(
444 '--json_file', dest='json_file', help='output json filepath')
445
446 def parse_args(self, args=None, values=None):
447 options, args = optparse.OptionParser.parse_args(self, args, values)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000448 # Host is always required
449 assert options.host, "--host not defined."
dimu833c94c2017-01-18 17:36:15 -0800450 levels = [logging.WARNING, logging.INFO, logging.DEBUG]
451 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
452 return options, args
453
454
455def main(argv):
456 if sys.hexversion < 0x02060000:
457 print('\nYour python version %s is unsupported, please upgrade.\n'
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000458 % (sys.version.split(' ', 1)[0],),
dimu833c94c2017-01-18 17:36:15 -0800459 file=sys.stderr)
460 return 2
461 dispatcher = subcommand.CommandDispatcher(__name__)
462 return dispatcher.execute(OptionParser(), argv)
463
464
465if __name__ == '__main__':
466 # These affect sys.stdout so do it outside of main() to simplify mocks in
467 # unit testing.
468 fix_encoding.fix_encoding()
469 setup_color.init()
470 try:
471 sys.exit(main(sys.argv[1:]))
472 except KeyboardInterrupt:
473 sys.stderr.write('interrupted\n')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200474 sys.exit(1)