Execute a ruby command with rbenv's shims from the user or the system

    CLI Example:

    .. code-block:: bash

        salt '*' rbenv.do 'gem list bundler'
        salt '*' rbenv.do 'gem list bundler' deploy
190629
def do(cmdline, runas=None, env=None):
    '''
    
    '''
    if not cmdline:
        # This is a positional argument so this should never happen, but this
        # will handle cases where someone explicitly passes a false value for
        # cmdline.
        raise SaltInvocationError('Command must be specified')

    path = _rbenv_path(runas)
    if not env:
        env = {}

    # NOTE: Env vars (and their values) need to be str type on both Python 2
    # and 3. The code below first normalizes all path components to unicode to
    # stitch them together, and then converts the result back to a str type.
    env[str('PATH')] = salt.utils.stringutils.to_str(   # future lint: disable=blacklisted-function
        os.pathsep.join((
            salt.utils.path.join(path, 'shims'),
            salt.utils.stringutils.to_unicode(os.environ['PATH'])
        ))
    )

    try:
        cmdline = salt.utils.args.shlex_split(cmdline)
    except AttributeError:
        cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))

    result = __salt__['cmd.run_all'](
        cmdline,
        runas=runas,
        env=env,
        python_shell=False
    )

    if result['retcode'] == 0:
        rehash(runas=runas)
        return result['stdout']
    else:
        return False
883736
def execute(self, name, command):
        
        if name in ["localhost"]:
            r = '\n'.join(Shell.sh("-c", command).split()[-1:])
        else:
            r = '\n'.join(Shell.ssh(name, command).split()[-1:])
        return r
248334
def command(command):
    
    with cd(env.remote_path):
        sudo(env.python + ' manage.py %s' % command, user=env.remote_user)
160604
def sh(cmd, silent = false)

    if RbConfig::CONFIG["host_os"] != "mingw32"
      full_cmd = "export PATH=#{@settings['PATH']} && #{cmd}"
    else
      full_cmd = "PATH = #{@settings['PATH']} & #{cmd}"
    end

    if silent
      system full_cmd
    else
      Rake::sh full_cmd
    end
  end
581737
def main(argv):  # pylint: disable=W0613
    '''
    
    '''
    thin_path = os.path.join(OPTIONS.saltdir, THIN_ARCHIVE)
    if os.path.isfile(thin_path):
        if OPTIONS.checksum != get_hash(thin_path, OPTIONS.hashfunc):
            need_deployment()
        unpack_thin(thin_path)
        # Salt thin now is available to use
    else:
        if not sys.platform.startswith('win'):
            scpstat = subprocess.Popen(['/bin/sh', '-c', 'command -v scp']).wait()
            if scpstat != 0:
                sys.exit(EX_SCP_NOT_FOUND)

        if os.path.exists(OPTIONS.saltdir) and not os.path.isdir(OPTIONS.saltdir):
            sys.stderr.write(
                'ERROR: salt path "{0}" exists but is'
                ' not a directory\n'.format(OPTIONS.saltdir)
            )
            sys.exit(EX_CANTCREAT)

        if not os.path.exists(OPTIONS.saltdir):
            need_deployment()

        code_checksum_path = os.path.normpath(os.path.join(OPTIONS.saltdir, 'code-checksum'))
        if not os.path.exists(code_checksum_path) or not os.path.isfile(code_checksum_path):
            sys.stderr.write('WARNING: Unable to locate current code checksum: {0}.\n'.format(code_checksum_path))
            need_deployment()
        with open(code_checksum_path, 'r') as vpo:
            cur_code_cs = vpo.readline().strip()
        if cur_code_cs != OPTIONS.code_checksum:
            sys.stderr.write('WARNING: current code checksum {0} is different to {1}.\n'.format(cur_code_cs,
                                                                                                OPTIONS.code_checksum))
            need_deployment()
        # Salt thin exists and is up-to-date - fall through and use it

    salt_call_path = os.path.join(OPTIONS.saltdir, 'salt-call')
    if not os.path.isfile(salt_call_path):
        sys.stderr.write('ERROR: thin is missing "{0}"\n'.format(salt_call_path))
        need_deployment()

    with open(os.path.join(OPTIONS.saltdir, 'minion'), 'w') as config:
        config.write(OPTIONS.config + '\n')
    if OPTIONS.ext_mods:
        ext_path = os.path.join(OPTIONS.saltdir, EXT_ARCHIVE)
        if os.path.exists(ext_path):
            unpack_ext(ext_path)
        else:
            version_path = os.path.join(OPTIONS.saltdir, 'ext_version')
            if not os.path.exists(version_path) or not os.path.isfile(version_path):
                need_ext()
            with open(version_path, 'r') as vpo:
                cur_version = vpo.readline().strip()
            if cur_version != OPTIONS.ext_mods:
                need_ext()
    # Fix parameter passing issue
    if len(ARGS) == 1:
        argv_prepared = ARGS[0].split()
    else:
        argv_prepared = ARGS

    salt_argv = [
        get_executable(),
        salt_call_path,
        '--retcode-passthrough',
        '--local',
        '--metadata',
        '--out', 'json',
        '-l', 'quiet',
        '-c', OPTIONS.saltdir
    ]

    try:
        if argv_prepared[-1].startswith('--no-parse='):
            salt_argv.append(argv_prepared.pop(-1))
    except (IndexError, TypeError):
        pass

    salt_argv.append('--')
    salt_argv.extend(argv_prepared)

    sys.stderr.write('SALT_ARGV: {0}\n'.format(salt_argv))

    # Only emit the delimiter on *both* stdout and stderr when completely successful.
    # Yes, the flush() is necessary.
    sys.stdout.write(OPTIONS.delimiter + '\n')
    sys.stdout.flush()
    if not OPTIONS.tty:
        sys.stderr.write(OPTIONS.delimiter + '\n')
        sys.stderr.flush()
    if OPTIONS.cmd_umask is not None:
        old_umask = os.umask(OPTIONS.cmd_umask)  # pylint: disable=blacklisted-function
    if OPTIONS.tty:
        proc = subprocess.Popen(salt_argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        # Returns bytes instead of string on python 3
        stdout, _ = proc.communicate()
        sys.stdout.write(stdout.decode(encoding=get_system_encoding(), errors="replace"))
        sys.stdout.flush()
        retcode = proc.returncode
        if OPTIONS.wipe:
            shutil.rmtree(OPTIONS.saltdir)
    elif OPTIONS.wipe:
        retcode = subprocess.call(salt_argv)
        shutil.rmtree(OPTIONS.saltdir)
    else:
        retcode = subprocess.call(salt_argv)
    if OPTIONS.cmd_umask is not None:
        os.umask(old_umask)  # pylint: disable=blacklisted-function
    return retcode
1313377
def list_env(self, saltenv='base'):
        '''
        
        '''
        load = {'saltenv': saltenv,
                'cmd': '_file_list'}
        return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \
            else self.channel.send(load)
1164844
def salt_main():
    '''
    
    '''
    import salt.cli.salt
    if '' in sys.path:
        sys.path.remove('')
    client = salt.cli.salt.SaltCMD()
    _install_signal_handlers(client)
    client.run()
566884
def _check_and_install_ruby(ret, ruby, default=False, user=None):
    '''
    
    '''
    ret = _ruby_installed(ret, ruby, user=user)
    if not ret['result']:
        if __salt__['rbenv.install_ruby'](ruby, runas=user):
            ret['result'] = True
            ret['changes'][ruby] = 'Installed'
            ret['comment'] = 'Successfully installed ruby'
            ret['default'] = default
        else:
            ret['result'] = False
            ret['comment'] = 'Failed to install ruby'
            return ret

    if default:
        __salt__['rbenv.default'](ruby, runas=user)

    return ret
145760
def exec_nb_cmd(self, cmd):
        '''
        
        '''
        r_out = []
        r_err = []
        rcode = None
        cmd = self._cmd_str(cmd)

        logmsg = 'Executing non-blocking command: {0}'.format(cmd)
        if self.passwd:
            logmsg = logmsg.replace(self.passwd, ('*' * 6))
        log.debug(logmsg)

        for out, err, rcode in self._run_nb_cmd(cmd):
            if out is not None:
                r_out.append(out)
            if err is not None:
                r_err.append(err)
            yield None, None, None
        yield ''.join(r_out), ''.join(r_err), rcode
1268483
def _check_and_install_ruby(ret, ruby, default=False, user=None, opts=None, env=None):
    '''
    
    '''
    ret = _check_ruby(ret, ruby, user=user)
    if not ret['result']:
        if __salt__['rvm.install_ruby'](ruby, runas=user, opts=opts, env=env):
            ret['result'] = True
            ret['changes'][ruby] = 'Installed'
            ret['comment'] = 'Successfully installed ruby.'
            ret['default'] = False
        else:
            ret['result'] = False
            ret['comment'] = 'Could not install ruby.'
            return ret

    if default:
        __salt__['rvm.set_default'](ruby, runas=user)

    return ret
351826
def _run(cmd):
    '''
    
    '''
    return __salt__['cmd.run_all'](cmd, env={'HOME': os.path.expanduser('~{0}'.format(__opts__['user']))})
603952
def salt_run():
    '''
    
    '''
    import salt.cli.run
    if '' in sys.path:
        sys.path.remove('')
    client = salt.cli.run.SaltRun()
    _install_signal_handlers(client)
    client.run()
1279892
def _exec(**kwargs):
    '''
    
    '''
    if 'ignore_retcode' not in kwargs:
        kwargs['ignore_retcode'] = True
    if 'output_loglevel' not in kwargs:
        kwargs['output_loglevel'] = 'quiet'
    return salt.modules.cmdmod.run_all(**kwargs)
1304530
def salt_master(project, target, module, args=None, kwargs=None):
    
    client = project.cluster.head.ssh_client

    cmd = ['salt']
    cmd.extend(generate_salt_cmd(target, module, args, kwargs))
    cmd.append('--timeout=300')
    cmd.append('--state-output=mixed')
    cmd = ' '.join(cmd)

    output = client.exec_command(cmd, sudo=True)
    if output['exit_code'] == 0:
        return output['stdout']
    else:
        return output['stderr']
700030
def __execute_cmd(name, cmd):
    '''
    
    '''
    return __salt__['cmd.run_all'](
        '{0} {1}'.format(salt.utils.path.which(name), cmd)
    )
91854
def run_specs(options = nil)
      options ||= {}
      files = options.fetch(:files, 'spec')
      rspec_options = options.fetch(:options, '--color')
      # We need to override the gemfile explicitely, since we have a default Gemfile in the project root
      gemfile = options.fetch(:gemfile, Gemika::Env.gemfile)
      fatal = options.fetch(:fatal, true)
      runner = binary(:gemfile => gemfile)
      bundle_exec = options.fetch(:bundle_exec) ? 'bundle exec' : nil
      command = [bundle_exec, runner, rspec_options, files].compact.join(' ')
      result = shell_out(command)
      if result
        true
      elsif fatal
        raise RSpecFailed, "RSpec failed: #{command}"
      else
        false
      end
    end
878466
def run(args = ARGV)
      opts.parse!(args)

      if !analyze_gemfile? && args.empty?
        puts opts.parser
        exit 1
      end

      print_requires(options, args)
    end