backend.py: Separate out the main work of `_update'.
authorMark Wooding <mdw@distorted.org.uk>
Fri, 23 May 2014 15:01:18 +0000 (16:01 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Sat, 24 May 2014 21:59:19 +0000 (22:59 +0100)
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

index 1967cda..54c5374 100644 (file)
@@ -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')
 
 ###--------------------------------------------------------------------------