Explorar o código

Raise FileLocked in GitFile.

Jelmer Vernooij %!s(int64=7) %!d(string=hai) anos
pai
achega
d4899f081f
Modificáronse 3 ficheiros con 26 adicións e 6 borrados
  1. 5 0
      NEWS
  2. 18 3
      dulwich/file.py
  3. 3 3
      dulwich/tests/test_file.py

+ 5 - 0
NEWS

@@ -4,6 +4,11 @@
 
   * Fix cwd for hooks. (Fabian Grünbichler)
 
+ API CHANGES
+
+  * GitFile now raises ``FileLocked`` when encountering a lock
+    rather than OSError(EEXIST). (Jelmer Vernooij)
+
 0.18.4	2017-10-01
 
  BUG FIXES

+ 18 - 3
dulwich/file.py

@@ -90,6 +90,15 @@ def GitFile(filename, mode='rb', bufsize=-1):
         return io.open(filename, mode, bufsize)
 
 
+class FileLocked(Exception):
+    """File is already locked."""
+
+    def __init__(self, filename, lockfilename):
+        self.filename = filename
+        self.lockfilename = lockfilename
+        super(FileLocked, self).__init__(filename, lockfilename)
+
+
 class _GitFile(object):
     """File that follows the git locking protocol for writes.
 
@@ -110,9 +119,14 @@ class _GitFile(object):
     def __init__(self, filename, mode, bufsize):
         self._filename = filename
         self._lockfilename = '%s.lock' % self._filename
-        fd = os.open(
-            self._lockfilename,
-            os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0))
+        try:
+            fd = os.open(
+                self._lockfilename,
+                os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0))
+        except OSError as e:
+            if e.errno == errno.EEXIST:
+                raise FileLocked(filename, self._lockfilename)
+            raise
         self._file = os.fdopen(fd, mode, bufsize)
         self._closed = False
 
@@ -149,6 +163,7 @@ class _GitFile(object):
         """
         if self._closed:
             return
+        os.fsync(self._file.fileno())
         self._file.close()
         try:
             try:

+ 3 - 3
dulwich/tests/test_file.py

@@ -25,7 +25,7 @@ import shutil
 import sys
 import tempfile
 
-from dulwich.file import GitFile, _fancy_rename
+from dulwich.file import FileLocked, GitFile, _fancy_rename
 from dulwich.tests import (
     SkipTest,
     TestCase,
@@ -158,8 +158,8 @@ class GitFileTests(TestCase):
         try:
             f2 = GitFile(foo, 'wb')
             self.fail()
-        except OSError as e:
-            self.assertEqual(errno.EEXIST, e.errno)
+        except FileLocked as e:
+            pass
         else:
             f2.close()
         f1.write(b' contents')