fix help
[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 = "input rspec file")
17     parser.add_option("-f", "--filter", dest="filter", default=None,  help = "filter rspec for this tag")
18     parser.add_option("-r", "--recursive", dest="print_children", default=False,  action="store_true", help = "print the tag's child nodes")
19    
20     return parser    
21
22 print 
23
24 def print_dict(rdict, print_children, counter=1):
25     lists = []
26     tab = "    "
27     if not isinstance(rdict, dict):
28         raise "%s not a dict" % rdict 
29     for (key, value) in rdict.items():
30         if isinstance(value, StringTypes):
31             print tab * counter + "%s: %s" % (key, value)
32         elif isinstance(value, list):
33             for listitem in value:
34                 if isinstance(listitem, dict):
35                     lists.append((key, listitem))
36         elif isinstance(value, dict):
37             lists.append((key, value)) 
38     
39     if counter == 1 or print_children: 
40         for (key, listitem) in lists:
41             if isinstance(listitem, dict):
42                 print tab * (counter - 1) + key
43                 print_dict(listitem, print_children, counter+1)
44     else:
45         keys = set([key for (key, listitem) in lists])
46         if keys: print tab * (counter) + "(children: %s)" % (",".join(keys))    
47         
48
49 def main():
50     parser = create_parser(); 
51     (options, args) = parser.parse_args()
52
53     if not options.infile:
54         print "Rspec file not specified"
55         return 
56         
57     rspec = Rspec()
58     try:
59         rspec.parseFile(options.infile)
60     except:
61         print "Error reading rspec file"
62
63     if options.filter:
64         filter_name = options.filter
65         rspec_dicts = rspec.getDictsByTagName(options.filter)
66         rspec_dict = {filter_name: rspec_dicts}
67     else:
68         rspec_dict = rspec.toDict()     
69     
70     print_dict(rspec_dict, options.print_children)
71
72     return
73
74 if __name__ == '__main__':
75     try: main()
76     except Exception, e:
77         raise
78         print e