How to use the sh.ErrorReturnCode function in sh

To help you get started, we’ve selected a few sh examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chrisdev / wagtail-cookiecutter-foundation / tests / test_cookiecutter_generation.py View on Github external
def test_flake8_compliance(cookies):
    """generated project should pass flake8"""
    result = cookies.bake()
    try:
        sh.flake8(str(result.project))
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
github datastax / cstar_perf / tool / cstar_perf / tool / benchmark.py View on Github external
def build_stress(stress_revision, name=None):
    # Build a stress revision

    try:
        git_id = sh.git('--git-dir={home}/fab/cassandra.git'
                        .format(home=HOME), 'rev-parse', stress_revision).strip()
    except sh.ErrorReturnCode:
        raise AssertionError('Invalid stress_revision: {}'.format(stress_revision))

    path = os.path.join(CASSANDRA_STRESS_PATH, git_id)
    if not os.path.exists(path):
        logger.info("Building cassandra-stress '{}' in '{}'.".format(stress_revision, path))
        os.makedirs(path)
        sh.tar(
            sh.git("--git-dir={home}/fab/cassandra.git".format(home=HOME), "archive", git_id),
            'x', '-C', path
        )
        antcmd('-Dbasedir={}'.format(path), '-f', '{}/build.xml'.format(path),
               'realclean', 'jar', _env={"JAVA_TOOL_OPTIONS": "-Dfile.encoding=UTF8",
                                         "JAVA_HOME": JAVA_HOME})

    name = name if name else stress_revision
    return {name: git_id}
github WordOps / WordOps / wo / core / git.py View on Github external
def add(self, paths, msg="Intializating"):
        """
            Initializes Directory as repository if not already git repo.
            and adds uncommited changes automatically
        """
        for path in paths:
            global git
            wogit = git.bake("-C", "{0}".format(path))
            if os.path.isdir(path):
                if not os.path.isdir(path + "/.git"):
                    try:
                        Log.debug(self, "WOGit: git init at {0}"
                                  .format(path))
                        wogit.init(path)
                    except ErrorReturnCode as e:
                        Log.debug(self, "{0}".format(e))
                        Log.error(self, "Unable to git init at {0}"
                                  .format(path))
                status = wogit.status("-s")
                if len(status.splitlines()) > 0:
                    try:
                        Log.debug(self, "WOGit: git commit at {0}"
                                  .format(path))
                        wogit.add("--all")
                        wogit.commit("-am {0}".format(msg))
                    except ErrorReturnCode as e:
                        Log.debug(self, "{0}".format(e))
                        Log.error(self, "Unable to git commit at {0} "
                                  .format(path))
            else:
                Log.debug(self, "WOGit: Path {0} not present".format(path))
github Mirantis / stackalytics / stackalytics / processor / vcs.py View on Github external
def _checkout(self, branch):
        try:
            sh.git('clean', '-d', '--force')
            sh.git('reset', '--hard')
            sh.git('checkout', 'origin/' + branch)
            return True
        except sh.ErrorReturnCode:
            LOG.error('Unable to checkout branch %(branch)s from repo '
                      '%(uri)s. Ignore it',
                      {'branch': branch, 'uri': self.repo['uri']},
                      exc_info=True)
            return False
github S2E / s2e-env / s2e_env / commands / build.py View on Github external
self._make = sh.Command('make').bake(directory=build_dir, file=makefile, _env=env_vars)

        # If the user has specified any components to rebuild, do this before
        # the build
        if components:
            self._rebuild_components(components)

        try:
            # Run make
            if options['debug']:
                logger.info('Building S2E (debug) in %s', build_dir)
                self._make('all-debug', _out=sys.stdout, _err=sys.stderr)
            else:
                logger.info('Building S2E (release) in %s', build_dir)
                self._make('install', _out=sys.stdout, _err=sys.stderr)
        except ErrorReturnCode as e:
            raise CommandError(e)

        logger.success('S2E built')
github S2E / s2e-env / s2e_env / commands / import_project.py View on Github external
def _get_project_name(archive):
    """
    Get the project name from the archive.

    The project name is the name of the root directory in the archive.
    """
    try:
        contents = tar(exclude='*/*', list=True, file=archive)
        return os.path.dirname(str(contents))
    except ErrorReturnCode as e:
        raise CommandError('Failed to list archive - %s' % e)
github datastax / cstar_perf / tool / cstar_perf / tool / scripts / flamegraph.py View on Github external
def try_kill(process_line):
        try:
            sh.sudo.pkill('-f', '-9', process_line)
        except (sh.ErrorReturnCode, sh.SignalException):
            pass
github amoffat / sh / sh.py View on Github external
exc_stderr = self.stderr
        if truncate:
            exc_stderr = exc_stderr[:self.truncate_cap]
            err_delta = len(self.stderr) - len(exc_stderr)
            if err_delta:
                exc_stderr += ("... (%d more, please see e.stderr)" % err_delta).encode()

        msg_tmpl = unicode("\n\n  RAN: {cmd}\n\n  STDOUT:\n{stdout}\n\n  STDERR:\n{stderr}")

        msg = msg_tmpl.format(
            cmd=self.full_cmd,
            stdout=exc_stdout.decode(DEFAULT_ENCODING, "replace"),
            stderr=exc_stderr.decode(DEFAULT_ENCODING, "replace")
        )

        super(ErrorReturnCode, self).__init__(msg)
github WordOps / WordOps / wo / core / aptget.py View on Github external
def auto_remove(self):
        """
        Similar to `apt-get autoremove`
        """
        try:
            Log.debug(self, "Running apt-get autoremove")
            apt_get.autoremove("-y")
        except ErrorReturnCode as e:
            Log.debug(self, "{0}".format(e))
            Log.error(self, "Unable to apt-get autoremove")
github zatosource / zato / code / zato-server / src / zato / server / connection / connector / subprocess_ / impl / sftp.py View on Github external
def _on_OUTGOING_SFTP_EXECUTE(self, msg, is_reconnect=False, _utcnow=datetime.utcnow):
        out = {}
        connection = self.connections[msg.id] # type: SFTPConnection
        start_time = _utcnow()

        try:
            result = connection.execute(msg.cid, msg.data, msg.log_level) # type: Output
        except ErrorReturnCode as e:
            out['stdout'] = e.stdout
            out['stderr'] = e.stderr
        except Exception as e:
            out['stderr'] = format_exc()
            out['is_ok'] = False
        else:
            out.update(result.to_dict())
        finally:
            out['cid'] = msg.cid
            out['command_no'] = connection.command_no
            out['response_time'] = str(_utcnow() - start_time)

        return Response(data=dumps(out))