<commit_before>#!/usr/bin/env python

# http://gerrit-documentation.googlecode.com/svn/Documentation/2.2.2/cmd-
# query.html

import pkg_resources
import subprocess
from datetime import datetime
import simplejson as json
import time
import tempfile
import textwrap
import pydoc
import os


class FGerrit(object):

    def __init__(self, ssh_user, ssh_host, project, ssh_port=29418,
                 status="open"):
        self.ssh_user = ssh_user
        self.ssh_host = ssh_host
        self.ssh_port = ssh_port
        self.project = project
        self.status = status
        term_info = os.popen('stty size', 'r').read().split()
        self.term_rows = int(term_info[0])
        self.full_width = int(term_info[1])

    def _cprint(self, output):
        """either print output or invoke pager"""
        if self.term_rows < sum([len(i.split('\n')) for i in output]):
            pydoc.pager('\n'.join(output))
        else:
            print '\n'.join(output)

    def _conv_ts(self, timestamp, terse=False):
        if terse:
            when = time.time() - timestamp
            if when < 60:
                return '%4.1fs' % when
            elif when < 3600:
                return '%4.1fm' % (when / 60)
            elif when < 86400:
                return '%4.1fh' % (when / 3600)
            else:
                return '%4.1fd' % (when / 86400)
        else:
            return datetime.fromtimestamp(int(timestamp))

    def _run_query(self, qargs, plain=False):
        if not plain:
            sshcmd = 'ssh -p %d %s@%s "gerrit query --format=JSON %s"' % \
                (self.ssh_port, self.ssh_user, self.ssh_host, qargs)
        else:
            sshcmd = 'ssh -p %d %s@%s "gerrit query --format=TEXT %s"' % \
                (self.ssh_port, self.ssh_user, self.ssh_host, qargs)
        print repr(sshcmd)
        p = subprocess.Popen(sshcmd, shell=True, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        retval = p.wait()
        if retval != 0:
            raise Exception('Error on ssh to gerrit %s' % p.stdout.readlines())
        if not plain:
            result = []
            for line in p.stdout.readlines():
                result.append(json.loads(line))
            retval = p.wait()
            return [x for x in result if 'status' in x]
        else:
            return " ".join(p.stdout.readlines())

    def _run_cmd(self, cargs):
        sshcmd = "ssh -p %d %s@%s 'gerrit %s'" % (self.ssh_port, self.ssh_user, self.ssh_host, cargs.replace("'", "'\"'\"'"))
        p = subprocess.Popen(sshcmd, shell=True, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        retval = p.wait()
        if retval != 0:
            raise Exception('Error on ssh to gerrit %s' % p.stdout.readlines())
        return " ".join(p.stdout.readlines())

    def list_reviews(self):
        return self._run_query(
            'status:%s project:%s --current-patch-set' % (self.status,
                                                          self.project))

    def _parse_approvals(self, review):
        retval = [' ', ' ', ' ']
        for i in review.get('currentPatchSet', {}).get('approvals', []):
            typ = i['type']
            idx = {'VRIF': 0, 'CRVW': 1, 'APRV': 2}.get(typ)
            if idx is not None:
                val = int(i['value'])
                if val < 0:
                    retval[idx] = '-'
                elif typ == 'CRVW':
                    if val > 1 and retval[idx] == ' ':
                        retval[idx] = '+'
                elif val > 0 and retval[idx] == ' ':
                    retval[idx] = '+'
        return retval

    def get_review(self, review_id, comments=False, text=False):
        """Either a short id (5264) or long hash"""
        if comments:
            return self._run_query('commit:%s --current-patch-set --comments --commit-message' % review_id, plain=text)
        else:
            return self._run_query(review_id, plain=text)

    def delete_change(self, patchset):
        payload = "review %s --delete" % patchset
        return self._run_cmd(payload)

    def abandon_change(self, patchset):
        payload = "review %s --abandon" % patchset
        return self._run_cmd(payload)

    def restore_change(self, patchset):
        payload = "review %s --restore" % patchset
        return self._run_cmd(payload)

    def get_message(self, message):
        if not message:
            editor = os.environ.get(
                'FGERRIT_EDITOR', os.environ.get('EDITOR', 'vi'))
            with tempfile.NamedTemporaryFile() as fp:
                p = subprocess.Popen('%s %s' % (editor, fp.name), shell=True)
                retval = p.wait()
                if retval != 0:
                    raise Exception('Error on editor exit code %d' % retval)
                message = fp.read().strip()
            if not message:
                raise Exception('Abort, no message')
        return "'%s'" % message.replace("'", "'\"'\"'")

    def post_message(self, review_id, message):
        if not message:
            raise Exception('Abort, no message')
        payload = "review commit:%s --message=%s" % (review_id, message)
        return self._run_cmd(payload)

    def verify_change(self, review_id, score, message=None):
        valid_scores = ["-1", "0", "+1"]
        if message:
            payload = "review commit:%s --verified %s --message='%s'" % (review_id,
                                                                  score,
                                                                  message)
        else:
            payload = "review commit:%s --verified %s" % (review_id, score)
        if score in valid_scores:
            return self._run_cmd(payload)
        else:
            raise Exception(
                'Score should be one of: %s' % ' '.join(valid_scores))

    def code_review(self, review_id, score, message=None):
        valid_scores = ["-2", "-1", "0", "+1", "+2"]
        if message:
            payload = "review commit:%s --code-review %s --message=%s" % (
                review_id, score, message)
        else:
            payload = "review commit:%s --code-review %s" % (review_id, score)
        if score in valid_scores:
            return self._run_cmd(payload)
        else:
            raise Exception(
                'Score should be one of: %s' % ' '.join(valid_scores))

    def approve_review(self, review_id, score, message=None):
        valid_scores = ["0", "+1"]
        if message:
            payload = "approve commit:%s --approve %s --message='%s'" % (review_id,
                                                                  score,
                                                                  message)
        else:
            payload = "approve commit:%s --approve %s" % (review_id, score)
        if score in valid_scores:
            return self._run_cmd(payload)
        else:
            raise Exception(
                'Score should be one of: %s' % ' '.join(valid_scores))

    def print_reviews_list(self, reviews):
        title = "Open Reviews for %s" % self.project
        tlen = len(title)
        sep = "=" * (self.full_width - 1)
        output = []
        output.append(sep)<commit_msg>Fixed run_cmd to /not/ send commit:x<commit_after>#!/usr/bin/env python

# http://gerrit-documentation.googlecode.com/svn/Documentation/2.2.2/cmd-
# query.html

import pkg_resources
import subprocess
from datetime import datetime
import simplejson as json
import time
import tempfile
import textwrap
import pydoc
import os


class FGerrit(object):

    def __init__(self, ssh_user, ssh_host, project, ssh_port=29418,
                 status="open"):
        self.ssh_user = ssh_user
        self.ssh_host = ssh_host
        self.ssh_port = ssh_port
        self.project = project
        self.status = status
        term_info = os.popen('stty size', 'r').read().split()
        self.term_rows = int(term_info[0])
        self.full_width = int(term_info[1])

    def _cprint(self, output):
        """either print output or invoke pager"""
        if self.term_rows < sum([len(i.split('\n')) for i in output]):
            pydoc.pager('\n'.join(output))
        else:
            print '\n'.join(output)

    def _conv_ts(self, timestamp, terse=False):
        if terse:
            when = time.time() - timestamp
            if when < 60:
                return '%4.1fs' % when
            elif when < 3600:
                return '%4.1fm' % (when / 60)
            elif when < 86400:
                return '%4.1fh' % (when / 3600)
            else:
                return '%4.1fd' % (when / 86400)
        else:
            return datetime.fromtimestamp(int(timestamp))

    def _run_query(self, qargs, plain=False):
        if not plain:
            sshcmd = 'ssh -p %d %s@%s "gerrit query --format=JSON %s"' % \
                (self.ssh_port, self.ssh_user, self.ssh_host, qargs)
        else:
            sshcmd = 'ssh -p %d %s@%s "gerrit query --format=TEXT %s"' % \
                (self.ssh_port, self.ssh_user, self.ssh_host, qargs)
        p = subprocess.Popen(sshcmd, shell=True, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        retval = p.wait()
        if retval != 0:
            raise Exception('Error on ssh to gerrit %s' % p.stdout.readlines())
        if not plain:
            result = []
            for line in p.stdout.readlines():
                result.append(json.loads(line))
            retval = p.wait()
            return [x for x in result if 'status' in x]
        else:
            return " ".join(p.stdout.readlines())

    def _run_cmd(self, cargs):
        sshcmd = "ssh -p %d %s@%s 'gerrit %s'" % (self.ssh_port, self.ssh_user, self.ssh_host, cargs.replace("'", "'\"'\"'"))
        p = subprocess.Popen(sshcmd, shell=True, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        retval = p.wait()
        if retval != 0:
            raise Exception('Error on ssh to gerrit %s' % p.stdout.readlines())
        return " ".join(p.stdout.readlines())

    def list_reviews(self):
        return self._run_query(
            'status:%s project:%s --current-patch-set' % (self.status,
                                                          self.project))

    def _parse_approvals(self, review):
        retval = [' ', ' ', ' ']
        for i in review.get('currentPatchSet', {}).get('approvals', []):
            typ = i['type']
            idx = {'VRIF': 0, 'CRVW': 1, 'APRV': 2}.get(typ)
            if idx is not None:
                val = int(i['value'])
                if val < 0:
                    retval[idx] = '-'
                elif typ == 'CRVW':
                    if val > 1 and retval[idx] == ' ':
                        retval[idx] = '+'
                elif val > 0 and retval[idx] == ' ':
                    retval[idx] = '+'
        return retval

    def get_review(self, review_id, comments=False, text=False):
        """Either a short id (5264) or long hash"""
        if comments:
            return self._run_query('commit:%s --current-patch-set --comments --commit-message' % review_id, plain=text)
        else:
            return self._run_query(review_id, plain=text)

    def delete_change(self, patchset):
        payload = "review %s --delete" % patchset
        return self._run_cmd(payload)

    def abandon_change(self, patchset):
        payload = "review %s --abandon" % patchset
        return self._run_cmd(payload)

    def restore_change(self, patchset):
        payload = "review %s --restore" % patchset
        return self._run_cmd(payload)

    def get_message(self, message):
        if not message:
            editor = os.environ.get(
                'FGERRIT_EDITOR', os.environ.get('EDITOR', 'vi'))
            with tempfile.NamedTemporaryFile() as fp:
                p = subprocess.Popen('%s %s' % (editor, fp.name), shell=True)
                retval = p.wait()
                if retval != 0:
                    raise Exception('Error on editor exit code %d' % retval)
                message = fp.read().strip()
            if not message:
                raise Exception('Abort, no message')
        return "'%s'" % message.replace("'", "'\"'\"'")

    def post_message(self, review_id, message):
        if not message:
            raise Exception('Abort, no message')
        payload = "review %s --message=%s" % (review_id, message)
        return self._run_cmd(payload)

    def verify_change(self, review_id, score, message=None):
        valid_scores = ["-1", "0", "+1"]
        if message:
            payload = "review %s --verified %s --message='%s'" % (review_id,
                                                                  score,
                                                                  message)
        else:
            payload = "review %s --verified %s" % (review_id, score)
        if score in valid_scores:
            return self._run_cmd(payload)
        else:
            raise Exception(
                'Score should be one of: %s' % ' '.join(valid_scores))

    def code_review(self, review_id, score, message=None):
        valid_scores = ["-2", "-1", "0", "+1", "+2"]
        if message:
            payload = "review %s --code-review %s --message=%s" % (
                review_id, score, message)
        else:
            payload = "review %s --code-review %s" % (review_id, score)
        if score in valid_scores:
            return self._run_cmd(payload)
        else:
            raise Exception(
                'Score should be one of: %s' % ' '.join(valid_scores))

    def approve_review(self, review_id, score, message=None):
        valid_scores = ["0", "+1"]
        if message:
            payload = "approve %s --approve %s --message='%s'" % (review_id,
                                                                  score,
                                                                  message)
        else:
            payload = "approve %s --approve %s" % (review_id, score)
        if score in valid_scores:
            return self._run_cmd(payload)
        else:
            raise Exception(
                'Score should be one of: %s' % ' '.join(valid_scores))

    def print_reviews_list(self, reviews):
        title = "Open Reviews for %s" % self.project
        tlen = len(title)
        sep = "=" * (self.full_width - 1)
        output = []
        output.append(sep)
{'fraction_non_alphanumeric': 0.12892973122365783, 'fraction_numerical': 0.008844054446210184, 'mean_word_length': 1.640277271068953, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3992216', 'n_tokens_mistral': 4409, 'n_tokens_neox': 4161, 'n_words': 1096}