# 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.config.sections import ConfigSections from dodai.exception import InvalidConfigParser from dodai.exception import FileDoesNotExist from dodai.exception import FileIsDirectory class ConfigFiles(object): REQUIRED_METHODS = ['read', 'sections', 'options', 'get'] def __init__(self, ordered_dict_object, section_object, string_object): self._ordered_dict_object = ordered_dict_object self._section_object = section_object self._string_object = string_object self.parser_objects = [] self.files = self._ordered_dict_object() self.files_read = [] def register_parser_object(self, parser_object): """Registers a config file parser with this object. Raises InvalidConfigParser error if the parser does not have the 'read', 'sections', 'options' and 'get' methods. """ if self.check_parser_object(parser_object): self.parser_objects.append(parser_object) def check_parser_object(self, parser_object): """Checks the given parser object to insure it has all of the required methods needed to parse files. """ for name in self.REQUIRED_METHODS: if not hasattr(parser_object, name): raise InvalidConfigParser(self.REQUIRED_METHODS, parser_object.__name__) return True def add(self, filename, encoding=None): """Adds the given filename to this object to be parsed. """ if os.path.exists(filename): if os.path.isdir(filename): raise FileIsDirectory(filename) else: filename = os.path.realpath(filename) self.files[filename] = encoding else: raise FileDoesNotExist(filename) def _read(self): self.files_read = [] out = self._ordered_dict_object() for filename, encoding in self.files.items(): error = False for parser_obj in self.parser_objects: try: parser = parser_obj() parser.read(filename) except Exception, e: error = True else: out[filename] = self._ordered_dict_object() out[filename]['encoding'] = encoding out[filename]['parser'] = parser self.files_read.append(filename) error = False break if error: raise e return out def load(self): """Returns a ConfigSections object, which acts like a dictionary, that contains all parsed data. """ files = self._read() sections = ConfigSections(self._ordered_dict_object, self._section_object, self._string_object) for filename, data in files.items(): encoding = data['encoding'] parser = data['parser'] sections(parser, encoding) return sections