# 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 . 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