mirror of
https://github.com/pre-commit/pre-commit.git
synced 2026-02-17 00:04:42 +04:00
Limit repository creation to one process
This commit is contained in:
parent
bba711f468
commit
625aaf54aa
6 changed files with 133 additions and 46 deletions
53
pre_commit/file_lock.py
Normal file
53
pre_commit/file_lock.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import contextlib
|
||||
import errno
|
||||
|
||||
|
||||
try: # pragma: no cover (windows)
|
||||
import msvcrt
|
||||
|
||||
# https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/locking
|
||||
|
||||
# on windows we lock "regions" of files, we don't care about the actual
|
||||
# byte region so we'll just pick *some* number here.
|
||||
_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
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
# From cursory testing, it seems to get unlocked when the file is
|
||||
# closed so this may not be necessary.
|
||||
# The documentation however states:
|
||||
# "Regions should be locked only briefly and should be unlocked
|
||||
# before closing a file or exiting the program."
|
||||
msvcrt.locking(fileno, msvcrt.LK_UNLCK, _region)
|
||||
except ImportError: # pragma: no cover (posix)
|
||||
import fcntl
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _locked(fileno):
|
||||
fcntl.flock(fileno, fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(fileno, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def lock(path):
|
||||
with open(path, 'a+') as f:
|
||||
with _locked(f.fileno()):
|
||||
yield
|
||||
Loading…
Add table
Add a link
Reference in a new issue