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