Update imports and rename lock_file to open_locked and make it more idiomatic
authorBen Steffen <bds@mit.edu>
Tue, 26 Nov 2019 19:23:55 +0000 (14:23 -0500)
committerBen Steffen <bds@mit.edu>
Tue, 26 Nov 2019 19:23:55 +0000 (14:23 -0500)
python/invirt/common.py

index effb237..7d1eb21 100644 (file)
@@ -1,30 +1,10 @@
-import unittest
-from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
-import contextlib as clib
-import subprocess
+import fcntl
+import contextlib
+
 
 class InvirtConfigError(AttributeError):
     pass
 
-
-@clib.contextmanager
-def lock_file(path, exclusive = True):
-    with clib.closing(open(path, 'w')) as f:
-        if exclusive:
-            locktype = LOCK_EX
-        else:
-            locktype = LOCK_SH
-        flock(f, locktype)
-        try:
-            yield
-        finally:
-            flock(f, LOCK_UN)
-
-
-#
-# Exceptions.
-#
-
 class InvalidInput(Exception):
     """Exception for user-provided input is invalid but maybe in good faith.
 
@@ -32,17 +12,22 @@ class InvalidInput(Exception):
     typo) but not setting an invalid boot CD (which requires bypassing
     the select box).
     """
+
     def __init__(self, err_field, err_value, expl=None):
-        Exception.__init__(self, expl)
+        super().__init__(expl)
         self.err_field = err_field
         self.err_value = err_value
 
 class CodeError(Exception):
     """Exception for internal errors or bad faith input."""
-    pass
 
-#
-# Tests.
-#
 
+@contextlib.contextmanager
+def open_locked(path, exclusive=True):
+    with open(path, 'w') as f:
+        fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
 
+        try:
+            yield f
+        finally:
+            fcntl.flock(f, fcntl.LOCK_UN)