Coverage for torxtools/xdgtools.py: 100%

9 statements  

« prev     ^ index     » next       coverage.py v7.6.9, created at 2024-12-20 22:02 +0000

1""" 

2Functions for working with xdg paths and environment. 

3 

4The :func:`setenv` function sets all XDG single directory environment variables to their values. It is also called on module instantiation. 

5""" 

6 

7import os 

8 

9from torxtools.pathtools import expandpath 

10 

11__all__ = [ 

12 "setenv", 

13] 

14 

15_defaults = { 

16 "XDG_CONFIG_DIR": "/etc/xdg", 

17 "XDG_DATA_DIR": "/usr/local/share:/usr/share", 

18 "XDG_CACHE_HOME": "$HOME/.cache", 

19 "XDG_CONFIG_HOME": "$HOME/.config", 

20 "XDG_DATA_HOME": "$HOME/.local/share", 

21 "XDG_RUNTIME_DIR": None, 

22} 

23 

24 

25def setenv() -> None: 

26 """ 

27 XDG Base Directory Specification environment variables setter. 

28 

29 Sets all XDG environment variables (:ev:`XDG_CACHE_HOME`, 

30 :ev:`XDG_CONFIG_HOME`, :ev:`XDG_DATA_HOME`, :ev:`XDG_CONFIG_DIRS`, 

31 :ev:`XDG_DATA_DIRS`, and :ev:`XDG_RUNTIME_DIR`) to their respective values 

32 according to current os.environ or their defaults. 

33 

34 All paths will be expanded before being set. 

35 

36 Example 

37 ------- 

38 

39 .. code-block:: python 

40 

41 from torxtools import xdgtools, pathtools 

42 

43 try: 

44 del os.environ["XDG_CONFIG_HOME"] 

45 except: 

46 pass 

47 # We changed the XDG environment: 

48 xdgtools.setenv() 

49 assert os.environ["XDG_CONFIG_HOME"] == pathtools.expandpath("$HOME/.config") 

50 

51 See Also 

52 -------- 

53 `XDG Base Directory Specification <https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html>`__ 

54 """ 

55 for k, v in _defaults.items(): 

56 path = os.environ.get(k, v) 

57 if path: 

58 os.environ[k] = expandpath(path)