Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
unix.py276 linesDownload Raw Back to platformdirs
1"""Unix."""2 3from __future__ import annotations4 5import os6import sys7from configparser import ConfigParser8from pathlib import Path9from typing import Iterator, NoReturn10 11from .api import PlatformDirsABC12 13if sys.platform == "win32":14 15    def getuid() -> NoReturn:16        msg = "should only be used on Unix"17        raise RuntimeError(msg)18 19else:20    from os import getuid21 22 23class Unix(PlatformDirsABC):  # noqa: PLR090424    """25    On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec-26    latest.html>`_.27 28    The spec allows overriding directories with environment variables. The examples shown are the default values,29    alongside the name of the environment variable that overrides them. Makes use of the `appname30    <platformdirs.api.PlatformDirsABC.appname>`, `version <platformdirs.api.PlatformDirsABC.version>`, `multipath31    <platformdirs.api.PlatformDirsABC.multipath>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists32    <platformdirs.api.PlatformDirsABC.ensure_exists>`.33 34    """35 36    @property37    def user_data_dir(self) -> str:38        """39        :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or40         ``$XDG_DATA_HOME/$appname/$version``41        """42        path = os.environ.get("XDG_DATA_HOME", "")43        if not path.strip():44            path = os.path.expanduser("~/.local/share")  # noqa: PTH11145        return self._append_app_name_and_version(path)46 47    @property48    def _site_data_dirs(self) -> list[str]:49        path = os.environ.get("XDG_DATA_DIRS", "")50        if not path.strip():51            path = f"/usr/local/share{os.pathsep}/usr/share"52        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]53 54    @property55    def site_data_dir(self) -> str:56        """57        :return: data directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is58         enabled and ``XDG_DATA_DIRS`` is set and a multi path the response is also a multi path separated by the59         OS path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version``60        """61        # XDG default for $XDG_DATA_DIRS; only first, if multipath is False62        dirs = self._site_data_dirs63        if not self.multipath:64            return dirs[0]65        return os.pathsep.join(dirs)66 67    @property68    def user_config_dir(self) -> str:69        """70        :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or71         ``$XDG_CONFIG_HOME/$appname/$version``72        """73        path = os.environ.get("XDG_CONFIG_HOME", "")74        if not path.strip():75            path = os.path.expanduser("~/.config")  # noqa: PTH11176        return self._append_app_name_and_version(path)77 78    @property79    def _site_config_dirs(self) -> list[str]:80        path = os.environ.get("XDG_CONFIG_DIRS", "")81        if not path.strip():82            path = "/etc/xdg"83        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]84 85    @property86    def site_config_dir(self) -> str:87        """88        :return: config directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>`89         is enabled and ``XDG_CONFIG_DIRS`` is set and a multi path the response is also a multi path separated by90         the OS path separator), e.g. ``/etc/xdg/$appname/$version``91        """92        # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False93        dirs = self._site_config_dirs94        if not self.multipath:95            return dirs[0]96        return os.pathsep.join(dirs)97 98    @property99    def user_cache_dir(self) -> str:100        """101        :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or102         ``~/$XDG_CACHE_HOME/$appname/$version``103        """104        path = os.environ.get("XDG_CACHE_HOME", "")105        if not path.strip():106            path = os.path.expanduser("~/.cache")  # noqa: PTH111107        return self._append_app_name_and_version(path)108 109    @property110    def site_cache_dir(self) -> str:111        """:return: cache directory shared by users, e.g. ``/var/cache/$appname/$version``"""112        return self._append_app_name_and_version("/var/cache")113 114    @property115    def user_state_dir(self) -> str:116        """117        :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or118         ``$XDG_STATE_HOME/$appname/$version``119        """120        path = os.environ.get("XDG_STATE_HOME", "")121        if not path.strip():122            path = os.path.expanduser("~/.local/state")  # noqa: PTH111123        return self._append_app_name_and_version(path)124 125    @property126    def user_log_dir(self) -> str:127        """:return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it"""128        path = self.user_state_dir129        if self.opinion:130            path = os.path.join(path, "log")  # noqa: PTH118131            self._optionally_create_directory(path)132        return path133 134    @property135    def user_documents_dir(self) -> str:136        """:return: documents directory tied to the user, e.g. ``~/Documents``"""137        return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents")138 139    @property140    def user_downloads_dir(self) -> str:141        """:return: downloads directory tied to the user, e.g. ``~/Downloads``"""142        return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads")143 144    @property145    def user_pictures_dir(self) -> str:146        """:return: pictures directory tied to the user, e.g. ``~/Pictures``"""147        return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures")148 149    @property150    def user_videos_dir(self) -> str:151        """:return: videos directory tied to the user, e.g. ``~/Videos``"""152        return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos")153 154    @property155    def user_music_dir(self) -> str:156        """:return: music directory tied to the user, e.g. ``~/Music``"""157        return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music")158 159    @property160    def user_desktop_dir(self) -> str:161        """:return: desktop directory tied to the user, e.g. ``~/Desktop``"""162        return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop")163 164    @property165    def user_runtime_dir(self) -> str:166        """167        :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or168         ``$XDG_RUNTIME_DIR/$appname/$version``.169 170         For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if171         exists, otherwise ``/tmp/runtime-$(id -u)/$appname/$version``, if``$XDG_RUNTIME_DIR``172         is not set.173        """174        path = os.environ.get("XDG_RUNTIME_DIR", "")175        if not path.strip():176            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):177                path = f"/var/run/user/{getuid()}"178                if not Path(path).exists():179                    path = f"/tmp/runtime-{getuid()}"  # noqa: S108180            else:181                path = f"/run/user/{getuid()}"182        return self._append_app_name_and_version(path)183 184    @property185    def site_runtime_dir(self) -> str:186        """187        :return: runtime directory shared by users, e.g. ``/run/$appname/$version`` or \188        ``$XDG_RUNTIME_DIR/$appname/$version``.189 190        Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will191        fall back to paths associated to the root user instead of a regular logged-in user if it's not set.192 193        If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir`194        instead.195 196        For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.197        """198        path = os.environ.get("XDG_RUNTIME_DIR", "")199        if not path.strip():200            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):201                path = "/var/run"202            else:203                path = "/run"204        return self._append_app_name_and_version(path)205 206    @property207    def site_data_path(self) -> Path:208        """:return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""209        return self._first_item_as_path_if_multipath(self.site_data_dir)210 211    @property212    def site_config_path(self) -> Path:213        """:return: config path shared by the users, returns the first item, even if ``multipath`` is set to ``True``"""214        return self._first_item_as_path_if_multipath(self.site_config_dir)215 216    @property217    def site_cache_path(self) -> Path:218        """:return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""219        return self._first_item_as_path_if_multipath(self.site_cache_dir)220 221    def _first_item_as_path_if_multipath(self, directory: str) -> Path:222        if self.multipath:223            # If multipath is True, the first path is returned.224            directory = directory.split(os.pathsep)[0]225        return Path(directory)226 227    def iter_config_dirs(self) -> Iterator[str]:228        """:yield: all user and site configuration directories."""229        yield self.user_config_dir230        yield from self._site_config_dirs231 232    def iter_data_dirs(self) -> Iterator[str]:233        """:yield: all user and site data directories."""234        yield self.user_data_dir235        yield from self._site_data_dirs236 237 238def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:239    media_dir = _get_user_dirs_folder(env_var)240    if media_dir is None:241        media_dir = os.environ.get(env_var, "").strip()242        if not media_dir:243            media_dir = os.path.expanduser(fallback_tilde_path)  # noqa: PTH111244 245    return media_dir246 247 248def _get_user_dirs_folder(key: str) -> str | None:249    """250    Return directory from user-dirs.dirs config file.251 252    See https://freedesktop.org/wiki/Software/xdg-user-dirs/.253 254    """255    user_dirs_config_path = Path(Unix().user_config_dir) / "user-dirs.dirs"256    if user_dirs_config_path.exists():257        parser = ConfigParser()258 259        with user_dirs_config_path.open() as stream:260            # Add fake section header, so ConfigParser doesn't complain261            parser.read_string(f"[top]\n{stream.read()}")262 263        if key not in parser["top"]:264            return None265 266        path = parser["top"][key].strip('"')267        # Handle relative home paths268        return path.replace("$HOME", os.path.expanduser("~"))  # noqa: PTH111269 270    return None271 272 273__all__ = [274    "Unix",275]276 
codekingpro/portable-devtools · Team Ai