Current File : /home/jvzmxxx/wiki1/extensions/MobileFrontend/dev-scripts/pre-review
#!/usr/bin/env python
# Enable this pre-review hook by running 'make installhooks'
import sys
import urllib2
import subprocess
import json

MAX_OPEN_PATCHES = 7
PROJECT_NAME = "mediawiki/extensions/MobileFrontend"

def get_last_commit():
    command = "git log -1"
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    #Launch the shell command:
    output, error = process.communicate()
    return output

def query_gerrit():
    url = "https://gerrit.wikimedia.org/r/changes/?n=25&o=LABELS&q=status:open+project:%s" % PROJECT_NAME
    req = urllib2.Request(url)
    req.add_header('Accept', 'application/json')
    resp, data = urllib2.urlopen(req)
    return json.loads(data)

changes = query_gerrit()
open_patches = 0
commit = get_last_commit()

if len(changes) == 0:
    print "WARNING: Gerrit API did not return any changes for project %s!" % PROJECT_NAME
    print "This is suspicious and should not happen unless there are no open changes."
    print "If you are sure that this is the case, you can skip this check by running `git review --no-custom-script`."
    sys.exit(1)

for change in changes:
    # This patch is updating an existing one so let's allow it.
    if change["change_id"] in commit:
        sys.exit()

    reviews = change["labels"]["Code-Review"]
    jenkins = change["labels"]["Verified"]

    if (
        'disliked' not in reviews and
        'rejected' not in reviews and
        'approved' not in reviews and
        'rejected' not in jenkins and
        'WIP' not in change['subject']
    ):
        open_patches += 1

'''
Run jsduck and complain if there is an non zero exit code
@returns string if there are warnings
@returns false if no warnings
'''
def js_duck_warnings():
    command = "make jsduck"
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    #Launch the shell command:
    output, error = process.communicate()
    if error:
        return error
    else:
        return False

js_duck_warnings = js_duck_warnings()
if js_duck_warnings:
    print 'Please fix the jsduck warnings before submitting this for code review:'
    print js_duck_warnings
    sys.exit(1)

if open_patches > MAX_OPEN_PATCHES:
    print 'Do some code review first! There are %s open unreviewed patches!' % open_patches
    print 'You can still send this review by running `git review --no-custom-script` but note this will generate bad karma.'
    sys.exit(1)