From 612419ac09c0def4b15b101cf0520a4d21bb9911 Mon Sep 17 00:00:00 2001 Message-Id: <612419ac09c0def4b15b101cf0520a4d21bb9911.1715429496.git.mdw@distorted.org.uk> From: Mark Wooding Date: Fri, 23 May 2014 16:01:18 +0100 Subject: [PATCH] backend.py: Separate out the main work of `_update'. Organization: Straylight/Edgeware From: Mark Wooding This makes it easier to add other kinds of operations on the database later. Also check for errors, such as a missing record. --- backend.py | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/backend.py b/backend.py index 1967cda..54c5374 100644 --- a/backend.py +++ b/backend.py @@ -181,8 +181,20 @@ class FlatFileBackend (object): return rec raise UnknownUser, user - def _update(me, rec): - """Update the record REC in the file.""" + def _rewrite(me, op, rec): + """ + Rewrite the file, according to OP. + + The OP may be one of the following. + + `create' There must not be a record matching REC; add a new + one. + + `remove' There must be a record matching REC: remove it. + + `update' There must be a record matching REC: write REC in its + place. + """ ## The main update function. def doit(): @@ -200,14 +212,26 @@ class FlatFileBackend (object): ## Copy the old file to the new one, changing the user's record if ## and when we encounter it. + found = False with OS.fdopen(fd, 'w') as f_out: with open(me._file) as f_in: for line in f_in: r = me._parse(line) if r.user != rec.user: f_out.write(line) + elif op == 'create': + raise U.ExpectedError, \ + (500, "Record for `%s' already exists" % rec.user) else: - f_out.write(rec._format()) + found = True + if op != 'remove': f_out.write(rec._format()) + if found: + pass + elif op == 'create': + f_out.write(rec._format()) + else: + raise U.ExpectedError, \ + (500, "Record for `%s' not found" % rec.user) ## Update the permissions on the new file. Don't try to fix the ## ownership (we shouldn't be running as root) or the group (the @@ -238,6 +262,10 @@ class FlatFileBackend (object): """Convenience function for constructing a record.""" return FlatFileRecord(line, me._delim, me._fmap, backend = me) + def _update(me, rec): + """Update the record REC in the file.""" + me._rewrite('update', rec) + CONF.export('FlatFileBackend') ###-------------------------------------------------------------------------- -- [mdw]