support printing all or specified tags
[sfa.git] / cmdline / getNodes.py
1 #!/usr/bin/python
2
3 import sys
4 import os
5 from optparse import OptionParser
6 from pprint import pprint
7 from types import StringTypes
8 from geni.util.rspec import Rspec
9
10 def create_parser():
11     command = sys.argv[0]
12     argv = sys.argv[1:]
13     usage = "%(command)s [options]" % locals()
14     description = """getNodes will open a rspec file and print all key/values, or filter results based on a given key or set of keys."""
15     parser = OptionParser(usage=usage,description=description)
16     parser.add_option("-i", "--infile", dest="infile", default=None,  help = "record file path")
17     parser.add_option("-f", "--filter", dest="filter", default=None,  help = "record file path")
18     parser.add_option("-r", "--recursive", dest="recursive", default=False,  action="store_true", help = "record file path")
19    
20     return parser    
21
22 print 
23
24 def print_dict(rdict, counter=1):
25     lists = []
26     if not isinstance(rdict, dict):
27         raise "%s not a dict" % rdict 
28     for (key, value) in rdict.items():
29         if isinstance(value, StringTypes):
30             print "    " * counter + "%s: %s" % (key, value)
31         elif isinstance(value, list):
32             for listitem in value:
33                 if isinstance(listitem, dict):
34                     lists.append((key, listitem))
35         elif isinstance(value, dict):
36             lists.append((key, value)) 
37
38     for (key, listitem) in lists:
39         if isinstance(listitem, dict):
40             print "    " * (counter - 1) + key
41             print_dict(listitem, counter+1)   
42         
43
44 def main():
45     parser = create_parser(); 
46     (options, args) = parser.parse_args()
47
48     if not options.infile:
49         print "Rspec file not specified"
50         return 
51         
52     rspec = Rspec()
53     try:
54         rspec.parseFile(options.infile)
55     except:
56         print "Error reading rspec file"
57
58     if options.filter:
59         filter_name = options.filter
60         rspec_dicts = rspec.getDictsByTagName(options.filter)
61         rspec_dict = {filter_name: rspec_dicts}
62     else:
63         rspec_dict = rspec.toDict()     
64
65     print_dict(rspec_dict, options.recursive)
66
67     return
68
69 if __name__ == '__main__':
70     try: main()
71     except Exception, e:
72         raise
73         print e