2
# Copyright (c) 2008 Canonical
4
# Written by Marc Tardif <marc@interunion.ca>
6
# This file is part of Checkbox.
8
# Checkbox is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation, either version 3 of the License, or
11
# (at your option) any later version.
13
# Checkbox is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
18
# You should have received a copy of the GNU General Public License
19
# along with Checkbox. If not, see <http://www.gnu.org/licenses/>.
25
from ConfigParser import ConfigParser
28
class IncludeDict(dict):
30
def __init__(self, parser):
31
super(IncludeDict, self).__init__()
34
for (key, value) in os.environ.items():
35
super(IncludeDict, self).__setitem__(key.lower(), value)
37
def __setitem__(self, key, value):
39
for path in re.split(r"\s+", value):
40
path = self._parser._interpolate("DEFAULT", None, path, self)
41
if not posixpath.exists(path):
42
raise Exception, "No such configuration file: %s" % path
43
self._parser.read(path)
45
# Environment has precedence over configuration
46
elif key.upper() not in os.environ.keys():
47
super(IncludeDict, self).__setitem__(key, value)
50
class ConfigSection(object):
52
def __init__(self, parent, name, attributes={}):
55
self.attributes = attributes
57
def _get_value(self, name):
58
return self.attributes.get(name)
60
def __getattr__(self, name):
61
if name in self.attributes:
62
return self._get_value(name)
64
raise AttributeError, name
67
class ConfigDefaults(ConfigSection):
69
def _get_value(self, name):
70
return os.environ.get(name.upper()) \
71
or os.environ.get(name.lower()) \
72
or super(ConfigDefaults, self)._get_value(name)
74
def __getattr__(self, name):
75
if name in self.attributes:
76
return self._get_value(name)
78
raise AttributeError, name
83
def __init__(self, path, configs=[]):
86
self._parser = ConfigParser()
87
self._parser._defaults = IncludeDict(self._parser)
89
if not posixpath.exists(path):
90
raise Exception, "No such configuration file: %s" % path
91
self._parser.read(path)
93
for config in configs:
94
match = re.match("(.*)/([^/]+)=(.*)", config)
96
raise Exception, "Invalid config string: %s" % config
98
(name, option, value) = match.groups()
99
if not self._parser.has_section(name):
100
self._parser.add_section(name)
102
self._parser.set(name, option, value)
104
def get_defaults(self):
105
attributes = self._parser.defaults()
106
return ConfigDefaults(self, 'DEFAULT', attributes)
108
def get_section(self, name):
109
if self._parser.has_section(name):
110
attributes = dict(self._parser.items(name))
111
return ConfigSection(self, name, attributes)
115
def get_section_names(self):
116
return self._parser.sections()