windows.py 6.3 KB

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