Given a path to a file, parse its lines in ini-like format, and then
    set them in the current namespace.

    Quiet by default. Set verbose to True to see the absolute path to the config
    files printed on stderr.
777624
def load_config(app_name, *args, **kwargs):
    
    configure_logging()

    # compatible with Python 2 and 3.
    prefix = kwargs.get('prefix', 'etc')
    verbose = kwargs.get('verbose', False)
    location = kwargs.get('location', None)
    passphrase = kwargs.get('passphrase',
        os.getenv("%s_SETTINGS_CRYPT_KEY" % app_name.upper(),
            os.getenv("SETTINGS_CRYPT_KEY", None)))
    confnames = args

    if not location:
        location = os.getenv("%s_SETTINGS_LOCATION" % app_name.upper(), None)
    if not location:
        location = os.getenv("SETTINGS_LOCATION", None)
        if location:
            location = "%s/%s" % (location, app_name)

    config = {}
    for confname in confnames:
        content = None
        if location and location.startswith('s3://'):
            try:
                import boto
                _, bucket_name, prefix = urlparse(location)[:3]
                try:
                    conn = boto.connect_s3()
                    bucket = conn.get_bucket(bucket_name)
                    key_name = '%s/%s' % (prefix, confname)
                    key = bucket.get_key(key_name)
                    content = key.get_contents_as_string()
                    if verbose:
                        LOGGER.info("config loaded from 's3://%s/%s'",
                            bucket_name, key_name)
                except (boto.exception.NoAuthHandlerFound,
                        boto.exception.S3ResponseError) as _:
                    pass
            except ImportError:
                pass

        # We cannot find a deployutils S3 bucket. Let's look on the filesystem.
        if not content:
            confpath = locate_config(
                confname, app_name, location=location,
                prefix=prefix, verbose=verbose)
            if confpath:
                with open(confpath, 'rb') as conffile:
                    content = conffile.read()

        if content:
            if passphrase:
                content = crypt.decrypt(content, passphrase)
            if hasattr(content, 'decode'):
                content = content.decode('utf-8')
            for line in content.split('\n'):
                if not line.startswith('#'):
                    look = re.match(r'(\w+)\s*=\s*(.*)', line)
                    if look:
                        try:
                            # We used to parse the file line by line.
                            # Once Django 1.5 introduced ALLOWED_HOSTS
                            # (a tuple that definitely belongs to the site.conf
                            # set), we had no choice other than resort
                            # to eval(value, {}, {}).
                            # We are not resorting to import conf module yet
                            # but that might be necessary once we use
                            # dictionary configs for some of the apps...
                            # TODO: consider using something like ConfigObj
                            # for this:
                            # http://www.voidspace.org.uk/python/configobj.html
                            #pylint:disable=eval-used
                            config.update({look.group(1).upper():
                                eval(look.group(2), {}, {})})
                        except Exception:
                            raise

    return config
1345036
def load_file(self, path=None, env=None, silent=True, key=None):
        
        env = (env or self.current_env).upper()
        files = ensure_a_list(path)
        if files:
            self.logger.debug("Got %s files to process", files)
            already_loaded = set()
            for _filename in files:
                self.logger.debug("Processing file %s", _filename)
                filepath = os.path.join(self._root_path, _filename)
                self.logger.debug("File path is %s", filepath)
                # Handle possible *.globs sorted alphanumeric
                for path in sorted(glob.glob(filepath)):
                    self.logger.debug("Loading %s", path)
                    if path in already_loaded:  # pragma: no cover
                        self.logger.debug("Skipping %s, already loaded", path)
                        continue
                    settings_loader(
                        obj=self,
                        env=env,
                        silent=silent,
                        key=key,
                        filename=path,
                    )
                    already_loaded.add(path)
            if not already_loaded:
                self.logger.warning(
                    "Not able to locate the files %s to load", files
                )
653561
def normalizeFilePath(value):
    
    if not isinstance(value, basestring):
        raise TypeError("File paths must be strings, not %s."
                        % type(value).__name__)
    return unicode(value)
337233
def _config_ini(path):
    
    conf = configparser.ConfigParser()
    conf.read(path)
    return dict(conf)
232092
def modify_config(path):
    
    if isinstance(path, str):
        path = Path(path)
    config = _read_pkg_ini(path)
    _validate_config(config, path)

    # don't catch exception, we won't write the new config.
    yield config

    _validate_config(config, path)
    with path.open('w') as f:
        config.write(f)
253505
def parse_file(self, sls_path):
        '''
        
        '''
        config = self.state.document.settings.env.config
        formulas_dirs = config.formulas_dirs
        fpath = sls_path.replace('.', '/')

        name_options = (
            '{0}.sls'.format(fpath),
            os.path.join(fpath, 'init.sls')
        )

        paths = [os.path.join(fdir, fname)
                for fname in name_options
                    for fdir in formulas_dirs]

        for i in paths:
            try:
                with open(i, 'rb') as f:
                    return f.readlines()
            except IOError:
                pass

        raise IOError("Could not find sls file '{0}'".format(sls_path))
96610
def _set_defaults(self, namespace, optional_cfg_files):
        
        # Add current configuration directory
        namespace["config_dir"] = self.config_dir

        # Load defaults
        for idx, cfg_file in enumerate([self.CONFIG_INI] + optional_cfg_files):
            if any(i in cfg_file for i in set('/' + os.sep)):
                continue # skip any non-plain filenames

            try:
                defaults = pymagic.resource_string("pyrocore", "data/config/" + cfg_file) #@UndefinedVariable
            except IOError as exc:
                if idx and exc.errno == errno.ENOENT:
                    continue
                raise

            ini_file = ConfigParser.SafeConfigParser()
            ini_file.optionxform = str # case-sensitive option names
            ini_file.readfp(StringIO.StringIO(defaults), "<defaults>")
            self._set_from_ini(namespace, ini_file)
559445
def _read_from_paths():
    
    home = os.environ.get("HOME", "")
    home_path = os.path.join(home, _SETTINGS_PATH)
    etc_path = os.path.join("/etc", _SETTINGS_PATH)
    env_path = os.environ.get("SETTINGS_PATH", "")

    read_path = None
    if env_path and os.path.exists(env_path):
        read_path = env_path
    elif home and os.path.exists(home_path):
        read_path = home_path
    elif os.path.exists(etc_path):
        read_path = etc_path

    if not read_path:
        return "{}"

    with open(read_path) as f:
        return f.read()
643216
def load_path(self, path):
        
        logger.debug("load_path(path=%s)" % path)
        if os.path.isfile(path):
            configtype = self.guess_type(path)
            logger.debug("Detected config type: %s" % self._type_to_str(configtype))
            if configtype in self.TYPES:
                logger.debug("Opening config for reading")
                with open(path, 'r') as f:
                    data = f.read()
                datadict = self.TYPES[configtype]().reverse(data)
                return self.load_data(datadict)
            else:
                raise ValueError("Unsupported config type")
        else:
            logger.warn("load_path couldn't find the path: %s" % path)
1217768
def read_config(
        config_filepath,
        logger=logging.getLogger('ProsperCommon'),
):
    
    config_parser = configparser.ConfigParser(
        interpolation=ExtendedInterpolation(),
        allow_no_value=True,
        delimiters=('='),
        inline_comment_prefixes=('#')
    )
    logger.debug('config_filepath=%s', config_filepath)

    with open(config_filepath, 'r') as filehandle:
        config_parser.read_file(filehandle)

    return config_parser
617981
def parse_config_file(path: str, final: bool = True) -> None:
    
    return options.parse_config_file(path, final=final)
142217
def _rewrite_paths_in_file(config_file, paths_to_replace):
        
        lines = []
        # make a copy of config
        import shutil
        shutil.copyfile(config_file, str(config_file + '_original'))
        with open(config_file) as infile:
            for line in infile:
                for old_path in paths_to_replace:
                    if old_path in line:
                        new_path = os.path.split(old_path)[-1]
                        line = line.replace(old_path, new_path)
                        logger.debug("Changed path {0} ---> {1} in file {2}".format(old_path, new_path, config_file))
                lines.append(line)
        with open(config_file, 'w') as outfile:
            for line in lines:
                outfile.write(line)
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
571183
def read(file)

      Pathname.new(file).read.each_line do |line|
          # skip blank lines and those starting with #
          next if line =~ /^\s*(#|$)/

          line.strip =~ /^(\w+?):\s*(\S.*)$/
          next unless $1
          attr = $1.to_sym
          setter = "#{attr}=".to_sym
          value = $2.strip

          if CONF_KEYS.keys.include? attr
            if value
              # convert the value to the correct class
              value = value.send(CONF_KEYS[attr])
            end
            self.send(setter, value)
          end  # if
        end # do line

    end
939426
def _parse_config_files(self, filenames=None):
        
        from setuptools.extern.six.moves.configparser import ConfigParser

        # Ignore install directory options if we have a venv
        if six.PY3 and sys.prefix != sys.base_prefix:
            ignore_options = [
                'install-base', 'install-platbase', 'install-lib',
                'install-platlib', 'install-purelib', 'install-headers',
                'install-scripts', 'install-data', 'prefix', 'exec-prefix',
                'home', 'user', 'root']
        else:
            ignore_options = []

        ignore_options = frozenset(ignore_options)

        if filenames is None:
            filenames = self.find_config_files()

        if DEBUG:
            self.announce("Distribution.parse_config_files():")

        parser = ConfigParser()
        for filename in filenames:
            with io.open(filename, encoding='utf-8') as reader:
                if DEBUG:
                    self.announce("  reading {filename}".format(**locals()))
                (parser.read_file if six.PY3 else parser.readfp)(reader)
            for section in parser.sections():
                options = parser.options(section)
                opt_dict = self.get_option_dict(section)

                for opt in options:
                    if opt != '__name__' and opt not in ignore_options:
                        val = self._try_str(parser.get(section, opt))
                        opt = opt.replace('-', '_')
                        opt_dict[opt] = (filename, val)

            # Make the ConfigParser forget everything (so we retain
            # the original filenames that options come from)
            parser.__init__()

        # If there was a "global" section in the config file, use it
        # to set Distribution options.

        if 'global' in self.command_options:
            for (opt, (src, val)) in self.command_options['global'].items():
                alias = self.negative_opt.get(opt)
                try:
                    if alias:
                        setattr(self, alias, not strtobool(val))
                    elif opt in ('verbose', 'dry_run'):  # ugh!
                        setattr(self, opt, strtobool(val))
                    else:
                        setattr(self, opt, val)
                except ValueError as msg:
                    raise DistutilsOptionError(msg)
1063336
def read_env(path=None, environ=None, recurse=True):
    
    environ = environ if environ is not None else os.environ

    # By default, start search from the same file this function is called
    if path is None:
        frame = inspect.currentframe().f_back
        caller_dir = os.path.dirname(frame.f_code.co_filename)
        path = os.path.join(os.path.abspath(caller_dir), ENV)
    if recurse:
        current = path
        pardir = os.path.abspath(os.path.join(current, os.pardir))
        while current != pardir:
            target = os.path.join(current, ENV)
            if os.path.exists(target):
                path = os.path.abspath(target)
                break
            else:
                current = os.path.abspath(os.path.join(current, os.pardir))
                pardir = os.path.abspath(os.path.join(current, os.pardir))
        if not path:
            raise FileNotFoundError('Could not find a .env file')

    with open(path, 'r') as fp:
        content = fp.read()
    parsed = parse_env(content)
    for key, value in parsed.items():
        environ.setdefault(key, value)
1355701
def listen_ignore_paths(options)
      source = Pathname.new(options["source"]).expand_path
      paths  = to_exclude(options)

      paths.map do |p|
        absolute_path = Pathname.new(normalize_encoding(p, options["source"].encoding)).expand_path
        next unless absolute_path.exist?

        begin
          relative_path = absolute_path.relative_path_from(source).to_s
          relative_path = File.join(relative_path, "") if absolute_path.directory?
          unless relative_path.start_with?("../")
            path_to_ignore = %r!^#{Regexp.escape(relative_path)}!
            Jekyll.logger.debug "Watcher:", "Ignoring #{path_to_ignore}"
            path_to_ignore
          end
        rescue ArgumentError
          # Could not find a relative path
        end
      end.compact + [%r!^\.jekyll\-metadata!]
    end