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