blob: 9e9082d250079e8f9ea98e1d9589a596b4d57dd3 [file] [log] [blame]
Josip Sokcevic848a5362021-03-22 22:58:00 +00001#!/usr/bin/env python
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:
9 ./gerrit_client.py [command] [args]""
10"""
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):
42 parser.add_option('-p', '--param', dest='params', action='append',
43 help='repeatable query parameter, format: -p key=value')
44 parser.add_option('--destination_branch', dest='destination_branch',
45 help='where to move changes to')
46
47 (opt, args) = parser.parse_args(args)
48 assert opt.destination_branch, "--destination_branch not defined"
Mike Frysinger8820ab82020-11-25 00:52:31 +000049 for p in opt.params:
50 assert '=' in p, '--param is key=value, not "%s"' % p
Josip Sokcevicc39ab992020-09-24 20:09:15 +000051 host = urlparse.urlparse(opt.host).netloc
52
53 limit = 100
54 while True:
55 result = gerrit_util.QueryChanges(
56 host,
57 list(tuple(p.split('=', 1)) for p in opt.params),
58 limit=limit,
59 )
60 for change in result:
61 gerrit_util.MoveChange(host, change['id'], opt.destination_branch)
62
63 if len(result) < limit:
64 break
65 logging.info("Done")
66
67
68@subcommand.usage('[args ...]')
dimu833c94c2017-01-18 17:36:15 -080069def CMDbranchinfo(parser, args):
70 parser.add_option('--branch', dest='branch', help='branch name')
71
72 (opt, args) = parser.parse_args(args)
73 host = urlparse.urlparse(opt.host).netloc
Josip Sokcevicc99efb22020-03-17 00:35:34 +000074 project = quote_plus(opt.project)
75 branch = quote_plus(opt.branch)
dimu833c94c2017-01-18 17:36:15 -080076 result = gerrit_util.GetGerritBranch(host, project, branch)
77 logging.info(result)
78 write_result(result, opt)
79
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000080
dimu833c94c2017-01-18 17:36:15 -080081@subcommand.usage('[args ...]')
82def CMDbranch(parser, args):
83 parser.add_option('--branch', dest='branch', help='branch name')
84 parser.add_option('--commit', dest='commit', help='commit hash')
85
86 (opt, args) = parser.parse_args(args)
Josip Sokcevicc99efb22020-03-17 00:35:34 +000087 assert opt.project, "--project not defined"
88 assert opt.branch, "--branch not defined"
89 assert opt.commit, "--commit not defined"
dimu833c94c2017-01-18 17:36:15 -080090
Josip Sokcevicc99efb22020-03-17 00:35:34 +000091 project = quote_plus(opt.project)
dimu833c94c2017-01-18 17:36:15 -080092 host = urlparse.urlparse(opt.host).netloc
Josip Sokcevicc99efb22020-03-17 00:35:34 +000093 branch = quote_plus(opt.branch)
94 commit = quote_plus(opt.commit)
dimu833c94c2017-01-18 17:36:15 -080095 result = gerrit_util.CreateGerritBranch(host, project, branch, commit)
96 logging.info(result)
97 write_result(result, opt)
98
99
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200100@subcommand.usage('[args ...]')
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000101def CMDhead(parser, args):
102 parser.add_option('--branch', dest='branch', help='branch name')
103
104 (opt, args) = parser.parse_args(args)
105 assert opt.project, "--project not defined"
106 assert opt.branch, "--branch not defined"
107
108 project = quote_plus(opt.project)
109 host = urlparse.urlparse(opt.host).netloc
110 branch = quote_plus(opt.branch)
111 result = gerrit_util.UpdateHead(host, project, branch)
112 logging.info(result)
113 write_result(result, opt)
114
115
116@subcommand.usage('[args ...]')
117def CMDheadinfo(parser, args):
118
119 (opt, args) = parser.parse_args(args)
120 assert opt.project, "--project not defined"
121
122 project = quote_plus(opt.project)
123 host = urlparse.urlparse(opt.host).netloc
124 result = gerrit_util.GetHead(host, project)
125 logging.info(result)
126 write_result(result, opt)
127
128
129@subcommand.usage('[args ...]')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200130def CMDchanges(parser, args):
131 parser.add_option('-p', '--param', dest='params', action='append',
132 help='repeatable query parameter, format: -p key=value')
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +0200133 parser.add_option('-o', '--o-param', dest='o_params', action='append',
134 help='gerrit output parameters, e.g. ALL_REVISIONS')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200135 parser.add_option('--limit', dest='limit', type=int,
136 help='maximum number of results to return')
137 parser.add_option('--start', dest='start', type=int,
138 help='how many changes to skip '
139 '(starting with the most recent)')
140
141 (opt, args) = parser.parse_args(args)
Mike Frysinger8820ab82020-11-25 00:52:31 +0000142 for p in opt.params:
143 assert '=' in p, '--param is key=value, not "%s"' % p
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200144
145 result = gerrit_util.QueryChanges(
146 urlparse.urlparse(opt.host).netloc,
147 list(tuple(p.split('=', 1)) for p in opt.params),
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +0200148 start=opt.start, # Default: None
149 limit=opt.limit, # Default: None
150 o_params=opt.o_params, # Default: None
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200151 )
152 logging.info('Change query returned %d changes.', len(result))
153 write_result(result, opt)
154
155
LaMont Jones9eed4232021-04-02 16:29:49 +0000156@subcommand.usage('[args ...]')
157def CMDcreatechange(parser, args):
158 parser.add_option('-s', '--subject', help='subject for change')
159 parser.add_option('-b',
160 '--branch',
161 default='main',
162 help='target branch for change')
163 parser.add_option(
164 '-p',
165 '--param',
166 dest='params',
167 action='append',
168 help='repeatable field value parameter, format: -p key=value')
169
170 (opt, args) = parser.parse_args(args)
171 for p in opt.params:
172 assert '=' in p, '--param is key=value, not "%s"' % p
173
174 result = gerrit_util.CreateChange(
175 urlparse.urlparse(opt.host).netloc,
176 opt.project,
177 branch=opt.branch,
178 subject=opt.subject,
179 params=list(tuple(p.split('=', 1)) for p in opt.params),
180 )
181 logging.info(result)
182 write_result(result, opt)
183
184
185@subcommand.usage('[args ...]')
186def CMDchangeedit(parser, args):
187 parser.add_option('-c', '--change', type=int, help='change number')
188 parser.add_option('--path', help='path for file')
189 parser.add_option('--file', help='file to place at |path|')
190
191 (opt, args) = parser.parse_args(args)
192
193 with open(opt.file) as f:
194 data = f.read()
195 result = gerrit_util.ChangeEdit(
196 urlparse.urlparse(opt.host).netloc, opt.change, opt.path, data)
197 logging.info(result)
198 write_result(result, opt)
199
200
201@subcommand.usage('[args ...]')
202def CMDpublishchangeedit(parser, args):
203 parser.add_option('-c', '--change', type=int, help='change number')
204 parser.add_option('--notify', help='whether to notify')
205
206 (opt, args) = parser.parse_args(args)
207
208 result = gerrit_util.PublishChangeEdit(
209 urlparse.urlparse(opt.host).netloc, opt.change, opt.notify)
210 logging.info(result)
211 write_result(result, opt)
212
213
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000214@subcommand.usage('')
215def CMDabandon(parser, args):
216 parser.add_option('-c', '--change', type=int, help='change number')
217 parser.add_option('-m', '--message', default='', help='reason for abandoning')
218
219 (opt, args) = parser.parse_args(args)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000220 assert opt.change, "-c not defined"
Sergiy Belozorovfe347232019-02-27 15:07:33 +0000221 result = gerrit_util.AbandonChange(
222 urlparse.urlparse(opt.host).netloc,
223 opt.change, opt.message)
224 logging.info(result)
225 write_result(result, opt)
226
227
Josip Sokcevice1a98942021-04-07 21:35:29 +0000228@subcommand.usage('''Mass abandon changes
229
230Mass abandon abandons CLs that match search criteria provided by user. Before
231any change is actually abandoned, user is presented with a list of CLs that
232will be affected if user confirms. User can skip confirmation by passing --force
233parameter.
234
235The script can abandon up to 100 CLs per invocation.
236
237Examples:
238gerrit_client.py mass-abandon --host https://HOST -p 'project=repo2'
239gerrit_client.py mass-abandon --host https://HOST -p 'message=testing'
Josip Sokcevicf5c6d8a2021-05-12 18:23:24 +0000240gerrit_client.py mass-abandon --host https://HOST -p 'is=wip' -p 'age=1y'
Josip Sokcevice1a98942021-04-07 21:35:29 +0000241''')
242def CMDmass_abandon(parser, args):
243 parser.add_option('-p',
244 '--param',
245 dest='params',
246 action='append',
247 default=[],
248 help='repeatable query parameter, format: -p key=value')
249 parser.add_option('-m', '--message', default='', help='reason for abandoning')
250 parser.add_option('-f',
251 '--force',
252 action='store_true',
253 help='Don\'t prompt for confirmation')
254
255 opt, args = parser.parse_args(args)
256
257 for p in opt.params:
258 assert '=' in p, '--param is key=value, not "%s"' % p
259 search_query = list(tuple(p.split('=', 1)) for p in opt.params)
260 if not any(t for t in search_query if t[0] == 'owner'):
261 # owner should always be present when abandoning changes
262 search_query.append(('owner', 'me'))
263 search_query.append(('status', 'open'))
264 logging.info("Searching for: %s" % search_query)
265
266 host = urlparse.urlparse(opt.host).netloc
267
268 result = gerrit_util.QueryChanges(
269 host,
270 search_query,
271 # abandon at most 100 changes as not all Gerrit instances support
272 # unlimited results.
273 limit=100,
274 )
275 if len(result) == 0:
276 logging.warn("Nothing to abandon")
277 return
278
279 logging.warn("%s CLs match search query: " % len(result))
280 for change in result:
281 logging.warn("[ID: %d] %s" % (change['_number'], change['subject']))
282
283 if not opt.force:
284 q = raw_input(
285 'Do you want to move forward with abandoning? [y to confirm] ').strip()
286 if q not in ['y', 'Y']:
287 logging.warn("Aborting...")
288 return
289
290 for change in result:
291 logging.warning("Abandoning: %s" % change['subject'])
292 gerrit_util.AbandonChange(host, change['id'], opt.message)
293
294 logging.warning("Done")
295
296
dimu833c94c2017-01-18 17:36:15 -0800297class OptionParser(optparse.OptionParser):
298 """Creates the option parse and add --verbose support."""
299 def __init__(self, *args, **kwargs):
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000300 optparse.OptionParser.__init__(self, *args, version=__version__, **kwargs)
dimu833c94c2017-01-18 17:36:15 -0800301 self.add_option(
302 '--verbose', action='count', default=0,
303 help='Use 2 times for more debugging info')
304 self.add_option('--host', dest='host', help='Url of host.')
305 self.add_option('--project', dest='project', help='project name')
306 self.add_option(
307 '--json_file', dest='json_file', help='output json filepath')
308
309 def parse_args(self, args=None, values=None):
310 options, args = optparse.OptionParser.parse_args(self, args, values)
Josip Sokcevicc99efb22020-03-17 00:35:34 +0000311 # Host is always required
312 assert options.host, "--host not defined."
dimu833c94c2017-01-18 17:36:15 -0800313 levels = [logging.WARNING, logging.INFO, logging.DEBUG]
314 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
315 return options, args
316
317
318def main(argv):
319 if sys.hexversion < 0x02060000:
320 print('\nYour python version %s is unsupported, please upgrade.\n'
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000321 % (sys.version.split(' ', 1)[0],),
dimu833c94c2017-01-18 17:36:15 -0800322 file=sys.stderr)
323 return 2
324 dispatcher = subcommand.CommandDispatcher(__name__)
325 return dispatcher.execute(OptionParser(), argv)
326
327
328if __name__ == '__main__':
329 # These affect sys.stdout so do it outside of main() to simplify mocks in
330 # unit testing.
331 fix_encoding.fix_encoding()
332 setup_color.init()
333 try:
334 sys.exit(main(sys.argv[1:]))
335 except KeyboardInterrupt:
336 sys.stderr.write('interrupted\n')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200337 sys.exit(1)