7 key_pattern = re.compile("^[A-Za-z0-9_-]+$")
9 class MoeStatusInvalid(Exception):
13 """Moe status file."""
18 def __getitem__(self, k):
19 if not self.stat.has_key(k): return None
21 if type(v) == types.ListType:
22 if len(v) > 0: return v[0]
26 def __setitem__(self, k, v):
30 return self.stat.keys()
32 def get_list(self, k):
36 elif type(m[k]) != types.ListType:
40 def str_lines(self, indent=""):
41 "Return a list of lines, `indent` is indent prefix."
43 for k,v in self.stat.items():
44 if type(v) == types.ListType: vals = v
47 if isinstance(w, MoeStatus):
48 l.append("\t" * indent + k + "(\n")
49 l.extend(self.str_lines(indent+" "))
50 l.append("\t" * indent + ")\n")
52 l.append("\t" * indent + k + ":" + str(w) + "\n")
55 def write(self, file=None, name=None):
58 file = open(name, "w")
61 self.write_nested(file, 0)
63 def write_nested(self, file, indent):
64 for k,v in self.stat.items():
65 if type(v) == types.ListType: vals = v
68 if isinstance(w, MoeStatus):
69 file.write("\t" * indent + k + "(\n")
70 w.write_nested(file, indent+1);
71 file.write("\t" * indent + ")\n")
73 file.write("\t" * indent + k + ":" + str(w) + "\n")
75 def read(self, file=None, name=None):
78 file = open(name, "r")
84 def read_val(self, k, v):
85 if not key_pattern.match(k):
86 raise MoeStatusInvalid, "Parse error: invalid key syntax"
91 self.get_list(k).append(v)
93 def do_read(self, file):
96 for x in file.readlines():
97 x = x.rstrip("\n").lstrip(" \t")
98 if x=="" or x.startswith("#"):
106 elif x.endswith("("):
109 this.read_val(k, new)
114 raise MoeStatusInvalid, "Parse error: incorrect nesting"
118 raise MoeStatusInvalid, "Parse error: malformed line"