Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/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
19 :raises OSError: as if the file was opened for writing.
21 """
22 try: # use stat to do exists + can write to check without race condition
23 file_stat = os.stat(filename) # noqa: PTH116
24 except OSError:
25 return # swallow does not exist or other errors
27 if file_stat.st_mtime != 0: # if os.stat returns but modification is zero that's an invalid os.stat - ignore it
28 if not (file_stat.st_mode & stat.S_IWUSR):
29 raise PermissionError(EACCES, "Permission denied", filename)
31 if stat.S_ISDIR(file_stat.st_mode):
32 if sys.platform == "win32": # pragma: win32 cover
33 # On Windows, this is PermissionError
34 raise PermissionError(EACCES, "Permission denied", filename)
35 else: # pragma: win32 no cover # noqa: RET506
36 # On linux / macOS, this is IsADirectoryError
37 raise IsADirectoryError(EISDIR, "Is a directory", filename)
40def ensure_directory_exists(filename: Path | str) -> None:
41 """
42 Ensure the directory containing the file exists (create it if necessary).
44 :param filename: file.
46 """
47 Path(filename).parent.mkdir(parents=True, exist_ok=True)
50__all__ = [
51 "ensure_directory_exists",
52 "raise_on_not_writable_file",
53]