Debian Codegraph @

pyinstrument/vendor/appdirs.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2005-2010 ActiveState Software Inc.
3 # Copyright (c) 2013 Eddy Petrișor
4
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the
7 # "Software"), to deal in the Software without restriction, including
8 # without limitation the rights to use, copy, modify, merge, publish,
9 # distribute, sublicense, and/or sell copies of the Software, and to
10 # permit persons to whom the Software is furnished to do so, subject to
11 # the following conditions:
12
13 # The above copyright notice and this permission notice shall be included
14 # in all copies or substantial portions of the Software.
15
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
24 """Utilities for determining application-specific dirs.
25
26 See <https://github.com/ActiveState/appdirs> for details and usage.
27 """
28 # Dev Notes:
29 # - MSDN on where to store app data files:
30 # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120
31 # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html
32 # - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
33
34 __version__ = "1.4.4"
35 __version_info__ = tuple(int(segment) for segment in __version__.split("."))
36
37
38 import sys
39 import os
40
41 PY3 = sys.version_info[0] == 3
42
43 if PY3:
44 unicode = str
45
46 if sys.platform.startswith('java'):
47 import platform
48 os_name = platform.java_ver()[3][0]
49 if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc.
50 system = 'win32'
51 elif os_name.startswith('Mac'): # "Mac OS X", etc.
52 system = 'darwin'
53 else: # "Linux", "SunOS", "FreeBSD", etc.
54 # Setting this to "linux2" is not ideal, but only Windows or Mac
55 # are actually checked for and the rest of the module expects
56 # *sys.platform* style strings.
57 system = 'linux2'
58 else:
59 system = sys.platform
60
61
62
63 def user_data_dir(appname=None, appauthor=None, version=None, roaming=False) -> str:
64 r"""Return full path to the user-specific data dir for this application.
65
66 "appname" is the name of application.
67 If None, just the system directory is returned.
68 "appauthor" (only used on Windows) is the name of the
69 appauthor or distributing body for this application. Typically
70 it is the owning company name. This falls back to appname. You may
71 pass False to disable it.
72 "version" is an optional version path element to append to the
73 path. You might want to use this if you want multiple versions
74 of your app to be able to run independently. If used, this
75 would typically be "<major>.<minor>".
76 Only applied when appname is present.
77 "roaming" (boolean, default False) can be set True to use the Windows
78 roaming appdata directory. That means that for users on a Windows
79 network setup for roaming profiles, this user data will be
80 sync'd on login. See
81 <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
82 for a discussion of issues.
83
84 Typical user data directories are:
85 Mac OS X: ~/Library/Application Support/<AppName>
86 Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
87 Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
88 Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
89 Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
90 Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>
91
92 For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
93 That means, by default "~/.local/share/<AppName>".
94 """
95 if system == "win32":
96 if appauthor is None:
97 appauthor = appname
98 const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
99 path = os.path.normpath(_get_win_folder(const))
100 if appname:
101 if appauthor is not False:
102 path = os.path.join(path, appauthor, appname)
103 else:
104 path = os.path.join(path, appname)
105 elif system == 'darwin':
106 path = os.path.expanduser('~/Library/Application Support/')
107 if appname:
108 path = os.path.join(path, appname)
109 else:
110 path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share"))
111 if appname:
112 path = os.path.join(path, appname)
113 if appname and version:
114 path = os.path.join(path, version)
115 return path
116
117
118 def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
119 r"""Return full path to the user-shared data dir for this application.
120
121 "appname" is the name of application.
122 If None, just the system directory is returned.
123 "appauthor" (only used on Windows) is the name of the
124 appauthor or distributing body for this application. Typically
125 it is the owning company name. This falls back to appname. You may
126 pass False to disable it.
127 "version" is an optional version path element to append to the
128 path. You might want to use this if you want multiple versions
129 of your app to be able to run independently. If used, this
130 would typically be "<major>.<minor>".
131 Only applied when appname is present.
132 "multipath" is an optional parameter only applicable to *nix
133 which indicates that the entire list of data dirs should be
134 returned. By default, the first item from XDG_DATA_DIRS is
135 returned, or '/usr/local/share/<AppName>',
136 if XDG_DATA_DIRS is not set
137
138 Typical site data directories are:
139 Mac OS X: /Library/Application Support/<AppName>
140 Unix: /usr/local/share/<AppName> or /usr/share/<AppName>
141 Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName>
142 Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
143 Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7.
144
145 For Unix, this is using the $XDG_DATA_DIRS[0] default.
146
147 WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
148 """
149 if system == "win32":
150 if appauthor is None:
151 appauthor = appname
152 path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA"))
153 if appname:
154 if appauthor is not False:
155 path = os.path.join(path, appauthor, appname)
156 else:
157 path = os.path.join(path, appname)
158 elif system == 'darwin':
159 path = os.path.expanduser('/Library/Application Support')
160 if appname:
161 path = os.path.join(path, appname)
162 else:
163 # XDG default for $XDG_DATA_DIRS
164 # only first, if multipath is False
165 path = os.getenv('XDG_DATA_DIRS',
166 os.pathsep.join(['/usr/local/share', '/usr/share']))
167 pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
168 if appname:
169 if version:
170 appname = os.path.join(appname, version)
171 pathlist = [os.sep.join([x, appname]) for x in pathlist]
172
173 if multipath:
174 path = os.pathsep.join(pathlist)
175 else:
176 path = pathlist[0]
177 return path
178
179 if appname and version:
180 path = os.path.join(path, version)
181 return path
182
183
184 def user_config_dir(appname=None, appauthor=None, version=None, roaming=False):
185 r"""Return full path to the user-specific config dir for this application.
186
187 "appname" is the name of application.
188 If None, just the system directory is returned.
189 "appauthor" (only used on Windows) is the name of the
190 appauthor or distributing body for this application. Typically
191 it is the owning company name. This falls back to appname. You may
192 pass False to disable it.
193 "version" is an optional version path element to append to the
194 path. You might want to use this if you want multiple versions
195 of your app to be able to run independently. If used, this
196 would typically be "<major>.<minor>".
197 Only applied when appname is present.
198 "roaming" (boolean, default False) can be set True to use the Windows
199 roaming appdata directory. That means that for users on a Windows
200 network setup for roaming profiles, this user data will be
201 sync'd on login. See
202 <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
203 for a discussion of issues.
204
205 Typical user config directories are:
206 Mac OS X: ~/Library/Preferences/<AppName>
207 Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined
208 Win *: same as user_data_dir
209
210 For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
211 That means, by default "~/.config/<AppName>".
212 """
213 if system == "win32":
214 path = user_data_dir(appname, appauthor, None, roaming)
215 elif system == 'darwin':
216 path = os.path.expanduser('~/Library/Preferences/')
217 if appname:
218 path = os.path.join(path, appname)
219 else:
220 path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
221 if appname:
222 path = os.path.join(path, appname)
223 if appname and version:
224 path = os.path.join(path, version)
225 return path
226
227
228 def site_config_dir(appname=None, appauthor=None, version=None, multipath=False):
229 r"""Return full path to the user-shared data dir for this application.
230
231 "appname" is the name of application.
232 If None, just the system directory is returned.
233 "appauthor" (only used on Windows) is the name of the
234 appauthor or distributing body for this application. Typically
235 it is the owning company name. This falls back to appname. You may
236 pass False to disable it.
237 "version" is an optional version path element to append to the
238 path. You might want to use this if you want multiple versions
239 of your app to be able to run independently. If used, this
240 would typically be "<major>.<minor>".
241 Only applied when appname is present.
242 "multipath" is an optional parameter only applicable to *nix
243 which indicates that the entire list of config dirs should be
244 returned. By default, the first item from XDG_CONFIG_DIRS is
245 returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set
246
247 Typical site config directories are:
248 Mac OS X: same as site_data_dir
249 Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in
250 $XDG_CONFIG_DIRS
251 Win *: same as site_data_dir
252 Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
253
254 For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False
255
256 WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
257 """
258 if system == 'win32':
259 path = site_data_dir(appname, appauthor)
260 if appname and version:
261 path = os.path.join(path, version)
262 elif system == 'darwin':
263 path = os.path.expanduser('/Library/Preferences')
264 if appname:
265 path = os.path.join(path, appname)
266 else:
267 # XDG default for $XDG_CONFIG_DIRS
268 # only first, if multipath is False
269 path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg')
270 pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
271 if appname:
272 if version:
273 appname = os.path.join(appname, version)
274 pathlist = [os.sep.join([x, appname]) for x in pathlist]
275
276 if multipath:
277 path = os.pathsep.join(pathlist)
278 else:
279 path = pathlist[0]
280 return path
281
282
283 def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):
284 r"""Return full path to the user-specific cache dir for this application.
285
286 "appname" is the name of application.
287 If None, just the system directory is returned.
288 "appauthor" (only used on Windows) is the name of the
289 appauthor or distributing body for this application. Typically
290 it is the owning company name. This falls back to appname. You may
291 pass False to disable it.
292 "version" is an optional version path element to append to the
293 path. You might want to use this if you want multiple versions
294 of your app to be able to run independently. If used, this
295 would typically be "<major>.<minor>".
296 Only applied when appname is present.
297 "opinion" (boolean) can be False to disable the appending of
298 "Cache" to the base app data dir for Windows. See
299 discussion below.
300
301 Typical user cache directories are:
302 Mac OS X: ~/Library/Caches/<AppName>
303 Unix: ~/.cache/<AppName> (XDG default)
304 Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache
305 Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache
306
307 On Windows the only suggestion in the MSDN docs is that local settings go in
308 the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming
309 app data dir (the default returned by `user_data_dir` above). Apps typically
310 put cache data somewhere *under* the given dir here. Some examples:
311 ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
312 ...\Acme\SuperApp\Cache\1.0
313 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
314 This can be disabled with the `opinion=False` option.
315 """
316 if system == "win32":
317 if appauthor is None:
318 appauthor = appname
319 path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA"))
320 if appname:
321 if appauthor is not False:
322 path = os.path.join(path, appauthor, appname)
323 else:
324 path = os.path.join(path, appname)
325 if opinion:
326 path = os.path.join(path, "Cache")
327 elif system == 'darwin':
328 path = os.path.expanduser('~/Library/Caches')
329 if appname:
330 path = os.path.join(path, appname)
331 else:
332 path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
333 if appname:
334 path = os.path.join(path, appname)
335 if appname and version:
336 path = os.path.join(path, version)
337 return path
338
339
340 def user_state_dir(appname=None, appauthor=None, version=None, roaming=False):
341 r"""Return full path to the user-specific state dir for this application.
342
343 "appname" is the name of application.
344 If None, just the system directory is returned.
345 "appauthor" (only used on Windows) is the name of the
346 appauthor or distributing body for this application. Typically
347 it is the owning company name. This falls back to appname. You may
348 pass False to disable it.
349 "version" is an optional version path element to append to the
350 path. You might want to use this if you want multiple versions
351 of your app to be able to run independently. If used, this
352 would typically be "<major>.<minor>".
353 Only applied when appname is present.
354 "roaming" (boolean, default False) can be set True to use the Windows
355 roaming appdata directory. That means that for users on a Windows
356 network setup for roaming profiles, this user data will be
357 sync'd on login. See
358 <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
359 for a discussion of issues.
360
361 Typical user state directories are:
362 Mac OS X: same as user_data_dir
363 Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined
364 Win *: same as user_data_dir
365
366 For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state>
367 to extend the XDG spec and support $XDG_STATE_HOME.
368
369 That means, by default "~/.local/state/<AppName>".
370 """
371 if system in ["win32", "darwin"]:
372 path = user_data_dir(appname, appauthor, None, roaming)
373 else:
374 path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state"))
375 if appname:
376 path = os.path.join(path, appname)
377 if appname and version:
378 path = os.path.join(path, version)
379 return path
380
381
382 def user_log_dir(appname=None, appauthor=None, version=None, opinion=True):
383 r"""Return full path to the user-specific log dir for this application.
384
385 "appname" is the name of application.
386 If None, just the system directory is returned.
387 "appauthor" (only used on Windows) is the name of the
388 appauthor or distributing body for this application. Typically
389 it is the owning company name. This falls back to appname. You may
390 pass False to disable it.
391 "version" is an optional version path element to append to the
392 path. You might want to use this if you want multiple versions
393 of your app to be able to run independently. If used, this
394 would typically be "<major>.<minor>".
395 Only applied when appname is present.
396 "opinion" (boolean) can be False to disable the appending of
397 "Logs" to the base app data dir for Windows, and "log" to the
398 base cache dir for Unix. See discussion below.
399
400 Typical user log directories are:
401 Mac OS X: ~/Library/Logs/<AppName>
402 Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined
403 Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs
404 Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs
405
406 On Windows the only suggestion in the MSDN docs is that local settings
407 go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
408 examples of what some windows apps use for a logs dir.)
409
410 OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
411 value for Windows and appends "log" to the user cache dir for Unix.
412 This can be disabled with the `opinion=False` option.
413 """
414 if system == "darwin":
415 path = os.path.join(
416 os.path.expanduser('~/Library/Logs'),
417 appname)
418 elif system == "win32":
419 path = user_data_dir(appname, appauthor, version)
420 version = False
421 if opinion:
422 path = os.path.join(path, "Logs")
423 else:
424 path = user_cache_dir(appname, appauthor, version)
425 version = False
426 if opinion:
427 path = os.path.join(path, "log")
428 if appname and version:
429 path = os.path.join(path, version)
430 return path
431
432
433 class AppDirs(object):
434 """Convenience wrapper for getting application dirs."""
435 def __init__(self, appname=None, appauthor=None, version=None,
436 roaming=False, multipath=False):
437 self.appname = appname
438 self.appauthor = appauthor
439 self.version = version
440 self.roaming = roaming
441 self.multipath = multipath
442
443 @property
444 def user_data_dir(self):
445 return user_data_dir(self.appname, self.appauthor,
446 version=self.version, roaming=self.roaming)
447
448 @property
449 def site_data_dir(self):
450 return site_data_dir(self.appname, self.appauthor,
451 version=self.version, multipath=self.multipath)
452
453 @property
454 def user_config_dir(self):
455 return user_config_dir(self.appname, self.appauthor,
456 version=self.version, roaming=self.roaming)
457
458 @property
459 def site_config_dir(self):
460 return site_config_dir(self.appname, self.appauthor,
461 version=self.version, multipath=self.multipath)
462
463 @property
464 def user_cache_dir(self):
465 return user_cache_dir(self.appname, self.appauthor,
466 version=self.version)
467
468 @property
469 def user_state_dir(self):
470 return user_state_dir(self.appname, self.appauthor,
471 version=self.version)
472
473 @property
474 def user_log_dir(self):
475 return user_log_dir(self.appname, self.appauthor,
476 version=self.version)
477
478
479 #---- internal support stuff
480
481 def _get_win_folder_from_registry(csidl_name):
482 """This is a fallback technique at best. I'm not sure if using the
483 registry for this guarantees us the correct answer for all CSIDL_*
484 names.
485 """
486 if PY3:
487 import winreg as _winreg
488 else:
489 import _winreg
490
491 shell_folder_name = {
492 "CSIDL_APPDATA": "AppData",
493 "CSIDL_COMMON_APPDATA": "Common AppData",
494 "CSIDL_LOCAL_APPDATA": "Local AppData",
495 }[csidl_name]
496
497 key = _winreg.OpenKey(
498 _winreg.HKEY_CURRENT_USER,
499 r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
500 )
501 dir, type = _winreg.QueryValueEx(key, shell_folder_name)
502 return dir
503
504
505 def _get_win_folder_with_ctypes(csidl_name):
506 import ctypes
507
508 csidl_const = {
509 "CSIDL_APPDATA": 26,
510 "CSIDL_COMMON_APPDATA": 35,
511 "CSIDL_LOCAL_APPDATA": 28,
512 }[csidl_name]
513
514 buf = ctypes.create_unicode_buffer(1024)
515 ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
516
517 # Downgrade to short path name if have highbit chars. See
518 # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
519 has_high_char = False
520 for c in buf:
521 if ord(c) > 255:
522 has_high_char = True
523 break
524 if has_high_char:
525 buf2 = ctypes.create_unicode_buffer(1024)
526 if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
527 buf = buf2
528
529 return buf.value
530
531 def _get_win_folder_with_jna(csidl_name):
532 import array
533 from com.sun import jna
534 from com.sun.jna.platform import win32
535
536 buf_size = win32.WinDef.MAX_PATH * 2
537 buf = array.zeros('c', buf_size)
538 shell = win32.Shell32.INSTANCE
539 shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
540 dir = jna.Native.toString(buf.tostring()).rstrip("\0")
541
542 # Downgrade to short path name if have highbit chars. See
543 # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
544 has_high_char = False
545 for c in dir:
546 if ord(c) > 255:
547 has_high_char = True
548 break
549 if has_high_char:
550 buf = array.zeros('c', buf_size)
551 kernel = win32.Kernel32.INSTANCE
552 if kernel.GetShortPathName(dir, buf, buf_size):
553 dir = jna.Native.toString(buf.tostring()).rstrip("\0")
554
555 return dir
556
557 if system == "win32":
558 try:
559 from ctypes import windll
560 except ImportError:
561 try:
562 import com.sun.jna
563 except ImportError:
564 _get_win_folder = _get_win_folder_from_registry
565 else:
566 _get_win_folder = _get_win_folder_with_jna
567 else:
568 _get_win_folder = _get_win_folder_with_ctypes
569
570
571 #---- self test code
572
573 if __name__ == "__main__":
574 appname = "MyApp"
575 appauthor = "MyCompany"
576
577 props = ("user_data_dir",
578 "user_config_dir",
579 "user_cache_dir",
580 "user_state_dir",
581 "user_log_dir",
582 "site_data_dir",
583 "site_config_dir")
584
585 print("-- app dirs %s --" % __version__)
586
587 print("-- app dirs (with optional 'version')")
588 dirs = AppDirs(appname, appauthor, version="1.0")
589 for prop in props:
590 print("%s: %s" % (prop, getattr(dirs, prop)))
591
592 print("\n-- app dirs (without optional 'version')")
593 dirs = AppDirs(appname, appauthor)
594 for prop in props:
595 print("%s: %s" % (prop, getattr(dirs, prop)))
596
597 print("\n-- app dirs (without optional 'appauthor')")
598 dirs = AppDirs(appname)
599 for prop in props:
600 print("%s: %s" % (prop, getattr(dirs, prop)))
601
602 print("\n-- app dirs (with disabled 'appauthor')")
603 dirs = AppDirs(appname, appauthor=False)
604 for prop in props:
605 print("%s: %s" % (prop, getattr(dirs, prop)))