Your IP : 216.73.217.87
| Current Path : /usr/X11R6/bin/ |
|
|
| Current File : //usr/X11R6/bin/reviewboard-am |
#!/usr/bin/env python
# encoding: utf-8
"""
Copyright 2013 Aurélien Gâteau <agateau@kde.org>
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holders.
"""
from __future__ import print_function
import sys
if sys.version_info[0] != 2:
print("ERROR: This script must be run with Python 2", file=sys.stderr)
sys.exit(1)
import json
import os
import subprocess
import urllib2
from argparse import ArgumentParser
RB_URL = "https://git.reviewboard.kde.org"
DEBUG_JSON = "DEBUG_JSON" in os.environ
def api_request(url):
if DEBUG_JSON:
print("DEBUG_JSON: Fetching", url)
fl = urllib2.urlopen(url)
dct = json.load(fl)
if DEBUG_JSON:
print("DEBUG_JSON:")
print(json.dumps(dct, sort_keys=True, indent=4))
return dct
def git(*args):
cmd = ["git"] + list(args)
print("Running '%s'" % " ".join(cmd))
return subprocess.call(cmd) == 0
class RBClientError(Exception):
pass
class RBClient(object):
def __init__(self, url):
self.url = url
def get_request_info(self, request_id):
try:
dct = api_request(self.url + "/api/review-requests/%d/" % request_id)
except urllib2.HTTPError, exc:
if exc.code == 404:
raise RBClientError("HTTP Error 404: there is probably no request with id %d." % request_id)
raise
return dct["review_request"]
def get_author_info(self, submitter_url):
dct = api_request(submitter_url)
return dct["user"]
def download_diff(self, request_id):
fl = urllib2.urlopen(self.url + "/r/%d/diff/raw/" % request_id)
return fl.read()
def parse_author_info(author_info):
def loop_raw_input(prompt):
while True:
out = raw_input(prompt)
if out:
return out
print("Invalid value.")
fullname = author_info.get("fullname")
email = author_info.get("email")
username = author_info["username"]
if fullname is None:
fullname = loop_raw_input("Could not get fullname for user '%s'. Please enter it: " % username)
if email is None:
email = loop_raw_input("Could not get email for user '%s'. Please enter it: " % username)
return fullname, email
def write_patch(fl, fullname, email, summary, description, diff):
author = "%s <%s>" % (fullname, email)
print("From:", author.encode("utf-8"), file=fl)
print("Subject:", summary.encode("utf-8"), file=fl)
print(file=fl)
print(description.encode("utf-8"), file=fl)
print(file=fl)
fl.write(diff)
def detect_p_value(diff):
for line in diff.splitlines():
if line.startswith("diff --git a/"):
return 1
elif line.startswith("diff --git "):
return 0
return 1
def main():
parser = ArgumentParser()
parser.add_argument("request_id", type=int,
help="reviewboard ID to apply")
parser.add_argument("-b", "--branch",
action="store_true", dest="branch", default=False,
help="create a branch named after the reviewboard ID")
args = parser.parse_args()
request_id = args.request_id
rb = RBClient(RB_URL)
print("Fetching request info")
try:
request_info = rb.get_request_info(request_id)
except RBClientError, exc:
print(exc)
return 1
author_info = rb.get_author_info(request_info["links"]["submitter"]["href"])
summary = request_info["summary"]
description = request_info["description"]
description += "\n\nREVIEW: " + str(request_id)
for bug_closed in request_info["bugs_closed"]:
description += "\nBUG: " + bug_closed
fullname, email = parse_author_info(author_info)
print("Downloading diff")
diff = rb.download_diff(request_id)
name = "rb-%d.patch" % request_id
print("Creating %s" % name)
with open(name, "w") as fl:
write_patch(fl, fullname, email, summary, description, diff)
if args.branch:
if not git("checkout", "-b", "rb-%d" % request_id):
return 1
p_value = detect_p_value(diff)
if not git("am", "-p%d" % p_value, name):
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
# vi: ts=4 sw=4 et