2 from __future__
import annotations
7 from functools
import lru_cache
8 from typing
import TYPE_CHECKING
10 from .api
import PlatformDirsABC
13 from collections
.abc
import Callable
16 class Windows(PlatformDirsABC
):
18 `MSDN on where to store app data files
19 <http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120>`_.
21 `appname <platformdirs.api.PlatformDirsABC.appname>`,
22 `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`,
23 `version <platformdirs.api.PlatformDirsABC.version>`,
24 `roaming <platformdirs.api.PlatformDirsABC.roaming>`,
25 `opinion <platformdirs.api.PlatformDirsABC.opinion>`,
26 `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.
30 def user_data_dir(self
) -> str:
32 :return: data directory tied to the user, e.g.
33 ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
34 ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
36 const
= "CSIDL_APPDATA" if self
.roaming
else "CSIDL_LOCAL_APPDATA"
37 path
= os
.path
.normpath(get_win_folder(const
))
38 return self
._append
_parts
(path
)
40 def _append_parts(self
, path
: str, *, opinion_value
: str |
None = None) -> str:
43 if self
.appauthor
is not False:
44 author
= self
.appauthor
or self
.appname
46 params
.append(self
.appname
)
47 if opinion_value
is not None and self
.opinion
:
48 params
.append(opinion_value
)
50 params
.append(self
.version
)
51 path
= os
.path
.join(path
, *params
) # noqa: PTH118
52 self
._optionally
_create
_directory
(path
)
56 def site_data_dir(self
) -> str:
57 """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
58 path
= os
.path
.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
59 return self
._append
_parts
(path
)
62 def user_config_dir(self
) -> str:
63 """:return: config directory tied to the user, same as `user_data_dir`"""
64 return self
.user_data_dir
67 def site_config_dir(self
) -> str:
68 """:return: config directory shared by the users, same as `site_data_dir`"""
69 return self
.site_data_dir
72 def user_cache_dir(self
) -> str:
74 :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
75 ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
77 path
= os
.path
.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
78 return self
._append
_parts
(path
, opinion_value
="Cache")
81 def site_cache_dir(self
) -> str:
82 """:return: cache directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname\\Cache\\$version``"""
83 path
= os
.path
.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
84 return self
._append
_parts
(path
, opinion_value
="Cache")
87 def user_state_dir(self
) -> str:
88 """:return: state directory tied to the user, same as `user_data_dir`"""
89 return self
.user_data_dir
92 def user_log_dir(self
) -> str:
93 """:return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
94 path
= self
.user_data_dir
96 path
= os
.path
.join(path
, "Logs") # noqa: PTH118
97 self
._optionally
_create
_directory
(path
)
101 def user_documents_dir(self
) -> str:
102 """:return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``"""
103 return os
.path
.normpath(get_win_folder("CSIDL_PERSONAL"))
106 def user_downloads_dir(self
) -> str:
107 """:return: downloads directory tied to the user e.g. ``%USERPROFILE%\\Downloads``"""
108 return os
.path
.normpath(get_win_folder("CSIDL_DOWNLOADS"))
111 def user_pictures_dir(self
) -> str:
112 """:return: pictures directory tied to the user e.g. ``%USERPROFILE%\\Pictures``"""
113 return os
.path
.normpath(get_win_folder("CSIDL_MYPICTURES"))
116 def user_videos_dir(self
) -> str:
117 """:return: videos directory tied to the user e.g. ``%USERPROFILE%\\Videos``"""
118 return os
.path
.normpath(get_win_folder("CSIDL_MYVIDEO"))
121 def user_music_dir(self
) -> str:
122 """:return: music directory tied to the user e.g. ``%USERPROFILE%\\Music``"""
123 return os
.path
.normpath(get_win_folder("CSIDL_MYMUSIC"))
126 def user_desktop_dir(self
) -> str:
127 """:return: desktop directory tied to the user, e.g. ``%USERPROFILE%\\Desktop``"""
128 return os
.path
.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
131 def user_runtime_dir(self
) -> str:
133 :return: runtime directory tied to the user, e.g.
134 ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
136 path
= os
.path
.normpath(os
.path
.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp")) # noqa: PTH118
137 return self
._append
_parts
(path
)
140 def site_runtime_dir(self
) -> str:
141 """:return: runtime directory shared by users, same as `user_runtime_dir`"""
142 return self
.user_runtime_dir
145 def get_win_folder_from_env_vars(csidl_name
: str) -> str:
146 """Get folder from environment variables."""
147 result
= get_win_folder_if_csidl_name_not_env_var(csidl_name
)
148 if result
is not None:
152 "CSIDL_APPDATA": "APPDATA",
153 "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
154 "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
156 if env_var_name
is None:
157 msg
= f
"Unknown CSIDL name: {csidl_name}"
158 raise ValueError(msg
)
159 result
= os
.environ
.get(env_var_name
)
161 msg
= f
"Unset environment variable: {env_var_name}"
162 raise ValueError(msg
)
166 def get_win_folder_if_csidl_name_not_env_var(csidl_name
: str) -> str |
None:
167 """Get folder for a CSIDL name that does not exist as an environment variable."""
168 if csidl_name
== "CSIDL_PERSONAL":
169 return os
.path
.join(os
.path
.normpath(os
.environ
["USERPROFILE"]), "Documents") # noqa: PTH118
171 if csidl_name
== "CSIDL_DOWNLOADS":
172 return os
.path
.join(os
.path
.normpath(os
.environ
["USERPROFILE"]), "Downloads") # noqa: PTH118
174 if csidl_name
== "CSIDL_MYPICTURES":
175 return os
.path
.join(os
.path
.normpath(os
.environ
["USERPROFILE"]), "Pictures") # noqa: PTH118
177 if csidl_name
== "CSIDL_MYVIDEO":
178 return os
.path
.join(os
.path
.normpath(os
.environ
["USERPROFILE"]), "Videos") # noqa: PTH118
180 if csidl_name
== "CSIDL_MYMUSIC":
181 return os
.path
.join(os
.path
.normpath(os
.environ
["USERPROFILE"]), "Music") # noqa: PTH118
185 def get_win_folder_from_registry(csidl_name
: str) -> str:
187 Get folder from the registry.
189 This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
190 for all CSIDL_* names.
192 shell_folder_name
= {
193 "CSIDL_APPDATA": "AppData",
194 "CSIDL_COMMON_APPDATA": "Common AppData",
195 "CSIDL_LOCAL_APPDATA": "Local AppData",
196 "CSIDL_PERSONAL": "Personal",
197 "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
198 "CSIDL_MYPICTURES": "My Pictures",
199 "CSIDL_MYVIDEO": "My Video",
200 "CSIDL_MYMUSIC": "My Music",
202 if shell_folder_name
is None:
203 msg
= f
"Unknown CSIDL name: {csidl_name}"
204 raise ValueError(msg
)
205 if sys
.platform
!= "win32": # only needed for mypy type checker to know that this code runs only on Windows
206 raise NotImplementedError
209 key
= winreg
.OpenKey(winreg
.HKEY_CURRENT_USER
, r
"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
210 directory
, _
= winreg
.QueryValueEx(key
, shell_folder_name
)
211 return str(directory
)
214 def get_win_folder_via_ctypes(csidl_name
: str) -> str:
215 """Get folder with ctypes."""
216 # There is no 'CSIDL_DOWNLOADS'.
217 # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.
218 # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
222 "CSIDL_COMMON_APPDATA": 35,
223 "CSIDL_LOCAL_APPDATA": 28,
225 "CSIDL_MYPICTURES": 39,
228 "CSIDL_DOWNLOADS": 40,
229 "CSIDL_DESKTOPDIRECTORY": 16,
231 if csidl_const
is None:
232 msg
= f
"Unknown CSIDL name: {csidl_name}"
233 raise ValueError(msg
)
235 buf
= ctypes
.create_unicode_buffer(1024)
236 windll
= getattr(ctypes
, "windll") # noqa: B009 # using getattr to avoid false positive with mypy type checker
237 windll
.shell32
.SHGetFolderPathW(None, csidl_const
, None, 0, buf
)
239 # Downgrade to short path name if it has high-bit chars.
240 if any(ord(c
) > 255 for c
in buf
): # noqa: PLR2004
241 buf2
= ctypes
.create_unicode_buffer(1024)
242 if windll
.kernel32
.GetShortPathNameW(buf
.value
, buf2
, 1024):
245 if csidl_name
== "CSIDL_DOWNLOADS":
246 return os
.path
.join(buf
.value
, "Downloads") # noqa: PTH118
251 def _pick_get_win_folder() -> Callable
[[str], str]:
252 if hasattr(ctypes
, "windll"):
253 return get_win_folder_via_ctypes
255 import winreg
# noqa: F401
257 return get_win_folder_from_env_vars
259 return get_win_folder_from_registry
262 get_win_folder
= lru_cache(maxsize
=None)(_pick_get_win_folder())