a little nicer wrt pep8
[sfa.git] / clientbin / getRecord.py
1 #!/usr/bin/env python3
2
3 """
4 Filters/Prints record objects
5
6
7 faiyaza at cs dot princeton dot edu
8 Copyright (c) 2009 Board of Trustees, Princeton University
9
10 """
11
12 import sys
13 import os
14 from optparse import OptionParser
15 from pprint import pprint
16 from xml.parsers.expat import ExpatError
17 from sfa.util.xml import XML
18
19
20 def create_parser():
21     command = sys.argv[0]
22     argv = sys.argv[1:]
23     usage = "%(command)s [options]" % locals()
24     description = """getRecord will parse a supplied (via stdin) record and print all values or key/values, and filter results based on a given key or set of keys."""
25     parser = OptionParser(usage=usage, description=description)
26     parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
27                       default=False, help="record file path")
28     parser.add_option("-k", "--key", dest="withkey", action="store_true",
29                       default=False, help="print SSH keys and certificates")
30     parser.add_option("-p", "--plinfo", dest="plinfo", action="store_true",
31                       default=False, help="print PlanetLab specific internal fields")
32
33     return parser
34
35
36 def printRec(record_dict, filters, options):
37     line = ""
38     if len(filters):
39         for filter in filters:
40             if options.DEBUG:
41                 print("Filtering on %s" % filter)
42             line += "%s: %s\n" % (filter,
43                                   printVal(record_dict.get(filter, None)))
44         print(line)
45     else:
46         # print the wole thing
47         for (key, value) in record_dict.items():
48             if (not options.withkey and key in ('gid', 'keys')) or\
49                     (not options.plinfo and key == 'pl_info'):
50                 continue
51             line += "%s: %s\n" % (key, printVal(value))
52         print(line)
53
54
55 # fix the iteratable values
56 def printVal(value):
57     line = ""
58     if type(value) in (tuple, list):
59         for i in value:
60             line += "%s " % i
61     elif value != None:
62         line += value
63     return line.rstrip("\n")
64
65
66 def main():
67     parser = create_parser()
68     (options, args) = parser.parse_args()
69
70     stdin = sys.stdin.read()
71
72     record = XML(stdin)
73     record_dict = record.todict()
74
75     if options.DEBUG:
76         pprint(record.toxml())
77         print("#####################################################")
78
79     printRec(record_dict, args, options)
80
81 if __name__ == '__main__':
82     try:
83         main()
84     except ExpatError as e:
85         print("RecordError.  Is your record valid XML?")
86         print(e)
87     except Exception as e:
88         print(e)