Read in a config file from a given path and process it into a dictionary
543073
def _read_conf_file(path):
    '''
    
    '''
    log.debug('Reading configuration from %s', path)
    with salt.utils.files.fopen(path, 'r') as conf_file:
        try:
            conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
        except salt.utils.yaml.YAMLError as err:
            message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
            log.error(message)
            raise salt.exceptions.SaltConfigurationError(message)

        # only interpret documents as a valid conf, not things like strings,
        # which might have been caused by invalid yaml syntax
        if not isinstance(conf_opts, dict):
            message = 'Error parsing configuration file: {0} - conf ' \
                      'should be a document, not {1}.'.format(path, type(conf_opts))
            log.error(message)
            raise salt.exceptions.SaltConfigurationError(message)

        # allow using numeric ids: convert int to string
        if 'id' in conf_opts:
            if not isinstance(conf_opts['id'], six.string_types):
                conf_opts['id'] = six.text_type(conf_opts['id'])
            else:
                conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
        return conf_opts
651172
def _parse_config(config_file_path):
    
    config_file = open(config_file_path, 'r')
    config = yaml.load(config_file)
    config_file.close()
    return config
357710
def load_config_file(self, path, profile=None):
        """"""
        config_cls = self.get_config_reader()
        return config_cls.load_config(self, path, profile=profile)
1337112
def dictionary(self) -> dict:
        """"""
        self.config.read(self.filepath)
        return self.config._sections
1016288
def __read_config(self, file_path: str):
        
        if not os.path.exists(file_path):
            raise FileNotFoundError("File path not found: %s", file_path)
        # check if file exists
        if not os.path.isfile(file_path):
            log(ERROR, "file not found: %s", file_path)
            raise FileNotFoundError("configuration file not found %s", file_path)

        self.config.read(file_path)
1247473
def load_from_file(self, file_path, format=None):
        
        if format is None:
            base_name, file_extension = os.path.splitext(file_path)
            if file_extension in (".yaml", ".yml"):
                format = "yaml"
            elif file_extension in (".json"):
                format = "json"
            else:
                raise ValueError("Config file \"%s\" undetermined" % file_extension)

        if format == "yaml":
            return yaml.load(open(file_path), Loader=yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader)
        elif format == "json":
            return json.load(open(file_path))
        else:
            raise ValueError("Format \"%s\" unknwon" % format)
337233
def _config_ini(path):
    
    conf = configparser.ConfigParser()
    conf.read(path)
    return dict(conf)
963020
def _read_config(filename):
    
    parser = configparser.RawConfigParser()
    if filename and not parser.read(filename):
        sys.stderr.write("Unable to open configuration file %s. Use --config='' to disable this warning.\n" % filename)

    config = {}

    for section, defaults in BASE_CONFIG.items():
        # Patterns are handled separately
        if section == 'patterns':
            continue

        for name, descr in defaults.items():
            kind, default = descr
            if section in parser.sections() and name in parser.options(section):
                if kind == 'int':
                    value = parser.getint(section, name)
                elif kind == 'float':
                    value = parser.getfloat(section, name)
                elif kind == 'bool':
                    value = parser.getboolean(section, name)
                else:
                    value = parser.get(section, name)
            else:
                value = default
            config[name] = value

    if 'patterns' in parser.sections():
        patterns = [parser.get('patterns', opt) for opt in parser.options('patterns')]
    else:
        patterns = DEFAULT_PATTERNS
    config['patterns'] = patterns

    return config
489995
def parse_ini_file(self, path):
        """"""
        cfgobj = ConfigObj(path, list_values=False)

        def extract_section(namespace, d):
            cfg = {}
            for key, val in d.items():
                if isinstance(d[key], dict):
                    cfg.update(extract_section(namespace + [key], d[key]))
                else:
                    cfg['_'.join(namespace + [key]).upper()] = val

            return cfg

        return extract_section([], cfgobj.dict())
643035
def _load_config(self, path):
        '''
        
        '''
        config = {}
        log.debug('Reading configuration from %s', path)
        if not os.path.isdir(path):
            msg = (
                'Unable to read from {path}: '
                'the directory does not exist!'
            ).format(path=path)
            log.error(msg)
            raise IOError(msg)
        # The directory tree should look like the following:
        # .
        # ├── __init__.py
        # ├── eos
        # │   └── init.yml
        # ├── iosxr
        # │   └── __init__.py
        # ├── junos
        # │   └── init.yml
        # │   └── bgp_read_message.py
        # │   └── BGP_PREFIX_THRESH_EXCEEDED.py
        # └── nxos
        #     └── init.yml
        os_subdirs = [sdpath[0] for sdpath in os.walk(path)][1:]
        if not os_subdirs:
            log.error('%s does not contain any OS subdirectories', path)
        for os_dir in os_subdirs:
            os_name = os.path.split(os_dir)[1]  # the network OS name
            if os_name.startswith('__'):
                log.debug('Ignoring %s', os_name)
                continue
            if not self._whitelist_blacklist(os_name):
                log.debug('Not building config for %s (whitelist-blacklist logic)', os_name)
                # Ignore devices that are not in the whitelist (if defined),
                #   or those operating systems that are on the blacklist.
                # This way we can prevent starting unwanted sub-processes.
                continue
            log.debug('Building config for %s:', os_name)
            log.debug('='*40)
            if os_name not in config:
                config[os_name] = {}
            files = os.listdir(os_dir)
            # Read all files under the OS dir
            for file_ in files:
                log.debug('Inspecting %s', file_)
                file_name, file_extension = os.path.splitext(file_)
                file_extension = file_extension.replace('.', '')
                filepath = os.path.join(os_dir, file_)
                comment = ''
                if file_extension in ('yml', 'yaml'):
                    try:
                        log.debug('Loading %s as YAML', file_)
                        with open(filepath, 'r') as fstream:
                            cfg = yaml.load(fstream)
                            # Reposition at the top and read the comments.
                            if file_name not in CONFIG.OS_INIT_FILENAMES:
                                # If the file name is not a profile init.
                                fstream.seek(0)
                                comment = self._extract_yaml_docstring(fstream)
                                if 'messages' in cfg:
                                    for message in cfg['messages']:
                                        message['__doc__'] = comment
                            napalm_logs.utils.dictupdate(config[os_name], cfg)
                    except yaml.YAMLError as yamlexc:
                        log.error('Invalid YAML file: %s', filepath, exc_info=True)
                        if file_name in CONFIG.OS_INIT_FILENAMES:
                            # Raise exception and break only when the init file is borked
                            #   otherwise, it will try loading best efforts.
                            raise IOError(yamlexc)
                elif file_extension == 'py':
                    log.debug('Lazy loading Python module %s', file_)
                    mod_fp, mod_file, mod_data = imp.find_module(file_name, [os_dir])
                    mod = imp.load_module(file_name, mod_fp, mod_file, mod_data)
                    if file_name in CONFIG.OS_INIT_FILENAMES:
                        # Init file defined as Python module
                        log.debug('%s seems to be a Python profiler', filepath)
                        # Init files require to define the `extract` function.
                        # Sample init file:
                        # def extract(message):
                        #     return {'tag': 'A_TAG', 'host': 'hostname'}
                        if hasattr(mod, CONFIG.INIT_RUN_FUN) and\
                           hasattr(getattr(mod, CONFIG.INIT_RUN_FUN), '__call__'):
                            # if extract is defined and is callable
                            if 'prefixes' not in config[os_name]:
                                config[os_name]['prefixes'] = []
                            config[os_name]['prefixes'].append({
                                'values': {'tag': ''},
                                'line': '',
                                '__python_fun__': getattr(mod, CONFIG.INIT_RUN_FUN),
                                '__python_mod__': filepath  # Will be used for debugging
                            })
                            log.info('Adding the prefix function defined under %s to %s',
                                     filepath, os_name)
                        elif file_name != '__init__':
                            # If __init__.py does not have the extractor function, no problem.
                            log.warning('%s does not have the "%s" function defined. Ignoring.',
                                        filepath, CONFIG.INIT_RUN_FUN)
                    else:
                        # Other python files require the `emit` function.
                        if hasattr(mod, '__tag__'):
                            mod_tag = getattr(mod, '__tag__')
                        else:
                            log.info('%s does not have __tag__, defaulting the tag to %s', filepath, file_name)
                            mod_tag = file_name
                        if hasattr(mod, '__error__'):
                            mod_err = getattr(mod, '__error__')
                        else:
                            log.info('%s does not have __error__, defaulting the error to %s', filepath, file_name)
                            mod_err = file_name
                        if hasattr(mod, '__match_on__'):
                            err_match = getattr(mod, '__match_on__')
                        else:
                            err_match = 'tag'
                        model = CONFIG.OPEN_CONFIG_NO_MODEL
                        if hasattr(mod, '__yang_model__'):
                            model = getattr(mod, '__yang_model__')
                        log.debug('Mathing on %s', err_match)
                        if hasattr(mod, CONFIG.CONFIG_RUN_FUN) and\
                           hasattr(getattr(mod, CONFIG.CONFIG_RUN_FUN), '__call__'):
                            log.debug('Adding %s with tag:%s, error:%s, matching on:%s',
                                      file_, mod_tag, mod_err, err_match)
                            # the structure below must correspond to the VALID_CONFIG structure enforcement
                            if 'messages' not in config[os_name]:
                                config[os_name]['messages'] = []
                            config[os_name]['messages'].append({
                                'tag': mod_tag,
                                'error': mod_err,
                                'match_on': err_match,
                                '__doc__': mod.__doc__,
                                '__python_fun__': getattr(mod, CONFIG.CONFIG_RUN_FUN),
                                '__python_mod__': filepath,  # Will be used for debugging
                                'line': '',
                                'model': model,
                                'values': {},
                                'mapping': {'variables': {}, 'static': {}}
                            })
                        else:
                            log.warning('%s does not have the "%s" function defined. Ignoring.',
                                        filepath, CONFIG.CONFIG_RUN_FUN)
                else:
                    log.info('Ignoring %s (extension not allowed)', filepath)
            log.debug('-'*40)
        if not config:
            msg = 'Could not find proper configuration files under {path}'.format(path=path)
            log.error(msg)
            raise IOError(msg)
        log.debug('Complete config:')
        log.debug(config)
        log.debug('ConfigParserg size in bytes: %d', sys.getsizeof(config))
        return config
24683
def load_config path
      return {} unless File.exist? path
      YAML.load File.read path
    end
304507
def read_dict_from_file(file_path):
    
    with open(file_path) as file:
        lines = file.read().splitlines()

    obj = {}
    for line in lines:
        key, value = line.split(':', maxsplit=1)
        obj[key] = eval(value)

    return obj
622625
def parse_config(config_file=None):
    '''
    
    '''
    if config_file is None:
        config_file = _config_file()
    ret = {}
    if _check_config_exists(config_file):
        with salt.utils.files.fopen(config_file) as ifile:
            for line in ifile:
                key, val = salt.utils.stringutils.to_unicode(line).split('=')
                ret[key] = val
        return ret

    return 'Could not find {0} on file system'.format(config_file)
773746
def _load_config(self, path):
        
        try:
            with open(path) as f:
                values = yaml.safe_load(f)
                if isinstance(values, dict):
                    return values
                else:
                    raise yaml.YAMLError('Unable to parse/load {}'.format(path))
        except(IOError, yaml.YAMLError) as e:
            if self.ignore_errors:
                return None
            else:
                raise e
614632
def read_config():
    
    if not os.path.isfile(CONFIG):
        with open(CONFIG, "w"):
            pass

    parser = ConfigParser()
    parser.read(CONFIG)

    return parser
991185
def _load_config(self, path):
        
        p = os.path.abspath(os.path.expanduser(path))
        logger.debug('Loading configuration from: %s', p)
        return read_json_file(p)
1060362
def parse_config(config, key, options):
        """"""
        conf = {}
        for source, destination, opt_type in options:
            opt_value = _get_opt(config, key, source, opt_type)
            if opt_value is not None:
                _set_opt(conf, destination, opt_value)
        return conf