Skip to content
This repository
tree: abfb09e516
Fetching contributors…

Cannot retrieve contributors at this time

executable file 363 lines (328 sloc) 14.27 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
#! /usr/bin/env python

import json
from urllib2 import urlopen
import sys
from optparse import OptionParser
from tempfile import mkdtemp
import subprocess
import os
from os.path import expandvars
import urllib2
import base64
from urllib import urlencode
import time

from utils import (cmd, github_get_pull_request,
        github_authenticate, pastehtml_upload, reviews_sympy_org_upload,
        github_add_comment_to_pull_request, list_pull_requests, format_repo,
        get_interpreter_version_info, get_interpreter_exe, github_get_user_info)
from testrunner import run_tests
from url_templates import URLs

default_testcommand = "setup.py test"
default_interpreter = "python"
default_interpreter3 = "python3"
default_proto = 'https'

def main():
    parser = OptionParser(usage="""\
[options] [commands]

Commands:

review NNN Reviews the pull request NNN; You can specify more than
one number to review several pull requests in a series.
You can also specify 'all' and 'mergeable' instead of
NNN to review all or only all mergeable pull requests.
list Lists all open pull requests
list-numbers Lists only the numbers of open pull requests;
Suitable for piping into 'xargs -L 1 sympy-bot review'""")
    parser.add_option("-n", "--no-upload",
            action="store_false", dest="upload",
            default=True, help="Do not upload the results into the pull request")
    parser.add_option("-R", "--repository",
            action="store", type="str", dest="repository",
            default=None, help="Change the default 'sympy/sympy' repository to "
            "something else. This allows to use sympy-bot with other projects.")
    parser.add_option("-r", "--reference",
            action="store", type="str", dest="reference",
            default=None, help="Passes this to 'git clone <sympy repo>'")
    parser.add_option("-t", "--testcommand", dest="testcommand",
            default=None, help="Command to run tests with. "
            "Use this to run only a subset of tests, rather than the full "
            "test suite. The default is `sympy-bot -t 'setup.py test'`. Note "
            "that the command is run as the arguments of `python`. To run a "
            "command without python, add '-V; ' to the beginning, like "
            "`sympy-bot -t '-V; mycommand'`.")
    parser.add_option("-i", "--interpreter", dest="interpreter",
            default=None, help="Select interpreter to run test with. If "
            "you select Python 3.x, source code will be automatically "
            "translated using 'bin/use2to3'. The default is 'python'.")
    parser.add_option("-3", "--python3",
            action="store_true", default=False, dest="python3",
            help="Shorthand for 'sympy-bot -i python3")
    parser.add_option("-s", "--server",
            action="store", type="str", dest="server",
            default="http://reviews.sympy.org",
            help="Server to upload results. Default is "
            "'http://reviews.sympy.org'")
    parser.add_option("-m", "--master-commit",
            action="store", type="str", dest="master_commit",
            default="origin/master", help="Commit to use as master for merging." "Use 'origin/master' to use the current master (the default) "
            "and 'HEAD' to not merge.")
    parser.add_option("--no-comment",
            action="store_false", default=True, dest="comment",
            help="Don't submit a summary comment to the pull request (but still upload the test report).")
    parser.add_option("-p", "--protocol",
            type='choice', choices=['https', 'git',],
            action="store", default="https", dest="proto",
            help="Choose git protocol if https failed")


    options, args = parser.parse_args()
    config = load_config_file()

    if options.repository is None:
        options.repository = config.get("repository", "sympy/sympy")
    if options.reference is None:
        options.reference = config.get("reference")
    if options.testcommand is None:
        options.testcommand = config.get("testcommand", default_testcommand)
    if options.interpreter is None:
        if options.python3:
            options.interpreter = config.get("interpreter3", default_interpreter3)
        else:
            options.interpreter = config.get("interpreter", default_interpreter)
    proto = options.proto if options.proto != default_proto else default_proto

    options.user = config.get("user")
    options.password = config.get("password")
    gh_user, gh_repo = options.repository.split("/")
    urls = URLs(user=gh_user, repo=gh_repo)

    if len(args) == 1:
        arg, = args
        if arg == "list":
            list_pull_requests(urls)
            return
        elif arg == "list-numbers":
            list_pull_requests(urls, numbers_only=True)
            return
        print "Unknown command"
        sys.exit(1)
    elif len(args) >= 2:
        arg1 = args[0]
        if arg1 == "review":
            args = args[1:]
            if len(args) == 1:
                if args[0] == "mergeable":
                    print "Reviewing all *mergeable* pull requests"
                    print
                    nonmergeable, mergeable = list_pull_requests( \
                            urls, numbers_only=True)
                    nums = mergeable
                elif args[0] == "all":
                    print "Reviewing *all* pull requests"
                    print
                    nonmergeable, mergeable = list_pull_requests( \
                            urls, numbers_only=True)
                    nums = nonmergeable + mergeable
                else:
                    # just a pull request #, convert it:
                    nums = [int(args[0])]
            else:
                # list of pull request numbers, convert it:
                nums = [int(x) for x in args]
            if options.upload:
                username, password = github_authenticate(urls.api_url, options)
            else:
                username = password = None
            try:
                for n in nums:
                    review(urls, n, options, username=username, password=password, \
                           proto=proto
                          )
            except KeyboardInterrupt:
                print "\n> Quitting on signal SIGINT."
                sys.exit(1)
            return
        print "Unknown command"
        sys.exit(1)
    elif len(args) == 0:
        pass
    else:
        print "Too many arguments"
        sys.exit(1)
    parser.print_help()

def formulate_review(report_url, report_status, xpassed, master_hash,
        branch_hash, user, config):
    user = user.get("login", None)

    if user:
        atuser = "@"+user+": "
    else:
        atuser = ""
    if report_status == "conflicts":
        summary = """:exclamation: There were merge conflicts; could not test the branch.

%sPlease rebase or merge your branch with master. \
See the report for a list of the merge conflicts.""" % atuser
    elif report_status == "fetch":
        summary = """:x: Could not fetch the branch.

%sPlease run the sympy-bot tests again.""" % atuser
    elif report_status == "Failed":
        summary = """:red_circle: There were test failures.

%sPlease fix the test failures.""" % atuser
    elif report_status == "Passed":
        summary = """:eight_spoked_asterisk: All tests have passed."""
    else:
        raise ValueError("Unknown report_status")

    details = get_platform_version(config.interpreter)
    if config.testcommand != default_testcommand:
        bold = "**"
    else:
        bold = ""
    details += """*Test command:* %s%s%s\n""" % (bold, config.testcommand, bold)
    details += """*master hash*: %s\n""" % master_hash
    details += """*branch hash*: %s\n""" % branch_hash

    report = """\
**SymPy Bot Summary:** %s

Test results html report: %s

%s
Automatic review by [SymPy Bot](https://github.com/sympy/sympy-bot).""" % \
    (summary, report_url, details,)

    return report

def load_config_file():
    conf_file = os.path.normpath('.sympy/sympy-bot.conf')
    conf_file = os.path.join('~', conf_file)
    conf_file = os.path.expanduser(conf_file)
    print conf_file

    if os.path.exists(conf_file):
        namespace = {}

        with open(conf_file) as f:
            try:
                exec f.read() in namespace
            except (SystemExit, KeyboardInterrupt):
                raise
            except:
                print "WARNING: The config file cannot be parsed."
                pass
            else:
                print "> Using %s" % conf_file
                return namespace

    return {}

def get_executable(interpreter):
    path = os.environ['PATH']
    paths = path.split(os.pathsep)
    interpreter_exe = None
    if os.name=="nt":
        return get_interpreter_exe(interpreter)
    if os.path.isfile(interpreter):
        return interpreter
    else:
        for p in paths:
            f = os.path.join(p, interpreter)
            if os.path.isfile(f):
                return f

def get_platform_version(interpreter):
    from os import getenv
    import platform
    code = 'import sys; print(getattr(sys, "maxint", None))'
    call = "%s -c '%s'" % (interpreter, code)
    size = cmd(call, capture=True)
    if size == 'None\n': #Python 3 doesn't have maxint
        code = 'import sys; print(sys.maxsize)'
        call = "%s -c '%s'" % (interpreter, code)
        size = cmd(call, capture=True)
    size = int(size)
    if size > 2**32:
        architecture = "64-bit"
    else:
        architecture = "32-bit"
    platfotm_system = platform.system()
    use_cache = getenv('SYMPY_USE_CACHE', 'yes').lower()
    executable = get_executable(interpreter)
    python_version = get_interpreter_version_info(interpreter)
    r = "*Interpreter:* %s (%s)\n" % (executable, python_version)
    r += "*Architecture:* %s (%s)\n" % (platfotm_system, architecture)
    r += "*Cache:* %s\n" % use_cache
    return r

def review(urls, n, config, **kwargs):
    # Make sure python3 is setup correctly
    # If set Python 3 interpreter with -i, be sure python3 is True
    username = kwargs.get("username", None)
    password = kwargs.get("password", None)
    proto = kwargs.get("proto", None) or default_proto
    if get_interpreter_version_info(config.interpreter)[0] == '3':
        config.python3 = True
    # If set Python 2 interpreter with -i and set -3, raise error
    elif config.python3:
        raise ValueError("Python 2 interpreter passed with -3 option")

    tmpdir = mkdtemp(prefix="sympy-bot-tmp")
    print "> Working directory: %s" % tmpdir
    pull = github_get_pull_request(urls.single_pull_template, n)
    assert pull["number"] == n
    print "> Reviewing pull request #%d" % n
    repo = pull["head"]['repo']["html_url"]
    repo = repo.replace(default_proto, proto) if proto != default_proto else repo
    branch = pull["head"]["ref"]
    user = pull["head"]["user"]
    user_info = github_get_user_info(urls.user_info_template, username)
    author = "\"%s\" <%s>" % (user_info.get("name", "unknown"),
                              user_info.get("email", ""))
    print "> Pull request info:"
    print unicode("> Author: %s" % author).encode('utf8')
    print "> Repository: %s" % repo
    print "> Branch: %s" % branch

    print format_repo("> Cloning {repo} master", config.repository)

    if config.reference:
        reference = os.path.abspath(os.path.expanduser(os.path.expandvars(config.reference)))
        cmd(format_repo("cd %s && git clone --reference %s git://github.com/{repo}.git", config.repository) % (tmpdir, reference))
    else:
        cmd(format_repo("cd %s && git clone git://github.com/{repo}.git",
            config.repository) % tmpdir)

    print "> Testing..."
    result = run_tests(format_repo("https://github.com/{repo}.git",
        config.repository),
            repo, branch, tmpdir + "/sympy", config.testcommand,
            config.interpreter, config.python3, config.master_commit)
    if result["result"] == "error":
        print "There was an error. Report not uploaded."
        sys.exit(1)
    print "Done."
    print
    log_file = os.path.join("%s" % tmpdir, "out", "log")
    print "View log at: %s" % log_file
    log = result["log"]
    report_status = result["result"]
    xpassed = result["xpassed"]
    bot_file = os.path.realpath(os.path.abspath(__file__))
    bot_dir = os.path.dirname(bot_file)

    master_hash = result["master_hash"]
    branch_hash = result["branch_hash"]

    if os.name=='nt':
        mkdir_command = "mkdir"
    else:
        mkdir_command = "mkdir -p"
    cmd("%s %s" % (mkdir_command, os.path.join(tmpdir, "out")))
    open(log_file, "w").write(log)
    if config.upload:
        print "> Uploading test results"
        url_base = config.server
        data = {
                "num": n,
                "result": report_status,
                "interpreter": config.interpreter,
                "testcommand": config.testcommand,
                "log": log,
                "master_hash": master_hash,
                "branch_hash": branch_hash,
                }
        report_url = reviews_sympy_org_upload(data, url_base)
        print "> Uploaded report at: %s" % report_url
        review = formulate_review(report_url, report_status,
                xpassed, master_hash, branch_hash, user, config)
    else:
        review = formulate_review("(report was not uploaded)",
                report_status, xpassed, master_hash, branch_hash, user, config)
    print "> Review:"
    print review
    if config.upload and config.comment:
        print "> Uploading the review to the GitHub pull request ..."
        github_add_comment_to_pull_request(urls.issue_comment_template, \
                                           username, password, n, review
                                          )
        print "> Done."
        print format_repo("> Check the results: https://github.com/{repo}/pull/%d", config.repository) % n
    print "> Merged pull request available in: %s" % tmpdir

if __name__ == "__main__":
    main()
    sys.exit(0)
Something went wrong with that request. Please try again.