24b2ac9004077dc268c2147850eb098649a4f308
[sfa.git] / cmdline / getRecord.py
1 #!/usr/bin/python
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 $Id$
11 $HeadURL$
12 """
13
14 import sys
15 import os
16 from optparse import OptionParser
17 from pprint import pprint
18
19 from geni.util.rspec import RecordSpec
20
21
22 def create_parser():
23     command = sys.argv[0]
24     argv = sys.argv[1:]
25     usage = "%(command)s [options]" % locals()
26     description = """getRecord will open a record file and print all key/values, or filter results based on a given key or set of keys."""
27     parser = OptionParser(usage=usage,description=description)
28     parser.add_option("-i", "--infile", dest="infile", metavar="FILE", 
29         default=None,  help = "record file path")
30     parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
31         default=False,  help = "record file path")
32    
33     return parser    
34
35 def findRoot(r, filter):
36     root = None
37     if type(r) == dict:
38         if not r.has_key(filter):
39             for k in r.keys():
40                 root = findRoot(r[k], filter)
41                 if root != None: return root
42         else:
43             return r[filter]
44     elif type(r) in (tuple, list):
45         for j in r: 
46             root = findRoot(j, filter)
47             if root != None: return root
48     else:
49         return root
50
51 def main():
52     parser = create_parser(); 
53     (options, args) = parser.parse_args()
54
55     # Check the the file was specified  
56     if not options.infile:
57         print "You must specify a record file"
58         return -1
59     try: 
60         print "Openning %s.\n" % options.infile
61         f = open(options.infile)
62     except: raise
63
64     record = RecordSpec(xml = f)
65
66     if options.DEBUG: 
67         pprint(record.dict)
68         print "#####################################################"
69
70
71     if args:
72         if options.DEBUG: 
73             print "Filtering on key: %s" % args[0]
74             pprint(findRoot(record.dict, args[0]))
75         record.pprint({args[0]: findRoot(record.dict, args[0])})
76     else:
77         record.pprint(record.dict)
78
79 if __name__ == '__main__':
80     try: main()
81     except Exception, e:
82         print e