Added 'basedir' module for freedesktop.org Base Directory specification.
[rox-lib.git] / python / rox / basedir.py
blob84a883a0a87512abc4fee217cd4b04d1cb709666
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 print >>file(basedir.save_config_path('MyProg/Options'), 'w'),
16 "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
23 import stat
25 _home = os.environ.get('HOME', '/')
26 xdg_data_home = os.environ.get('XDG_DATA_HOME',
27 os.path.join(_home, '.local', 'share'))
29 xdg_data_dirs = [xdg_data_home] + \
30 os.environ.get('XDG_DATA_DIRS', '/usr/local/share:/usr/share').split(':')
32 xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
33 os.path.join(_home, '.config'))
35 xdg_config_dirs = [xdg_config_home] + \
36 os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg').split(':')
38 xdg_data_dirs = filter(lambda x: x, xdg_data_dirs)
39 xdg_config_dirs = filter(lambda x: x, xdg_config_dirs)
41 print "Config load", xdg_config_dirs
42 print "Config save", xdg_config_home
43 print
44 print "Data load", xdg_data_dirs
45 print "Data save", xdg_data_home
47 def save_config_path(resource):
48 """Ensure $XDG_CONFIG_HOME/<resource>/ exists, and return its path.
49 'resource' should normally be the name of your application. Use this
50 when SAVING configuration settings. Use the xdg_config_dirs variable
51 for loading."""
52 assert not resource.startswith('/')
53 path = os.path.join(xdg_config_home, resource)
54 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
60 for loading."""
61 assert not resource.startswith('/')
62 path = os.path.join(xdg_data_home, resource)
63 os.makedirs(path)
65 def load_config_paths(resource):
66 """Returns an iterator which gives each directory named 'resource' in the
67 configuration search path. Information provided by earlier directories should
68 take precedence over later ones (ie, the user's config dir comes first)."""
69 for dir in xdg_config_dirs:
70 path = os.path.join(dir, resource)
71 if os.path.exists(path): yield path
73 def load_data_paths(resource):
74 """Returns an iterator which gives each directory named 'resource' in the
75 shared data search path. Information provided by earlier directories should
76 take precedence over later ones."""
77 for dir in xdg_data_dirs:
78 path = os.path.join(dir, resource)
79 if os.path.exists(path): yield path