Skip to content

file

Functions:

check_perms

check_perms(
    file: FilePathType,
    mode: OpenTextMode | OpenBinaryMode,
    strict: bool = False,
    *,
    func: FuncExcept | None = None,
) -> bool

Confirm whether the user has write/read access to a file.

Parameters:

:param: True if the user has write/read access, else False.

Raises:

Source code in jetpytools/utils/file.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def check_perms(
    file: FilePathType, mode: OpenTextMode | OpenBinaryMode, strict: bool = False, *, func: FuncExcept | None = None
) -> bool:
    """
    Confirm whether the user has write/read access to a file.

    Args:
        file: Path to file.
        mode: Read/Write mode.
        func: Function that this was called from, only useful to *func writers.

    :param:                         True if the user has write/read access, else False.

    Raises:
        FileNotExistsError: File could not be found.
        FilePermissionError: User does not have access to the file.
        FileIsADirectoryError: Given path is a directory, not a file.
        FileWasNotFoundError: Parent directories exist, but the given file could not be found.
    """
    import os

    file = Path(str(file))
    got_perms = False

    mode_i = os.F_OK

    if func is not None and not str(file):
        raise FileNotExistsError(file, func)

    for char in "rbU":
        mode_str = mode.replace(char, "")

    if not mode_str:  # pyright: ignore[reportPossiblyUnboundVariable]
        mode_i = os.R_OK
    elif "x" in mode_str:
        mode_i = os.X_OK
    elif "+" in mode_str or "w" in mode_str:
        mode_i = os.W_OK

    check_file = file

    if not strict and mode_i != os.R_OK:
        while not check_file.exists():
            check_file = check_file.parent

    if strict and file.is_dir():
        raise FileIsADirectoryError(file, func)

    got_perms = os.access(check_file, mode_i)

    if func is not None and not got_perms:
        if strict and not file.exists():
            if file.parent.exists():
                raise FileWasNotFoundError(file, func)

            raise FileNotExistsError(file, func)

        raise FilePermissionError(file, func)

    return got_perms

get_script_path

get_script_path() -> SPath
Source code in jetpytools/utils/file.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def get_script_path() -> SPath:
    for hook in reversed(_script_path_hooks):
        if (script_path := hook()) is not None:
            return SPath(script_path)

    lib_root = __name__.split(".", 1)[0] if "." in __name__ else __name__

    frame = sys._getframe(1)
    try:
        while frame:
            f_globals = frame.f_globals
            module_name: str = f_globals.get("__name__", "")

            # Skip if the frame belongs to the current library family
            if module_name.startswith(lib_root):
                frame = frame.f_back
                continue

            filename = frame.f_code.co_filename
            pfilename = SPath(filename)

            # - No __package__ (execution entry point)
            # - Not in site-packages
            # - Not in the bin or Scripts folder
            # - Is a file on disk
            # - Is a virtual file
            if (
                not f_globals.get("__package__")
                and "site-packages" not in filename
                and pfilename.parent.name not in ("bin", "Scripts")
                and (pfilename.is_file() or filename in linecache.cache)
            ):
                return SPath(filename)

            frame = frame.f_back

        raise CustomRuntimeError("Couldn't find the script path")
    finally:
        del frame

get_user_data_dir

get_user_data_dir() -> Path

Get user data dir path.

Source code in jetpytools/utils/file.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def get_user_data_dir() -> Path:
    """Get user data dir path."""
    import os

    if sys.platform == "win32":
        import ctypes

        buf = ctypes.create_unicode_buffer(1024)
        ctypes.windll.shell32.SHGetFolderPathW(None, 28, None, 0, buf)

        if any(ord(c) > 255 for c in buf):
            buf2 = ctypes.create_unicode_buffer(1024)
            if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
                buf = buf2

        return Path(os.path.normpath(buf.value))
    elif sys.platform == "darwin":
        return Path(os.path.expanduser("~/Library/Application Support/"))
    else:
        return Path(os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")))