# This program 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 2 of the License, or # (at your option) any later version. # # This program 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 Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Copyright 2005 Dan Williams and Red Hat, Inc. import os from ConfigParser import ConfigParser class ConfigError(Exception): pass class BaseConfig: def __init__(self, filename): self._filename = filename self._config = ConfigParser() def open(self, filename=None): if not filename: filename = self._filename if not os.path.exists(filename): raise ConfigError("Config file '%s' missing." % filename) self._config.read(filename) self._filename = filename def has_option(self, section, name): return self._config.has_option(section, name) def get_option(self, section, name): if not self._config.has_section(section): raise ConfigError("Invalid section: %s" % section) if self._config.has_option(section, name): return self._config.get(section, name) raise ConfigError("Config file %s does not have option: %s/%s" % (self._filename, section, name)) def get_str(self, section, name): return self.get_option(section, name) def get_bool(self, section, name): opt = self.get_option(section, name) if type(opt) == type(""): if opt.lower() == 'yes' or opt.lower() == 'true': return True elif opt.lower() == 'no' or opt.lower() == 'false': return False raise ConfigError("Invalid format for %s/%s. Should be one of [yes, no, true, false]." % (section, name)) def get_list(self, section, name): opt = self.get_option(section, name) if type(opt) == type(""): if not len(opt): return [] try: return opt.split() except Exception: pass raise ConfigError("Invalid format for %s/%s. Should be a space-separate list." % (section, name)) def get_int(self, section, name): opt = self.get_option(section, name) try: return int(opt) except Exception: pass raise ConfigError("Invalid format for %s/%s. Should be a valid integer." % (section, name)) def add_section(self, section): self._config.add_section(section) def set_option(self, section, name, value): if not self._config.has_section(section): self._config.add_section(section) self._config.set(section, name, value) def save(self, filename=None): if not filename: filename = self._filename fp = open(filename, 'w') self._config.write(fp) self._filename = filename