# -*- mode: python; coding: utf-8 -*-
# vim:smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class:ts=4:sts=4:sta:et:ai:shiftwidth=4
#
# arch-tag: e3611d7d-af0d-47ce-8cd1-2a89ea641796
#
# Copyright ©  2004 Canonical Ltd.
#	Author: Robert Collins <robertc@robertcollins.net>

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

import ConfigParser as BaseConfig

class ConfigParser(BaseConfig.ConfigParser):
    """extend ConfigParser with a useful shortcut. Perhaps should be a decorator.."""

    def get_option_worker(self, method, short, section, option, *args, **kwargs):
        """get the value for an option. *args takes:
        default (raise an exception if the option is not present and no default)
        raw (defaults to False)
        vars (defaults to None)
        """
        default_present=False
        args=list(args)
        if len(args):
            default=args.pop()
            default_present=True
        if len(args):
            raw=args.pop()
        else:
            raw=kwargs.get('raw', False)
        if len(args):
            vars=args.pop()
        else:
            vars=kwargs.get('vars', None)
        if self.has_option(section, option):
            if not short:
                return method(section, option, raw, vars)
            else:
                return method(section, option)
        elif default_present:
            return default
        else:
            raise KeyError("no such option")

    def get_option(self, section, option, *args, **kwargs):
        """delegates to get_option_worker(self.get)"""
        return self.get_option_worker(self.get, False, section, option, *args, **kwargs)

    def get_boolean_option(self, section, option, *args, **kwargs):
        """delegates to get_option_worker(self.getboolean)"""
        return self.get_option_worker(self.getboolean, True, section, option, *args, **kwargs)

    def section_items(self, section):
        """Get the items present solely in section."""
        result = []
        for name, value in self.items(section):
            if not self.has_option("DEFAULT", name):
                result.append((name, value))
        return result
