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.
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.
21 from __future__
import generators
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 #print "Config load", xdg_config_dirs
41 #print "Config save", xdg_config_home
42 #print "Data load", xdg_data_dirs
43 #print "Data save", xdg_data_home
45 def save_config_path(resource
):
46 """Ensure $XDG_CONFIG_HOME/<resource>/ exists, and return its path.
47 'resource' should normally be the name of your application. Use this
48 when SAVING configuration settings. Use the xdg_config_dirs variable
50 assert not resource
.startswith('/')
51 path
= os
.path
.join(xdg_config_home
, resource
)
52 if not os
.path
.isdir(path
):
53 os
.makedirs(path
, 0700)
56 def save_data_path(resource
):
57 """Ensure $XDG_DATA_HOME/<resource>/ exists, and return its path.
58 'resource' is the name of some shared resource. Use this when updating
59 a shared (between programs) database. Use the xdg_data_dirs variable
61 assert not resource
.startswith('/')
62 path
= os
.path
.join(xdg_data_home
, resource
)
63 if not os
.path
.isdir(path
):
67 def load_config_paths(resource
):
68 """Returns an iterator which gives each directory named 'resource' in the
69 configuration search path. Information provided by earlier directories should
70 take precedence over later ones (ie, the user's config dir comes first)."""
71 for dir in xdg_config_dirs
:
72 path
= os
.path
.join(dir, resource
)
73 if os
.path
.exists(path
): yield path
75 def load_data_paths(resource
):
76 """Returns an iterator which gives each directory named 'resource' in the
77 shared data search path. Information provided by earlier directories should
78 take precedence over later ones."""
79 for dir in xdg_data_dirs
:
80 path
= os
.path
.join(dir, resource
)
81 if os
.path
.exists(path
): yield path