blob: f2501f1ed8a7979dce0bc32fc75466822f51c3da [file] [log] [blame]
dimu833c94c2017-01-18 17:36:15 -08001#!/usr/bin/python
2# 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
19import urllib
20import urlparse
21
22from third_party import colorama
23import fix_encoding
24import gerrit_util
25import setup_color
26
27__version__ = '0.1'
28# Shortcut since it quickly becomes redundant.
29Fore = colorama.Fore
30
31
32def write_result(result, opt):
33 if opt.json_file:
34 with open(opt.json_file, 'w') as json_file:
35 json_file.write(json.dumps(result))
36
37
38@subcommand.usage('[args ...]')
39def CMDbranchinfo(parser, args):
40 parser.add_option('--branch', dest='branch', help='branch name')
41
42 (opt, args) = parser.parse_args(args)
43 host = urlparse.urlparse(opt.host).netloc
44 project = urllib.quote_plus(opt.project)
45 branch = urllib.quote_plus(opt.branch)
46 result = gerrit_util.GetGerritBranch(host, project, branch)
47 logging.info(result)
48 write_result(result, opt)
49
50@subcommand.usage('[args ...]')
51def CMDbranch(parser, args):
52 parser.add_option('--branch', dest='branch', help='branch name')
53 parser.add_option('--commit', dest='commit', help='commit hash')
54
55 (opt, args) = parser.parse_args(args)
56
57 project = urllib.quote_plus(opt.project)
58 host = urlparse.urlparse(opt.host).netloc
59 branch = urllib.quote_plus(opt.branch)
60 commit = urllib.quote_plus(opt.commit)
61 result = gerrit_util.CreateGerritBranch(host, project, branch, commit)
62 logging.info(result)
63 write_result(result, opt)
64
65
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020066@subcommand.usage('[args ...]')
67def CMDchanges(parser, args):
68 parser.add_option('-p', '--param', dest='params', action='append',
69 help='repeatable query parameter, format: -p key=value')
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +020070 parser.add_option('-o', '--o-param', dest='o_params', action='append',
71 help='gerrit output parameters, e.g. ALL_REVISIONS')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020072 parser.add_option('--limit', dest='limit', type=int,
73 help='maximum number of results to return')
74 parser.add_option('--start', dest='start', type=int,
75 help='how many changes to skip '
76 '(starting with the most recent)')
77
78 (opt, args) = parser.parse_args(args)
79
80 result = gerrit_util.QueryChanges(
81 urlparse.urlparse(opt.host).netloc,
82 list(tuple(p.split('=', 1)) for p in opt.params),
Paweł Hajdan, Jr24025d32017-07-11 16:38:21 +020083 start=opt.start, # Default: None
84 limit=opt.limit, # Default: None
85 o_params=opt.o_params, # Default: None
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020086 )
87 logging.info('Change query returned %d changes.', len(result))
88 write_result(result, opt)
89
90
dimu833c94c2017-01-18 17:36:15 -080091class OptionParser(optparse.OptionParser):
92 """Creates the option parse and add --verbose support."""
93 def __init__(self, *args, **kwargs):
94 optparse.OptionParser.__init__(
95 self, *args, prog='git cl', version=__version__, **kwargs)
96 self.add_option(
97 '--verbose', action='count', default=0,
98 help='Use 2 times for more debugging info')
99 self.add_option('--host', dest='host', help='Url of host.')
100 self.add_option('--project', dest='project', help='project name')
101 self.add_option(
102 '--json_file', dest='json_file', help='output json filepath')
103
104 def parse_args(self, args=None, values=None):
105 options, args = optparse.OptionParser.parse_args(self, args, values)
106 levels = [logging.WARNING, logging.INFO, logging.DEBUG]
107 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
108 return options, args
109
110
111def main(argv):
112 if sys.hexversion < 0x02060000:
113 print('\nYour python version %s is unsupported, please upgrade.\n'
114 %(sys.version.split(' ', 1)[0],),
115 file=sys.stderr)
116 return 2
117 dispatcher = subcommand.CommandDispatcher(__name__)
118 return dispatcher.execute(OptionParser(), argv)
119
120
121if __name__ == '__main__':
122 # These affect sys.stdout so do it outside of main() to simplify mocks in
123 # unit testing.
124 fix_encoding.fix_encoding()
125 setup_color.init()
126 try:
127 sys.exit(main(sys.argv[1:]))
128 except KeyboardInterrupt:
129 sys.stderr.write('interrupted\n')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200130 sys.exit(1)