1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# Copyright (C) 2010 Leonard Thomas
#
# This file is part of Dodai.
#
# Dodai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Dodai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Dodai. If not, see <http://www.gnu.org/licenses/>.
import os
import ConfigParser
from dodai.tools.himo import String2Himo
from dodai.config.sections import ConfigSections
class ConfigFiles(object):
def __init__(self):
self._default_parser = ConfigParser.ConfigParser()
self._string_object = String2Himo()
self._files = {}
def set_default_parser(self, parser):
self.check_config_parser(parser)
self._default_parser = parser
def set_string_object(self, obj):
self._string_object = obj
def add(self, path, encoding=None, parser=None):
if parser:
self.check_config_parser(parser)
if os.path.exists(path):
if parser:
self._files[path] = [parser, encoding]
else:
self._files[path] = [self._default_parser, encoding]
else:
raise FileDoesNotExist(path)
def is_valid_config_parser(self, obj):
out = True
if not hasattr(obj, 'read'):
out = False
return out
def check_config_parser(self, obj):
if self.is_valid_config_parser(obj):
return True
else:
raise InvalidConfigParser("Please make sure your object "\
"has the following methods: "\
"sections, options, read and get.")
def load(self, sections_object=None):
paths = []
sections = sections_object or ConfigSections(self._string_object)
for path, data in self._files.items():
parser = data[0]
encoding = data[1]
parser.read(path)
sections(parser, encoding)
return sections
class InvalidConfigParser(Exception):
pass
class FileDoesNotExist(Exception):
pass
|