Changed Rspec --> RSpec throughout.
[sfa.git] / sfa / client / 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 sfa.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 = """setRecord will edit a record (from stdin), modify its contents, then print the new record to stdout"""
27     parser = OptionParser(usage=usage,description=description)
28     parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
29         default=False,  help = "print debug info")
30    
31     return parser    
32
33
34 def editDict(args, recordDict, options):
35     """
36     Takes the arg list, seperates into tag/value, creates a dict, then munges args.
37     """
38     # find out if its iterable.
39     for vect in args:
40         if vect.count("+="):
41             # append value
42             modDict({vect.split("+=")[0]: returnVal(vect.split("+=")[1])},
43                          recordDict, options) 
44  
45         elif vect.count("="):
46             # reassign value
47             replaceDict({vect.split("=")[0]: returnVal("=".join(vect.split("=")[1:]))},
48                          recordDict, options) 
49         else:
50             if vect in recordDict:
51                 del recordDict[vect]
52             else:
53                 raise TypeError, "Argument error: Records are updated with \n" \
54                             "key=val1,val2,valN or\n" \
55                             "key+=val1,val2,valN \n%s Unknown key/val" % vect
56
57
58 def replaceDict(newval, recordDict, options):
59     """
60     Replaces field in dict
61     """
62     # Check type of old field matches type of new field
63     for (key, val) in newval.iteritems():
64         recordDict[key] = val
65
66 def modDict(newval, recordDict, options):
67     """
68     Checks type of existing field, addends new field
69     """
70     for (key, val) in newval.iteritems():
71         if (type(recordDict[key]) == list):
72             if (type(val) == list):
73                 recordDict[key] = recordDict[key] + val
74             else:
75                 recordDict[key].append(val)
76         elif type(val) == list:
77             val.append(recordDict[key])
78             recordDict[key] = val
79         else:
80             recordDict[key] = [recordDict[key], val]
81
82
83 def returnVal(arg):
84     """
85     if given input has ",", then its assumed to be a list.
86     """
87     if arg.count(","):
88         return list(arg.split(","))
89     else:
90         return arg
91
92 def main():
93     parser = create_parser(); 
94     (options, args) = parser.parse_args()
95
96     record = RecordSpec(xml = sys.stdin.read())
97
98     if args:
99         editDict(args, record.dict["record"], options)
100     if options.DEBUG:
101         print "New Record:\n%s" % record.dict
102         record.pprint()
103
104     record.parseDict(record.dict)
105     s = record.toxml()
106     sys.stdout.write(s)
107
108 if __name__ == '__main__':
109     try: main()
110     except Exception, e:
111         print e