Format line system environment variables + defaults
323518
def interpolate_sysenv(line, defaults={}):
    '''
    
    '''
    map = ChainMap(os.environ, defaults)
    return line.format(**map)
247755
function strFromEnvironmentVarSetting(functionsVar, envVar) {
  if (!process.env[envVar]) {
    const msg = `${envVar} does not exist on within environment variables`
    warn(msg)
    return ''
  }
  return `${functionsVar}="${process.env[envVar]}"`
}
1290413
def override_env_variables():
    """"""
    env_vars = ("LOGNAME", "USER", "LNAME", "USERNAME")
    old = [os.environ[v] if v in os.environ else None for v in env_vars]

    for v in env_vars:
        os.environ[v] = "test"
    yield

    for i, v in enumerate(env_vars):
        if old[i]:
            os.environ[v] = old[i]
1018929
def format_cmdline(args, maxwidth=80):
    '''
    '''

    # Leave room for the space and backslash at the end of each line
    maxwidth -= 2

    def lines():
        line = ''
        for a in (shell_quote(a) for a in args):
            # If adding this argument will make the line too long,
            # yield the current line, and start a new one.
            if len(line) + len(a) + 1 > maxwidth:
                yield line
                line = ''

            # Append this argument to the current line, separating
            # it by a space from the existing arguments.
            if line:
                line += ' ' + a
            else:
                line = a

        yield line

    return ' \\\n'.join(lines())
194964
def compile_rules(environment):
    """"""
    e = re.escape
    rules = [
        (len(environment.comment_start_string), 'comment',
         e(environment.comment_start_string)),
        (len(environment.block_start_string), 'block',
         e(environment.block_start_string)),
        (len(environment.variable_start_string), 'variable',
         e(environment.variable_start_string))
    ]

    if environment.line_statement_prefix is not None:
        rules.append((len(environment.line_statement_prefix), 'linestatement',
                      r'^\s*' + e(environment.line_statement_prefix)))
    if environment.line_comment_prefix is not None:
        rules.append((len(environment.line_comment_prefix), 'linecomment',
                      r'(?:^|(?<=\S))[^\S\r\n]*' +
                      e(environment.line_comment_prefix)))

    return [x[1:] for x in sorted(rules, reverse=True)]
868609
def make_copy_paste_env(env: Dict[str, str]) -> str:
    
    windows = platform.system() == "Windows"
    cmd = "set" if windows else "export"
    return (
        "\n".join(
            "{cmd} {k}={v}".format(
                cmd=cmd,
                k=k,
                v=env[k] if windows else subprocess.list2cmdline([env[k]])
            ) for k in sorted(env.keys())
        )
    )
861402
def _git_version():
    """"""

    import subprocess
    import os

    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        FNULL = open(os.devnull, 'w')
        cwd = os.path.dirname(os.path.realpath(__file__))
        proc = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=FNULL, env=env, cwd=cwd)
        out = proc.communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        return out.strip().decode('ascii')
    except OSError:
        return "unknown"
143931
def prepare_environment(default_settings=_default_settings, **kwargs):
    # pylint: disable=unused-argument
    '''
    
    '''
    for key, value in default_settings.items():
        os.environ.setdefault(key, value)
    os.environ.update(kwargs)
    if six.PY2:  # nocv
        warnings.warn(
            'Python 2.7 is deprecated and will dropped in 2.0, use Python >3.5',
            DeprecationWarning
        )
552164
def get_environment_vars(filename):
    """"""
    if sys.platform == "linux" or sys.platform == "linux2":
        return {
            'LD_PRELOAD': path.join(LIBFAKETIME_DIR, "libfaketime.so.1"),
            'FAKETIME_SKIP_CMDS': 'nodejs',     # node doesn't seem to work in the current version.
            'FAKETIME_TIMESTAMP_FILE': filename,
        }
    elif sys.platform == "darwin":
        return {
            'DYLD_INSERT_LIBRARIES': path.join(LIBFAKETIME_DIR, "libfaketime.1.dylib"),
            'DYLD_FORCE_FLAT_NAMESPACE': '1',
            'FAKETIME_TIMESTAMP_FILE': filename,
        }
    else:
        raise RuntimeError("libfaketime does not support '{}' platform".format(sys.platform))
1137630
def _format_syslog_config(cmd_ret):
    '''
    
    '''
    ret_dict = {'success': cmd_ret['retcode'] == 0}

    if cmd_ret['retcode'] != 0:
        ret_dict['message'] = cmd_ret['stdout']
    else:
        for line in cmd_ret['stdout'].splitlines():
            line = line.strip()
            cfgvars = line.split(': ')
            key = cfgvars[0].strip()
            value = cfgvars[1].strip()
            ret_dict[key] = value

    return ret_dict
257430
private void overrideFromEnvironmentVariables() {
        String  url = System.getenv("ACTIVEJDBC.URL");
        String  user = System.getenv("ACTIVEJDBC.USER");
        String  password = System.getenv("ACTIVEJDBC.PASSWORD");
        String  driver = System.getenv("ACTIVEJDBC.DRIVER");
        if(!blank(url) && !blank(user) && !blank(password) && !blank(driver)){
            connectionSpecMap.put(getEnvironment(), new ConnectionJdbcSpec(driver, url, user, password));
        }

        String  jndi = System.getenv("ACTIVEJDBC.JNDI");
        if(!blank(jndi)){
            connectionSpecMap.put(getEnvironment(), new ConnectionJndiSpec(jndi));
        }
    }
1165947
function checkEnv(tmp) {
      if(typeof tmp === 'string') {
        var up = tmp.toUpperCase();
        if(up.indexOf("$ENV:") !== -1) {
          var envVariable = tmp.substr(5).trim();
          if(typeof process.env[envVariable] === 'undefined') {
            console.error('Environment variable: %s is missing, in config file: %s', envVariable, self.path);
            return;
          }
          return process.env[envVariable];
        }
        if(up.indexOf('$ARGV:') !== -1) {
          var argName = tmp.substr(6).trim(),
            argVal = crux.argv(argName);
          if(!argVal) {
            console.error('Argv variable: %s is missing, in config file: %s', argName, self.path);
            return;
          }
          return argVal;
        }
        return;
      }
      if(typeof tmp === 'object' && tmp !== null) {
        if(tmp instanceof Array) {
          for(var i= 0, len = tmp.length; i < len; i++) {
            var replacedVar = checkEnv(tmp[i]);
            if(typeof replacedVar !== 'undefined') {
              tmp[i] = replacedVar;
            }
          }
          return;
        }
        for(var key in tmp) {
          var replacedVar = checkEnv(tmp[key]);
          if(typeof replacedVar !== 'undefined') {
            tmp[key] = replacedVar;
          }
        }
      }
    }
1266562
def __import_vars(self, env_file):
        """"""
        with open(env_file, "r") as f:  # pylint: disable=invalid-name
            for line in f:
                try:
                    line = line.lstrip()
                    if line.startswith('export'):
                        line = line.replace('export', '', 1)
                    key, val = line.strip().split('=', 1)
                except ValueError:  # Take care of blank or comment lines
                    pass
                else:
                    if not callable(val):
                        if self.verbose_mode:
                            if key in self.app.config:
                                print(
                                    " * Overwriting an existing config var:"
                                    " {0}".format(key))
                            else:
                                print(
                                    " * Setting an entirely new config var:"
                                    " {0}".format(key))
                        self.app.config[key] = re.sub(
                            r"\A[\"']|[\"']\Z", "", val)
766134
def _format_default(client, value):
    """"""
    if isinstance(value, File):
        return os.path.relpath(
            str((client.workflow_path / value.path).resolve())
        )
    return value
1328492
def _format_type(lines, element, spacer=""):
    """"""
    rlines = []
    rlines.append(element.signature)
    _format_summary(rlines, element)

    rlines.append("")
    _format_generic(rlines, element, ["summary"])

    if len(element.executables) > 0:
        rlines.append("\nEMBEDDED PROCEDURES")
        for key, value in list(element.executables.items()):
            rlines.append("  {}".format(value.__str__()))
            target = value.target
            if target is not None:
                _format_executable(rlines, target, "  ")

    if len(element.members) > 0:
        rlines.append("\nEMBEDDED MEMBERS")
        for key, value in list(element.members.items()):
            _format_value_element(rlines, value, "  ")

    lines.extend([spacer + l for l in rlines])
848541
def get_env(env_file='.env'):
    
    try:
        with open(env_file) as f:
            for line in f.readlines():
                try:
                    key, val = line.split('=', maxsplit=1)
                    os.environ.setdefault(key.strip(), val.strip())
                except ValueError:
                    pass
    except FileNotFoundError:
        pass
446787
def default(self, line):
        """"""
        args = self._split_args(line, 0, 99)
        d1_cli.impl.util.print_error("Unknown command: {}".format(args[0]))