#|hide #|default_exp xdg #|export from fastcore.utils import * from contextlib import contextmanager @contextmanager def env(variable, value): old = os.environ.get(variable, None) try: os.environ[variable] = value yield finally: if old is None: del os.environ[variable] else: os.environ[variable] = old #|export def _path_from_env(variable, default): value = os.environ.get(variable) if value and os.path.isabs(value): return Path(value) return default #|export def _paths_from_env(variable, default): value = os.environ.get(variable) if value: paths = [Path(o) for o in value.split(":") if os.path.isabs(o)] if paths: return paths return default #|export def xdg_cache_home(): "Path corresponding to `XDG_CACHE_HOME`" return _path_from_env("XDG_CACHE_HOME", Path.home()/".cache") from fastcore.test import * test_eq(xdg_cache_home(), Path.home()/'.cache') with env('XDG_CACHE_HOME', '/home/fastai/.cache'): test_eq(xdg_cache_home(), Path('/home/fastai/.cache')) #|export def xdg_config_dirs(): "Paths corresponding to `XDG_CONFIG_DIRS`" return _paths_from_env("XDG_CONFIG_DIRS", [Path("/etc/xdg")]) test_eq(xdg_config_dirs(), [Path('/etc/xdg')]) with env('XDG_CONFIG_DIRS', '/home/fastai/.xdg:/home/fastai/.config'): test_eq(xdg_config_dirs(), [Path('/home/fastai/.xdg'), Path('/home/fastai/.config')]) #|export def xdg_config_home(): "Path corresponding to `XDG_CONFIG_HOME`" return _path_from_env("XDG_CONFIG_HOME", Path.home()/".config") test_eq(xdg_config_home(), Path.home()/'.config') with env('XDG_CONFIG_HOME', '/home/fastai/.config'): test_eq(xdg_config_home(), Path('/home/fastai/.config')) #|export def xdg_data_dirs(): "Paths corresponding to XDG_DATA_DIRS`" return _paths_from_env( "XDG_DATA_DIRS", [Path(o) for o in "/usr/local/share/:/usr/share/".split(":")]) #|export def xdg_data_home(): "Path corresponding to `XDG_DATA_HOME`" return _path_from_env("XDG_DATA_HOME", Path.home()/".local"/"share") test_eq(xdg_data_home(), Path.home()/'.local/share') with env('XDG_DATA_HOME', '/home/fastai/.data'): test_eq(xdg_data_home(), Path('/home/fastai/.data')) #|export def xdg_runtime_dir(): "Path corresponding to `XDG_RUNTIME_DIR`" value = os.getenv("XDG_RUNTIME_DIR") return Path(value) if value and os.path.isabs(value) else None #|export def xdg_state_home(): "Path corresponding to `XDG_STATE_HOME`" return _path_from_env("XDG_STATE_HOME", Path.home()/".local"/"state") test_eq(xdg_state_home(), Path.home()/'.local/state') with env('XDG_STATE_HOME', '/home/fastai/.state'): test_eq(xdg_state_home(), Path('/home/fastai/.state')) #|hide #|eval: false from nbdev import nbdev_export nbdev_export()