-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgsshcli.py
More file actions
executable file
·239 lines (194 loc) · 8.51 KB
/
gsshcli.py
File metadata and controls
executable file
·239 lines (194 loc) · 8.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/env python
# encoding: utf-8
'''
Simple CLI script to use gerritssh to talk to a site
This is a simple script intended to be used in testing gerritssh against
live Gerrit instances (instead of the mock ones used in the unit tests).
'''
import sys
import logging
import argparse
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
import gerritssh as gssh
__all__ = []
__version__ = gssh.__version__
######################################################################
#
# Set up the root logger so that log statements in the library will
# actually display. Without a StreamHandler(), the NullHandler in the
# library simply swallows all the logs.
#
######################################################################
log = logging.getLogger()
_handler = logging.StreamHandler()
_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
log.addHandler(_handler)
################################################################
#
# The following functions actually demonstrate using the library
#
################################################################
def connect_to_site(site):
''' Connect to the specified site '''
return gssh.Site(site).connect()
def version_cmd(site, args):
''' Print the version of Gerrit running on the connected Site '''
log.debug('Version command called with args: ' + str(args))
vstr = str(site.version)
print('{0} is running version {1} of Gerrit'.format(site.site,
vstr))
return 0
def reconstitute(args):
res = []
for key, value in args.__dict__.items():
if key in ['help', 'verbose', 'site', 'operation']:
continue
if not value:
continue
keystr = '--' + key.replace('_', '-')
if value == True:
res.append(keystr)
elif isinstance(value, list):
allf = [' '.join([keystr, str(v)]) for v in value]
res.append(' '.join(allf))
else:
res.append(' '.join([keystr, str(value)]))
return ' '.join(res).strip()
def query_cmd(site, args):
'''
Execute the query command and print out the results
grouped by project and ordered by change number.
'''
b = 'branch:{0}'.format(args.branch) if args.branch else ''
p = 'project:{0}'.format(args.project) if args.project else ''
s = 'status:{0}'.format(args.qstatus) if args.qstatus else ''
q = ' '.join(args.querystring) if args.querystring else ''
qry = gssh.Query('', ' '.join([b, p, s, q]),
max_results=args.maxresults or 0)
log.debug('Executing query command {0} on {1}'.format(qry._Query__query,
site.site))
qry.execute_on(site)
last_project = ''
for r in sorted(qry, key=lambda rvw: ' '.join([rvw.project, rvw.ref])):
if r.project != last_project:
print('\n{0}:'.format(r.project))
last_project = r.project
print('\t({0})\t{1}'.format(r.ref, r.summary))
return 0
def lp_cmd(site, args):
''' List the projects on the connected Site '''
lp = gssh.ProjectList(reconstitute(args))
lp.execute_on(site)
for p in lp:
print(p)
return 0
def execute(args):
try:
site = connect_to_site(args.site)
except gssh.SSHConnectionError as e:
print(e)
sys.exit(1)
log.debug('Connected Successfully')
cmds = {'query': query_cmd,
'projects': lp_cmd,
'version': version_cmd}
cmds[args.operation](site, args)
return 0
################################################################
#
# The rest of the file is all about parsing the command line
#
################################################################
class CLIError(Exception):
'''Generic exception to raise and log different fatal errors.'''
def __init__(self, msg):
super(CLIError).__init__(type(self))
self.msg = "E: %s" % msg
def __str__(self):
return self.msg
def __unicode__(self):
return self.msg
def parse_command_line():
program_version = "v%s" % __version__
program_license = '''
Copyright 2014 Keith Derrick. All rights reserved.
Licensed under the Apache License 2.0
http://www.apache.org/licenses/LICENSE-2.0
Distributed on an "AS IS" basis without warranties
or conditions of any kind, either express or implied.
'''
program_version_message = '%%(prog)s %s\n\n%s' % (program_version,
program_license)
program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
# Setup argument parser
parser = ArgumentParser(description=program_shortdesc,
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("-v", "--verbose", dest="verbose", action="count",
help="set verbosity level [default: %(default)s]")
parser.add_argument('-V', '--version', action='version',
version=program_version_message)
subparsers = parser.add_subparsers(dest='operation')
subparsers.required = True
lp_parser = subparsers.add_parser('projects',
help='List the projects')
lp_parser.add_argument('site',
help=('The Gerrit instance to connect to, '
'e.g review.openstack,org'))
lp_parser.add_argument('-a', '--all', dest='listall',
action='store_true', default=False,
help='List all project types')
lp_parser.add_argument('-b', '--show-branch', dest='show_branch',
action='append',
help='Show SHA for head of branch')
lp_parser.add_argument('--type', choices=['code', 'permissions', 'all'],
help='Restrict the type of projects returned')
lp_parser.add_argument('--format',
choices=['json', 'text', 'json_compact'],
help='specify the return type for the command')
lp_parser.add_argument('--limit', dest='limit', action='store', nargs=1,
help='Limit the number of projects returned')
lp_parser.add_argument('--has-acl-for', action='store', dest='has_acl_for',
help='Only show projects with ACL for named group')
g = lp_parser.add_mutually_exclusive_group()
g.add_argument('-d', '--description',
action='store_true', default=False,
help='Return the project description')
g.add_argument('-t', '--tree', action='store_true',
help='Display project inheritance')
query_parser = subparsers.add_parser('query',
help='Search for reviews')
query_parser.add_argument('site',
help=('The Gerrit instance to connect to, '
'e.g review.openstack,org'))
query_parser.add_argument('-s', '--status', dest='qstatus',
choices=['open', 'merged', 'abandoned'],
help='Find all reviews with he given status')
query_parser.add_argument('-b', '--branch', dest='branch',
help='Restrict search to a given branch')
query_parser.add_argument('-l', '--limit', dest='maxresults',
type=int,
help='Limit the number of results')
query_parser.add_argument('-p', '--project', dest='project',
help='Project for which reviews are required')
# query_parser.add_argument('--', dest='query string',
# help='Standard query options and flags')
query_parser.add_argument('querystring', metavar='QUERY',
nargs=argparse.REMAINDER)
v_parser = subparsers.add_parser('version', help='Show the Gerrit version')
v_parser.add_argument('site',
help=('The Gerrit instance to connect to, '
'e.g review.openstack,org'))
# Process arguments
args = parser.parse_args()
# Set the logging level
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
verbose = args.verbose or 0
log.setLevel(levels[max(min(verbose, 2), 0)])
log.debug('parser results: {0}'.format(args))
return args
if __name__ == "__main__":
args = parse_command_line()
log.debug(args)
log.debug(reconstitute(args))
execute(args)