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
23 usage = "%(command)s [options]" % locals()
24 description = """setRecord will edit a record (from stdin), modify its contents, then print the new record to stdout"""
25 parser = OptionParser(usage=usage, description=description)
26 parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
27 default=False, help="print debug info")
32 def editDict(args, recordDict, options):
34 Takes the arg list, seperates into tag/value, creates a dict, then munges args.
36 # find out if its iterable.
40 modDict({vect.split("+=")[0]: returnVal(vect.split("+=")[1])},
45 replaceDict({vect.split("=")[0]: returnVal("=".join(vect.split("=")[1:]))},
48 if vect in recordDict:
51 raise TypeError("Argument error: Records are updated with \n"
52 "key=val1,val2,valN or\n"
53 "key+=val1,val2,valN \n%s Unknown key/val" % vect)
56 def replaceDict(newval, recordDict, options):
58 Replaces field in dict
60 # Check type of old field matches type of new field
61 for (key, val) in newval.items():
65 def modDict(newval, recordDict, options):
67 Checks type of existing field, addends new field
69 for (key, val) in newval.items():
70 if (type(recordDict[key]) == list):
71 if (type(val) == list):
72 recordDict[key] = recordDict[key] + val
74 recordDict[key].append(val)
75 elif type(val) == list:
76 val.append(recordDict[key])
79 recordDict[key] = [recordDict[key], val]
84 if given input has ",", then its assumed to be a list.
87 return list(arg.split(","))
93 parser = create_parser()
94 (options, args) = parser.parse_args()
96 record = XML(sys.stdin.read())
97 record_dict = record.todict()
99 editDict(args, record_dict, options)
101 print("New Record:\n%s" % record_dict)
103 record.parse_dict(record_dict)
107 if __name__ == '__main__':
110 except Exception as e: