Coverage for torxtools/xdgtools.py: 100%

9 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-18 01: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""" 

6import os 

7 

8from torxtools.pathtools import expandpath 

9 

10__all__ = [ 

11 "setenv", 

12] 

13 

14_defaults = { 

15 "XDG_CONFIG_DIR": "/etc/xdg", 

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

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

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

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

20 "XDG_RUNTIME_DIR": None, 

21} 

22 

23 

24def setenv() -> None: 

25 """ 

26 XDG Base Directory Specification environment variables setter. 

27 

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

29 :ev:`XDG_CONFIG_HOME`, :ev:`XDG_DATA_HOME`, :ev:`XDG_CONFIG_DIRS`, 

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

31 according to current os.environ or their defaults. 

32 

33 All paths will be expanded before being set. 

34 

35 Example 

36 ------- 

37 

38 .. code-block:: python 

39 

40 from torxtools import xdgtools, pathtools 

41 

42 try: 

43 del os.environ["XDG_CONFIG_HOME"] 

44 except: 

45 pass 

46 # We changed the XDG environment: 

47 xdgtools.setenv() 

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

49 

50 See Also 

51 -------- 

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

53 """ 

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

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

56 if path: 

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