Parses the given ini file contents and converts to a dictionary of key/value pairs.
    :param ini_file_contents: the contents of the ini file
    :return: dictionary where the variable names are key and their values are the values
515523
def _read_ini_config(ini_file_contents: str) -> Dict[str, str]:
    
    config = configparser.ConfigParser()
    config.optionxform = str
    config.read_string(_FAKE_SECTION + ini_file_contents)

    items = {}
    for section in config.sections():
        items.update(dict(config[section].items()))

    return items
156470
def hash_contents(contents):
    
    assert isinstance(contents, GroupNode)

    result = hashlib.sha256()

    def _hash_int(value):
        result.update(struct.pack(">L", value))

    def _hash_str(string):
        assert isinstance(string, string_types)
        _hash_int(len(string))
        result.update(string.encode())

    def _hash_object(obj):
        _hash_str(obj.json_type)
        if isinstance(obj, (TableNode, FileNode)):
            hashes = obj.hashes
            _hash_int(len(hashes))
            for hval in hashes:
                _hash_str(hval)
        elif isinstance(obj, GroupNode):
            children = obj.children
            _hash_int(len(children))
            for key, child in sorted(iteritems(children)):
                _hash_str(key)
                _hash_object(child)
        else:
            assert False, "Unexpected object: %r" % obj

        # Backward compatibility: only hash metadata_hash if it's present.
        if obj.metadata_hash is not None:
            _hash_str(obj.metadata_hash)

    _hash_object(contents)

    return result.hexdigest()
1187085
def parse_config_file(config_file_path):
  
  extension = os.path.splitext(config_file_path)[1]
  if extension == '.pyc':
    raise ValueError("Skipping .pyc file as config")
  if extension == '.json':
    with open(config_file_path) as config_file:
      try:
        mapping = json.load(config_file)
      except ValueError as e:
        logger.error("Did not load json configs", e)
        raise SyntaxError('Unable to parse config file:%s due to malformed JSON. Aborting' %(config_file_path))
  elif extension == '.py':
    mapping = {}
    file_dict = load_module(config_file_path)
    for attr_name in dir(file_dict):
      if not (attr_name.startswith('_') or attr_name.startswith('__')):
        attr = getattr(file_dict, attr_name)
        if type(attr) is dict:
          mapping.update(attr)
  else:
    with open(config_file_path) as config_file:
      lines = [line.rstrip() for line in config_file if line.rstrip() != "" and not line.startswith("#")]
      mapping = parse_config_list(lines)

  return mapping
248668
def parse_config(file_name='/usr/local/etc/pkg.conf'):
    '''
    
    '''
    ret = {}
    if not os.path.isfile(file_name):
        return 'Unable to find {0} on file system'.format(file_name)

    with salt.utils.files.fopen(file_name) as ifile:
        for line in ifile:
            line = salt.utils.stringutils.to_unicode(line)
            if line.startswith('#') or line.startswith('\n'):
                pass
            else:
                key, value = line.split('\t')
                ret[key] = value
    ret['config_file'] = file_name
    return ret
226431
def pci_contents(self, use_dict=None, as_class=dict):
        """"""
        if _debug: PCI._debug("pci_contents use_dict=%r as_class=%r", use_dict, as_class)

        # make/extend the dictionary of content
        if use_dict is None:
            use_dict = as_class()

        # save the values
        for k, v in (('user_data', self.pduUserData), ('source', self.pduSource), ('destination', self.pduDestination)):
            if _debug: PCI._debug("    - %r: %r", k, v)
            if v is None:
                continue

            if hasattr(v, 'dict_contents'):
                v = v.dict_contents(as_class=as_class)
            use_dict.__setitem__(k, v)

        # return what we built/updated
        return use_dict
654068
def dict_contents(self, use_dict=None, as_class=dict):
        """"""
        if _debug: Choice._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)

        # make/extend the dictionary of content
        if use_dict is None:
            use_dict = as_class()

        # look for the chosen element
        for element in self.choiceElements:
            value = getattr(self, element.name, None)
            if value is None:
                continue

            if issubclass(element.klass, Atomic):
                mapped_value = value                    ### ambiguous
            elif issubclass(element.klass, AnyAtomic):
                mapped_value = value.value              ### ambiguous
            elif isinstance(value, element.klass):
                mapped_value = value.dict_contents(as_class=as_class)

            use_dict.__setitem__(element.name, mapped_value)
            break

        # return what we built/updated
        return use_dict
404999
def _set_from_ini(self, namespace, ini_file):
        
        # Isolate global values
        global_vars = dict((key, val)
            for key, val in namespace.items()
            if isinstance(val, basestring)
        )

        # Copy all sections
        for section in ini_file.sections():
            # Get values set so far
            if section == "GLOBAL":
                raw_vars = global_vars
            else:
                raw_vars = namespace.setdefault(section.lower(), {})

            # Override with values set in this INI file
            raw_vars.update(dict(ini_file.items(section, raw=True)))

            # Interpolate and validate all values
            if section == "FORMATS":
                self._interpolation_escape(raw_vars)
            raw_vars.update(dict(
                (key, validate(key, val))
                for key, val in ini_file.items(section, vars=raw_vars)
            ))

        # Update global values
        namespace.update(global_vars)
650728
def dict_contents(self, use_dict=None, as_class=dict):
        """"""
        if _debug: PDU._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)

        # make/extend the dictionary of content
        if use_dict is None:
            use_dict = as_class()

        # call into the two base classes
        self.pci_contents(use_dict=use_dict, as_class=as_class)
        self.pdudata_contents(use_dict=use_dict, as_class=as_class)

        # return what we built/updated
        return use_dict
337233
def _config_ini(path):
    
    conf = configparser.ConfigParser()
    conf.read(path)
    return dict(conf)
661337
def load_config(config_file='~/.stancache.ini'):
    
    if not os.path.exists(config_file):
        logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file))
        return
    ## get user-level config in *.ini format
    config = configparser.ConfigParser()
    config.read(config_file)
    if not config.has_section('main'):
        raise ValueError('Config file {} has no section "main"'.format(config_file))
    for (key, val) in config.items('main'):
        _set_value(key.upper(), val)
    return
101474
def read(self, module_name):
        
        self.parser.read("{}/{}.ini".format(self.path, module_name.split(".")[-1]))
460595
def parse(self, file_obj):
        
        order = 1
        host = {"host": ['*'], "config": {}, }
        for line in file_obj:
            line = line.rstrip('\n').lstrip()
            if line == '':
                self._config.append({
                    'type': 'empty_line',
                    'value': line,
                    'host': '',
                    'order': order,
                })
                order += 1
                continue

            if line.startswith('#'):
                self._config.append({
                    'type': 'comment',
                    'value': line,
                    'host': '',
                    'order': order,
                })
                order += 1
                continue

            if '=' in line:
                # Ensure ProxyCommand gets properly split
                if line.lower().strip().startswith('proxycommand'):
                    proxy_re = re.compile(r"^(proxycommand)\s*=*\s*(.*)", re.I)
                    match = proxy_re.match(line)
                    key, value = match.group(1).lower(), match.group(2)
                else:
                    key, value = line.split('=', 1)
                    key = key.strip().lower()
            else:
                # find first whitespace, and split there
                i = 0
                while (i < len(line)) and not line[i].isspace():
                    i += 1
                if i == len(line):
                    raise Exception('Unparsable line: %r' % line)
                key = line[:i].lower()
                value = line[i:].lstrip()
            if key == 'host':
                self._config.append(host)
                value = value.split()
                host = {
                    key: value,
                    'config': {},
                    'type': 'entry',
                    'order': order
                }
                order += 1
            elif key in ['identityfile', 'localforward', 'remoteforward']:
                if key in host['config']:
                    host['config'][key].append(value)
                else:
                    host['config'][key] = [value]
            elif key not in host['config']:
                host['config'].update({key: value})
        self._config.append(host)
1190747
def _get_config(config_file):
    ''''''
    parser = ConfigParser.SafeConfigParser()
    if os.path.lexists(config_file):
        try:
            log.info('Reading config: %s', config_file)
            inp = open(config_file)
            parser.readfp(inp)
            return parser
        except (IOError, ConfigParser.ParsingError), err:
            raise ConfigError("Failed to read configuration %s\n%s" % (config_file, err))
    return None
1114250
def to_dict(self) -> Dict[str, List[int]]:
        
        return {fn: list(lines)
                for (fn, lines) in self.__contents.items()}
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)
174545
def convert_ini(config_dict):
    
    config_lines = []

    for env, configs in sorted(config_dict.items()):
        for resource, app_properties in sorted(configs.items()):
            try:
                for app_property, value in sorted(app_properties.items()):
                    variable = '{env}_{resource}_{app_property}'.format(
                        env=env, resource=resource, app_property=app_property).upper()

                    if isinstance(value, (dict, DeepChainMap)):
                        safe_value = "'{0}'".format(json.dumps(dict(value)))
                    else:
                        safe_value = json.dumps(value)

                    line = "{variable}={value}".format(variable=variable, value=safe_value)

                    LOG.debug('INI line: %s', line)
                    config_lines.append(line)
            except AttributeError:
                resource = resource.upper()
                app_properties = "'{}'".format(json.dumps(app_properties))
                line = '{0}={1}'.format(resource, app_properties)

                LOG.debug('INI line: %s', line)
                config_lines.append(line)
    return config_lines