1 | #!/usr/bin/python |
---|
2 | """qy: A scriptable, command-line Moira client.""" |
---|
3 | |
---|
4 | import optparse |
---|
5 | |
---|
6 | import moira |
---|
7 | |
---|
8 | |
---|
9 | def parser(): |
---|
10 | p = optparse.OptionParser(usage='Usage: %prog [options] query args...') |
---|
11 | p.add_option('--db', '--database', |
---|
12 | dest='database', |
---|
13 | default='', |
---|
14 | help='Host and port of the Moira database to contact') |
---|
15 | p.add_option('-n', '--noauth', |
---|
16 | dest='auth', |
---|
17 | action='store_false', |
---|
18 | default=True, |
---|
19 | help="Don't use Kerberos authentication") |
---|
20 | p.add_option('-p', '--program', |
---|
21 | dest='program', |
---|
22 | default='pyqy', |
---|
23 | help='Program name to use when identifying to the Moira database') |
---|
24 | p.add_option('-s', '--single', |
---|
25 | dest='single', |
---|
26 | action='store_true', |
---|
27 | default=False, |
---|
28 | help='Print each result on a single line') |
---|
29 | p.add_option('-f', '--fields', |
---|
30 | dest='fields', |
---|
31 | help='Only print out values from this list of comma-separated fields') |
---|
32 | |
---|
33 | return p |
---|
34 | |
---|
35 | |
---|
36 | def filter_fields(result, fields): |
---|
37 | return [(k, v) for (k, v) in result if \ |
---|
38 | not fields or k in fields] |
---|
39 | |
---|
40 | |
---|
41 | def main(): |
---|
42 | p = parser() |
---|
43 | options, args = p.parse_args() |
---|
44 | |
---|
45 | if len(args) < 1: |
---|
46 | p.error('No query specified.') |
---|
47 | |
---|
48 | if options.fields: |
---|
49 | options.fields = set(options.fields.split(',')) |
---|
50 | |
---|
51 | moira.connect(options.database) |
---|
52 | if options.auth: |
---|
53 | moira.auth(options.program) |
---|
54 | |
---|
55 | if args[0].startswith('_'): |
---|
56 | print '\n'.join(', '.join(x) for x in |
---|
57 | moira._list_query(*args)) |
---|
58 | else: |
---|
59 | results = moira.query(fmt=tuple, *args) |
---|
60 | |
---|
61 | for r in results: |
---|
62 | keylen = max(len(k) for (k, v) in r) |
---|
63 | r = filter_fields(r, options.fields) |
---|
64 | |
---|
65 | if options.single: |
---|
66 | print ', '.join(v for (k, v) in r) |
---|
67 | else: |
---|
68 | for k, v in r: |
---|
69 | print '%-*s: %s' % (keylen, k, v) |
---|
70 | print |
---|
71 | |
---|
72 | if __name__ == '__main__': |
---|
73 | main() |
---|