Internal helper for converting pythonic values to configuration file values
549546
def _sanitize_value(value):
    ''''''
    # dump dict into compated
    if isinstance(value, dict):
        new_value = []
        new_value.append('(')
        for k, v in value.items():
            new_value.append(k)
            new_value.append('=')
            new_value.append(v)
            new_value.append(',')
        new_value.append(')')
        return "".join(six.text_type(v) for v in new_value).replace(',)', ')')
    elif isinstance(value, list):
        new_value = []
        new_value.append('(')
        for item in value:
            if isinstance(item, OrderedDict):
                item = dict(item)
                for k, v in item.items():
                    new_value.append(k)
                    new_value.append('=')
                    new_value.append(v)
            else:
                new_value.append(item)
            new_value.append(',')
        new_value.append(')')
        return "".join(six.text_type(v) for v in new_value).replace(',)', ')')
    else:
        # note: we can't use shelx or pipes quote here because it makes zonecfg barf
        return '"{0}"'.format(value) if ' ' in value else value
811306
def read_yaml_configuration(filename):
    '''
    '''
    with open(filename, 'r') as f:
        config = yaml.load(f.read())
    return config
711341
def dump_config(self):
        """"""
        yaml_content = self.get_merged_config()
        print('YAML Configuration\n%s\n' % yaml_content.read())
        try:
            self.load()
            print('Python Configuration\n%s\n' % pretty(self.yamldocs))
        except ConfigError:
            sys.stderr.write(
                'config parse error. try running with --logfile=/dev/tty\n')
            raise
242193
def _GenConfig(self, cfg):
    """"""
    # Some setting names may have a + or - suffix. These indicate that the
    # settings modify the default values.
    merged = self.default.copy()
    for setting, vals in iteritems(cfg):
      option, operator = (setting.split(None, 1) + [None])[:2]
      vals = set(vals)
      default = set(self.default.get(option, []))
      # If there is an operator, updated values accordingly.
      if operator == "+":
        vals = default.union(vals)
      elif operator == "-":
        vals = default.difference(vals)
      merged[option] = list(vals)
    return rdf_protodict.AttributedDict(**merged)
80746
def config_value_keys(self, sortkey = False):
        
        ret = set()
        cls = type(self)
        while True:
            root = cls.getConfigRoot()
            if root:
                ret = ret.union(set(root.config_value_keys()))
            parent = None
            for c in cls.__bases__:
                if issubclass(c, Configurable):
                    parent = c
            if parent is None:
                break
            cls = parent
        if sortkey:
            return sorted(list(ret))
        else:
            return list(ret)
701617
def dict_conf(filename):
  

  f, ext = os.path.splitext(filename)
  ext = ext.lower()

  if ext == "conf" or ext == "ini":
    # python config via config parser

    config = ConfigParser()
    config.optionxform=str
    config.read(filename)
    rv = {}
    for section in config.sections():
      rv[section] = {}
      for key,value in config.items(section):
        rv[section][key] = value.strip('"').strip("'").decode("string_escape")
    return rv
  else:
    # other type of config, use munge
    if munge_config:
      src = munge_config.parse_url(filename)
      return src.cls().load(open(filename)).get("vodka")
    else:
      raise Exception("'%s' type of config encountered, install munge" % ext)
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)
421425
def of(cls, value):
        
        if isinstance(value, ConfigSource):
            return value
        elif isinstance(value, dict):
            return ConfigSource(value)
        else:
            raise TypeError(u'source value must be a dict')
1320234
def format_values(self):
        
        source_key_to_display_value_map = {
            _COMMAND_LINE_SOURCE_KEY: "Command Line Args: ",
            _ENV_VAR_SOURCE_KEY: "Environment Variables:\n",
            _CONFIG_FILE_SOURCE_KEY: "Config File (%s):\n",
            _DEFAULTS_SOURCE_KEY: "Defaults:\n"
        }

        r = StringIO()
        for source, settings in self._source_to_settings.items():
            source = source.split("|")
            source = source_key_to_display_value_map[source[0]] % tuple(source[1:])
            r.write(source)
            for key, (action, value) in settings.items():
                if key:
                    r.write("  %-19s%s\n" % (key+":", value))
                else:
                    if isinstance(value, str):
                        r.write("  %s\n" % value)
                    elif isinstance(value, list):
                        r.write("  %s\n" % ' '.join(value))

        return r.getvalue()
883117
def config_from_file(self, config_file=None):
        """"""
        if PYLINT_VERSION >= (1, 5):
            self.read_config_file(config_file)
            if self.cfgfile_parser.has_option('MASTER', 'load-plugins'):
                # pylint: disable=protected-access
                plugins = _splitstrip(self.cfgfile_parser.get('MASTER', 'load-plugins'))
                self.load_plugin_modules(plugins)
            self.load_config_file()
            return True

        self.load_file_configuration(config_file)
        return False
983790
def get_config(config_file):
    
    config = {}
    tobool = lambda s: True if s.lower() == 'true' else False
    if config_file:
        try:
            f = open(config_file, 'r')
        except:
            print ("Unable to open configuration file '{0}'".format(config_file))
        else:
            for line in f.readlines():
                if len(line.strip()):
                    key, value = line.split("=", 1)
                    key, value = key.strip(), value.strip()
                    if key in ['init2class', 'first_line', 'convert_only']:
                        value = tobool(value)
                    config[key] = value
    return config
703407
def _parse_conf(conf_file=default_conf):
    '''
    
    '''
    ret = {}
    with salt.utils.files.fopen(conf_file, 'r') as ifile:
        for line in ifile:
            line = salt.utils.stringutils.to_unicode(line).strip()
            if not line:
                continue
            if line.startswith('#'):
                continue
            splitline = line.split(' ', 1)
            ret[splitline[0]] = splitline[1]
    return ret
909664
def conf_from_file(filepath):
    '''
    
    '''

    abspath = os.path.abspath(os.path.expanduser(filepath))
    conf_dict = {}
    if not os.path.isfile(abspath):
        raise RuntimeError('`%s` is not a file.' % abspath)

    # First, make sure the code will actually compile (and has no SyntaxErrors)
    with open(abspath, 'rb') as f:
        compiled = compile(f.read(), abspath, 'exec')

    # Next, attempt to actually import the file as a module.
    # This provides more verbose import-related error reporting than exec()
    absname, _ = os.path.splitext(abspath)
    basepath, module_name = absname.rsplit(os.sep, 1)
    if six.PY3:
        SourceFileLoader(module_name, abspath).load_module(module_name)
    else:
        imp.load_module(
            module_name,
            *imp.find_module(module_name, [basepath])
        )

    # If we were able to import as a module, actually exec the compiled code
    exec(compiled, globals(), conf_dict)
    conf_dict['__file__'] = abspath

    return conf_from_dict(conf_dict)
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
1307968
def new_as_dict(self, raw=True, vars=None):
    """"""
    # Load INI file into a dict
    result = {}
    for section in self.sections():
        if section not in result:
            result[section] = {}
        for option in self.options(section):
            value = self.get(section, option, raw=raw, vars=vars)
            try:
                value = cherrypy.lib.reprconf.unrepr(value)
            except Exception:
                x = sys.exc_info()[1]
                msg = ("Config error in section: %r, option: %r, "
                       "value: %r. Config values must be valid Python." %
                       (section, option, value))
                raise ValueError(msg, x.__class__.__name__, x.args)
            result[section][option] = value
    return result
492584
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'configuration_id' in _dict:
            args['configuration_id'] = _dict.get('configuration_id')
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        else:
            raise ValueError(
                'Required property \'name\' not present in Configuration JSON')
        if 'created' in _dict:
            args['created'] = string_to_datetime(_dict.get('created'))
        if 'updated' in _dict:
            args['updated'] = string_to_datetime(_dict.get('updated'))
        if 'description' in _dict:
            args['description'] = _dict.get('description')
        if 'conversions' in _dict:
            args['conversions'] = Conversions._from_dict(
                _dict.get('conversions'))
        if 'enrichments' in _dict:
            args['enrichments'] = [
                Enrichment._from_dict(x) for x in (_dict.get('enrichments'))
            ]
        if 'normalizations' in _dict:
            args['normalizations'] = [
                NormalizationOperation._from_dict(x)
                for x in (_dict.get('normalizations'))
            ]
        if 'source' in _dict:
            args['source'] = Source._from_dict(_dict.get('source'))
        return cls(**args)
481082
def get_config(config_file):
    """"""
    config_path = os.path.abspath(config_file)

    try:
        with open(config_path, 'r') as data:
            config = yaml.safe_load(data)
    except IOError as exc:
        sys.exit(str(exc))

    return config