Moved non-gui parts to their own dir.
[zeroinstall.git] / injector / basedir.py
blobe389ee03abf0d8c7ffbabcb579a7f154b9b238c8
1 from __future__ import generators
2 import os
4 _home = os.environ.get('HOME', '/')
5 xdg_data_home = os.environ.get('XDG_DATA_HOME',
6 os.path.join(_home, '.local', 'share'))
8 xdg_data_dirs = [xdg_data_home] + \
9 os.environ.get('XDG_DATA_DIRS', '/usr/local/share:/usr/share').split(':')
11 xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
12 os.path.join(_home, '.config'))
14 xdg_config_dirs = [xdg_config_home] + \
15 os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg').split(':')
17 xdg_data_dirs = filter(lambda x: x, xdg_data_dirs)
18 xdg_config_dirs = filter(lambda x: x, xdg_config_dirs)
20 def save_config_path(*resource):
21 """Ensure $XDG_CONFIG_HOME/<resource>/ exists, and return its path.
22 'resource' should normally be the name of your application. Use this
23 when SAVING configuration settings. Use the xdg_config_dirs variable
24 for loading."""
25 resource = os.path.join(*resource)
26 assert not resource.startswith('/')
27 path = os.path.join(xdg_config_home, resource)
28 if not os.path.isdir(path):
29 os.makedirs(path, 0700)
30 return path
32 def save_data_path(*resource):
33 """Ensure $XDG_DATA_HOME/<resource>/ exists, and return its path.
34 'resource' is the name of some shared resource. Use this when updating
35 a shared (between programs) database. Use the xdg_data_dirs variable
36 for loading."""
37 resource = os.path.join(*resource)
38 assert not resource.startswith('/')
39 path = os.path.join(xdg_data_home, resource)
40 if not os.path.isdir(path):
41 os.makedirs(path)
42 return path
44 def load_config_paths(*resource):
45 """Returns an iterator which gives each directory named 'resource' in the
46 configuration search path. Information provided by earlier directories should
47 take precedence over later ones (ie, the user's config dir comes first)."""
48 resource = os.path.join(*resource)
49 for config_dir in xdg_config_dirs:
50 path = os.path.join(config_dir, resource)
51 if os.path.exists(path): yield path
53 def load_first_config(*resource):
54 """Returns the first result from load_config_paths, or None if there is nothing
55 to load."""
56 for x in load_config_paths(*resource):
57 return x
58 return None
60 def load_data_paths(*resource):
61 """Returns an iterator which gives each directory named 'resource' in the
62 shared data search path. Information provided by earlier directories should
63 take precedence over later ones."""
64 resource = os.path.join(*resource)
65 for data_dir in xdg_data_dirs:
66 path = os.path.join(data_dir, resource)
67 if os.path.exists(path): yield path