windows.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from __future__ import annotations
  2. import ctypes
  3. import os
  4. import sys
  5. from functools import lru_cache
  6. from typing import Callable
  7. from .api import PlatformDirsABC
  8. class Windows(PlatformDirsABC):
  9. """`MSDN on where to store app data files
  10. <http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120>`_.
  11. Makes use of the
  12. `appname <platformdirs.api.PlatformDirsABC.appname>`,
  13. `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`,
  14. `version <platformdirs.api.PlatformDirsABC.version>`,
  15. `roaming <platformdirs.api.PlatformDirsABC.roaming>`,
  16. `opinion <platformdirs.api.PlatformDirsABC.opinion>`."""
  17. @property
  18. def user_data_dir(self) -> str:
  19. """
  20. :return: data directory tied to the user, e.g.
  21. ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
  22. ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
  23. """
  24. const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
  25. path = os.path.normpath(get_win_folder(const))
  26. return self._append_parts(path)
  27. def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
  28. params = []
  29. if self.appname:
  30. if self.appauthor is not False:
  31. author = self.appauthor or self.appname
  32. params.append(author)
  33. params.append(self.appname)
  34. if opinion_value is not None and self.opinion:
  35. params.append(opinion_value)
  36. if self.version:
  37. params.append(self.version)
  38. return os.path.join(path, *params)
  39. @property
  40. def site_data_dir(self) -> str:
  41. """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
  42. path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
  43. return self._append_parts(path)
  44. @property
  45. def user_config_dir(self) -> str:
  46. """:return: config directory tied to the user, same as `user_data_dir`"""
  47. return self.user_data_dir
  48. @property
  49. def site_config_dir(self) -> str:
  50. """:return: config directory shared by the users, same as `site_data_dir`"""
  51. return self.site_data_dir
  52. @property
  53. def user_cache_dir(self) -> str:
  54. """
  55. :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
  56. ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
  57. """
  58. path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
  59. return self._append_parts(path, opinion_value="Cache")
  60. @property
  61. def user_state_dir(self) -> str:
  62. """:return: state directory tied to the user, same as `user_data_dir`"""
  63. return self.user_data_dir
  64. @property
  65. def user_log_dir(self) -> str:
  66. """
  67. :return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it
  68. """
  69. path = self.user_data_dir
  70. if self.opinion:
  71. path = os.path.join(path, "Logs")
  72. return path
  73. @property
  74. def user_documents_dir(self) -> str:
  75. """
  76. :return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``
  77. """
  78. return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
  79. @property
  80. def user_runtime_dir(self) -> str:
  81. """
  82. :return: runtime directory tied to the user, e.g.
  83. ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
  84. """
  85. path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))
  86. return self._append_parts(path)
  87. def get_win_folder_from_env_vars(csidl_name: str) -> str:
  88. """Get folder from environment variables."""
  89. if csidl_name == "CSIDL_PERSONAL": # does not have an environment name
  90. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")
  91. env_var_name = {
  92. "CSIDL_APPDATA": "APPDATA",
  93. "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
  94. "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
  95. }.get(csidl_name)
  96. if env_var_name is None:
  97. raise ValueError(f"Unknown CSIDL name: {csidl_name}")
  98. result = os.environ.get(env_var_name)
  99. if result is None:
  100. raise ValueError(f"Unset environment variable: {env_var_name}")
  101. return result
  102. def get_win_folder_from_registry(csidl_name: str) -> str:
  103. """Get folder from the registry.
  104. This is a fallback technique at best. I'm not sure if using the
  105. registry for this guarantees us the correct answer for all CSIDL_*
  106. names.
  107. """
  108. shell_folder_name = {
  109. "CSIDL_APPDATA": "AppData",
  110. "CSIDL_COMMON_APPDATA": "Common AppData",
  111. "CSIDL_LOCAL_APPDATA": "Local AppData",
  112. "CSIDL_PERSONAL": "Personal",
  113. }.get(csidl_name)
  114. if shell_folder_name is None:
  115. raise ValueError(f"Unknown CSIDL name: {csidl_name}")
  116. if sys.platform != "win32": # only needed for mypy type checker to know that this code runs only on Windows
  117. raise NotImplementedError
  118. import winreg
  119. key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
  120. directory, _ = winreg.QueryValueEx(key, shell_folder_name)
  121. return str(directory)
  122. def get_win_folder_via_ctypes(csidl_name: str) -> str:
  123. """Get folder with ctypes."""
  124. csidl_const = {
  125. "CSIDL_APPDATA": 26,
  126. "CSIDL_COMMON_APPDATA": 35,
  127. "CSIDL_LOCAL_APPDATA": 28,
  128. "CSIDL_PERSONAL": 5,
  129. }.get(csidl_name)
  130. if csidl_const is None:
  131. raise ValueError(f"Unknown CSIDL name: {csidl_name}")
  132. buf = ctypes.create_unicode_buffer(1024)
  133. windll = getattr(ctypes, "windll") # noqa: B009 # using getattr to avoid false positive with mypy type checker
  134. windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
  135. # Downgrade to short path name if it has highbit chars.
  136. if any(ord(c) > 255 for c in buf):
  137. buf2 = ctypes.create_unicode_buffer(1024)
  138. if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
  139. buf = buf2
  140. return buf.value
  141. def _pick_get_win_folder() -> Callable[[str], str]:
  142. if hasattr(ctypes, "windll"):
  143. return get_win_folder_via_ctypes
  144. try:
  145. import winreg # noqa: F401
  146. except ImportError:
  147. return get_win_folder_from_env_vars
  148. else:
  149. return get_win_folder_from_registry
  150. get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())
  151. __all__ = [
  152. "Windows",
  153. ]