Only print that the lock is being acquired when waiting

This commit is contained in:
Anthony Sottile 2017-09-04 11:27:47 -07:00
parent 4aa787db19
commit 7cb3e00731
5 changed files with 34 additions and 28 deletions

View file

@ -12,18 +12,22 @@ try: # pragma: no cover (windows)
_region = 0xffff
@contextlib.contextmanager
def _locked(fileno):
while True:
try:
msvcrt.locking(fileno, msvcrt.LK_LOCK, _region)
except OSError as e:
# Locking violation. Returned when the _LK_LOCK or _LK_RLCK
# flag is specified and the file cannot be locked after 10
# attempts.
if e.errno != errno.EDEADLOCK:
raise
else:
break
def _locked(fileno, blocked_cb):
try:
msvcrt.locking(fileno, msvcrt.LK_NBLCK, _region)
except IOError:
blocked_cb()
while True:
try:
msvcrt.locking(fileno, msvcrt.LK_LOCK, _region)
except IOError as e:
# Locking violation. Returned when the _LK_LOCK or _LK_RLCK
# flag is specified and the file cannot be locked after 10
# attempts.
if e.errno != errno.EDEADLOCK:
raise
else:
break
try:
yield
@ -38,8 +42,12 @@ except ImportError: # pragma: no cover (posix)
import fcntl
@contextlib.contextmanager
def _locked(fileno):
fcntl.flock(fileno, fcntl.LOCK_EX)
def _locked(fileno, blocked_cb):
try:
fcntl.flock(fileno, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
blocked_cb()
fcntl.flock(fileno, fcntl.LOCK_EX)
try:
yield
finally:
@ -47,7 +55,7 @@ except ImportError: # pragma: no cover (posix)
@contextlib.contextmanager
def lock(path):
def lock(path, blocked_cb):
with open(path, 'a+') as f:
with _locked(f.fileno()):
with _locked(f.fileno(), blocked_cb):
yield

View file

@ -47,10 +47,11 @@ class Store(object):
self.directory = directory
@contextlib.contextmanager
def exclusive_lock(self, quiet=False):
if not quiet:
def exclusive_lock(self):
def blocked_cb(): # pragma: no cover (tests are single-process)
logger.info('Locking pre-commit directory')
with file_lock.lock(os.path.join(self.directory, '.lock')):
with file_lock.lock(os.path.join(self.directory, '.lock'), blocked_cb):
yield
def _write_readme(self):
@ -89,7 +90,7 @@ class Store(object):
if os.path.exists(self.db_path):
return
with self.exclusive_lock(quiet=True):
with self.exclusive_lock():
# Another process may have already completed this work
if os.path.exists(self.db_path): # pragma: no cover (race)
return