Title: [270871] trunk/Tools
Revision
270871
Author
[email protected]
Date
2020-12-15 15:34:40 -0800 (Tue, 15 Dec 2020)

Log Message

[webkitscmpy] Support remote GitHub repository
https://bugs.webkit.org/show_bug.cgi?id=219602
<rdar://problem/72050026>

Reviewed by Stephanie Lewis.

Services often need to interact with the WebKit repository without actually downloading the
repository. In particular, it is useful to be able to retrieve commits and their identifiers.

* Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py: Bump version.
* Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py:
(Git): Move GIT_SVN_REVISION regex to base class.
* Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/__init__.py: Add GitHub class.
* Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py: Added.
(GitHub): Mock request router for a limited subset of GitHub's API.
(GitHub.__init__):
(GitHub.commit): Return a commit object given a reference.
(GitHub._api_response):
(GitHub._list_refs_response):
(GitHub._commit_response):
(GitHub._compare_response):
(GitHub._branches_for_request):
(GitHub._parents_of_request):
(GitHub.request): Return a response object for the specified request.
* Scripts/libraries/webkitscmpy/webkitscmpy/remote/__init__.py: Add GitHub class.
* Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py: Added.
(GitHub): Repository object representing a GitHub remote.
(GitHub.is_webserver): True if the provided URL is a GitHub webserver.
(GitHub.__init__): Verify the provided URL and split it into it's composite parts.
(GitHub.is_git): Return True.
(GitHub.request): Make an API request, combining pagination into a single request.
(GitHub._count_for_ref): Scrape the GitHub UI to find the number of parent commits for a specified
branch or commit.
(GitHub._difference): Compute the number of commits a specified reference is ahead of another.
(GitHub._branches_for): Scrape the GitHub UI to determine what branches a commit is on.
(GitHub.default_branch): Query GitHub to determine the default branch for a specified commit.
(GitHub.branches): Return all branches for a repository.
(GitHub.tags): Return all tags for a repository.
(GitHub.commit): Return a commit object given a revision, branch, identifier or tag.
(GitHub.find): Use git to match branches and tags to a hash instead of trying to do it ourselves.
* Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py:
(Scm.from_url): Add GitHub to the set of candidate remote repositories.
* Scripts/libraries/webkitscmpy/webkitscmpy/scm_base.py:
(ScmBase): Move GIT_SVN_REVISION regex to base class.
* Scripts/libraries/webkitscmpy/webkitscmpy/test/git_unittest.py:
(TestGitHub):
(TestGitHub.test_detection):
(TestGitHub.test_branches):
(TestGitHub.test_tags):
(TestGitHub.test_scm_type):
(TestGitHub.test_commit_revision):
(TestGitHub.test_commit_from_branch):
(TestGitHub.test_identifier):
(TestGitHub.test_non_cannonical_identifiers):
(TestGitHub.test_tag):
(TestGitHub.test_no_log):

Modified Paths

Added Paths

Diff

Modified: trunk/Tools/ChangeLog (270870 => 270871)


--- trunk/Tools/ChangeLog	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/ChangeLog	2020-12-15 23:34:40 UTC (rev 270871)
@@ -1,3 +1,62 @@
+2020-12-15  Jonathan Bedard  <[email protected]>
+
+        [webkitscmpy] Support remote GitHub repository
+        https://bugs.webkit.org/show_bug.cgi?id=219602
+        <rdar://problem/72050026>
+
+        Reviewed by Stephanie Lewis.
+
+        Services often need to interact with the WebKit repository without actually downloading the
+        repository. In particular, it is useful to be able to retrieve commits and their identifiers.
+
+        * Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py: Bump version.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py:
+        (Git): Move GIT_SVN_REVISION regex to base class.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/__init__.py: Add GitHub class.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py: Added.
+        (GitHub): Mock request router for a limited subset of GitHub's API.
+        (GitHub.__init__):
+        (GitHub.commit): Return a commit object given a reference.
+        (GitHub._api_response):
+        (GitHub._list_refs_response):
+        (GitHub._commit_response):
+        (GitHub._compare_response):
+        (GitHub._branches_for_request):
+        (GitHub._parents_of_request):
+        (GitHub.request): Return a response object for the specified request.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/remote/__init__.py: Add GitHub class.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py: Added.
+        (GitHub): Repository object representing a GitHub remote.
+        (GitHub.is_webserver): True if the provided URL is a GitHub webserver.
+        (GitHub.__init__): Verify the provided URL and split it into it's composite parts.
+        (GitHub.is_git): Return True.
+        (GitHub.request): Make an API request, combining pagination into a single request.
+        (GitHub._count_for_ref): Scrape the GitHub UI to find the number of parent commits for a specified
+        branch or commit.
+        (GitHub._difference): Compute the number of commits a specified reference is ahead of another.
+        (GitHub._branches_for): Scrape the GitHub UI to determine what branches a commit is on.
+        (GitHub.default_branch): Query GitHub to determine the default branch for a specified commit.
+        (GitHub.branches): Return all branches for a repository.
+        (GitHub.tags): Return all tags for a repository.
+        (GitHub.commit): Return a commit object given a revision, branch, identifier or tag.
+        (GitHub.find): Use git to match branches and tags to a hash instead of trying to do it ourselves.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py:
+        (Scm.from_url): Add GitHub to the set of candidate remote repositories.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/scm_base.py:
+        (ScmBase): Move GIT_SVN_REVISION regex to base class.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/test/git_unittest.py:
+        (TestGitHub):
+        (TestGitHub.test_detection):
+        (TestGitHub.test_branches):
+        (TestGitHub.test_tags):
+        (TestGitHub.test_scm_type):
+        (TestGitHub.test_commit_revision):
+        (TestGitHub.test_commit_from_branch):
+        (TestGitHub.test_identifier):
+        (TestGitHub.test_non_cannonical_identifiers):
+        (TestGitHub.test_tag):
+        (TestGitHub.test_no_log):
+
 2020-12-15  Sihui Liu  <[email protected]>
 
         Add webkit- prefix to SpeechRecognition

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py (270870 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -46,7 +46,7 @@
         "Please install webkitcorepy with `pip install webkitcorepy --extra-index-url <package index URL>`"
     )
 
-version = Version(0, 5, 5)
+version = Version(0, 6, 0)
 
 AutoInstall.register(Package('fasteners', Version(0, 15, 0)))
 AutoInstall.register(Package('monotonic', Version(1, 5)))

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py (270870 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -31,7 +31,6 @@
 
 class Git(Scm):
     GIT_COMMIT = re.compile(r'commit (?P<hash>[0-9a-f]+)')
-    GIT_SVN_REVISION = re.compile(r'git-svn-id: \S+:\/\/.+@(?P<revision>\d+) .+-.+-.+-.+')
 
     @classmethod
     @decorators.Memoize()

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/__init__.py (270870 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/__init__.py	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/__init__.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -20,4 +20,5 @@
 # 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.
 
+from webkitscmpy.mocks.remote.git_hub import GitHub
 from webkitscmpy.mocks.remote.svn import Svn

Added: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py (0 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py	                        (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -0,0 +1,240 @@
+# Copyright (C) 2020 Apple Inc. All rights reserved.
+#
+# 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 APPLE INC. AND ITS CONTRIBUTORS "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 APPLE INC. OR ITS 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.
+
+import os
+import json
+
+from datetime import datetime
+from webkitcorepy import mocks
+from webkitscmpy import Commit, remote as scmremote
+
+
+class GitHub(mocks.Requests):
+    top = None
+
+    def __init__(
+        self, remote='github.example.com/WebKit/webkit', datafile=None,
+        default_branch='main', git_svn=False,
+    ):
+        if not scmremote.GitHub.is_webserver('https://{}'.format(remote)):
+            raise ValueError('"{}" is not a valid GitHub remote'.format(remote))
+
+        self.default_branch = default_branch
+        self.remote = remote
+        hostname = self.remote.split('/')[0]
+        self.api_remote = 'api.{hostname}/repos/{repo}'.format(
+            hostname=hostname,
+            repo='/'.join(self.remote.split('/')[1:]),
+        )
+
+        super(GitHub, self).__init__(hostname, 'api.{}'.format(hostname))
+
+        with open(datafile or os.path.join(os.path.dirname(os.path.dirname(__file__)), 'git-repo.json')) as file:
+            self.commits = json.load(file)
+        for key, commits in self.commits.items():
+            self.commits[key] = [Commit(**kwargs) for kwargs in commits]
+            if not git_svn:
+                for commit in self.commits[key]:
+                    commit.revision = None
+
+        self.head = self.commits[self.default_branch][-1]
+        self.tags = {}
+
+    def commit(self, ref):
+        if ref in self.commits:
+            return self.commits[ref][-1]
+        if ref in self.tags:
+            return self.tags[ref]
+
+        for branch, commits in self.commits.items():
+            for commit in commits:
+                if commit.hash.startswith(ref):
+                    return commit
+
+        if '~' not in ref:
+            return None
+        ref, delta = ref.split('~')
+        commit = self.commit(ref)
+        if not commit:
+            return None
+        delta = int(delta)
+
+        if delta < commit.identifier:
+            return self.commits[commit.branch][commit.identifier - delta - 1]
+        delta -= commit.identifier
+        if delta < commit.branch_point:
+            return self.commits[self.default_branch][commit.branch_point - delta - 1]
+        return None
+
+    def _api_response(self, url):
+        return mocks.Response.fromJson({
+            'id': 1,
+            'name': self.remote.split('/')[2],
+            'url': url,
+            'default_branch': self.default_branch,
+            'owner': {
+                'login': self.remote.split('/')[1],
+            }, 'organization': {
+                'login': self.remote.split('/')[1],
+            }, 'html_url': self.remote,
+        }, url=""
+
+    def _list_refs_response(self, url, type):
+        return mocks.Response.fromJson([
+            {
+                'name': reference,
+                'commit': {
+                    'sha': commit[-1].hash if isinstance(commit, list) else commit.hash,
+                    'url': 'https://{}/commits/{}'.format(self.api_remote,
+                                                          commit[-1].hash if isinstance(commit, list) else commit.hash),
+                },
+            } for reference, commit in (self.commits if type == 'branches' else self.tags).items()
+        ], url=""
+
+    def _commit_response(self, url, ref):
+        commit = self.commit(ref)
+        if not commit:
+            return mocks.Response(
+                status_code=404,
+                url=""
+                text=json.dumps(dict(message='No commit found for SHA: {}'.format(ref))),
+            )
+        return mocks.Response.fromJson({
+            'sha': commit.hash,
+            'commit': {
+                'author': {
+                    'name': commit.author.name,
+                    'email': commit.author.email,
+                    'date': datetime.fromtimestamp(commit.timestamp).strftime('%Y-%m-%dT%H:%M:%SZ'),
+                }, 'committer': {
+                    'name': commit.author.name,
+                    'email': commit.author.email,
+                    'date': datetime.fromtimestamp(commit.timestamp).strftime('%Y-%m-%dT%H:%M:%SZ'),
+                }, 'message': commit.message,
+                'url': 'https://{}/git/commits/{}'.format(self.api_remote, commit.hash),
+            }, 'url': 'https://{}/commits/{}'.format(self.api_remote, commit.hash),
+            'html_url': 'https://{}/commit/{}'.format(self.remote, commit.hash),
+        }, url=""
+
+    def _compare_response(self, url, ref_a, ref_b):
+        commit_a = self.commit(ref_a)
+        commit_b = self.commit(ref_b)
+        if not commit_a or not commit_b:
+            return mocks.Response(
+                status_code=404,
+                url=""
+                text=json.dumps(dict(message='Not found')),
+            )
+
+        if commit_a.branch != self.default_branch or commit_b.branch == self.default_branch:
+            raise NotImplementedError(
+                'This is a valid comparison command, but has not been implemented in the mock GitHub API')
+
+        return mocks.Response.fromJson({
+            'status': 'diverged',
+            'ahead_by': commit_b.identifier,
+            'behind_by': commit_a.identifier - commit_b.branch_point,
+        }, url=""
+
+    def _branches_for_request(self, url, ref):
+        commit = self.commit(ref)
+        if not commit:
+            return mocks.Response.create404(url)
+        return mocks.Response.fromText(
+            '\n\n    <svg class="octicon octicon-git-branch"><path></path></svg>\n'
+            '    <ul class="branches-list">\n'
+            '        <li class="branch"><a href=""
+            '    </ul>\n'.format(
+                '/'.join(self.remote.split('/')[1:]),
+                commit.branch,
+            ), url=""
+        )
+
+    def _parents_of_request(self, url, ref):
+        commit = self.commit(ref)
+        if not commit:
+            return mocks.Response.create404(url)
+
+        # This response is abbreviated since most is unused
+        return mocks.Response.fromText(
+            '\n\n\n\n<!DOCTYPE html>\n'
+            '<html lang="en">\n'
+            '...\n'
+            '<div class="Box mb-3">\n'
+            '    <div class="Box-header Box-header--blue position-relative">\n'
+            '        <h2 class="sr-only">Latest commit</h2>\n'
+            '        <div class="..." data-issue-and-pr-hovercards-enabled>\n'
+            '            <include-fragment src="" aria-label="Loading latest commit">\n'
+            '            </include-fragment>\n'
+            '        <ul class="list-style-none d-flex">\n'
+            '            <li class="ml-0 ml-md-3">\n'
+            '                <a data-pjax href=""
+            '                    <svg class="octicon octicon-history text-gray"><path></path></svg>\n'
+            '                    <span class="d-none d-sm-inline">\n'
+            '                        <strong>{count}</strong>\n'
+            '                        <span aria-label="Commits on " class="...">commits</span>\n'
+            '                        </span>\n'
+            '                </a>\n'
+            '            </li>\n'
+            '        </ul>\n'
+            '        </div>\n'
+            '    </div>\n'
+            '</div>\n'
+            '...\n'
+            '</html>\n'.format(
+                ref=commit.hash,
+                count=commit.identifier + (commit.branch_point or 0),
+            ), url=""
+        )
+
+    def request(self, method, url, data="" **kwargs):
+        if not url.startswith('http://') and not url.startswith('https://'):
+            return mocks.Response.create404(url)
+
+        stripped_url = url.split('://')[-1]
+
+        # Top-level API request
+        if stripped_url == self.api_remote:
+            return self._api_response(url=""
+
+        # Branches/Tags
+        if stripped_url in ['{}/branches'.format(self.api_remote), '{}/tags'.format(self.api_remote)]:
+            return self._list_refs_response(url="" type=stripped_url.split('/')[-1])
+
+        # Extract single commit
+        if stripped_url.startswith('{}/commits/'.format(self.api_remote)):
+            return self._commit_response(url="" ref=stripped_url.split('/')[-1])
+
+        # Compare two commits
+        if stripped_url.startswith('{}/compare/'.format(self.api_remote)):
+            ref_a, ref_b = stripped_url.split('/')[-1].split('...')
+            return self._compare_response(url="" ref_a=ref_a, ref_b=ref_b)
+
+        # List branches a commit occurs on
+        if stripped_url.startswith('{}/branch_commits/'.format(self.remote)):
+            return self._branches_for_request(url="" ref=stripped_url.split('/')[-1])
+
+        # Find the number of parents a commit has
+        if stripped_url.startswith('{}/tree/'.format(self.remote)):
+            return self._parents_of_request(url="" ref=stripped_url.split('/')[-1])
+
+        return mocks.Response.create404(url)

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/__init__.py (270870 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/__init__.py	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/__init__.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -22,3 +22,4 @@
 
 from webkitscmpy.remote.scm import Scm
 from webkitscmpy.remote.svn import Svn
+from webkitscmpy.remote.git_hub import GitHub

Added: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py (0 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py	                        (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -0,0 +1,280 @@
+# Copyright (C) 2020 Apple Inc. All rights reserved.
+#
+# 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 APPLE INC. AND ITS CONTRIBUTORS "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 APPLE INC. OR ITS 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.
+
+import calendar
+import re
+import requests
+import six
+
+from datetime import datetime
+from webkitcorepy import decorators
+from webkitscmpy import Commit, Contributor
+from webkitscmpy.remote.scm import Scm
+from xml.dom import minidom
+
+
+class GitHub(Scm):
+    URL_RE = re.compile(r'\Ahttps?://github.(?P<domain>\S+)/(?P<owner>\S+)/(?P<repository>\S+)\Z')
+    EMAIL_RE = re.compile(r'(?P<email>[^@]+@[^@]+)(@.*)?')
+
+    @classmethod
+    def is_webserver(cls, url):
+        return True if cls.URL_RE.match(url) else False
+
+    def __init__(self, url, dev_branches=None, prod_branches=None, contributors=None):
+        match = self.URL_RE.match(url)
+        if not match:
+            raise self.Exception("'{}' is not a valid GitHub project".format(url))
+        self.api_url = 'https://api.github.{}'.format(match.group('domain'))
+        self.owner = match.group('owner')
+        self.name = match.group('repository')
+        self._hash_link_re = re.compile(r'/{owner}/{name}/commits?/(?P<hash>[0-9a-f]+)'.format(
+            owner=self.owner,
+            name=self.name,
+        ))
+
+        super(GitHub, self).__init__(url, dev_branches=dev_branches, prod_branches=prod_branches, contributors=contributors)
+
+    @property
+    def is_git(self):
+        return True
+
+    def request(self, path=None, params=None, headers=None):
+        headers = {key: value for key, value in headers.items()} if headers else dict()
+        headers['Accept'] = headers.get('Accept', 'application/vnd.github.v3+json')
+
+        params = {key: value for key, value in params.items()} if params else dict()
+        params['per_page'] = params.get('per_page', 100)
+        params['page'] = params.get('page', 1)
+
+        url = ''.format(
+            api_url=self.api_url,
+            owner=self.owner,
+            name=self.name,
+            path='/{}'.format(path) if path else '',
+        )
+        response = requests.get(url, params=params, headers=headers)
+        if response.status_code != 200:
+            return None
+        result = response.json()
+
+        while isinstance(response.json(), list) and len(response.json()) == params['per_page']:
+            params['page'] += 1
+            response = requests.get(url, params=params, headers=headers)
+            if response.status_code != 200:
+                raise self.Exception("Failed to assemble pagination requests for '{}', failed on page {}".format(url, params['page']))
+            result += response.json()
+        return result
+
+    def _count_for_ref(self, ref=None):
+        ref = ref or self.default_branch
+
+        # We need the number of parents a commit has to construct identifiers, which is not something GitHub's
+        # API lets us find, although the UI does have the information
+        response = requests.get('{}/tree/{}'.format(self.url, ref))
+        if response.status_code != 200:
+            raise self.Exception("Failed to query {}'s UI to find the number of parents {} has".format(self.url, ref))
+
+        # This parsing is pretty brittle, but the webpage may not be valid xml
+        count = None
+        hash = None
+        previous = None
+        for line in response.text.splitlines():
+            match = self._hash_link_re.search(line)
+            if match:
+                hash = match.group('hash')
+            elif 'aria-label="Commits on ' in line:
+                count = int(minidom.parseString(previous).documentElement.childNodes[0].data.replace(',', ''))
+                break
+            previous = line
+
+        if not hash or not count:
+            raise self.Exception("Failed to compute the number of parents to '{}'".format(ref))
+
+        return count, hash
+
+    def _difference(self, reference, head):
+        response = self.request('compare/{}...{}'.format(reference, head), headers=dict(Accept='application/vnd.github.VERSION.sha'))
+        if not response or not response.get('status') in ['diverged', 'ahead', 'behind']:
+            raise self.Exception('Failed to request the difference between {} and {}'.format(reference, head))
+        return int(response['behind_by' if response.get('status') == 'behind' else 'ahead_by'])
+
+    def _branches_for(self, hash):
+        # We need to find the branch that a commit is on. GitHub's UI provides this information, but the only way to
+        # retrieve this information via the API would be to check all branches for the commit, so we scrape the UI.
+        response = requests.get('{}/branch_commits/{}'.format(self.url, hash))
+        if response.status_code != 200:
+            return []
+
+        result = []
+        for line in response.text.splitlines():
+            if 'class="branch"' not in line:
+                continue
+            result.append(minidom.parseString(line).documentElement.childNodes[0].childNodes[0].data)
+
+        return result
+
+    @property
+    @decorators.Memoize()
+    def default_branch(self):
+        response = self.request()
+        if not response:
+            raise self.Exception("Failed to query {} for {}'s default branch".format(self.url, self.name))
+        return response.get('default_branch', 'master')
+
+    @property
+    def branches(self):
+        response = self.request('branches')
+        if not response:
+            return [self.default_branch]
+        return sorted([details.get('name') for details in response if details.get('name')])
+
+    @property
+    def tags(self):
+        response = self.request('tags')
+        if not response:
+            return []
+        return sorted([details.get('name') for details in response if details.get('name')])
+
+    def commit(self, hash=None, revision=None, identifier=None, branch=None, tag=None, include_log=True):
+        if revision:
+            raise self.Exception('Cannot map revisions to commits on GitHub')
+
+        if identifier is not None:
+            if revision:
+                raise ValueError('Cannot define both revision and identifier')
+            if hash:
+                raise ValueError('Cannot define both hash and identifier')
+            if tag:
+                raise ValueError('Cannot define both tag and identifier')
+
+            parsed_branch_point, identifier, parsed_branch = Commit._parse_identifier(identifier, do_assert=True)
+            if parsed_branch:
+                if branch and branch != parsed_branch:
+                    raise ValueError(
+                        "Caller passed both 'branch' and 'identifier', but specified different branches ({} and {})".format(
+                            branch, parsed_branch,
+                        ),
+                    )
+                branch = parsed_branch
+
+            branch = branch or self.default_branch
+            is_default = branch == self.default_branch
+
+            if is_default and parsed_branch_point:
+                raise self.Exception('Cannot provide a branch point for a commit on the default branch')
+
+            if is_default:
+                base_count, base_ref = self._count_for_ref(ref=self.default_branch)
+            else:
+                _, base_ref = self._count_for_ref(ref=branch)
+                base_count = self._difference(self.default_branch, base_ref)
+
+            if identifier > base_count:
+                raise self.Exception('Identifier {} cannot be found on {}'.format(identifier, branch))
+
+            # Negative identifiers are actually commits on the default branch, we will need to re-compute the identifier
+            if identifier < 0 and is_default:
+                raise self.Exception('Illegal negative identifier on the default branch')
+
+            commit_data = self.request('commits/{}~{}'.format(base_ref, base_count - identifier))
+            if not commit_data:
+                raise self.Exception("Failed to retrieve commit information for '{}@{}'".format(identifier, branch or 'HEAD'))
+
+            # If an identifier is negative, unset it so we re-compute before constructing the commit.
+            if identifier <= 0:
+                identifier = None
+
+        elif branch or tag:
+            if hash:
+                raise ValueError('Cannot define both tag/branch and hash')
+            if branch and tag:
+                raise ValueError('Cannot define both tag and branch')
+            commit_data = self.request('commits/{}'.format(branch or tag))
+            if not commit_data:
+                raise self.Exception("Failed to retrieve commit information for '{}'".format(branch or tag))
+
+        else:
+            hash = Commit._parse_hash(hash, do_assert=True)
+            commit_data = self.request('commits/{}'.format(hash or self.default_branch))
+            if not commit_data:
+                raise self.Exception("Failed to retrieve commit information for '{}'".format(hash or 'HEAD'))
+
+        branches = self._branches_for(commit_data['sha'])
+        if branches:
+            branch = self.prioritize_branches(branches)
+
+        else:
+            # A commit not on any branches cannot have an identifier
+            identifier = None
+            branch = None
+
+        branch_point = None
+        if branch and branch == self.default_branch:
+            if not identifier:
+                result = self._count_for_ref(ref=commit_data['sha'])
+                if not result:
+                    raise Exception('{} {}'.format(result, commit_data['sha']))
+                identifier, _ = result
+
+        elif branch:
+            if not identifier:
+                identifier = self._difference(self.default_branch, commit_data['sha'])
+            branch_point = self._count_for_ref(ref=commit_data['sha'])[0] - identifier
+
+        match = self.GIT_SVN_REVISION.search(commit_data['commit']['message'])
+        revision = int(match.group('revision')) if match else None
+
+        date = datetime.strptime(commit_data['commit']['committer']['date'], '%Y-%m-%dT%H:%M:%SZ')
+        email_match = self.EMAIL_RE.match(commit_data['commit']['author']['email'])
+
+        return Commit(
+            hash=commit_data['sha'],
+            revision=revision,
+            branch_point=branch_point,
+            identifier=identifier,
+            branch=branch,
+            timestamp=int(calendar.timegm(date.timetuple())),
+            author=self.contributors.create(
+                commit_data['commit']['author']['name'],
+                email_match.group('email') if email_match else None,
+            ), message=commit_data['commit']['message'] if include_log else None,
+        )
+
+    def find(self, argument, include_log=True):
+        if not isinstance(argument, six.string_types):
+            raise ValueError("Expected 'argument' to be a string, not '{}'".format(type(argument)))
+
+        parsed_commit = Commit.parse(argument, do_assert=False)
+        if parsed_commit:
+            return self.commit(
+                hash=parsed_commit.hash,
+                revision=parsed_commit.revision,
+                identifier=parsed_commit.identifier,
+                branch=parsed_commit.branch,
+                include_log=include_log,
+            )
+
+        commit_data = self.request('commits/{}'.format(argument))
+        if not commit_data:
+            raise ValueError("'{}' is not an argument recognized by git".format(argument))
+        return self.commit(hash=commit_data['sha'], include_log=include_log)

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py (270870 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -32,6 +32,8 @@
 
         if remote.Svn.is_webserver(url):
             return remote.Svn(url, contributors=contributors)
+        if remote.GitHub.is_webserver(url):
+            return remote.GitHub(url, contributors=contributors)
         raise OSError("'{}' is not a known SCM server".format(url))
 
     def __init__(self, url, dev_branches=None, prod_branches=None, contributors=None):

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/scm_base.py (270870 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/scm_base.py	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/scm_base.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -37,6 +37,7 @@
     # the following idioms seem common enough to be shared.
     DEV_BRANCHES = re.compile(r'.*[(eng)(dev)(bug)]/.+')
     PROD_BRANCHES = re.compile(r'\S+-[\d+\.]+-branch')
+    GIT_SVN_REVISION = re.compile(r'git-svn-id: \S+:\/\/.+@(?P<revision>\d+) .+-.+-.+-.+')
 
     def __init__(self, dev_branches=None, prod_branches=None, contributors=None):
         self.dev_branches = dev_branches or self.DEV_BRANCHES

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/git_unittest.py (270870 => 270871)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/git_unittest.py	2020-12-15 23:18:33 UTC (rev 270870)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/git_unittest.py	2020-12-15 23:34:40 UTC (rev 270871)
@@ -26,7 +26,7 @@
 from datetime import datetime
 from webkitcorepy import LoggerCapture
 from webkitcorepy.mocks import Time as MockTime
-from webkitscmpy import local, mocks
+from webkitscmpy import local, mocks, remote
 
 
 class TestGit(unittest.TestCase):
@@ -250,3 +250,106 @@
         for mock in [mocks.local.Git(self.path), mocks.local.Git(self.path, git_svn=True)]:
             with mock:
                 self.assertIsNone(local.Git(self.path).commit(identifier='4@main', include_log=False).message)
+
+
+class TestGitHub(unittest.TestCase):
+    remote = 'https://github.example.com/WebKit/webkit'
+
+    def test_detection(self):
+        self.assertEqual(remote.GitHub.is_webserver('https://github.example.com/WebKit/webkit'), True)
+        self.assertEqual(remote.GitHub.is_webserver('http://github.example.com/WebKit/webkit'), True)
+        self.assertEqual(remote.GitHub.is_webserver('https://svn.example.org/repository/webkit'), False)
+
+    def test_branches(self):
+        with mocks.remote.GitHub():
+            self.assertEqual(
+                remote.GitHub(self.remote).branches,
+                ['branch-a', 'branch-b', 'main'],
+            )
+
+    def test_tags(self):
+        with mocks.remote.GitHub() as mock:
+            mock.tags['tag-1'] = mock.commits['branch-a'][-1]
+            mock.tags['tag-2'] = mock.commits['branch-b'][-1]
+
+            self.assertEqual(
+                remote.GitHub(self.remote).tags,
+                ['tag-1', 'tag-2'],
+            )
+
+    def test_scm_type(self):
+        self.assertFalse(remote.GitHub(self.remote).is_svn)
+        self.assertTrue(remote.GitHub(self.remote).is_git)
+
+    def test_commit_revision(self):
+        with mocks.remote.GitHub():
+            self.assertEqual('1@main', str(remote.GitHub(self.remote).commit(hash='9b8311f2')))
+            self.assertEqual('2@main', str(remote.GitHub(self.remote).commit(hash='fff83bb2')))
+            self.assertEqual('2.1@branch-a', str(remote.GitHub(self.remote).commit(hash='a30ce849')))
+            self.assertEqual('3@main', str(remote.GitHub(self.remote).commit(hash='1abe25b4')))
+            self.assertEqual('2.2@branch-b', str(remote.GitHub(self.remote).commit(hash='3cd32e35')))
+            self.assertEqual('4@main', str(remote.GitHub(self.remote).commit(hash='bae5d1e9')))
+            self.assertEqual('2.2@branch-a', str(remote.GitHub(self.remote).commit(hash='621652ad')))
+            self.assertEqual('2.3@branch-b', str(remote.GitHub(self.remote).commit(hash='790725a6')))
+
+    def test_commit_from_branch(self):
+        with mocks.remote.GitHub():
+            self.assertEqual('4@main', str(remote.GitHub(self.remote).commit(branch='main')))
+            self.assertEqual('2.2@branch-a', str(remote.GitHub(self.remote).commit(branch='branch-a')))
+            self.assertEqual('2.3@branch-b', str(remote.GitHub(self.remote).commit(branch='branch-b')))
+
+    def test_identifier(self):
+        with mocks.remote.GitHub():
+            self.assertEqual(
+                '9b8311f25a77ba14923d9d5a6532103f54abefcb',
+                remote.GitHub(self.remote).commit(identifier='1@main').hash,
+            )
+            self.assertEqual(
+                'fff83bb2d9171b4d9196e977eb0508fd57e7a08d',
+                remote.GitHub(self.remote).commit(identifier='2@main').hash,
+            )
+            self.assertEqual(
+                'a30ce8494bf1ac2807a69844f726be4a9843ca55',
+                remote.GitHub(self.remote).commit(identifier='2.1@branch-a').hash,
+            )
+            self.assertEqual(
+                '1abe25b443e985f93b90d830e4a7e3731336af4d',
+                remote.GitHub(self.remote).commit(identifier='3@main').hash,
+            )
+            self.assertEqual(
+                '3cd32e352410565bb543821fbf856a6d3caad1c4',
+                remote.GitHub(self.remote).commit(identifier='2.2@branch-b').hash,
+            )
+            self.assertEqual(
+                'bae5d1e90999d4f916a8a15810ccfa43f37a2fd6',
+                remote.GitHub(self.remote).commit(identifier='4@main').hash,
+            )
+            self.assertEqual(
+                '621652add7fc416099bd2063366cc38ff61afe36',
+                remote.GitHub(self.remote).commit(identifier='2.2@branch-a').hash,
+            )
+            self.assertEqual(
+                '790725a6d79e28db2ecdde29548d2262c0bd059d',
+                remote.GitHub(self.remote).commit(identifier='2.3@branch-b').hash,
+            )
+
+    def test_non_cannonical_identifiers(self):
+        with mocks.remote.GitHub():
+            self.assertEqual('2@main', str(remote.GitHub(self.remote).commit(identifier='0@branch-a')))
+            self.assertEqual('1@main', str(remote.GitHub(self.remote).commit(identifier='-1@branch-a')))
+
+            self.assertEqual('2@main', str(remote.GitHub(self.remote).commit(identifier='0@branch-b')))
+            self.assertEqual('1@main', str(remote.GitHub(self.remote).commit(identifier='-1@branch-b')))
+
+    def test_tag(self):
+        with mocks.remote.GitHub() as mock:
+            mock.tags['tag-1'] = mock.commits['branch-a'][-1]
+
+            self.assertEqual(
+                '621652add7fc416099bd2063366cc38ff61afe36',
+                remote.GitHub(self.remote).commit(tag='tag-1').hash,
+            )
+
+    def test_no_log(self):
+        with mocks.remote.GitHub():
+            self.assertIsNone(remote.GitHub(self.remote).commit(identifier='4@main', include_log=False).message)
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to