Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/filelock/_soft.py: 46%

26 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-25 06:08 +0000

1from __future__ import annotations 

2 

3import os 

4import sys 

5from contextlib import suppress 

6from errno import EACCES, EEXIST 

7from pathlib import Path 

8 

9from ._api import BaseFileLock 

10from ._util import ensure_directory_exists, raise_on_not_writable_file 

11 

12 

13class SoftFileLock(BaseFileLock): 

14 """Simply watches the existence of the lock file.""" 

15 

16 def _acquire(self) -> None: 

17 raise_on_not_writable_file(self.lock_file) 

18 ensure_directory_exists(self.lock_file) 

19 # first check for exists and read-only mode as the open will mask this case as EEXIST 

20 flags = ( 

21 os.O_WRONLY # open for writing only 

22 | os.O_CREAT 

23 | os.O_EXCL # together with above raise EEXIST if the file specified by filename exists 

24 | os.O_TRUNC # truncate the file to zero byte 

25 ) 

26 try: 

27 file_handler = os.open(self.lock_file, flags, self._context.mode) 

28 except OSError as exception: # re-raise unless expected exception 

29 if not ( 

30 exception.errno == EEXIST # lock already exist 

31 or (exception.errno == EACCES and sys.platform == "win32") # has no access to this lock 

32 ): # pragma: win32 no cover 

33 raise 

34 else: 

35 self._context.lock_file_fd = file_handler 

36 

37 def _release(self) -> None: 

38 assert self._context.lock_file_fd is not None # noqa: S101 

39 os.close(self._context.lock_file_fd) # the lock file is definitely not None 

40 self._context.lock_file_fd = None 

41 with suppress(OSError): # the file is already deleted and that's what we want 

42 Path(self.lock_file).unlink() 

43 

44 

45__all__ = [ 

46 "SoftFileLock", 

47]