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