4 home = os.getenv("HOME")
5 if home is None or not os.path.isdir(home):
6 raise Exception("Could not find home directory for profile keeping")
7 basedir = pj(home, ".manga", "profiles")
9 def openwdir(nm, mode="r"):
10 if os.path.exists(nm):
13 d = os.path.dirname(nm)
14 if not os.path.isdir(d):
20 if c == "\\": return "\\"
21 elif c == '"': return '"'
22 elif c == " ": return " "
23 elif c == "n": return "\n"
44 elif c == "\\" and p < len(line):
53 elif c == "\\" and p < len(line):
65 if any((c == "\\" or c == '"' or c == "\n" for c in w)):
68 if c == "\\": wb += "\\\\"
69 elif c == '"': wb += '\\"'
70 elif c == "\n": wb += "\\n"
73 if w == "" or any((c.isspace() for c in w)):
81 def __init__(self, profile, libnm, id, path):
82 self.profile = profile
86 self.props = self.loadprops()
90 with openwdir(self.path) as f:
92 words = splitline(line)
93 if len(words) < 1: continue
94 if words[0] == "set" and len(words) > 2:
95 ret[words[1]] = words[2]
96 elif words[0] == "lset" and len(words) > 1:
97 ret[words[1]] = words[2:]
100 def prop(self, key, default=KeyError):
101 if key not in self.props:
102 if default is KeyError:
105 return self.props[key]
107 def setprop(self, key, val):
108 self.props[key] = val
111 with openwdir(self.path, "w") as f:
112 for key, val in self.props.iteritems():
113 if isinstance(val, str):
114 f.write(consline("set", key, val) + "\n")
116 f.write(consline("lset", key, *val) + "\n")
120 return lib.findlib(self.libnm).byid(self.id)
122 class profile(object):
123 def __init__(self, dir):
127 def getmapping(self):
130 if os.path.exists(pj(self.dir, "map")):
131 with openwdir(pj(self.dir, "map")) as f:
133 words = splitline(ln)
136 if words[0] == "seq" and len(words) > 1:
141 elif words[0] == "manga" and len(words) > 3:
143 ret[words[1], words[2]] = int(words[3])
148 def savemapping(self, seq, m):
149 with openwdir(pj(self.dir, "map"), "w") as f:
150 f.write(consline("seq", str(seq)) + "\n")
151 for (libnm, id), num in m.iteritems():
152 f.write(consline("manga", libnm, id, str(num)) + "\n")
154 def getmanga(self, libnm, id, creat=False):
155 seq, m = self.getmapping()
157 return manga(self, libnm, id, pj(self.dir, "%i.manga" % m[(libnm, id)]))
159 raise KeyError("no such manga: (%s, %s)" % (libnm, id))
162 fp = openwdir(pj(self.dir, "%i.manga" % seq), "wx")
169 self.savemapping(seq, m)
170 return manga(self, libnm, id, pj(self.dir, "%i.manga" % seq))
173 if self.name is None:
174 raise ValueError("profile at " + self.dir + " has no name")
175 with openwdir(pj(basedir, "last"), "w") as f:
176 f.write(self.name + "\n")
179 def byname(cls, name):
180 if not name or name == "last" or name[0] == '.':
181 raise KeyError("invalid profile name: " + name)
182 ret = cls(pj(basedir, name))
188 if not os.path.exists(pj(basedir, "last")):
189 raise KeyError("there is no last used profile")
190 with open(pj(basedir, "last")) as f:
191 return cls.byname(f.readline().strip())