5 key_pattern = re.compile("\A[A-Za-z0-9_-]+\Z")
7 class MoeInvalidStatusFile(Exception):
12 (One subtree of) Moe status file.
18 def __getitem__(self, k):
21 def __setitem__(self, k, v):
27 def update(self, stat2):
29 Updates values of `self` with values of `stat2`, recursively.
31 Directly references objects (values and subtrees) of `stat2`, so making a deep copy of `stat2`
32 may be necessary if you intend to modify `stat2` afterwards.
35 for k,v2 in stat2.d.items():
40 if isinstance(v, Status) != isinstance(v2, Status):
41 raise TypeError("Mixing Status and value while updating key %r"%k)
42 if isinstance(v, Status):
47 def dump(self, prefix=""):
49 Dump Status in status file format.
50 Returns a list of lines, ``prefix`` is indentation prefix.
54 for k,v in self.d.items():
55 if isinstance(v, Status):
56 l.append(prefix + k + " (")
57 l.extend(self.dump(prefix+" "))
58 l.append(prefix + ")")
60 d = str(v).split('\n')
61 l.append(prefix + k + ":" + d[0])
63 l.append(prefix + ' '*len(k) + ':' + i)
66 def write(self, f=None, name=None):
68 Write Status to File ``f`` or overwrite file ``name`` or write to ``stdout`` (otherwise).
71 if not f and name is not None:
72 with open(name, "w") as f:
81 def read(self, f=None, name=None):
83 Parse Status from File ``f`` or from file ``name`` or from ``stdin`` (otherwise)
84 Deletes all contents of the Status.
88 if not f and name is not None:
89 with open(name, 'r') as f:
96 def read_val(self, k, v):
98 Internal: Safely add a new value
101 if not key_pattern.match(k):
102 raise MoeInvalidStatusFile("Parse error: invalid key %r"%k)
104 raise MoeInvalidStatusFile("Multiple occurences of key %r"%k)
107 def do_read(self, f):
109 Internal: Parse an open file
114 for x in f.readlines():
115 x = x.rstrip("\n").lstrip(" \t")
116 if x=="" or x.startswith("#"):
121 k = x[:sep].rstrip(" \t")
124 elif x.endswith("("):
125 k = x[:-1].rstrip(" \t")
127 this.read_val(k, new)
132 raise MoeInvalidStatusFile("Parse error: incorrect nesting")
136 raise MoeInvalidStatusFile("Parse error: malformed line")