reviewboard: don't use ReviewBoardClient as a context manager; r=smacleod draft
authorGregory Szorc <gps@mozilla.com>
Mon, 11 Jan 2016 15:57:45 -0800
changeset 6718 7fd4fa6a1e1995f16658c4d7a59260ed52d0241a
parent 6717 c85f73a6b2af2290021cd24ea966215ef85e6f05
child 6719 547f340304e13fa0fa8cf7fe954c52563734d326
child 6720 0a35fe8105d07422beb9238f25fb47966fa02587
push id513
push usergszorc@mozilla.com
push dateWed, 13 Jan 2016 02:13:15 +0000
reviewerssmacleod
reviewboard: don't use ReviewBoardClient as a context manager; r=smacleod Because it no longer needs to be one. The diff looks painful but it is mostly whitespace.
hgext/reviewboard/hgrb/proto.py
hgext/reviewboard/server.py
pylib/reviewboardmods/reviewboardmods/pushhooks.py
testing/vcttesting/reviewboard/__init__.py
--- a/hgext/reviewboard/hgrb/proto.py
+++ b/hgext/reviewboard/hgrb/proto.py
@@ -97,40 +97,40 @@ def post_reviews(*args, **kwargs):
 
 
 def submit_reviews(url, repoid, identifier, commits, hgresp,
                    username=None, apikey=None):
     """Submit commits to Review Board."""
     import json
     from reviewboardmods.pushhooks import ReviewBoardClient
 
-    with ReviewBoardClient(url, username=username, apikey=apikey) as client:
-        root = client.get_root()
+    client = ReviewBoardClient(url, username=username, apikey=apikey)
+    root = client.get_root()
 
-        batch_request_resource = root.get_extension(
-            extension_name='mozreview.extension.MozReviewExtension')\
-            .get_batch_review_requests()
-        series_result = batch_request_resource.create(
-            # This assumes that we pushed to the repository/URL that Review Board is
-            # configured to use. This assumption may not always hold.
-            repo_id=repoid,
-            identifier=identifier,
-            commits=json.dumps(commits, encoding='utf-8'))
+    batch_request_resource = root.get_extension(
+        extension_name='mozreview.extension.MozReviewExtension')\
+        .get_batch_review_requests()
+    series_result = batch_request_resource.create(
+        # This assumes that we pushed to the repository/URL that Review Board is
+        # configured to use. This assumption may not always hold.
+        repo_id=repoid,
+        identifier=identifier,
+        commits=json.dumps(commits, encoding='utf-8'))
 
-        for w in series_result.warnings:
-            hgresp.append(b'display %s' % w.encode('utf-8'))
+    for w in series_result.warnings:
+        hgresp.append(b'display %s' % w.encode('utf-8'))
 
-        nodes = {node.encode('utf-8'): str(rid)
-                 for node, rid in series_result.nodes.iteritems()}
+    nodes = {node.encode('utf-8'): str(rid)
+             for node, rid in series_result.nodes.iteritems()}
 
-        return (
-            str(series_result.squashed_rr),
-            nodes,
-            series_result.review_requests,
-        )
+    return (
+        str(series_result.squashed_rr),
+        nodes,
+        series_result.review_requests,
+    )
 
 
 def associate_ldap_username(*args, **kwargs):
     from reviewboardmods.pushhooks import associate_ldap_username as alu
     return alu(*args, **kwargs)
 
 
 def getpayload(proto, args):
@@ -424,72 +424,72 @@ def pullreviews(repo, proto, args=None):
 
     o = parsepayload(proto, args)
     if isinstance(o, ServerError):
         return formatresponse(str(o))
 
     lines = ['1']
 
     from reviewboardmods.pushhooks import ReviewBoardClient
-    with ReviewBoardClient(repo.ui.config('reviewboard', 'url').rstrip('/'),
-                           username=o['bzusername'],
-                           apikey=o['bzapikey']) as client:
-        root = client.get_root()
+    client = ReviewBoardClient(repo.ui.config('reviewboard', 'url').rstrip('/'),
+                               username=o['bzusername'],
+                               apikey=o['bzapikey'])
+    root = client.get_root()
 
-        for k, v in o['other']:
-            if k != 'reviewid':
-                continue
+    for k, v in o['other']:
+        if k != 'reviewid':
+            continue
 
-            identifier = urllib.unquote(v)
-            rrs = root.get_review_requests(commit_id=identifier)
+        identifier = urllib.unquote(v)
+        rrs = root.get_review_requests(commit_id=identifier)
 
-            if rrs.total_results != 1:
-                continue
+        if rrs.total_results != 1:
+            continue
 
-            rr = rrs[0]
-            extra_data = rr.extra_data
+        rr = rrs[0]
+        extra_data = rr.extra_data
 
-            try:
-                is_squashed = extra_data['p2rb.is_squashed']
-            except KeyError:
-                is_squashed = None
+        try:
+            is_squashed = extra_data['p2rb.is_squashed']
+        except KeyError:
+            is_squashed = None
 
-            # 'True' in RB <= 2.0.11; True in 2.0.11+. We may have old
-            # values in the database, so keep checking for 'True' until we
-            # have a migration.
-            if is_squashed is True or is_squashed == 'True':
-                if 'p2rb.commits' in extra_data:
-                    commits = extra_data['p2rb.commits']
+        # 'True' in RB <= 2.0.11; True in 2.0.11+. We may have old
+        # values in the database, so keep checking for 'True' until we
+        # have a migration.
+        if is_squashed is True or is_squashed == 'True':
+            if 'p2rb.commits' in extra_data:
+                commits = extra_data['p2rb.commits']
+            else:
+                draft = rr.get_draft()
+                if 'p2rb.commits' in draft.extra_data:
+                    commits = draft.extra_data['p2rb.commits']
                 else:
-                    draft = rr.get_draft()
-                    if 'p2rb.commits' in draft.extra_data:
-                        commits = draft.extra_data['p2rb.commits']
-                    else:
-                        commits = '[]'
+                    commits = '[]'
 
-                lines.append('parentreview %s %s' % (
-                    urllib.quote(identifier), rr.id))
-                for relation in json.loads(commits):
-                    node = relation[0].encode('utf-8')
-                    rid = str(relation[1])
+            lines.append('parentreview %s %s' % (
+                urllib.quote(identifier), rr.id))
+            for relation in json.loads(commits):
+                node = relation[0].encode('utf-8')
+                rid = str(relation[1])
 
-                    lines.append('csetreview %s %s %s' % (rr.id, node, rid))
-                    lines.append('reviewdata %s status %s' % (rid,
-                        urllib.quote(rr.status.encode('utf-8'))))
-                    lines.append('reviewdata %s public %s' % (rid, rr.public))
+                lines.append('csetreview %s %s %s' % (rr.id, node, rid))
+                lines.append('reviewdata %s status %s' % (rid,
+                    urllib.quote(rr.status.encode('utf-8'))))
+                lines.append('reviewdata %s public %s' % (rid, rr.public))
 
-            lines.append('reviewdata %s status %s' % (rr.id,
-                urllib.quote(rr.status.encode('utf-8'))))
-            lines.append('reviewdata %s public %s' % (rr.id, rr.public))
+        lines.append('reviewdata %s status %s' % (rr.id,
+            urllib.quote(rr.status.encode('utf-8'))))
+        lines.append('reviewdata %s public %s' % (rr.id, rr.public))
 
-            reviewers = [urllib.quote(p.title.encode('utf-8'))
-                         for p in rr.target_people]
-            if reviewers:
-                lines.append('reviewdata %s reviewers %s' %
-                             (rid, ','.join(reviewers)))
+        reviewers = [urllib.quote(p.title.encode('utf-8'))
+                     for p in rr.target_people]
+        if reviewers:
+            lines.append('reviewdata %s reviewers %s' %
+                         (rid, ','.join(reviewers)))
 
     res = '\n'.join(lines)
     assert isinstance(res, str)
 
     return res
 
 @wireproto.wireprotocommand('publishreviewrequests', '*')
 def publishreviewseries(repo, proto, args=None):
@@ -508,33 +508,33 @@ def publishreviewseries(repo, proto, arg
 
     o = parsepayload(proto, args)
     if isinstance(o, ServerError):
         return formatresponse(str(o))
 
     lines = ['1']
 
     from reviewboardmods.pushhooks import ReviewBoardClient
-    with ReviewBoardClient(repo.ui.config('reviewboard', 'url').rstrip('/'),
-                           username=o['bzusername'],
-                           apikey=o['bzapikey']) as client:
-        root = client.get_root()
+    client = ReviewBoardClient(repo.ui.config('reviewboard', 'url').rstrip('/'),
+                               username=o['bzusername'],
+                               apikey=o['bzapikey'])
+    root = client.get_root()
 
-        for k, v in o['other']:
-            if k != 'reviewid':
-                continue
+    for k, v in o['other']:
+        if k != 'reviewid':
+            continue
 
-            rrid = urllib.unquote(v)
-            try:
-                rr = root.get_review_request(review_request_id=rrid)
-                draft = rr.get_draft()
-                draft.update(public=True)
-                lines.append('success %s' % rrid)
-            except APIError as e:
-                lines.append('error %s %s' % (rrid, str(e)))
+        rrid = urllib.unquote(v)
+        try:
+            rr = root.get_review_request(review_request_id=rrid)
+            draft = rr.get_draft()
+            draft.update(public=True)
+            lines.append('success %s' % rrid)
+        except APIError as e:
+            lines.append('error %s %s' % (rrid, str(e)))
 
     res = '\n'.join(lines)
     assert isinstance(res, str)
     return res
 
 @wireproto.wireprotocommand('listreviewrepos')
 def listreviewrepos(repo, proto, args=None):
     """List review repositories we can push to.
--- a/hgext/reviewboard/server.py
+++ b/hgext/reviewboard/server.py
@@ -184,32 +184,32 @@ def listreviewrepos(repo):
         repos[root] = urls
 
     return repos
 
 
 def getreposfromreviewboard(repo):
     from reviewboardmods.pushhooks import ReviewBoardClient
 
-    with ReviewBoardClient(repo.ui.config('reviewboard', 'url').rstrip('/')) as client:
-        root = client.get_root()
-        urls = set()
+    client = ReviewBoardClient(repo.ui.config('reviewboard', 'url').rstrip('/'))
+    root = client.get_root()
+    urls = set()
 
-        repos = root.get_repositories(max_results=250, tool='Mercurial')
-        try:
-            while True:
-                for r in repos:
-                    urls.add(r.path)
+    repos = root.get_repositories(max_results=250, tool='Mercurial')
+    try:
+        while True:
+            for r in repos:
+                urls.add(r.path)
 
-                repos = repos.get_next()
+            repos = repos.get_next()
 
-        except StopIteration:
-            pass
+    except StopIteration:
+        pass
 
-        return urls
+    return urls
 
 
 def wrappedwireprotoheads(orig, repo, proto, *args, **kwargs):
     """Wraps "heads" wire protocol command.
 
     This will short circuit pushes and pulls on discovery repos. If we don't do
     this, clients will waste time uploading a bundle only to find out that the
     server doesn't support pushing!
--- a/pylib/reviewboardmods/reviewboardmods/pushhooks.py
+++ b/pylib/reviewboardmods/reviewboardmods/pushhooks.py
@@ -3,18 +3,16 @@
 This module contains code for taking commits from version control (Git,
 Mercurial, etc) and adding them to Review Board.
 
 It is intended for this module to be generic and applicable to any
 Review Board install. Please abstract away Mozilla implementation
 details.
 """
 
-from contextlib import contextmanager
-
 from rbtools.api.client import RBClient
 from rbtools.api.errors import APIError
 
 
 def associate_ldap_username(url, ldap_username, privileged_username,
                             privileged_password, username, apikey):
     """Associate a Review Board user with an ldap username.
 
@@ -48,51 +46,47 @@ def associate_ldap_username(url, ldap_us
 
     if not username or not apikey:
         return False
 
     try:
         # We first verify that the provided credentials are valid and
         # retrieve the username associated with that Review Board
         # account.
-        with ReviewBoardClient(url, username=username, apikey=apikey) as rbc:
-            root = rbc.get_root()
-            session = root.get_session()
+        rbc = ReviewBoardClient(url, username=username, apikey=apikey)
+        root = rbc.get_root()
+        session = root.get_session()
 
-            if not session.authenticated:
-                return False
+        if not session.authenticated:
+            return False
 
-            user = session.get_user()
-            username = user.username
+        user = session.get_user()
+        username = user.username
 
         # Now that we have proven ownership over the user, take the provided
         # ldap_username and associate it with the account.
-        with ReviewBoardClient(url, username=privileged_username,
-                               password=privileged_password) as rbc:
-            root = rbc.get_root()
-            ext = root.get_extension(
-                extension_name='mozreview.extension.MozReviewExtension')
-            ldap = ext.get_ldap_associations().get_item(username)
-            ldap.update(ldap_username=ldap_username)
+        rbc = ReviewBoardClient(url, username=privileged_username,
+                                password=privileged_password)
+        root = rbc.get_root()
+        ext = root.get_extension(
+            extension_name='mozreview.extension.MozReviewExtension')
+        ldap = ext.get_ldap_associations().get_item(username)
+        ldap.update(ldap_username=ldap_username)
 
     except APIError:
         return False
 
     return True
 
 
-@contextmanager
 def ReviewBoardClient(url, username=None, password=None, apikey=None):
-    """Obtain a RBClient instance via a context manager.
-
-    This exists as a context manager for historical reasons.
-    """
+    """Obtain a RBClient instance."""
     if username and apikey:
         rbc = RBClient(url, save_cookies=False, allow_caching=False)
         login_resource = rbc.get_path(
             'extensions/mozreview.extension.MozReviewExtension/'
             'bugzilla-api-key-logins/')
         login_resource.create(username=username, api_key=apikey)
     else:
         rbc = RBClient(url, username=username, password=password,
                        save_cookies=False, allow_caching=False)
 
-    yield rbc
+    return rbc
--- a/testing/vcttesting/reviewboard/__init__.py
+++ b/testing/vcttesting/reviewboard/__init__.py
@@ -1,30 +1,26 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import json
 import logging
 
-from contextlib import contextmanager
-
 from rbtools.api.client import RBClient
 
 
 logger = logging.getLogger(__name__)
 
 
-@contextmanager
 def ReviewBoardClient(url, username, password):
 
-    rbclient = RBClient(url, save_cookies=False,
-                        allow_caching=False,
-                        username=username, password=password)
-    yield rbclient
+    return RBClient(url, save_cookies=False,
+                    allow_caching=False,
+                    username=username, password=password)
 
 
 class MozReviewBoard(object):
     """Interact with a Mozilla-flavored Review Board install."""
 
     def __init__(self, docker, cid, url, bugzilla_url=None,
                  pulse_host=None, pulse_port=None,
                  pulse_user='guest', pulse_password='guest'):
@@ -34,44 +30,43 @@ class MozReviewBoard(object):
         self.bugzilla_url = bugzilla_url
         self.pulse_host = pulse_host
         self.pulse_port = pulse_port
         self.pulse_user = pulse_user
         self.pulse_password = pulse_password
 
     def login_user(self, username, password):
         """Log in the specified user to Review Board."""
-        with ReviewBoardClient(self.url, username, password) as c:
-            c.get_root()
+        ReviewBoardClient(self.url, username, password).get_root()
 
     def add_repository(self, name, url, bugzilla_url,
                        username='admin@example.com',
                        password='password'):
         """Add a repository to Review Board."""
         bugzilla_url = bugzilla_url.rstrip('/')
         bug_url = '%s/show_bug.cgi?id=%%s' % bugzilla_url
 
-        with ReviewBoardClient(self.url, username, password) as c:
-            root = c.get_root()
-            repos = root.get_repositories()
-            repo = repos.create(name=name, path=url, tool='Mercurial',
-                                bug_tracker=bug_url)
+        c = ReviewBoardClient(self.url, username, password)
+        root = c.get_root()
+        repos = root.get_repositories()
+        repo = repos.create(name=name, path=url, tool='Mercurial',
+                            bug_tracker=bug_url)
 
-            # This should arguaby be a separate API. But for now we in-line
-            # review group and default reviewers because every repo on
-            # MozReview is configured that way.
-            groups = root.get_groups()
-            group = groups.create(display_name=name, name=name, visible=True,
-                                  invite_only=False)
+        # This should arguaby be a separate API. But for now we in-line
+        # review group and default reviewers because every repo on
+        # MozReview is configured that way.
+        groups = root.get_groups()
+        group = groups.create(display_name=name, name=name, visible=True,
+                              invite_only=False)
 
-            reviewers = root.get_default_reviewers()
-            reviewers.create(name=name, file_regex='.*', groups=name,
-                             repositories=str(repo.id))
+        reviewers = root.get_default_reviewers()
+        reviewers.create(name=name, file_regex='.*', groups=name,
+                         repositories=str(repo.id))
 
-            return repo.id
+        return repo.id
 
     def make_admin(self, email):
         """Make the user with the specified email an admin.
 
         This grants superuser and staff privileges to the user.
         """
         self._docker.execute(self._cid, ['/make-admin', email])
         logger.info('made %s an admin' % email)