a little nicer wrt pep8
[sfa.git] / clientbin / setRecord.py
1 #!/usr/bin/env python3
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 from sfa.util.xml import XML
18
19
20 def create_parser():
21     command = sys.argv[0]
22     argv = sys.argv[1:]
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")
28
29     return parser
30
31
32 def editDict(args, recordDict, options):
33     """
34     Takes the arg list, seperates into tag/value, creates a dict, then munges args.
35     """
36     # find out if its iterable.
37     for vect in args:
38         if vect.count("+="):
39             # append value
40             modDict({vect.split("+=")[0]: returnVal(vect.split("+=")[1])},
41                     recordDict, options)
42
43         elif vect.count("="):
44             # reassign value
45             replaceDict({vect.split("=")[0]: returnVal("=".join(vect.split("=")[1:]))},
46                         recordDict, options)
47         else:
48             if vect in recordDict:
49                 del recordDict[vect]
50             else:
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)
54
55
56 def replaceDict(newval, recordDict, options):
57     """
58     Replaces field in dict
59     """
60     # Check type of old field matches type of new field
61     for (key, val) in newval.items():
62         recordDict[key] = val
63
64
65 def modDict(newval, recordDict, options):
66     """
67     Checks type of existing field, addends new field
68     """
69     for (key, val) in newval.items():
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
92 def main():
93     parser = create_parser()
94     (options, args) = parser.parse_args()
95
96     record = XML(sys.stdin.read())
97     record_dict = record.todict()
98     if args:
99         editDict(args, record_dict, options)
100     if options.DEBUG:
101         print("New Record:\n%s" % record_dict)
102
103     record.parse_dict(record_dict)
104     s = record.toxml()
105     sys.stdout.write(s)
106
107 if __name__ == '__main__':
108     try:
109         main()
110     except Exception as e:
111         print(e)