Update manpage.
[laditools.git] / laditools / config.py
blobeba817f19c5cfc800cfed0bf0a296089074364e0
1 #!/usr/bin/python
2 # LADITools - Linux Audio Desktop Integration Tools
3 # Copyright (C) 2011-2012 Alessio Treglia <quadrispro@ubuntu.com>
4 # Copyright (C) 2007-2010, Marc-Olivier Barre <marco@marcochapeau.org>
5 # Copyright (C) 2007-2009, Nedko Arnaudov <nedko@arnaudov.name>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from os import environ, sep, mkdir, path
21 from os.path import exists
22 from xdg import BaseDirectory as basedir
23 import sys
25 if sys.version_info.major == 3:
26 from configparser import SafeConfigParser, MissingSectionHeaderError
27 elif sys.version_info.major == 2:
28 from ConfigParser import SafeConfigParser, MissingSectionHeaderError
29 else:
30 raise Exception("Unsupported Python's interpreter version.")
32 try:
33 import yaml
34 except:
35 yaml = None
37 class MalformedConfigError(Exception):
38 def __init__(self):
39 Exception.__init__(self, """Malformed configuration file, \
40 delete the file '%s' and let me create a new one.""" % config_filename)
42 # Note to users of the config class. Only applications should create an instance
43 # of the config object. The ladimenu is *NOT* an application...
44 class LadiConfiguration(SafeConfigParser):
45 """Convenient class for parsing and updating configuration files.
47 It is recommended to avoid abuses of these objects, only applications
48 should create instances of this class.
49 """
51 def _migrate_configuration(self):
52 """Migrate configuration from old YAML coding style to the new one."""
53 try:
54 with open (self.config_filename, 'r') as config_file:
55 appdict = yaml.load (config_file)
56 except:
57 sys.stderr.write("Config file doesn't exist, creating a new one...\n")
58 sys.stderr.flush()
59 return 1
61 for section in appdict:
62 if not section in self.sections():
63 self.add_section(section)
64 for opt in appdict[section]:
65 if not isinstance(opt, dict):
66 self.set(section, opt, str(appdict[section][opt]))
67 else:
68 for k in opt:
69 self.set(section, k, opt[k])
71 return 0
73 def __init__ (self, app_name, defaults = {}, filename = None):
75 SafeConfigParser.__init__(self)
77 # First setup default values for apps specified
78 # by the call to the contructor
79 self.set_config_section(app_name, defaults)
81 self.config_dir = config_dir = path.join(basedir.xdg_config_home, 'laditools')
82 if not filename:
83 filename = app_name + '.conf'
84 self.config_filename = config_filename = path.join(config_dir, filename)
85 if not exists (config_dir):
86 mkdir (config_dir, 0o755)
88 try:
89 self.read(config_filename)
90 except MissingSectionHeaderError:
91 if yaml:
92 if self._migrate_configuration() == 0:
93 self.save()
94 else: # new empty file
95 pass
96 # go on otherwise
97 except:
98 raise MalformedConfigError()
100 def get_config_section (self, app_name):
101 """Returns the section named <app_name> from the global configuration.
103 If the section doesn't exist, returns an empty dictionary."""
104 appdict = {}
105 if self.has_section(app_name):
106 for opt in self.options(app_name):
107 appdict[opt] = self.get(app_name, opt)
108 return appdict
110 # Saves the section named <app_name> into the global config
111 def set_config_section (self, app_name, param_dict):
112 """Save the section named <app_name> into the global configuration."""
113 if not self.has_section(app_name):
114 self.add_section(app_name)
115 for key in param_dict:
116 value = param_dict[key]
117 self.set(app_name, key, str(value))
119 # This writes the config file to the disk
120 def save (self):
121 """Write configuration to file."""
122 config_file = open (self.config_filename, 'w')
123 self.write(config_file)
124 config_file.close ()