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

18 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 07:11 +0000

1from __future__ import annotations 

2 

3import os 

4import stat 

5import sys 

6from errno import EACCES, EISDIR 

7 

8 

9def raise_on_not_writable_file(filename: str) -> None: 

10 """ 

11 Raise an exception if attempting to open the file for writing would fail. 

12 This is done so files that will never be writable can be separated from 

13 files that are writable but currently locked 

14 :param filename: file to check 

15 :raises OSError: as if the file was opened for writing 

16 """ 

17 try: 

18 file_stat = os.stat(filename) # use stat to do exists + can write to check without race condition 

19 except OSError: 

20 return None # swallow does not exist or other errors 

21 

22 if file_stat.st_mtime != 0: # if os.stat returns but modification is zero that's an invalid os.stat - ignore it 

23 if not (file_stat.st_mode & stat.S_IWUSR): 

24 raise PermissionError(EACCES, "Permission denied", filename) 

25 

26 if stat.S_ISDIR(file_stat.st_mode): 

27 if sys.platform == "win32": # pragma: win32 cover 

28 # On Windows, this is PermissionError 

29 raise PermissionError(EACCES, "Permission denied", filename) 

30 else: # pragma: win32 no cover 

31 # On linux / macOS, this is IsADirectoryError 

32 raise IsADirectoryError(EISDIR, "Is a directory", filename) 

33 

34 

35__all__ = [ 

36 "raise_on_not_writable_file", 

37]