Exemplo n.º 1
0
    def _extend(self, filename, override=False):
        """Expand the config with another file."""
        if not os.path.isfile(filename):
            raise IOError('No such file: %s' % filename)
        parser = ConfigParser(**self._configparser_kwargs())
        parser.optionxform = lambda option: option
        parser.filename = filename
        parser.read([filename])
        serialize = self._interpolation._serialize

        for section in parser:
            if section in self:
                for option in parser[section]:
                    if option not in self[section] or override:
                        value = parser[section][option]
                        self[section][option] = serialize(value)
            else:
                self[section] = parser[section]
Exemplo n.º 2
0
    def _extend(self, filename, override=False):
        """Expand the config with another file."""
        if not os.path.isfile(filename):
            raise IOError('No such file: %s' % filename)
        parser = ConfigParser(**self._configparser_kwargs())
        parser.optionxform = lambda option: option
        parser.filename = filename
        parser.read([filename])
        # pylint: disable=E1101,W0212
        serialize = self._interpolation._serialize

        for section in parser:
            if section in self:
                for option in parser[section]:
                    if option not in self[section] or override:
                        value = parser[section][option]
                        self[section][option] = serialize(value)
            else:
                self[section] = parser[section]
Exemplo n.º 3
0
def parse_cfg(cfg_file='', msgs=[], new=False):
    '''
    Parse a configuration file.

    Arguments:

        cfg_file (str): path to a configuration file.

        msgs (list): list of pending messages.

        new (bool): if ``True`` and `cfg_file` does not exist, create the file.

    Returns:

        (ConfigParser, str, list):
        first argument is the parsed configuration,
        second argument is the corresponding file path,
        third argument is the list of pending messages.

    *new in version 0.5:* the returned `ConfigParser` object contains an extra
        attribute `filename` which value equals to the second returned argument.

    '''
    if cfg_file:
        err_msg_if_missing = 'file not found: {}'.format(cfg_file)
    else:
        err_msg_if_missing = 'cannot find a valid configuration file'
        candidates = default_conf_files + [None]
        for cfg_file in candidates:
            if cfg_file and os.path.isfile(cfg_file):
                break
        if not cfg_file:
            try:  # check if superuser
                cfg_file = default_conf_files[-1]  # global conf file
                with open(cfg_file, 'a'):
                    pass
            except IOError:  # [Errno13] Permission denied:
                cfg_file = default_conf_files[0]
    if not os.path.isfile(cfg_file):
        if new:
            import logging
            msgs.append((logging.INFO, "creating new configuration file '%s'",
                         cfg_file))
            cfg_dir = os.path.dirname(cfg_file)
            if not os.path.isdir(cfg_dir):
                os.makedirs(cfg_dir)
            with open(cfg_file, 'w'):
                pass  # touch
        else:
            raise IOError(err_msg_if_missing)
    with open(cfg_file, 'r') as f:
        while True:
            line = f.readline()
            if f.tell() == 0:  # file is empty
                break
            stripped = line.strip()
            if stripped and any([stripped[0] == s for s in '#;']):
                stripped = ''
            if stripped:
                break
        if not line.startswith('[{}]'.format(default_section)):
            line = "[{}]\n{}".format(default_section, line)
        raw_cfg = "{}{}".format(line, f.read())
    if PYTHON_VERSION == 3:
        config = ConfigParser(default_section=default_section)
        config.read_string(raw_cfg, source=cfg_file)
    elif PYTHON_VERSION == 2:
        assert default_section == 'DEFAULT'
        assert isinstance(raw_cfg, str)
        config = ConfigParser()
        import io
        try:
            config.readfp(io.BytesIO(raw_cfg), filename=cfg_file)
        except UnicodeDecodeError:
            raw_cfg = "\n".join([
                line.decode('utf-8').encode('unicode-escape')
                for line in raw_cfg.splitlines()
            ])
            config.readfp(io.BytesIO(raw_cfg), filename=cfg_file)
            config = crawl_config(lambda a: a.decode('unicode-escape'), config)
    config.filename = cfg_file
    return (config, cfg_file, msgs)