dont print child node/tags by default
[sfa.git] / cmdline / setRecord.py
1 #!/usr/bin/python
2
3 """
4 Updates 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
36 def editDict(replacewith, recordDict, options):
37     # first we find the part of the tree we want to replace
38     # and check it exists.
39     for (key, val) in replacewith.items():
40         if not recordDict.has_key(key):
41             print "Cannot find key %s in record %s.  Adding new key."\
42                  % (key, options.infile)
43         else:
44             print "Replacing %s = %s with %s\n" % (key, recordDict[key], val)
45         recordDict[key] = val
46    
47
48 def patchDict(args):
49     """
50     Takes the arg list, seperates into tag/value, creates a dict.
51     """
52     patch = {}
53     for vect in args:
54         if vect.count("="):
55             patch[vect.split("=")[0]] = vect.split("=")[1]
56         else:
57             raise TypeError, "Argument error: Records are updated with key=val\n" \
58                             "%s Unknown key/val" % vect
59     return patch
60
61
62 def main():
63     parser = create_parser(); 
64     (options, args) = parser.parse_args()
65
66     # Check the the file was specified  
67     if not options.infile:
68         print "You must specify a record file"
69         return -1
70     try: 
71         print "Openning %s.\n" % options.infile
72         f = open(options.infile)
73         record = RecordSpec(xml = f)
74         f.close()
75     except: raise
76
77
78     if args:
79         patch = patchDict(args)
80         if options.DEBUG:  print "Replace w/ %s" %  patch
81         editDict(patch, record.dict["record"], options)
82     if options.DEBUG:
83         print "New Record:\n%s" % record.dict
84
85     record.pprint()
86
87     record.rootNode = record.dict2dom(record.dict)
88     s = record.toxml()
89     f = open(options.infile,"w")
90     f.write(s)
91
92 if __name__ == '__main__':
93     try: main()
94     except Exception, e:
95         print e