1 from __future__ import annotations
6 from functools import lru_cache
7 from typing import Callable
9 from .api import PlatformDirsABC
12 class Windows(PlatformDirsABC):
13 """`MSDN on where to store app data files
14 <http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120>`_.
16 `appname <platformdirs.api.PlatformDirsABC.appname>`,
17 `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`,
18 `version <platformdirs.api.PlatformDirsABC.version>`,
19 `roaming <platformdirs.api.PlatformDirsABC.roaming>`,
20 `opinion <platformdirs.api.PlatformDirsABC.opinion>`."""
23 def user_data_dir(self) -> str:
25 :return: data directory tied to the user, e.g.
26 ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
27 ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
29 const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
30 path = os.path.normpath(get_win_folder(const))
31 return self._append_parts(path)
33 def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
36 if self.appauthor is not False:
37 author = self.appauthor or self.appname
39 params.append(self.appname)
40 if opinion_value is not None and self.opinion:
41 params.append(opinion_value)
43 params.append(self.version)
44 return os.path.join(path, *params)
47 def site_data_dir(self) -> str:
48 """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
49 path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
50 return self._append_parts(path)
53 def user_config_dir(self) -> str:
54 """:return: config directory tied to the user, same as `user_data_dir`"""
55 return self.user_data_dir
58 def site_config_dir(self) -> str:
59 """:return: config directory shared by the users, same as `site_data_dir`"""
60 return self.site_data_dir
63 def user_cache_dir(self) -> str:
65 :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
66 ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
68 path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
69 return self._append_parts(path, opinion_value="Cache")
72 def user_state_dir(self) -> str:
73 """:return: state directory tied to the user, same as `user_data_dir`"""
74 return self.user_data_dir
77 def user_log_dir(self) -> str:
79 :return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it
81 path = self.user_data_dir
83 path = os.path.join(path, "Logs")
87 def user_documents_dir(self) -> str:
89 :return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``
91 return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
94 def user_runtime_dir(self) -> str:
96 :return: runtime directory tied to the user, e.g.
97 ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
99 path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))
100 return self._append_parts(path)
103 def get_win_folder_from_env_vars(csidl_name: str) -> str:
104 """Get folder from environment variables."""
105 if csidl_name == "CSIDL_PERSONAL": # does not have an environment name
106 return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")
109 "CSIDL_APPDATA": "APPDATA",
110 "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
111 "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
113 if env_var_name is None:
114 raise ValueError(f"Unknown CSIDL name: {csidl_name}")
115 result = os.environ.get(env_var_name)
117 raise ValueError(f"Unset environment variable: {env_var_name}")
121 def get_win_folder_from_registry(csidl_name: str) -> str:
122 """Get folder from the registry.
124 This is a fallback technique at best. I'm not sure if using the
125 registry for this guarantees us the correct answer for all CSIDL_*
128 shell_folder_name = {
129 "CSIDL_APPDATA": "AppData",
130 "CSIDL_COMMON_APPDATA": "Common AppData",
131 "CSIDL_LOCAL_APPDATA": "Local AppData",
132 "CSIDL_PERSONAL": "Personal",
134 if shell_folder_name is None:
135 raise ValueError(f"Unknown CSIDL name: {csidl_name}")
136 if sys.platform != "win32": # only needed for mypy type checker to know that this code runs only on Windows
137 raise NotImplementedError
140 key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
141 directory, _ = winreg.QueryValueEx(key, shell_folder_name)
142 return str(directory)
145 def get_win_folder_via_ctypes(csidl_name: str) -> str:
146 """Get folder with ctypes."""
149 "CSIDL_COMMON_APPDATA": 35,
150 "CSIDL_LOCAL_APPDATA": 28,
153 if csidl_const is None:
154 raise ValueError(f"Unknown CSIDL name: {csidl_name}")
156 buf = ctypes.create_unicode_buffer(1024)
157 windll = getattr(ctypes, "windll") # noqa: B009 # using getattr to avoid false positive with mypy type checker
158 windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
160 # Downgrade to short path name if it has highbit chars.
161 if any(ord(c) > 255 for c in buf):
162 buf2 = ctypes.create_unicode_buffer(1024)
163 if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
169 def _pick_get_win_folder() -> Callable[[str], str]:
170 if hasattr(ctypes, "windll"):
171 return get_win_folder_via_ctypes
173 import winreg # noqa: F401
175 return get_win_folder_from_env_vars
177 return get_win_folder_from_registry
180 get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())