Parse the haproxy config file

        Raises:
            Exception: when there are unsupported section

        Returns:
            config.Configuration: haproxy config object
551775
def build_configuration(self):
        
        configuration = config.Configuration()
        pegtree = pegnode.parse(self.filestring)
        for section_node in pegtree:
            if isinstance(section_node, pegnode.GlobalSection):
                configuration.globall = self.build_global(section_node)
            elif isinstance(section_node, pegnode.FrontendSection):
                configuration.frontends.append(
                    self.build_frontend(section_node))
            elif isinstance(section_node, pegnode.DefaultsSection):
                configuration.defaults.append(
                    self.build_defaults(section_node))
            elif isinstance(section_node, pegnode.ListenSection):
                configuration.listens.append(
                    self.build_listen(section_node))
            elif isinstance(section_node, pegnode.UserlistSection):
                configuration.userlists.append(
                    self.build_userlist(section_node))
            elif isinstance(section_node, pegnode.BackendSection):
                configuration.backends.append(
                    self.build_backend(section_node))

        return configuration
259655
def read_config(self, filename):
        
        if not os.path.exists(filename):
            raise Exception("Configuration file cannot be found: %s" % filename)
        with io.open(filename, encoding='UTF-8') as stream:
            return yaml.safe_load(stream)
538218
def _read_remote_config(self):
        
        try:
            import requests
        except ImportError:
            requests = None
        if not requests:
            raise ValueError(
                'Remote config URL specified but requests not installed')
        result = requests.get(self._file_path)
        if not result.ok:
            raise ValueError(
                'Failed to retrieve remote config: {}'.format(
                    result.status_code))
        return result.text
220047
def load_configuration_file(self):
        
        if not os.path.exists(self.config_file):
            return
        try:
            with open(self.config_file, 'r') as file:
                csvreader = csv.reader(file, delimiter='=',
                                       escapechar='\\', quoting=csv.QUOTE_NONE)
                for line in csvreader:
                    if len(line) == 2:
                        key, value = line
                        self.config_dict[key] = value
                    else:
                        self.config_dict = dict()
                        self.logger.warning("Malformed configuration file {0}, ignoring it.".
                                            format(self.config_file))
                        return
        except (OSError, IOError) as e:
            self.logger.warning("Could not load configuration file: {0}".\
                format(utils.exc_as_decoded_string(e)))
592465
def _setup_parser(self, filename=None):
        
        assert isinstance(filename, str) or filename is None

        # If we are not overriding the config filename
        if not filename:
            filename = MACKUP_CONFIG_FILE

        parser = configparser.SafeConfigParser(allow_no_value=True)
        parser.read(os.path.join(os.path.join(os.environ['HOME'], filename)))

        return parser
359615
def _read_s3_config(self):
        
        try:
            import boto3
            import botocore.exceptions
        except ImportError:
            boto3, botocore = None, None

        if not boto3:
            raise ValueError(
                's3 URL specified for configuration but boto3 not installed')
        parsed = parse.urlparse(self._file_path)
        try:
            response = boto3.client(
                's3', endpoint_url=os.environ.get('S3_ENDPOINT')).get_object(
                    Bucket=parsed.netloc, Key=parsed.path.lstrip('/'))
        except botocore.exceptions.ClientError as e:
            raise ValueError(
                'Failed to download configuration from S3: {}'.format(e))
        return response['Body'].read().decode('utf-8')
1217524
def parse_config_file():
    
    for filename in ('.tagcube', os.path.expanduser('~/.tagcube')):

        filename = os.path.abspath(filename)

        if not os.path.exists(filename):
            msg = 'TagCube configuration file "%s" does not exist'
            cli_logger.debug(msg % filename)
            continue

        msg = 'Parsing tagcube configuration file "%s"'
        cli_logger.debug(msg % filename)

        email, api_key = _parse_config_file_impl(filename)
        if email is not None and api_key is not None:
            msg = ('Found authentication credentials:\n'
                   '    email: %s\n'
                   '    api_key: %s')
            tokenized_api_key = '%s...%s' % (api_key[:3], api_key[-3:])
            args = (email, tokenized_api_key)
            cli_logger.debug(msg % args)

            return email, api_key
        else:
            msg = 'Configuration file does not contain credentials'
            cli_logger.debug(msg)
    else:
        return None, None
1352171
def parse_config_file
      unless file? config_file
        logger.debug "Configuration file not found: #{config_file}"
        return {}
      end

      logger.debug "Reading configuration file: #{config_file}."
      symbolise YAML.load_file(config_file)
    rescue StandardError => error
      raise CONFIG_FILE_ERROR.new(config_file, error)
    end
1173676
def find_and_parse_config(config, default_config='default.yaml'):
    

    def load_config(path):
        if os.path.isfile(path):
            with open(path, 'r') as f:
                config_dict_ = yaml.load(f)
            return config_dict_

    config_path = find_file(config)
    default_path = find_file(default_config)
    config = load_config(config_path)
    default_config = load_config(default_path)
    if config is None and default_config is None:
        raise ValueError('Both config and default_config return None')
    if config is None:
        config_dict = default_config
    elif default_config is None:
        config_dict = config
    else:
        config_dict = merge(default_config, config)

    return config_dict
297668
def load_config():
    
    configuration = MyParser()
    configuration.read(_config)

    d = configuration.as_dict()

    if 'jira' not in d:
        raise custom_exceptions.NotConfigured

    # Special handling of the boolean for error reporting
    d['jira']['error_reporting'] = configuration.getboolean('jira', 'error_reporting')

    return d
655989
def check_config(config):
    
    for section, expected_section_keys in SECTION_KEYS.items():
        section_content = config.get(section)
        if not section_content:
            raise ConfigurationError("Config file badly formed! Section {} is missing."
                                     .format(section))
        elif not _section_is_healthy(section_content, expected_section_keys):
            raise ConfigurationError("The {} section of the configuration file is badly formed!"
                                     .format(section))
1134374
protected function _load()
    {
        $file = new File($this->_file, "r");

        $data = @parse_ini_string($file->read(), true);
        if ($data === false) {
            throw new Exception\ParserErrorException(
                "Error parsing configuration file {$this->_file}"
            );
        }
        $this->_data = $data;
    }
191503
def read_config(config_path):
    
    section = "DUMMY"
    defaults = {'host': 'localhost',
                'consumerKey': '', 'consumerSecret': '',
                'token': '', 'tokenSecret':'',
                }
    # Insert an section header at the start of the config file,
    # so ConfigParser can understand it
    buf = io.StringIO()
    buf.write('[%s]\n' % section)
    with io.open(config_path, "r") as conf:
        buf.write(conf.read())

    buf.seek(0, os.SEEK_SET)
    parser = ConfigParser()
    parser.optionxform = str # Case-sensitive options
    try:
        parser.read_file(buf) # Python3
    except AttributeError:
        parser.readfp(buf) # Python2

    # Trim quotes
    config = parser.items(section)
    config = [(item[0].replace('"', ''), item[1].replace('"', ''))
              for item in config]
    config = [(item[0].replace("'", ""), item[1].replace("'", ""))
              for item in config]
    config = dict(config)

    # Apply defaults
    for key in defaults:
        if key not in config:
            config[key] = defaults[key]

    return config
459317
def get_default_config(self):
        
        config = super(HAProxyCollector, self).get_default_config()
        config.update({
            'method':           'http',
            'path':             'haproxy',
            'url':              'http://localhost/haproxy?stats;csv',
            'user':             'admin',
            'pass':             'password',
            'sock':             '/var/run/haproxy.sock',
            'ignore_servers':   False,
        })
        return config
1169863
def parse(self, url):
        
        parsed_url = urlparse.urlparse(url)
        try:
            default_config = self.CONFIG[parsed_url.scheme]
        except KeyError:
            raise ValueError(
                'unrecognised URL scheme for {}: {}'.format(
                    self.__class__.__name__, url))
        handler = self.get_handler_for_scheme(parsed_url.scheme)
        config = copy.deepcopy(default_config)
        return handler(parsed_url, config)
1128325
def parse_config(config_file):
    """"""
    try:
        with open(config_file, 'r') as f:
            return yaml.load(f)
    except IOError:
        print "Configuration file {} not found or not readable.".format(config_file)
        raise
536446
def _load_yaml_config(self):
        
        try:
            config = self._read_config()
        except OSError as error:
            raise ValueError('Could not read configuration file: %s' % error)
        try:
            return yaml.safe_load(config)
        except yaml.YAMLError as error:
            message = '\n'.join(['    > %s' % line
                                 for line in str(error).split('\n')])
            sys.stderr.write('\n\n  Error in the configuration file:\n\n'
                             '{}\n\n'.format(message))
            sys.stderr.write('  Configuration should be a valid YAML file.\n')
            sys.stderr.write('  YAML format validation available at '
                             'http://yamllint.com\n')
            raise ValueError(error)