unix.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. """Unix."""
  2. from __future__ import annotations
  3. import os
  4. import sys
  5. from configparser import ConfigParser
  6. from functools import cached_property
  7. from pathlib import Path
  8. from tempfile import gettempdir
  9. from typing import TYPE_CHECKING, NoReturn
  10. from ._xdg import XDGMixin
  11. from .api import PlatformDirsABC
  12. if TYPE_CHECKING:
  13. from collections.abc import Iterator
  14. if sys.platform == "win32":
  15. def getuid() -> NoReturn:
  16. msg = "should only be used on Unix"
  17. raise RuntimeError(msg)
  18. else:
  19. from os import getuid
  20. class _UnixDefaults(PlatformDirsABC): # noqa: PLR0904
  21. """Default directories for Unix/Linux without XDG environment variable overrides.
  22. The XDG env var handling is in :class:`~platformdirs._xdg.XDGMixin`.
  23. """
  24. @cached_property
  25. def _use_site(self) -> bool:
  26. return self.use_site_for_root and getuid() == 0
  27. @property
  28. def user_data_dir(self) -> str:
  29. """:returns: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or ``$XDG_DATA_HOME/$appname/$version``"""
  30. return self._append_app_name_and_version(os.path.expanduser("~/.local/share")) # noqa: PTH111
  31. @property
  32. def _site_data_dirs(self) -> list[str]:
  33. return [self._append_app_name_and_version("/usr/local/share"), self._append_app_name_and_version("/usr/share")]
  34. @property
  35. def user_config_dir(self) -> str:
  36. """:returns: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or ``$XDG_CONFIG_HOME/$appname/$version``"""
  37. return self._append_app_name_and_version(os.path.expanduser("~/.config")) # noqa: PTH111
  38. @property
  39. def _site_config_dirs(self) -> list[str]:
  40. return [self._append_app_name_and_version("/etc/xdg")]
  41. @property
  42. def user_cache_dir(self) -> str:
  43. """:returns: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or ``$XDG_CACHE_HOME/$appname/$version``"""
  44. return self._append_app_name_and_version(os.path.expanduser("~/.cache")) # noqa: PTH111
  45. @property
  46. def site_cache_dir(self) -> str:
  47. """:returns: cache directory shared by users, e.g. ``/var/cache/$appname/$version``"""
  48. return self._append_app_name_and_version("/var/cache")
  49. @property
  50. def user_state_dir(self) -> str:
  51. """:returns: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or ``$XDG_STATE_HOME/$appname/$version``"""
  52. return self._append_app_name_and_version(os.path.expanduser("~/.local/state")) # noqa: PTH111
  53. @property
  54. def site_state_dir(self) -> str:
  55. """:returns: state directory shared by users, e.g. ``/var/lib/$appname/$version``"""
  56. return self._append_app_name_and_version("/var/lib")
  57. @property
  58. def user_log_dir(self) -> str:
  59. """:returns: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it"""
  60. path = self.user_state_dir
  61. if self.opinion:
  62. path = os.path.join(path, "log") # noqa: PTH118
  63. self._optionally_create_directory(path)
  64. return path
  65. @property
  66. def site_log_dir(self) -> str:
  67. """:returns: log directory shared by users, e.g. ``/var/log/$appname/$version``
  68. Unlike `user_log_dir`, ``opinion`` has no effect since ``/var/log`` is inherently a log directory.
  69. """
  70. return self._append_app_name_and_version("/var/log")
  71. @property
  72. def user_documents_dir(self) -> str:
  73. """:returns: documents directory tied to the user, e.g. ``~/Documents``"""
  74. return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents")
  75. @property
  76. def user_downloads_dir(self) -> str:
  77. """:returns: downloads directory tied to the user, e.g. ``~/Downloads``"""
  78. return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads")
  79. @property
  80. def user_pictures_dir(self) -> str:
  81. """:returns: pictures directory tied to the user, e.g. ``~/Pictures``"""
  82. return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures")
  83. @property
  84. def user_videos_dir(self) -> str:
  85. """:returns: videos directory tied to the user, e.g. ``~/Videos``"""
  86. return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos")
  87. @property
  88. def user_music_dir(self) -> str:
  89. """:returns: music directory tied to the user, e.g. ``~/Music``"""
  90. return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music")
  91. @property
  92. def user_desktop_dir(self) -> str:
  93. """:returns: desktop directory tied to the user, e.g. ``~/Desktop``"""
  94. return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop")
  95. @property
  96. def user_bin_dir(self) -> str:
  97. """:returns: bin directory tied to the user, e.g. ``~/.local/bin``"""
  98. return os.path.expanduser("~/.local/bin") # noqa: PTH111
  99. @property
  100. def site_bin_dir(self) -> str:
  101. """:returns: bin directory shared by users, e.g. ``/usr/local/bin``"""
  102. return "/usr/local/bin"
  103. @property
  104. def user_applications_dir(self) -> str:
  105. """:returns: applications directory tied to the user, e.g. ``~/.local/share/applications``"""
  106. return os.path.join(os.path.expanduser("~/.local/share"), "applications") # noqa: PTH111, PTH118
  107. @property
  108. def _site_applications_dirs(self) -> list[str]:
  109. return [os.path.join(p, "applications") for p in ["/usr/local/share", "/usr/share"]] # noqa: PTH118
  110. @property
  111. def site_applications_dir(self) -> str:
  112. """:returns: applications directory shared by users, e.g. ``/usr/share/applications``"""
  113. dirs = self._site_applications_dirs
  114. return os.pathsep.join(dirs) if self.multipath else dirs[0]
  115. @property
  116. def user_runtime_dir(self) -> str:
  117. """:returns: runtime directory tied to the user, e.g. ``$XDG_RUNTIME_DIR/$appname/$version``.
  118. If ``$XDG_RUNTIME_DIR`` is unset, tries the platform default (``/tmp/run/user/$(id -u)`` on OpenBSD, ``/var/run/user/$(id -u)`` on FreeBSD/NetBSD, ``/run/user/$(id -u)`` otherwise). If the default is not writable, falls back to a temporary directory.
  119. """
  120. if sys.platform.startswith("openbsd"):
  121. path = f"/tmp/run/user/{getuid()}" # noqa: S108
  122. elif sys.platform.startswith(("freebsd", "netbsd")):
  123. path = f"/var/run/user/{getuid()}"
  124. else:
  125. path = f"/run/user/{getuid()}"
  126. if not os.access(path, os.W_OK):
  127. path = f"{gettempdir()}/runtime-{getuid()}"
  128. return self._append_app_name_and_version(path)
  129. @property
  130. def site_runtime_dir(self) -> str:
  131. """:returns: runtime directory shared by users, e.g. ``/run/$appname/$version`` or ``$XDG_RUNTIME_DIR/$appname/$version``.
  132. Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will fall back to paths associated to the root user instead of a regular logged-in user if it's not set.
  133. If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir` instead.
  134. For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.
  135. """
  136. if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
  137. path = "/var/run"
  138. else:
  139. path = "/run"
  140. return self._append_app_name_and_version(path)
  141. @property
  142. def site_data_path(self) -> Path:
  143. """:returns: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
  144. return self._first_item_as_path_if_multipath(self.site_data_dir)
  145. @property
  146. def site_config_path(self) -> Path:
  147. """:returns: config path shared by users, returns the first item, even if ``multipath`` is set to ``True``"""
  148. return self._first_item_as_path_if_multipath(self.site_config_dir)
  149. @property
  150. def site_cache_path(self) -> Path:
  151. """:returns: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
  152. return self._first_item_as_path_if_multipath(self.site_cache_dir)
  153. def iter_config_dirs(self) -> Iterator[str]:
  154. """:yield: all user and site configuration directories."""
  155. yield self.user_config_dir
  156. yield from self._site_config_dirs
  157. def iter_data_dirs(self) -> Iterator[str]:
  158. """:yield: all user and site data directories."""
  159. yield self.user_data_dir
  160. yield from self._site_data_dirs
  161. class Unix(XDGMixin, _UnixDefaults):
  162. """On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir/latest/>`_.
  163. The spec allows overriding directories with environment variables. The examples shown are the default values,
  164. alongside the name of the environment variable that overrides them. Makes use of the `appname
  165. <platformdirs.api.PlatformDirsABC.appname>`, `version <platformdirs.api.PlatformDirsABC.version>`, `multipath
  166. <platformdirs.api.PlatformDirsABC.multipath>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists
  167. <platformdirs.api.PlatformDirsABC.ensure_exists>`.
  168. """
  169. @property
  170. def user_data_dir(self) -> str:
  171. """:returns: data directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  172. return self.site_data_dir if self._use_site else super().user_data_dir
  173. @property
  174. def user_config_dir(self) -> str:
  175. """:returns: config directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  176. return self.site_config_dir if self._use_site else super().user_config_dir
  177. @property
  178. def user_cache_dir(self) -> str:
  179. """:returns: cache directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  180. return self.site_cache_dir if self._use_site else super().user_cache_dir
  181. @property
  182. def user_state_dir(self) -> str:
  183. """:returns: state directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  184. return self.site_state_dir if self._use_site else super().user_state_dir
  185. @property
  186. def user_log_dir(self) -> str:
  187. """:returns: log directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  188. return self.site_log_dir if self._use_site else super().user_log_dir
  189. @property
  190. def user_applications_dir(self) -> str:
  191. """:returns: applications directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  192. return self.site_applications_dir if self._use_site else super().user_applications_dir
  193. @property
  194. def user_runtime_dir(self) -> str:
  195. """:returns: runtime directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  196. return self.site_runtime_dir if self._use_site else super().user_runtime_dir
  197. @property
  198. def user_bin_dir(self) -> str:
  199. """:returns: bin directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
  200. return self.site_bin_dir if self._use_site else super().user_bin_dir
  201. def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:
  202. if media_dir := _get_user_dirs_folder(env_var):
  203. return media_dir
  204. return os.path.expanduser(fallback_tilde_path) # noqa: PTH111
  205. def _get_user_dirs_folder(key: str) -> str | None:
  206. """Return directory from user-dirs.dirs config file.
  207. See https://freedesktop.org/wiki/Software/xdg-user-dirs/.
  208. """
  209. user_dirs_config_path = Path(os.path.expanduser("~/.config")) / "user-dirs.dirs" # noqa: PTH111
  210. if user_dirs_config_path.exists():
  211. parser = ConfigParser()
  212. with user_dirs_config_path.open() as stream:
  213. parser.read_string(f"[top]\n{stream.read()}")
  214. if key not in parser["top"]:
  215. return None
  216. path = parser["top"][key].strip('"')
  217. return path.replace("$HOME", os.path.expanduser("~")) # noqa: PTH111
  218. return None
  219. __all__ = [
  220. "Unix",
  221. ]