Clarified copyrights.
[zeroinstall.git] / zeroinstall / injector / basedir.py
blobeba43d40ba672ea898801baacdbf22950ed66b59
1 # Copyright (C) 2006, Thomas Leonard
2 # See the README file for details, or visit http://0install.net.
4 from __future__ import generators
5 import os
7 _home = os.environ.get('HOME', '/')
9 xdg_cache_home = os.environ.get('XDG_CACHE_HOME',
10 os.path.join(_home, '.cache'))
12 xdg_cache_dirs = [xdg_cache_home] + \
13 os.environ.get('XDG_CACHE_DIRS', '').split(':')
15 xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
16 os.path.join(_home, '.config'))
18 xdg_config_dirs = [xdg_config_home] + \
19 os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg').split(':')
21 xdg_cache_dirs = filter(lambda x: x, xdg_cache_dirs)
22 xdg_config_dirs = filter(lambda x: x, xdg_config_dirs)
24 def save_config_path(*resource):
25 """Ensure $XDG_CONFIG_HOME/<resource>/ exists, and return its path.
26 'resource' should normally be the name of your application. Use this
27 when SAVING configuration settings. Use the xdg_config_dirs variable
28 for loading."""
29 resource = os.path.join(*resource)
30 assert not resource.startswith('/')
31 path = os.path.join(xdg_config_home, resource)
32 if not os.path.isdir(path):
33 os.makedirs(path, 0700)
34 return path
36 def load_config_paths(*resource):
37 """Returns an iterator which gives each directory named 'resource' in the
38 configuration search path. Information provided by earlier directories should
39 take precedence over later ones (ie, the user's config dir comes first)."""
40 resource = os.path.join(*resource)
41 for config_dir in xdg_config_dirs:
42 path = os.path.join(config_dir, resource)
43 if os.path.exists(path): yield path
45 def load_first_config(*resource):
46 """Returns the first result from load_config_paths, or None if there is nothing
47 to load."""
48 for x in load_config_paths(*resource):
49 return x
50 return None
53 def save_cache_path(*resource):
54 """Ensure $XDG_CACHE_HOME/<resource>/ exists, and return its path.
55 'resource' should normally be the name of your application."""
56 resource = os.path.join(*resource)
57 assert not resource.startswith('/')
58 path = os.path.join(xdg_cache_home, resource)
59 if not os.path.isdir(path):
60 os.makedirs(path, 0700)
61 return path
63 def load_cache_paths(*resource):
64 """Returns an iterator which gives each directory named 'resource' in the
65 cache search path. Information provided by earlier directories should
66 take precedence over later ones (ie, the user's cache dir comes first)."""
67 resource = os.path.join(*resource)
68 for cache_dir in xdg_cache_dirs:
69 path = os.path.join(cache_dir, resource)
70 if os.path.exists(path): yield path
72 def load_first_cache(*resource):
73 """Returns the first result from load_cache_paths, or None if there is nothing
74 to load."""
75 for x in load_cache_paths(*resource):
76 return x
77 return None