comparison pytouhou/utils/xdg.py @ 567:b2269b9c6119

Add a configuration parser, and pass those options to argparse as defaults. Also include an xdg helper.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Tue, 01 Jul 2014 23:17:40 +0200
parents
children
comparison
equal deleted inserted replaced
566:04ae31809dc7 567:b2269b9c6119
1 # -*- encoding: utf-8
2 """
3 This module is based on a rox module (LGPL):
4
5 http://cvs.sourceforge.net/viewcvs.py/rox/ROX-Lib2/python/rox/basedir.py?rev=1.9&view=log
6
7 The freedesktop.org Base Directory specification provides a way for
8 applications to locate shared data and configuration:
9
10 http://standards.freedesktop.org/basedir-spec/
11
12 (based on version 0.6)
13
14 This module can be used to load and save from and to these directories.
15
16 Typical usage:
17
18 from rox import basedir
19
20 for dir in basedir.load_config_paths('mydomain.org', 'MyProg', 'Options'):
21 print "Load settings from", dir
22
23 dir = basedir.save_config_path('mydomain.org', 'MyProg')
24 print >>file(os.path.join(dir, 'Options'), 'w'), "foo=2"
25
26 Note: see the rox.Options module for a higher-level API for managing options.
27 """
28
29 import os
30
31 _home = os.path.expanduser('~')
32 xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or \
33 os.path.join(_home, '.config')
34
35 xdg_config_dirs = [xdg_config_home] + \
36 (os.environ.get('XDG_CONFIG_DIRS') or '/etc/xdg').split(':')
37
38 xdg_config_dirs = [x for x in xdg_config_dirs if x]
39
40
41 def save_config_path(*resource):
42 resource = os.path.join(*resource)
43 assert not resource.startswith('/')
44 path = os.path.join(xdg_config_home, resource)
45 if not os.path.isdir(path):
46 os.makedirs(path, 0o700)
47 return path
48
49
50 def load_config_paths(*resource):
51 resource = os.path.join(*resource)
52 for config_dir in xdg_config_dirs:
53 path = os.path.join(config_dir, resource)
54 if os.path.exists(path):
55 yield path