get_env

This function grabs key/value pair items and assigns them for the
config.JSON.  This essentially checks the environment for key locations within
the filesystem.
191886
def get_env(working_directory=None):
    
    working = working_directory if working_directory else os.getcwd()
    dist_dirs = glob.glob(working + "/f5-*-dist")
    print(dist_dirs)
    dist_dir_re = re.compile('/([^/]+)-dist/?')
    if dist_dirs:
        dist_dir = dist_dirs[0]
        match = dist_dir_re.search(dist_dir)
        if match:
            project_name = match.group(1)
        else:
            print("Unrecognized run location:\n" + working)
            exit_cleanly(errnum=errno.EIO)
    elif '-dist/scripts' in working:
        match = dist_dir_re.search(working)
        if match:
            project_name = match.group(1)
    else:
        print("Unable to determine the *-dist directory from " + working)
        exit_cleanly(errnum=errno.ENOSYS)
    stdeb_cfg = dist_dir + "/deb_dist/stdeb.cfg"
    setup_cfg = working + "/setup.cfg"
    stp_reqs = working + "/setup_requirements.txt"
    scripts = dist_dir + "/scripts"
    env = {'working': working, 'dist_dir': dist_dir, 'stdeb_cfg': stdeb_cfg,
           'setup_requirements': stp_reqs, 'setup_cfg': setup_cfg,
           'scripts': scripts, 'project': project_name}
    return env
1192024
def config_for_env(hash)
      return from_environment_key(hash) if environment_keys?(hash)

      hash.each_with_object(IndifferentHash[]) do |(k, v), acc|
        if environment_keys?(v)
          acc.merge!(k => v[environment.to_s]) if v.key?(environment.to_s)
        else
          acc.merge!(k => v)
        end
      end
    end
943232
def _get_envs(self):
        '''
        
        '''
        envs = ['base']
        if 'file_roots' in self.opts:
            envs.extend([x for x in list(self.opts['file_roots'])
                         if x not in envs])
        env_order = self.opts.get('env_order', [])
        # Remove duplicates while preserving the order
        members = set()
        env_order = [env for env in env_order if not (env in members or members.add(env))]
        client_envs = self.client.envs()
        if env_order and client_envs:
            return [env for env in env_order if env in client_envs]

        elif env_order:
            return env_order
        else:
            envs.extend([env for env in client_envs if env not in envs])
            return envs
988925
def setup_environment_from_config_file():
    

    from os.path import exists

    config_file = get_config_file()

    if not exists(config_file):
        return

    try:
        config = _ConfigParser.SafeConfigParser()
        config.read(config_file)

        __section = "Environment"

        if config.has_section(__section):
            items = config.items(__section)

            for k, v in items:
                try:
                    os.environ[k.upper()] = v
                except Exception as e:
                    print(("WARNING: Error setting environment variable "
                           "'%s = %s' from config file '%s': %s.")
                          % (k, str(v), config_file, str(e)) )
    except Exception as e:
        print("WARNING: Error reading config file '%s': %s." % (config_file, str(e)))
325626
def get_env_str(env):
    
    return ' '.join("{0}='{1}'".format(k, v) for k, v in env.items())
1290135
def get_conf_path_from_env():
    '''
    
    '''
    config_path = os.environ.get('PECAN_CONFIG')
    if not config_path:
        error = "PECAN_CONFIG is not set and " \
                "no config file was passed as an argument."
    elif not os.path.isfile(config_path):
        error = "PECAN_CONFIG was set to an invalid path: %s" % config_path
    else:
        return config_path

    raise RuntimeError(error)
1027091
def finalize_env(env):
    

    keys = _PLATFORM_ENV_KEYS.get(sys.platform, [])
    if 'PATH' not in keys:
        # this MUST be available due to Node.js (and others really)
        # needing something to look for binary locations when it shells
        # out to other binaries.
        keys.append('PATH')
    results = {
        key: os.environ.get(key, '') for key in keys
    }
    results.update(env)
    return results
140763
def get_env_path(cls):
        
        return os.path.dirname(Finder.python()) + os.pathsep + os.environ['PATH']
19689
def config(env=DEFAULT_ENV, default=None, **overrides):
    """"""

    config = {}

    s = os.environ.get(env, default)

    if s:
        config = parse(s)

    overrides = dict([(k.upper(), v) for k, v in overrides.items()])

    config.update(overrides)

    return config
1029598
def get(self, key, prompt_default='', prompt_help=''):
        """"""
        value = os.getenv(key)
        if not value:
            ns = self.namespace(key)
            value = self.keyring.get_password(ns, key)
        else:
            ns = 'environ'  
        if not value:
            ns = self.namespace(key, glob=True)
            value = self.keyring.get_password(ns, key)
        if not value:
            ns = ''
        if not value and self.prompt:
            value = self._prompt_for_value(key, prompt_default, prompt_help)
            if value:
                self.set(key, value)
        if ns:
            self.kns[key] = ns
        return value
195556
def load_env(self):
        
        for key, value in self.spec.items():
            if value['type'] in (dict, list):
                envar = (self.env_prefix + "_" + key).upper()
                try:
                    envvar = env.json(envar,
                                      default=getattr(self, key.upper(), value.get('default')))
                except ConfigurationError as _err:  #pragma: no cover
                    print(_err)
                    self.log.critical(f"Error parsing json from env var. {os.environ.get(envar)}")
                    print(envar)
                    raise
            else:
                envvar = env((self.env_prefix + "_" + key).upper(),
                             default=getattr(self, key.upper(), value.get('default')),
                             cast=value['type'])
            setattr(self, key.upper(), envvar)
845024
def get_env(name, default=None):
    """"""
    if name in os.environ:
        return os.environ[name]

    if default is not None:
        return default

    error_msg = "Set the {} env variable".format(name)
    raise ImproperlyConfigured(error_msg)
774463
def prepare_env(cls):
        
        os.environ['PATH'] = cls.get_env_path()
        return os.path.basename(Finder.python())
210062
def env(*args, **kwargs):
    
    for arg in args:
        value = os.environ.get(arg, None)
        if value:
            return value
    return kwargs.get("default", "")
420605
def get_client_settings_env(**_):
    

    return {
        'proxy': os.environ.get('https_proxy'),
        'username': os.environ.get('SL_USERNAME'),
        'api_key': os.environ.get('SL_API_KEY'),
    }
295485
def load_environment_vars(self, prefix=SANIC_PREFIX):
        
        for k, v in os.environ.items():
            if k.startswith(prefix):
                _, config_key = k.split(prefix, 1)
                try:
                    self[config_key] = int(v)
                except ValueError:
                    try:
                        self[config_key] = float(v)
                    except ValueError:
                        try:
                            self[config_key] = strtobool(v)
                        except ValueError:
                            self[config_key] = v
1196527
def get_env(path, ignore_git_branch=False):
    """"""
    if 'DEPLOY_ENVIRONMENT' in os.environ:
        return os.environ['DEPLOY_ENVIRONMENT']

    if ignore_git_branch:
        LOGGER.info('Skipping environment lookup from current git branch '
                    '("ignore_git_branch" is set to true in the runway '
                    'config)')
    else:
        # These are not located with the top imports because they throw an
        # error if git isn't installed
        from git import Repo as GitRepo
        from git.exc import InvalidGitRepositoryError

        try:
            b_name = GitRepo(
                path,
                search_parent_directories=True
            ).active_branch.name
            LOGGER.info('Deriving environment name from git branch %s...',
                        b_name)
            return get_env_from_branch(b_name)
        except InvalidGitRepositoryError:
            pass
    LOGGER.info('Deriving environment name from directory %s...', path)
    return get_env_from_directory(os.path.basename(path))