correction node_ids
[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 printRecord(r, depth = 0):
36     line = ""
37     # Set the dept
38     for tab in range(0,depth): line += "    "
39     # check if it's nested
40     if type(r) == dict:
41         for i in r.keys(): 
42             print line + "%s:" % i
43             printRecord(r[i], depth + 1)
44     elif type(r) in (tuple, list):
45         for j in r: printRecord(j, depth + 1)
46     # not nested so just print.
47     else:
48         print line + "%s" %  r
49
50
51 def findRoot(r, filter):
52     root = None
53     if type(r) == dict:
54         if not r.has_key(filter):
55             for k in r.keys():
56                 root = findRoot(r[k], filter)
57                 if root != None: return root
58         else:
59             return r[filter]
60     elif type(r) in (tuple, list):
61         for j in r: 
62             root = findRoot(j, filter)
63             if root != None: return root
64     else:
65         return root
66
67 def main():
68     parser = create_parser(); 
69     (options, args) = parser.parse_args()
70
71     # Check the the file was specified  
72     if not options.infile:
73         print "You must specify a record file"
74         return -1
75     try: 
76         print "Openning %s.\n" % options.infile
77         f = open(options.infile)
78     except: raise
79
80     record = RecordSpec(xml = f)
81
82     if options.DEBUG: 
83         pprint(record.dict)
84         print "#####################################################"
85
86
87     if args:
88         if options.DEBUG: 
89             print "Filtering on key: %s" % args[0]
90             pprint(findRoot(record.dict, args[0]))
91         printRecord({args[0]: findRoot(record.dict, args[0])})
92     else:
93         printRecord(record.dict)
94
95 if __name__ == '__main__':
96     try: main()
97     except Exception, e:
98         print e