1"""Unix."""
2
3from __future__ import annotations
4
5import os
6import sys
7from configparser import ConfigParser
8from pathlib import Path
9from typing import Iterator, NoReturn
10
11from .api import PlatformDirsABC
12
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 getuid
21
22
23class Unix(PlatformDirsABC): # noqa: PLR0904
24 """
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 `appname
30 <platformdirs.api.PlatformDirsABC.appname>`, `version <platformdirs.api.PlatformDirsABC.version>`, `multipath
31 <platformdirs.api.PlatformDirsABC.multipath>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists
32 <platformdirs.api.PlatformDirsABC.ensure_exists>`.
33
34 """
35
36 @property
37 def user_data_dir(self) -> str:
38 """
39 :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or
40 ``$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: PTH111
45 return self._append_app_name_and_version(path)
46
47 @property
48 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 @property
55 def site_data_dir(self) -> str:
56 """
57 :return: data directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is
58 enabled and ``XDG_DATA_DIRS`` is set and a multi path the response is also a multi path separated by the
59 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 False
62 dirs = self._site_data_dirs
63 if not self.multipath:
64 return dirs[0]
65 return os.pathsep.join(dirs)
66
67 @property
68 def user_config_dir(self) -> str:
69 """
70 :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or
71 ``$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: PTH111
76 return self._append_app_name_and_version(path)
77
78 @property
79 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 @property
86 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 by
90 the OS path separator), e.g. ``/etc/xdg/$appname/$version``
91 """
92 # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False
93 dirs = self._site_config_dirs
94 if not self.multipath:
95 return dirs[0]
96 return os.pathsep.join(dirs)
97
98 @property
99 def user_cache_dir(self) -> str:
100 """
101 :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or
102 ``~/$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: PTH111
107 return self._append_app_name_and_version(path)
108
109 @property
110 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 @property
115 def user_state_dir(self) -> str:
116 """
117 :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or
118 ``$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: PTH111
123 return self._append_app_name_and_version(path)
124
125 @property
126 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_dir
129 if self.opinion:
130 path = os.path.join(path, "log") # noqa: PTH118
131 self._optionally_create_directory(path)
132 return path
133
134 @property
135 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 @property
140 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 @property
145 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 @property
150 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 @property
155 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 @property
160 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 @property
165 def user_runtime_dir(self) -> str:
166 """
167 :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or
168 ``$XDG_RUNTIME_DIR/$appname/$version``.
169
170 For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if
171 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: S108
180 else:
181 path = f"/run/user/{getuid()}"
182 return self._append_app_name_and_version(path)
183
184 @property
185 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 will
191 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 @property
207 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 @property
212 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 @property
217 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_dir
230 yield from self._site_config_dirs
231
232 def iter_data_dirs(self) -> Iterator[str]:
233 """:yield: all user and site data directories."""
234 yield self.user_data_dir
235 yield from self._site_data_dirs
236
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: PTH111
244
245 return media_dir
246
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 complain
261 parser.read_string(f"[top]\n{stream.read()}")
262
263 if key not in parser["top"]:
264 return None
265
266 path = parser["top"][key].strip('"')
267 # Handle relative home paths
268 return path.replace("$HOME", os.path.expanduser("~")) # noqa: PTH111
269
270 return None
271
272
273__all__ = [
274 "Unix",
275]