Allow "" as a valid value in a OptionsBox menu (reported by Guido Schimmels).
[rox-lib.git] / python / rox / basedir.py
blobdd0386df3c5d9ea570f4ef67890128e77e3a399d
1 """The freedesktop.org Base Directory specification provides a way for
2 applications to locate shared data and configuration:
4 http://www.freedesktop.org/standards/
6 This module can be used to load and save from and to these directories.
8 Typical usage:
10 from rox import basedir
12 for dir in basedir.load_config_paths('MyProg/Options'):
13 print "Load settings from", dir
15 dir = basedir.save_config_path('MyProg')
16 print >>file(os.path.join(dir, 'Options'), 'w'), "foo=2"
18 Note: see the rox.Options module for a higher-level API for managing options.
19 """
21 from __future__ import generators
22 import os
24 _home = os.environ.get('HOME', '/')
25 xdg_data_home = os.environ.get('XDG_DATA_HOME',
26 os.path.join(_home, '.local', 'share'))
28 xdg_data_dirs = [xdg_data_home] + \
29 os.environ.get('XDG_DATA_DIRS', '/usr/local/share:/usr/share').split(':')
31 xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
32 os.path.join(_home, '.config'))
34 xdg_config_dirs = [xdg_config_home] + \
35 os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg').split(':')
37 xdg_data_dirs = filter(lambda x: x, xdg_data_dirs)
38 xdg_config_dirs = filter(lambda x: x, xdg_config_dirs)
40 def save_config_path(resource):
41 """Ensure $XDG_CONFIG_HOME/<resource>/ exists, and return its path.
42 'resource' should normally be the name of your application. Use this
43 when SAVING configuration settings. Use the xdg_config_dirs variable
44 for loading."""
45 assert not resource.startswith('/')
46 path = os.path.join(xdg_config_home, resource)
47 if not os.path.isdir(path):
48 os.makedirs(path, 0700)
49 return path
51 def save_data_path(resource):
52 """Ensure $XDG_DATA_HOME/<resource>/ exists, and return its path.
53 'resource' is the name of some shared resource. Use this when updating
54 a shared (between programs) database. Use the xdg_data_dirs variable
55 for loading."""
56 assert not resource.startswith('/')
57 path = os.path.join(xdg_data_home, resource)
58 if not os.path.isdir(path):
59 os.makedirs(path)
60 return path
62 def load_config_paths(resource):
63 """Returns an iterator which gives each directory named 'resource' in the
64 configuration search path. Information provided by earlier directories should
65 take precedence over later ones (ie, the user's config dir comes first)."""
66 for config_dir in xdg_config_dirs:
67 path = os.path.join(config_dir, resource)
68 if os.path.exists(path): yield path
70 def load_data_paths(resource):
71 """Returns an iterator which gives each directory named 'resource' in the
72 shared data search path. Information provided by earlier directories should
73 take precedence over later ones."""
74 for data_dir in xdg_data_dirs:
75 path = os.path.join(data_dir, resource)
76 if os.path.exists(path): yield path