Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/filelock/_util.py: 48%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import os
4import stat
5import sys
6from errno import EACCES, EISDIR
7from pathlib import Path
10def raise_on_not_writable_file(filename: str) -> None:
11 """
12 Raise an exception if attempting to open the file for writing would fail.
14 This is done so files that will never be writable can be separated from files that are writable but currently
15 locked.
17 :param filename: file to check
18 :raises OSError: as if the file was opened for writing.
20 """
21 try: # use stat to do exists + can write to check without race condition
22 file_stat = os.stat(filename) # noqa: PTH116
23 except OSError:
24 return # swallow does not exist or other errors
26 if file_stat.st_mtime != 0: # if os.stat returns but modification is zero that's an invalid os.stat - ignore it
27 if not (file_stat.st_mode & stat.S_IWUSR):
28 raise PermissionError(EACCES, "Permission denied", filename)
30 if stat.S_ISDIR(file_stat.st_mode):
31 if sys.platform == "win32": # pragma: win32 cover
32 # On Windows, this is PermissionError
33 raise PermissionError(EACCES, "Permission denied", filename)
34 else: # pragma: win32 no cover # noqa: RET506
35 # On linux / macOS, this is IsADirectoryError
36 raise IsADirectoryError(EISDIR, "Is a directory", filename)
39def ensure_directory_exists(filename: Path | str) -> None:
40 """
41 Ensure the directory containing the file exists (create it if necessary).
43 :param filename: file.
45 """
46 Path(filename).parent.mkdir(parents=True, exist_ok=True)
49__all__ = [
50 "ensure_directory_exists",
51 "raise_on_not_writable_file",
52]