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