Run zsh command to unify the environment
337015
def zsh_mode(self, delay_factor=1, prompt_terminator="$"):
        """"""
        delay_factor = self.select_delay_factor(delay_factor)
        self.clear_buffer()
        command = self.RETURN + "zsh" + self.RETURN
        self.write_channel(command)
        time.sleep(1 * delay_factor)
        self.set_prompt()
        self.clear_buffer()
297814
def merge_base(all_envs)
      base = all_envs["base"] || {}
      all_envs.each do |env, settings|
        all_envs[env] = base.merge(settings) unless env == "base"
      end
      all_envs
    end
440188
def start
      puts "\n******************************************************************************************************************************************\n\n"
      puts "  JumpStarting....\n".purple
      check_setup
      execute_install_command
      run_scripts_from_yaml(:run_after_install_command)
      parse_template_dir
      create_dirs
      populate_files_from_whole_templates
      populate_files_from_append_templates
      populate_files_from_line_templates
      remove_unwanted_files
      run_scripts_from_yaml(:run_after_jumpstart)
      check_for_strings_to_replace
      run_scripts_from_yaml(:run_after_string_replace)
      check_local_nginx_configuration
      exit_with_success
    end
390878
def _run(name,
         cmd,
         output=None,
         no_start=False,
         preserve_state=True,
         stdin=None,
         python_shell=True,
         output_loglevel='debug',
         use_vt=False,
         path=None,
         ignore_retcode=False,
         chroot_fallback=None,
         keep_env='http_proxy,https_proxy,no_proxy'):
    '''
    

    '''
    orig_state = state(name, path=path)
    try:
        if attachable(name, path=path):
            ret = __salt__['container_resource.run'](
                name,
                cmd,
                path=path,
                container_type=__virtualname__,
                exec_driver=EXEC_DRIVER,
                output=output,
                no_start=no_start,
                stdin=stdin,
                python_shell=python_shell,
                output_loglevel=output_loglevel,
                ignore_retcode=ignore_retcode,
                use_vt=use_vt,
                keep_env=keep_env)
        else:
            if not chroot_fallback:
                raise CommandExecutionError(
                    '{0} is not attachable.'.format(name))
            rootfs = info(name, path=path).get('rootfs')
            # Set context var to make cmd.run_chroot run cmd.run instead of
            # cmd.run_all.
            __context__['cmd.run_chroot.func'] = __salt__['cmd.run']
            ret = __salt__['cmd.run_chroot'](rootfs,
                                             cmd,
                                             stdin=stdin,
                                             python_shell=python_shell,
                                             output_loglevel=output_loglevel,
                                             ignore_retcode=ignore_retcode)
    except Exception:
        raise
    finally:
        # Make sure we honor preserve_state, even if there was an exception
        new_state = state(name, path=path)
        if preserve_state:
            if orig_state == 'stopped' and new_state != 'stopped':
                stop(name, path=path)
            elif orig_state == 'frozen' and new_state != 'frozen':
                freeze(name, start=True, path=path)

    if output in (None, 'all'):
        return ret
    else:
        return ret[output]
625689
def generate(env):
    """"""

    cplusplus.generate(env)

    env['CXX']         = 'CC'
    env['CXXFLAGS']    = SCons.Util.CLVar('-LANG:std')
    env['SHCXX']       = '$CXX'
    env['SHOBJSUFFIX'] = '.o'
    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
1054874
def _command(source, command, flags=None, opts=None,
             property_name=None, property_value=None,
             filesystem_properties=None, pool_properties=None,
             target=None):
    '''
    

    '''
    # NOTE: start with the zfs binary and command
    cmd = [_zpool_cmd() if source == 'zpool' else _zfs_cmd(), command]

    # NOTE: append flags if we have any
    if flags is None:
        flags = []
    for flag in flags:
        cmd.append(flag)

    # NOTE: append options
    #       we pass through 'sorted' to garentee the same order
    if opts is None:
        opts = {}
    for opt in sorted(opts):
        if not isinstance(opts[opt], list):
            opts[opt] = [opts[opt]]
        for val in opts[opt]:
            cmd.append(opt)
            cmd.append(to_str(val))

    # NOTE: append filesystem properties (really just options with a key/value)
    #       we pass through 'sorted' to garentee the same order
    if filesystem_properties is None:
        filesystem_properties = {}
    for fsopt in sorted(filesystem_properties):
        cmd.append('-O' if source == 'zpool' else '-o')
        cmd.append('{key}={val}'.format(
            key=fsopt,
            val=to_auto(fsopt, filesystem_properties[fsopt], source='zfs', convert_to_human=False),
        ))

    # NOTE: append pool properties (really just options with a key/value)
    #       we pass through 'sorted' to garentee the same order
    if pool_properties is None:
        pool_properties = {}
    for fsopt in sorted(pool_properties):
        cmd.append('-o')
        cmd.append('{key}={val}'.format(
            key=fsopt,
            val=to_auto(fsopt, pool_properties[fsopt], source='zpool', convert_to_human=False),
        ))

    # NOTE: append property and value
    #       the set command takes a key=value pair, we need to support this
    if property_name is not None:
        if property_value is not None:
            if not isinstance(property_name, list):
                property_name = [property_name]
            if not isinstance(property_value, list):
                property_value = [property_value]
            for key, val in zip(property_name, property_value):
                cmd.append('{key}={val}'.format(
                    key=key,
                    val=to_auto(key, val, source=source, convert_to_human=False),
                ))
        else:
            cmd.append(property_name)

    # NOTE: append the target(s)
    if target is not None:
        if not isinstance(target, list):
            target = [target]
        for tgt in target:
            # NOTE: skip None list items
            #       we do not want to skip False and 0!
            if tgt is None:
                continue
            cmd.append(to_str(tgt))

    return ' '.join(cmd)
299501
def run(cont, util, shell, argv=None):
    """"""
    cont.fetch_and_import("setup/python/setup.py").run(cont,
                                                       util,
                                                       shell,
                                                       argv)
    cmake_cont = cont.fetch_and_import("setup/cmake/setup.py").run(cont,
                                                                   util,
                                                                   shell,
                                                                   argv)

    # Now that the cmake container is set up, use its execute method
    # to find out where cmake scripts are actually installed.
    #
    # The answer might be obvious from just using "which" on OS X and
    # Linux, but on Windows, the binaries are symlinked into another
    # directory - we need the true install location.
    with cont.in_temp_cache_dir():
        with open("cmroot.cmake", "w") as root_script:
            root_script.write("message (${CMAKE_ROOT})")

        install_path = bytearray()

        def steal_output(process, outputs):
            """Steal output from container executor."""
            install_path.extend(outputs[1].read().strip())
            return process.wait()

        cmake_cont.execute(cont,
                           steal_output,
                           "cmake",
                           "-P",
                           root_script.name)

        # If we're on linux, then the returned path is going to be
        # relative to the container, so make that explicit, since we're
        # not running the tests inside the container.
        if platform.system() == "Linux":
            root_fs_path_bytes = cmake_cont.root_fs_path()
            install_path = os.path.join(root_fs_path_bytes.decode("utf-8"),
                                        install_path.decode("utf-8")[1:])
            install_path = os.path.normpath(install_path)
        else:
            install_path = install_path.decode("utf-8")

        util.overwrite_environment_variable(shell,
                                            "CMAKE_INSTALL_PATH",
                                            install_path)
944225
def setup(shell)
      shell.status "Cloning #{@source} ..."

      shell.run 'git', 'clone', '--depth', 1, @source, shell.uri.path

      shell.status "Cloned #{@source}."
    end
452726
def run(cmd, output_fpath=None, input_fpath=None, checks=None, stdout_to_outputfile=True,
        stdout_tx=True, reuse=False, env_vars=None):
    
    if output_fpath and reuse:
        if verify_file(output_fpath, silent=True):
            info(output_fpath + ' exists, reusing')
            return output_fpath
        if not output_fpath.endswith('.gz') and verify_file(output_fpath + '.gz', silent=True):
            info(output_fpath + '.gz exists, reusing')
            return output_fpath

    env = os.environ.copy()
    if env_vars:
        for k, v in env_vars.items():
            if v is None:
                if k in env:
                    del env[k]
            else:
                env[k] = v

    if checks is None:
        checks = [file_nonempty_check]

    def _try_run(_cmd, _output_fpath, _input_fpath):
        try:
            info(' '.join(str(x) for x in _cmd) if not isinstance(_cmd, six.string_types) else _cmd)
            _do_run(_cmd, checks, env, _output_fpath, _input_fpath)
        except:
            raise

    if output_fpath:
        if isfile(output_fpath):
            os.remove(output_fpath)
    if output_fpath:
        if stdout_tx:
            with file_transaction(None, output_fpath) as tx_out_file:
                if stdout_to_outputfile:
                    cmd += ' > ' + tx_out_file
                else:
                    cmd += '\n'
                    cmd = cmd.replace(' ' + output_fpath + ' ', ' ' + tx_out_file + ' ') \
                             .replace(' "' + output_fpath + '" ', ' ' + tx_out_file + '" ') \
                             .replace(' \'' + output_fpath + '\' ', ' ' + tx_out_file + '\' ') \
                             .replace(' ' + output_fpath + '\n', ' ' + tx_out_file) \
                             .replace(' "' + output_fpath + '"\n', ' ' + tx_out_file + '"') \
                             .replace(' \'' + output_fpath + '\'\n', ' ' + tx_out_file + '\'') \
                             .replace('\n', '')
                _try_run(cmd, tx_out_file, input_fpath)
        else:
            _try_run(cmd, output_fpath, input_fpath)

    else:
        _try_run(cmd, None, input_fpath)
1312848
def run(ctx, commandline):
    """"""
    file = ctx.obj['FILE']
    dotenv_as_dict = dotenv_values(file)
    if not commandline:
        click.echo('No command given.')
        exit(1)
    ret = run_command(commandline, dotenv_as_dict)
    exit(ret)
1372109
def shell_command(cmd, dry_run=False):
    
    if cmd[0] == '/usr/bin/rsync':
        if dry_run:
            cmd = [cmd[0], '-n'] + cmd[1:]
        LOGGER.info('run: %s', ' '.join(cmd))
        subprocess.check_call(cmd)
    else:
        LOGGER.info('run: %s', ' '.join(cmd))
        if not dry_run:
            subprocess.check_call(cmd)
763464
def run_cmd(cmd)
      raise "Unstubbed git command #{cmd}" if ENV['SCGITX_TEST'] == 'true'
      say "\n$ "
      say cmd.gsub("'", ''), :red
      raise "#{cmd} failed" unless system cmd
    end
1031390
def _setup_environment(self):
        """"""
        # Save the original working directory so that reload can launch
        # the new process with the same arguments as the original
        self._orig_workdir = os.getcwd()

        if self.chrootdir is not None:
            try:
                # Change the root directory
                os.chdir(self.chrootdir)
                os.chroot(self.chrootdir)
            except Exception as ex:
                raise DaemonError('Unable to change root directory '
                                  '({error})'.format(error=str(ex)))

        # Prevent the process from generating a core dump
        self._prevent_core_dump()

        try:
            # Switch directories
            os.chdir(self.workdir)
        except Exception as ex:
            raise DaemonError('Unable to change working directory '
                              '({error})'.format(error=str(ex)))

        # Create the directory for the pid file if necessary
        self._setup_piddir()

        try:
            # Set file creation mask
            os.umask(self.umask)
        except Exception as ex:
            raise DaemonError('Unable to change file creation mask '
                              '({error})'.format(error=str(ex)))

        try:
            # Switch users
            os.setgid(self.gid)
            os.setuid(self.uid)
        except Exception as ex:
            raise DaemonError('Unable to setuid or setgid '
                              '({error})'.format(error=str(ex)))
316083
function run() {
  var bin = path.resolve(__dirname, '../node_modules/.bin/mocha');
  var args = Array.prototype.slice.call(arguments);
  var fn = args.pop();
  var cmd = [bin].concat(args).join(' ') + ' --no-colors';
  exec(cmd, fn);
}
120746
def run():
    """"""

    # Use print() instead of logging when running in CLI mode:
    set_pyftpsync_logger(None)

    parser = argparse.ArgumentParser(
        description="Synchronize folders over FTP.",
        epilog="See also https://github.com/mar10/pyftpsync",
        parents=[verbose_parser],
    )

    # Note: we want to allow --version to be combined with --verbose. However
    # on Py2, argparse makes sub-commands mandatory, unless `action="version"` is used.
    if check_cli_verbose(3) > 3:
        version_info = "pyftpsync/{} Python/{} {}".format(
            __version__, PYTHON_VERSION, platform.platform()
        )
    else:
        version_info = "{}".format(__version__)

    parser.add_argument("-V", "--version", action="version", version=version_info)

    subparsers = parser.add_subparsers(help="sub-command help")

    # --- Create the parser for the "upload" command ---------------------------

    sp = subparsers.add_parser(
        "upload",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files to remote folder",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite remote files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["local", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove remote files if they don't exist locally",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove remote files if they don't exist locally "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="upload")

    # --- Create the parser for the "download" command -------------------------

    sp = subparsers.add_parser(
        "download",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files from remote folder to local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite local files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove local files if they don't exist on remote target",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove local files if they don't exist on remote target "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="download")

    # --- Create the parser for the "sync" command -----------------------------

    sp = subparsers.add_parser(
        "sync",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="synchronize new and modified files between remote folder and local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["old", "new", "local", "remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )

    sp.set_defaults(command="sync")

    # --- Create the parser for the "run" command -----------------------------

    add_run_parser(subparsers)

    # --- Create the parser for the "scan" command -----------------------------

    add_scan_parser(subparsers)

    # --- Parse command line ---------------------------------------------------

    args = parser.parse_args()

    args.verbose -= args.quiet
    del args.quiet

    # print("verbose", args.verbose)

    ftp_debug = 0
    if args.verbose >= 6:
        ftp_debug = 1

    # Modify the `args` from the `pyftpsync.yaml` config:
    if getattr(args, "command", None) == "run":
        handle_run_command(parser, args)

    if callable(getattr(args, "command", None)):
        # scan_handler
        try:
            return args.command(parser, args)
        except KeyboardInterrupt:
            print("\nAborted by user.", file=sys.stderr)
            sys.exit(3)

    elif not hasattr(args, "command"):
        parser.error(
            "missing command (choose from 'upload', 'download', 'run', 'sync', 'scan')"
        )

    # Post-process and check arguments
    if hasattr(args, "delete_unmatched") and args.delete_unmatched:
        args.delete = True

    args.local_target = make_target(args.local, {"ftp_debug": ftp_debug})

    if args.remote == ".":
        parser.error("'.' is expected to be the local target (not remote)")
    args.remote_target = make_target(args.remote, {"ftp_debug": ftp_debug})
    if not isinstance(args.local_target, FsTarget) and isinstance(
        args.remote_target, FsTarget
    ):
        parser.error("a file system target is expected to be local")

    # Let the command handler do its thing
    opts = namespace_to_dict(args)
    if args.command == "upload":
        s = UploadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "download":
        s = DownloadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "sync":
        s = BiDirSynchronizer(args.local_target, args.remote_target, opts)
    else:
        parser.error("unknown command '{}'".format(args.command))

    s.is_script = True

    try:
        s.run()
    except KeyboardInterrupt:
        print("\nAborted by user.", file=sys.stderr)
        sys.exit(3)
    finally:
        # Prevent sporadic exceptions in ftplib, when closing in __del__
        s.local.close()
        s.remote.close()

    stats = s.get_stats()
    if args.verbose >= 5:
        pprint(stats)
    elif args.verbose >= 1:
        if args.dry_run:
            print("(DRY-RUN) ", end="")
        print(
            "Wrote {}/{} files in {} directories, skipped: {}.".format(
                stats["files_written"],
                stats["local_files"],
                stats["local_dirs"],
                stats["conflict_files_skipped"],
            ),
            end="",
        )
        if stats["interactive_ask"]:
            print()
        else:
            print(" Elap: {}.".format(stats["elap_str"]))

    return
686108
def clean_env(uchroot_cmd, varnames):
    """"""
    env = uchroot_cmd["/usr/bin/env"]
    __clean_env = env["-u", ",".join(varnames)]
    return __clean_env
451319
def create_process(cmd, root_helper=None, addl_env=None, log_output=True):
    
    if root_helper:
        cmd = shlex.split(root_helper) + cmd
    cmd = map(str, cmd)

    log_output and LOG.info("Running command: %s", cmd)
    env = os.environ.copy()
    if addl_env:
        env.update(addl_env)

    obj = subprocess_popen(cmd, shell=False, stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           env=env)
    return obj, cmd