7 faiyaza at cs dot princeton dot edu
8 Copyright (c) 2009 Board of Trustees, Princeton University
15 from optparse import OptionParser
16 from pprint import pprint
17 from sfa.util.xml import XML
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")
31 def editDict(args, recordDict, options):
33 Takes the arg list, seperates into tag/value, creates a dict, then munges args.
35 # find out if its iterable.
39 modDict({vect.split("+=")[0]: returnVal(vect.split("+=")[1])},
44 replaceDict({vect.split("=")[0]: returnVal("=".join(vect.split("=")[1:]))},
47 if vect in recordDict:
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
55 def replaceDict(newval, recordDict, options):
57 Replaces field in dict
59 # Check type of old field matches type of new field
60 for (key, val) in newval.iteritems():
63 def modDict(newval, recordDict, options):
65 Checks type of existing field, addends new field
67 for (key, val) in newval.iteritems():
68 if (type(recordDict[key]) == list):
69 if (type(val) == list):
70 recordDict[key] = recordDict[key] + val
72 recordDict[key].append(val)
73 elif type(val) == list:
74 val.append(recordDict[key])
77 recordDict[key] = [recordDict[key], val]
82 if given input has ",", then its assumed to be a list.
85 return list(arg.split(","))
90 parser = create_parser();
91 (options, args) = parser.parse_args()
93 record = XML(sys.stdin.read())
94 record_dict = record.todict()
96 editDict(args, record_dict, options)
98 print "New Record:\n%s" % record_dict
100 record.parse_dict(record_dict)
104 if __name__ == '__main__':