Initial commit.
[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     for i in r.keys(): 
41         if type(r[i]) == dict:
42             # print the parent, carry return
43             print line + "%s :\n" % i
44             #recurse here, increment depth
45             printRecord(r[i], depth + 1)
46         else:
47             #assume we've hit the bottom
48             if (type(r[i]) == tuple) or (type(r[i]) == list):
49                 print line + " %s:" % i
50                 for j in r[i]:
51                     if type(j) == dict:
52                         printRecord(j, depth + 2)
53                     else: print line + line + " %s" % j
54             else:
55                 print line + " %s:    %s" % (i, r[i])
56
57 def main():
58     parser = create_parser(); 
59     (options, args) = parser.parse_args()
60
61     # Check the the file was specified  
62     if not options.infile:
63         print "You must specify a record file"
64         return -1
65     else:
66         try: 
67             record = RecordSpec()
68             print "Openning %s.\n" % options.infile
69             record.parseFile(options.infile)
70         except: raise 
71         record.dict = record.toDict()
72
73         if args:
74             print "Filtering on key: %s" % args
75
76         if options.DEBUG: 
77             pprint(record.dict)
78             print "#####################################################"
79
80         else:
81             printRecord(record.dict)
82
83 if __name__ == '__main__':
84     main()
85     #try: main()
86     #except Exception, e:
87     #    print e