Diff
Modified: trunk/Tools/ChangeLog (287685 => 287686)
--- trunk/Tools/ChangeLog 2022-01-06 15:57:49 UTC (rev 287685)
+++ trunk/Tools/ChangeLog 2022-01-06 16:23:45 UTC (rev 287686)
@@ -1,3 +1,46 @@
+2021-12-16 Jonathan Bedard <[email protected]>
+
+ [webkitbugspy] Initial library commit
+ https://bugs.webkit.org/show_bug.cgi?id=234400
+ <rdar://problem/86585683>
+
+ Reviewed by Dewei Zhu.
+
+ * Scripts/libraries/webkitbugspy/MANIFEST.in: Added.
+ * Scripts/libraries/webkitbugspy/README.md: Added.
+ * Scripts/libraries/webkitbugspy/setup.py: Added.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/__init__.py: Added.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/bugzilla.py: Added.
+ (Tracker): Bugzilla implementation of generic isssue tracker.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/github.py: Added.
+ (Tracker): GitHub implementation of generic isssue tracker.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/issue.py: Added.
+ (Issue): Dynamically fetched generic Issue object referencing parent Tracker.
+ (Issue.Comment): Issue comment including author and timestamp.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/mocks/__init__.py: Added.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/mocks/base.py: Added.
+ (Base): Base class for mocking http based issue trackers.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/mocks/bugzilla.py: Added.
+ (Bugzilla): Partial mock of Bugzilla webserver.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/mocks/data.py: Added.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/mocks/github.py: Added.
+ (GitHub): Partial mock of GitHub webserver.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/tests/__init__.py: Added.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/tests/bugzilla_unittest.py: Added.
+ (TestBugzilla):
+ * Scripts/libraries/webkitbugspy/webkitbugspy/tests/github_unittest.py: Added.
+ (TestGitHub):
+ * Scripts/libraries/webkitbugspy/webkitbugspy/tests/user_unittest.py: Added.
+ (TestUser):
+ * Scripts/libraries/webkitbugspy/webkitbugspy/tracker.py: Added.
+ (Tracker): Generic base of all issue trackers.
+ * Scripts/libraries/webkitbugspy/webkitbugspy/user.py: Added.
+ (User): User object tied to specific tracker.
+ (User.Encoder): User JSON encoder.
+ (User.Mapping): Mapping of user alias to User object.
+ * Scripts/webkitpy/test/main.py:
+ (main): Add webkitbugspy to subdirectories to be tested.
+
2022-01-05 Wenson Hsieh <[email protected]>
Modal container observer should detect and suppress elements that prevent user interaction
Added: trunk/Tools/Scripts/libraries/webkitbugspy/MANIFEST.in (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/MANIFEST.in (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/MANIFEST.in 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1 @@
+include README.md
Added: trunk/Tools/Scripts/libraries/webkitbugspy/README.md (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/README.md (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/README.md 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,32 @@
+# webkitbugspy
+
+Provides a shared API for various bug trackers.
+
+## Requirements
+
+- webkitcorepy
+
+## Usage
+
+The `webkitbugspy` library implements a generic issue tracker API compatible with multiple bug and issue trackers. To interact with an `Issue`, first instantiate a tracker:
+
+```
+from webkitbugspy import github
+
+tracker = github.Tracker('https://github.com/WebKit/WebKit')
+issue = tracker.issue(1)
+```
+
+You should register all trackers your project interacts with so that an `Issue` in one tracker can cross-reference issues in other trackers:
+
+```
+from webkitbugspy import bugzilla, github
+
+Tracker.register(bugzilla.Tracker('https://bugs.webkit.org', res=[
+ re.compile(r'\Ahttps?://webkit.org/b/(?P<id>\d+)\Z'),
+ re.compile(r'\Awebkit.org/b/(?P<id>\d+)\Z'),
+]))
+Tracker.register(github.Tracker('https://github.com/WebKit/WebKit'))
+
+print(Tracker.from_string('https://github.com/WebKit/WebKit/issues/47').references)
+```
Added: trunk/Tools/Scripts/libraries/webkitbugspy/setup.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/setup.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/setup.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,58 @@
+# Copyright (C) 2021 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.
+
+from setuptools import setup
+
+
+def readme():
+ with open('README.md') as f:
+ return f.read()
+
+
+setup(
+ name='webkitbugspy',
+ version='0.0.1',
+ description='Library containing a shared API for various bug trackers.',
+ long_description=readme(),
+ classifiers=[
+ 'Development Status :: 5 - Production/Stable',
+ 'Intended Audience :: Developers',
+ 'License :: Other/Proprietary License',
+ 'Operating System :: MacOS',
+ 'Natural Language :: English',
+ 'Programming Language :: Python :: 3',
+ 'Topic :: Software Development :: Libraries :: Python Modules',
+ ],
+ keywords='python unicode',
+ url='',
+ author='Jonathan Bedard',
+ author_email='[email protected]',
+ license='Modified BSD',
+ packages=[
+ 'webkitbugspy',
+ ],
+ install_requires=[
+ 'webkitcorepy',
+ ],
+ include_package_data=True,
+ zip_safe=False,
+)
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/__init__.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/__init__.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/__init__.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,55 @@
+# Copyright (C) 2021 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 logging
+import os
+import sys
+
+log = logging.getLogger('webkitbugspy')
+
+
+def _maybe_add_library_path(path):
+ # Hopefully we're beside the required library, otherwise that library will need to be installed.
+ libraries_path = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
+ library_path = os.path.join(libraries_path, path)
+ if os.path.isdir(library_path) and os.path.isdir(os.path.join(library_path, path)) and library_path not in sys.path:
+ sys.path.insert(0, library_path)
+
+
+_maybe_add_library_path('webkitcorepy')
+
+try:
+ from webkitcorepy import AutoInstall, Package, Version
+except ImportError:
+ raise ImportError(
+ "'webkitcorepy' could not be found on your Python path.\n" +
+ "You are not running from a WebKit checkout.\n" +
+ "Please install webkitcorepy with `pip install webkitcorepy --extra-index-url <package index URL>`"
+ )
+
+version = Version(0, 0, 1)
+
+from .user import User
+from .issue import Issue
+from .tracker import Tracker
+
+name = 'webkitbugspy'
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/bugzilla.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/bugzilla.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/bugzilla.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,173 @@
+# Copyright (C) 2021 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 os
+import re
+import requests
+import sys
+
+from .issue import Issue
+from .tracker import Tracker as GenericTracker
+
+from datetime import datetime
+from webkitcorepy import credentials, decorators, OutputCapture
+
+
+class Tracker(GenericTracker):
+ ROOT_RE = re.compile(r'\Ahttps?://(?P<domain>\S+)\Z')
+
+ def __init__(self, url, users=None, res=None):
+ super(Tracker, self).__init__(users=users)
+
+ match = self.ROOT_RE.match(url)
+ if not match:
+ raise self.Exception("'{}' is not a valid bugzilla url".format(url))
+ self.url = ""
+ self._res = [
+ re.compile(r'\Ahttps?://{}/show_bug.cgi\?id=(?P<id>\d+)\Z'.format(match.group('domain'))),
+ re.compile(r'\A{}/show_bug.cgi\?id=(?P<id>\d+)\Z'.format(match.group('domain'))),
+ ] + (res or [])
+
+ def user(self, name=None, username=None, email=None):
+ user = super(Tracker, self).user(name=name, username=username, email=email)
+ if user:
+ return user
+ if name and username and email:
+ return self.users.create(
+ name=name,
+ username=username,
+ emails=[email],
+ )
+
+ if not username and not email:
+ raise RuntimeError("Failed to find username for '{}'".format(name))
+ response = requests.get('{}/rest/user?names={}'.format(self.url, username or email or name))
+ response = response.json().get('users') if response.status_code // 100 == 2 else None
+ if not response:
+ return self.users.create(
+ name=name,
+ username=username,
+ emails=[email] if email else None,
+ )
+
+ return self.users.create(
+ name=response[0]['real_name'],
+ username=response[0]['name'],
+ emails=[response[0]['name']],
+ )
+
+ def from_string(self, string):
+ for regex in self._res:
+ match = regex.match(string)
+ if match:
+ return self.issue(int(match.group('id')))
+ return None
+
+ def credentials(self, required=True):
+ return credentials(
+ url=""
+ required=required,
+ prompt=self.url.split('//')[-1],
+ )
+
+ def issue(self, id):
+ return Issue(id=int(id), tracker=self)
+
+ def populate(self, issue, member=None):
+ issue._link = '{}/show_bug.cgi?id={}'.format(self.url, issue.id)
+
+ if member in ['title', 'timestamp', 'creator', 'opened', 'assignee', 'watchers']:
+ response = requests.get('{}/rest/bug/{}'.format(self.url, issue.id))
+ response = response.json().get('bugs', []) if response.status_code == 200 else None
+ if response:
+ response = response[0]
+ issue._title = response['summary']
+ issue._timestamp = int(calendar.timegm(datetime.strptime(response['creation_time'], '%Y-%m-%dT%H:%M:%SZ').timetuple()))
+ if response.get('creator_detail'):
+ issue._creator = self.user(
+ name=response['creator_detail'].get('real_name'),
+ username=response['creator_detail'].get('name'),
+ email=response['creator_detail'].get('email'),
+ )
+ else:
+ issue._creator = self.user(username=response['creator']) if response.get('creator') else None
+ issue._opened = response['status'] != 'RESOLVED'
+ if response.get('assigned_to_detail'):
+ issue._assignee = self.user(
+ name=response['assigned_to_detail'].get('real_name'),
+ username=response['assigned_to_detail'].get('name'),
+ email=response['assigned_to_detail'].get('email'),
+ )
+ else:
+ issue._assignee = self.user(username=response['assigned_to']) if response.get('assigned_to') else None
+ issue._watchers = []
+ for name in response.get('cc', []):
+ issue._watchers.append(self.user(username=name))
+
+ else:
+ sys.stderr.write("Failed to fetch '{}'\n".format(issue.link))
+
+ if member in ['description', 'comments']:
+ response = requests.get('{}/rest/bug/{}/comment'.format(self.url, issue.id))
+ if response.status_code == 200:
+ response = response.json().get('bugs', {}).get(str(issue.id), {}).get('comments', None)
+ else:
+ response = None
+
+ if response:
+ issue._description = response[0].get('text')
+ issue._comments = [
+ Issue.Comment(
+ user=self.user(username=comment['creator']),
+ timestamp=int(calendar.timegm(datetime.strptime(comment['creation_time'], '%Y-%m-%dT%H:%M:%SZ').timetuple())),
+ content=comment['text'],
+ ) for comment in response[1:]
+ ]
+ else:
+ sys.stderr.write("Failed to fetch comments for '{}'\n".format(issue.link))
+
+ if member == 'references':
+ issue._references = []
+ refs = set()
+
+ for text in [issue.description] + [comment.content for comment in issue.comments]:
+ for match in self.REFERENCE_RE.findall(text):
+ candidate = GenericTracker.from_string(match[0]) or self.from_string(match[0])
+ if not candidate or candidate.link in refs or candidate.id == issue.id:
+ continue
+ issue._references.append(candidate)
+ refs.add(candidate.link)
+
+ response = requests.get('{}/rest/bug/{}?include_fields=see_also'.format(self.url, issue.id))
+ response = response.json().get('bugs', []) if response.status_code == 200 else None
+ if response:
+ for link in response[0].get('see_also', []):
+ candidate = GenericTracker.from_string(link) or self.from_string(link)
+ if not candidate or candidate.link in refs or candidate.id == issue.id:
+ continue
+ issue._references.append(candidate)
+ refs.add(candidate.link)
+ else:
+ sys.stderr.write("Failed to fetch related issues for '{}'\n".format(issue.link))
+
+ return issue
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/github.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/github.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/github.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,234 @@
+# Copyright (C) 2021 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 sys
+
+from .issue import Issue
+from .tracker import Tracker as GenericTracker
+
+from datetime import datetime
+from requests.auth import HTTPBasicAuth
+from webkitcorepy import credentials, decorators
+
+
+class Tracker(GenericTracker):
+ ROOT_RE = re.compile(r'\Ahttps?://github.(?P<domain>\S+)/(?P<owner>\S+)/(?P<repository>\S+)\Z')
+ ISSUE_LINK_RE = re.compile(r'#(?P<id>\d+)')
+ USERNAME_RE = re.compile(r'(^|\s|\'|")@(?P<username>[^\s"\'<>]+)')
+
+ def __init__(self, url, users=None, res=None):
+ super(Tracker, self).__init__(users=users)
+
+ match = self.ROOT_RE.match(url)
+ if not match:
+ raise self.Exception("'{}' is not a valid GitHub project".format(url))
+
+ self._res = [
+ re.compile(r'\Ahttps?://github.{}/{}/{}/issues/(?P<id>\d+)\Z'.format(
+ match.group('domain'), match.group('owner'), match.group('repository'),
+ )), re.compile(r'\Agithub.{}/{}/{}/issues/(?P<id>\d+)\Z'.format(
+ match.group('domain'), match.group('owner'), match.group('repository'),
+ )),
+ ] + (res or [])
+
+ self.url = ""
+ self.api_url = 'https://api.github.{}'.format(match.group('domain'))
+ self.owner = match.group('owner')
+ self.name = match.group('repository')
+
+ def from_string(self, string):
+ for regex in self._res:
+ match = regex.match(string)
+ if match:
+ return self.issue(int(match.group('id')))
+ return None
+
+ def credentials(self, required=True):
+ return credentials(
+ url=""
+ required=required,
+ name=self.url.split('/')[2].replace('.', '_').upper(),
+ prompt="GitHub's API\nPlease generate a 'Personal access token' via 'Developer settings' for your user",
+ key_name='token',
+ )
+
+ def request(self, path=None, params=None, headers=None, authenticated=None, paginate=True):
+ headers = {key: value for key, value in headers.items()} if headers else dict()
+ headers['Accept'] = headers.get('Accept', 'application/vnd.github.v3+json')
+
+ username, access_token = self.credentials(required=bool(authenticated))
+ auth = HTTPBasicAuth(username, access_token) if username and access_token else None
+ if authenticated is False:
+ auth = None
+ if authenticated and not auth:
+ raise self.Exception('Request requires authentication, none provided')
+
+ 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, auth=auth)
+ if authenticated is None and not auth and response.status_code // 100 == 4:
+ return self.request(path=path, params=params, headers=headers, authenticated=True, paginate=paginate)
+ if response.status_code != 200:
+ sys.stderr.write("Request to '{}' returned status code '{}'\n".format(url, response.status_code))
+ message = response.json().get('message')
+ if message:
+ sys.stderr.write('Message: {}\n'.format(message))
+ return None
+ result = response.json()
+
+ while paginate and isinstance(response.json(), list) and len(response.json()) == params['per_page']:
+ params['page'] += 1
+ response = requests.get(url, params=params, headers=headers, auth=auth)
+ 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 user(self, name=None, username=None, email=None):
+ user = super(Tracker, self).user(name=name, username=username, email=email)
+ if user:
+ return user
+ if not username:
+ raise RuntimeError("Failed to find username for '{}'".format(name or email))
+
+ response = requests.get(
+ '{api_url}/users/{username}'.format(
+ api_url=self.api_url,
+ username=username,
+ ), auth=HTTPBasicAuth(*self.credentials(required=True)),
+ headers=dict(Accept='application/vnd.github.v3+json'),
+ )
+ if response.status_code // 100 != 2:
+ return None
+
+ data = ""
+ return self.users.create(
+ name=data.get('name', username),
+ username=username,
+ emails=[data.get('email')],
+ )
+
+ def issue(self, id):
+ return Issue(id=int(id), tracker=self)
+
+ def populate(self, issue, member=None):
+ issue._link = '{}/issues/{}'.format(self.url, issue.id)
+
+ if member in ('title', 'timestamp', 'creator', 'opened', 'assignee', 'description'):
+ response = self.request(path=issue.id)
+ if response:
+ issue._title = response['title']
+ issue._timestamp = int(calendar.timegm(datetime.strptime(response['created_at'], '%Y-%m-%dT%H:%M:%SZ').timetuple()))
+ issue._creator = self.user(username=response['user']['login']) if response.get('user') else None
+ issue._description = response['body']
+ issue._opened = response['state'] != 'closed'
+ issue._assignee = self.user(username=response['assignee']['login']) if response.get('assignee') else None
+ else:
+ sys.stderr.write("Failed to fetch '{}'\n".format(issue.link))
+
+ if member == 'watchers':
+ issue._watchers = []
+ refs = set()
+ response = self.request(path=issue.id)
+ if response:
+ for assignee in response['assignees']:
+ watcher = self.user(username=assignee['login'])
+ if not watcher or watcher.username in refs:
+ continue
+ refs.add(watcher.username)
+ issue._watchers.append(watcher)
+ else:
+ sys.stderr.write("Failed to fetch '{}'\n".format(issue.link))
+
+ for text in [issue.description] + [comment.content for comment in issue.comments]:
+ for match in self.USERNAME_RE.findall(text):
+ if match[1] in refs:
+ continue
+ user = self.user(username=match[1])
+ if not user:
+ continue
+ refs.add(user.username)
+ issue._watchers.append(user)
+
+ if member == 'comments':
+ response = self.request(path='{}/comments'.format(issue.id))
+ issue._comments = []
+ for node in response or []:
+ username = node.get('user', {}).get('login')
+ if not username:
+ continue
+ tm = node.get('updated_at', node.get('created_at'))
+ if tm:
+ tm = int(calendar.timegm(datetime.strptime(tm, '%Y-%m-%dT%H:%M:%SZ').timetuple()))
+
+ issue._comments.append(Issue.Comment(
+ user=self.user(username=username),
+ timestamp=tm,
+ content=node.get('body'),
+ ))
+
+ if member == 'references':
+ issue._references = []
+ refs = set()
+
+ for text in [issue.description] + [comment.content for comment in issue.comments]:
+ for match in self.ISSUE_LINK_RE.findall(text):
+ candidate = self.issue(int(match))
+ if candidate.link in refs or candidate.id == issue.id:
+ continue
+ issue._references.append(candidate)
+ refs.add(candidate.link)
+
+ for match in self.REFERENCE_RE.findall(text):
+ candidate = GenericTracker.from_string(match[0])
+ if not candidate or candidate.link in refs or candidate.id == issue.id:
+ continue
+ issue._references.append(candidate)
+ refs.add(candidate.link)
+
+ response = self.request(path='{}/timeline'.format(issue.id))
+ if response:
+ for event in response:
+ if not event.get('event'):
+ continue
+ id = event.get('source', {}).get('issue', {}).get('number', None)
+ if not id:
+ continue
+ candidate = self.issue(id)
+ if candidate.link in refs or candidate.id == issue.id:
+ continue
+ issue._references.append(candidate)
+ refs.add(candidate.link)
+
+ return issue
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/issue.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/issue.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/issue.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,161 @@
+# Copyright (C) 2021 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 six
+
+from .tracker import Tracker
+from .user import User
+from datetime import datetime
+
+
+class Issue(object):
+ class Comment(object):
+ def __init__(self, user, timestamp, content):
+ if user and not isinstance(user, User):
+ raise TypeError("Expected 'user' to be of type {}, got '{}'".format(User, user))
+ else:
+ self.user = user
+
+ if isinstance(timestamp, six.string_types) and timestamp.isdigit():
+ timestamp = int(timestamp)
+ if timestamp and not isinstance(timestamp, int):
+ raise TypeError("Expected 'timestamp' to be of type int, got '{}'".format(timestamp))
+ self.timestamp = timestamp
+
+ if content and not isinstance(content, six.string_types):
+ raise ValueError("Expected 'content' to be a string, got '{}'".format(content))
+ self.content = content
+
+ def __repr__(self):
+ return '({} @ {}) {}'.format(
+ self.user,
+ datetime.utcfromtimestamp(self.timestamp) if self.timestamp else '-',
+ self.content,
+ )
+
+ def __init__(self, id, tracker):
+ self.id = int(id)
+ self.tracker = tracker
+
+ self._link = None
+ self._title = None
+ self._timestamp = None
+ self._creator = None
+ self._description = None
+ self._opened = None
+ self._assignee = None
+ self._watchers = None
+ self._comments = None
+ self._references = None
+
+ self.tracker.populate(self, None)
+
+ def __str__(self):
+ return '{} {}'.format(self.link, self.title)
+
+ @property
+ def link(self):
+ if self._link is None:
+ self.tracker.populate(self, 'link')
+ return self._link
+
+ @property
+ def title(self):
+ if self._title is None:
+ self.tracker.populate(self, 'title')
+ return self._title
+
+ @property
+ def timestamp(self):
+ if self._timestamp is None:
+ self.tracker.populate(self, 'timestamp')
+ return self._timestamp
+
+ @property
+ def creator(self):
+ if self._creator is None:
+ self.tracker.populate(self, 'creator')
+ return self._creator
+
+ @property
+ def description(self):
+ if self._description is None:
+ self.tracker.populate(self, 'description')
+ return self._description
+
+ @property
+ def opened(self):
+ if self._opened is None:
+ self.tracker.populate(self, 'opened')
+ return self._opened
+
+ @property
+ def assignee(self):
+ if self._assignee is None:
+ self.tracker.populate(self, 'assignee')
+ return self._assignee
+
+ @property
+ def watchers(self):
+ if self._watchers is None:
+ self.tracker.populate(self, 'watchers')
+ return self._watchers
+
+ @property
+ def comments(self):
+ if self._comments is None:
+ self.tracker.populate(self, 'comments')
+ return self._comments or []
+
+ @property
+ def references(self):
+ if self._references is None:
+ self.tracker.populate(self, 'references')
+ return self._references or []
+
+ def __hash__(self):
+ return hash(self.link)
+
+ def __cmp__(self, other):
+ if not isinstance(other, Issue):
+ raise ValueError('Cannot compare {} with {}'.format(Issue, type(other)))
+ if self.link == other.link:
+ return 0
+ return 1 if self.link > other.link else -1
+
+ def __eq__(self, other):
+ return self.__cmp__(other) == 0
+
+ def __ne__(self, other):
+ return self.__cmp__(other) != 0
+
+ def __lt__(self, other):
+ return self.__cmp__(other) < 0
+
+ def __le__(self, other):
+ return self.__cmp__(other) <= 0
+
+ def __gt__(self, other):
+ return self.__cmp__(other) > 0
+
+ def __ge__(self, other):
+ return self.__cmp__(other) >= 0
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/__init__.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/__init__.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/__init__.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,25 @@
+# Copyright (C) 2021 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.
+
+from .bugzilla import Bugzilla
+from .data import ISSUES, USERS
+from .github import GitHub
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/base.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/base.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/base.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,65 @@
+# Copyright (C) 2021 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.
+
+from webkitbugspy import User
+from webkitcorepy import mocks
+
+
+class Base(mocks.Requests):
+ @classmethod
+ def transform_user(cls, user):
+ return User(
+ name=user.name,
+ username=user.username,
+ emails=user.emails,
+ )
+
+ def __init__(self, *hosts, **kwargs):
+ super(Base, self).__init__(*hosts)
+
+ users = kwargs.get('users', None)
+ issues = kwargs.get('issues', None)
+
+ self.users = User.Mapping()
+ for user in users or []:
+ self.users.add(type(self).transform_user(user))
+
+ self.issues = {}
+ for issue in issues or []:
+ self.add(issue)
+
+ def add(self, bug_data):
+ if not isinstance(bug_data, dict):
+ raise ValueError('Expected bug data to be dictionary')
+
+ id = bug_data.get('id')
+ if not id:
+ id = 1
+ while id in self.issues:
+ id += 1
+ bug_data['id'] = id
+
+ for user in [bug_data.get('creator'), bug_data.get('assignee')] + bug_data.get('watchers', []):
+ if user:
+ self.users.add(type(self).transform_user(user))
+
+ self.issues[id] = {key: value for key, value in bug_data.items()}
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/bugzilla.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/bugzilla.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/bugzilla.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,191 @@
+# Copyright (C) 2021 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 json
+import re
+
+from .base import Base
+
+from webkitbugspy import User
+from webkitcorepy import mocks
+
+
+class Bugzilla(Base):
+ top = None
+
+ @classmethod
+ def time_string(cls, timestamp):
+ from datetime import datetime, timedelta
+ return datetime.utcfromtimestamp(timestamp - timedelta(hours=7).seconds).strftime('%Y-%m-%dT%H:%M:%SZ')
+
+ @classmethod
+ def transform_user(cls, user):
+ return User(
+ name=user.name,
+ username=user.email,
+ emails=user.emails,
+ )
+
+ def __init__(self, hostname='bugs.example.com', users=None, issues=None):
+ super(Bugzilla, self).__init__(hostname, users=users, issues=issues)
+
+ def _user(self, url, username):
+ user = self.users[username]
+ if not user:
+ return mocks.Response(
+ url=""
+ headers={'Content-Type': 'text/json'},
+ status_code=404,
+ text=json.dumps(dict(
+ code=51,
+ error=True,
+ message="There is no user named '{}'. Either you mis-typed the name or that user has not yet registered for a Bugzilla account.".format(username),
+ )),
+ )
+ return mocks.Response.fromJson(dict(
+ users=[dict(
+ name=user.username,
+ real_name=user.name,
+ )],
+ ), url=""
+
+ def _issue(self, url, id):
+ if id not in self.issues:
+ return mocks.Response(
+ url=""
+ headers={'Content-Type': 'text/json'},
+ status_code=404,
+ text=json.dumps(dict(
+ code=101,
+ error=True,
+ message="Bug #{} does not exist.".format(id),
+ )),
+ )
+ issue = self.issues[id]
+ return mocks.Response.fromJson(dict(
+ bugs=[dict(
+ id=id,
+ summary=issue['title'],
+ creation_time=self.time_string(issue['timestamp']),
+ status='RESOLVED' if issue['opened'] else 'FIXED',
+ creator=self.users[issue['creator'].name].username,
+ creator_detail=dict(
+ email=issue['creator'].email,
+ name=self.users[issue['creator'].name].username,
+ real_name=issue['creator'].name,
+ ), assigned_to=self.users[issue['assignee'].name].username,
+ assigned_to_detail=dict(
+ email=issue['assignee'].email,
+ name=self.users[issue['assignee'].name].username,
+ real_name=issue['assignee'].name,
+ ), cc=[self.users[user.name].username for user in issue.get('watchers', [])],
+ cc_detail=[
+ dict(
+ email=user.email,
+ name=self.users[user.name].username,
+ real_name=user.name,
+ ) for user in issue.get('watchers', [])
+ ], see_also=[
+ 'https://{}/show_bug.cgi?id={}'.format(self.hosts[0], n) for n in issue.get('references', [])
+ ],
+ )],
+ ), url=""
+
+ def _see_also(self, url, id):
+ if id not in self.issues:
+ return mocks.Response(
+ url=""
+ headers={'Content-Type': 'text/json'},
+ status_code=404,
+ text=json.dumps(dict(
+ code=101,
+ error=True,
+ message="Bug #{} does not exist.".format(id),
+ )),
+ )
+ issue = self.issues[id]
+ return mocks.Response.fromJson(dict(
+ bugs=[dict(
+ id=id,
+ see_also=[
+ 'https://{}/show_bug.cgi?id={}'.format(self.hosts[0], n) for n in issue.get('references', [])
+ ],
+ )],
+ ), url=""
+
+ def _comments(self, url, id):
+ if id not in self.issues:
+ return mocks.Response(
+ url=""
+ headers={'Content-Type': 'text/json'},
+ status_code=404,
+ text=json.dumps(dict(
+ code=101,
+ error=True,
+ message="Bug #{} does not exist.".format(id),
+ )),
+ )
+
+ issue = self.issues[id]
+ return mocks.Response.fromJson(dict(
+ bugs={str(id): dict(comments=[
+ dict(
+ bug_id=id,
+ creator=self.users[issue['creator'].name].username,
+ creation_time=self.time_string(issue['timestamp']),
+ time=self.time_string(issue['timestamp']),
+ text=issue['description'],
+ ),
+ ] + [
+ dict(
+ bug_id=id,
+ creator=self.users[comment.user.name].username,
+ creation_time=self.time_string(comment.timestamp),
+ time=self.time_string(comment.timestamp),
+ text=comment.content,
+ ) for comment in issue['comments']
+ ])},
+ ), url=""
+
+ def request(self, method, url, data="" params=None, auth=None, json=None, **kwargs):
+ if not url.startswith('http://') and not url.startswith('https://'):
+ return mocks.Response.create404(url)
+
+ stripped_url = url.split('://')[-1]
+
+ match = re.match(r'{}/rest/user\?names=(?P<username>\S+)$'.format(self.hosts[0]), stripped_url)
+ if match and method == 'GET':
+ return self._user(url, match.group('username'))
+
+ match = re.match(r'{}/rest/bug/(?P<id>\d+)$'.format(self.hosts[0]), stripped_url)
+ if match and method == 'GET':
+ return self._issue(url, int(match.group('id')))
+
+ match = re.match(r'{}/rest/bug/(?P<id>\d+)\?include_fields=see_also$'.format(self.hosts[0]), stripped_url)
+ if match and method == 'GET':
+ return self._see_also(url, int(match.group('id')))
+
+ match = re.match(r'{}/rest/bug/(?P<id>\d+)/comment$'.format(self.hosts[0]), stripped_url)
+ if match and method == 'GET':
+ return self._comments(url, int(match.group('id')))
+
+ return mocks.Response.create404(url)
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/data.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/data.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/data.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,89 @@
+# Copyright (C) 2021 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.
+
+from webkitbugspy import Issue, User
+
+
+USERS = User.Mapping()
+USERS.create(
+ name='Tim Contributor',
+ emails=['[email protected]'],
+)
+USERS.create(
+ name='Felix Filer',
+ emails=['[email protected]'],
+)
+USERS.create(
+ name='Wilma Watcher',
+ emails=['[email protected]'],
+)
+
+ISSUES = [
+ dict(
+ title='Example issue 1',
+ timestamp=1639536160,
+ opened=True,
+ creator=USERS['Felix Filer'],
+ assignee=USERS['Tim Contributor'],
+ description='An example issue for testing',
+ comments=[
+ Issue.Comment(
+ user=USERS['Felix Filer'],
+ timestamp=1639536220,
+ content='Was able to reproduce on version 1.2.3',
+ ), Issue.Comment(
+ user=USERS['Tim Contributor'],
+ timestamp=1639550220,
+ content='Trying to prepare a fix for 1.2.4',
+ ),
+ ], watchers=[USERS['Felix Filer'], USERS['Tim Contributor'], USERS['Wilma Watcher']],
+ ), dict(
+ title='Example feature 1',
+ timestamp=1639536320,
+ opened=True,
+ creator=USERS['Tim Contributor'],
+ assignee=USERS['Tim Contributor'],
+ description='We need to support a new feature',
+ comments=[
+ Issue.Comment(
+ user=USERS['Tim Contributor'],
+ timestamp=1639539110,
+ content="Version 1.3.0 should behave differently, let's add a feature!",
+ ),
+ ], watchers=[USERS['Tim Contributor'], USERS['Wilma Watcher']],
+ references=[3],
+ ), dict(
+ title='Example issue 2',
+ timestamp=1639540010,
+ opened=False,
+ creator=USERS['Felix Filer'],
+ assignee=USERS['Tim Contributor'],
+ description='Another example issue for testing, example.com is broken',
+ comments=[
+ Issue.Comment(
+ user=USERS['Tim Contributor'],
+ timestamp=1639544065,
+ content="This is really a feature request, I already filed a bug for this.",
+ ),
+ ], watchers=[USERS['Felix Filer'], USERS['Tim Contributor'], USERS['Wilma Watcher']], references=[2],
+ ),
+]
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/github.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/github.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/mocks/github.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,170 @@
+# Copyright (C) 2021 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 json
+import os
+import re
+
+from .base import Base
+
+from webkitbugspy import User
+from webkitcorepy import mocks
+
+
+class GitHub(Base):
+ top = None
+
+ @classmethod
+ def transform_user(cls, user):
+ return User(
+ name=user.name,
+ username=user.email.split('@')[0],
+ emails=user.emails,
+ )
+
+ @classmethod
+ def time_string(cls, timestamp):
+ from datetime import datetime, timedelta
+ return datetime.utcfromtimestamp(timestamp - timedelta(hours=7).seconds).strftime('%Y-%m-%dT%H:%M:%SZ')
+
+ def __init__(self, hostname='github.example.com/WebKit/WebKit', users=None, issues=None):
+ hostname, repo = hostname.split('/', 1)
+ self.api_host = 'api.{hostname}/repos/{repo}'.format(hostname=hostname, repo=repo)
+
+ super(GitHub, self).__init__(hostname, 'api.{}'.format(hostname), users=users, issues=issues)
+
+ self._environment = None
+
+ def __enter__(self):
+ prefix = self.hosts[0].replace('.', '_').upper()
+ username_key = '{}_USERNAME'.format(prefix)
+ token_key = '{}_TOKEN'.format(prefix)
+ self._environment = {
+ username_key: os.environ.get(username_key),
+ token_key: os.environ.get(token_key),
+ }
+ os.environ[username_key] = 'username'
+ os.environ[token_key] = 'token'
+
+ return super(GitHub, self).__enter__()
+
+ def __exit__(self, *args, **kwargs):
+ result = super(GitHub, self).__exit__(*args, **kwargs)
+ for key in self._environment.keys():
+ if self._environment[key]:
+ os.environ[key] = self._environment[key]
+ else:
+ del os.environ[key]
+ return result
+
+ def _user(self, url, username):
+ user = self.users.get(username)
+ if not user:
+ return mocks.Response.create404(url)
+ return mocks.Response.fromJson(dict(
+ name=user.name,
+ login=user.username,
+ email=user.email,
+ ), url=""
+
+ def _issue(self, url, id):
+ if id not in self.issues:
+ return mocks.Response(
+ url=""
+ headers={'Content-Type': 'text/json'},
+ status_code=404,
+ text=json.dumps(dict(message="Not Found")),
+ )
+ issue = self.issues[id]
+ return mocks.Response.fromJson(dict(
+ title=issue['title'],
+ body=issue['description'],
+ user=dict(login=self.users[issue['creator'].name].username),
+ created_at=self.time_string(issue['timestamp']),
+ state='opened' if issue['opened'] else 'closed',
+ assignee=dict(login=self.users[issue['assignee'].name].username),
+ assignees=[dict(login=self.users[user.name].username) for user in issue['watchers']],
+ ))
+
+ def _comments(self, url, id):
+ if id not in self.issues:
+ return mocks.Response(
+ url=""
+ headers={'Content-Type': 'text/json'},
+ status_code=404,
+ text=json.dumps(dict(message="Not Found")),
+ )
+ issue = self.issues[id]
+ return mocks.Response.fromJson([
+ dict(
+ body=comment.content,
+ created_at=self.time_string(comment.timestamp),
+ user=dict(login=self.users[comment.user.name].username),
+
+ ) for comment in issue['comments']
+ ])
+
+ def _timelines(self, url, id):
+ if id not in self.issues:
+ return mocks.Response(
+ url=""
+ headers={'Content-Type': 'text/json'},
+ status_code=404,
+ text=json.dumps(dict(message="Not Found")),
+ )
+ issue = self.issues[id]
+ return mocks.Response.fromJson([
+ dict(
+ body=comment.content,
+ created_at=self.time_string(comment.timestamp),
+ actor=dict(login=self.users[comment.user.name].username),
+ ) for comment in issue['comments']
+ ] + [
+ dict(
+ event='cross-referenced',
+ source=dict(issue=dict(number=reference)),
+ ) for reference in issue.get('references', [])
+ ])
+
+ def request(self, method, url, data="" params=None, auth=None, json=None, **kwargs):
+ if not url.startswith('http://') and not url.startswith('https://'):
+ return mocks.Response.create404(url)
+
+ stripped_url = url.split('://')[-1]
+
+ match = re.match(r'{}/users/(?P<username>\S+)$'.format(self.hosts[1]), stripped_url)
+ if match and method == 'GET':
+ return self._user(url, match.group('username'))
+
+ match = re.match(r'{}/issues/(?P<id>\d+)$'.format(self.api_host), stripped_url)
+ if match and method == 'GET':
+ return self._issue(url, int(match.group('id')))
+
+ match = re.match(r'{}/issues/(?P<id>\d+)/comments$'.format(self.api_host), stripped_url)
+ if match and method == 'GET':
+ return self._comments(url, int(match.group('id')))
+
+ match = re.match(r'{}/issues/(?P<id>\d+)/timeline$'.format(self.api_host), stripped_url)
+ if match and method == 'GET':
+ return self._timelines(url, int(match.group('id')))
+
+ return mocks.Response.create404(url)
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/__init__.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/__init__.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/__init__.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,21 @@
+# Copyright (C) 2021 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.
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/bugzilla_unittest.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/bugzilla_unittest.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/bugzilla_unittest.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,142 @@
+# Copyright (C) 2021 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 json
+import unittest
+
+from webkitbugspy import Issue, User, bugzilla, mocks
+
+
+class TestBugzilla(unittest.TestCase):
+ URL = ''
+
+ def test_no_users(self):
+ with mocks.Bugzilla(self.URL.split('://')[1]):
+ self.assertEqual(
+ User.Encoder().default(bugzilla.Tracker(self.URL).user(
+ name='Tim Contributor', username='[email protected]', email='[email protected]',
+ )), dict(name='Tim Contributor', username='[email protected]', emails=['[email protected]']),
+ )
+ self.assertEqual(
+ User.Encoder().default(bugzilla.Tracker(self.URL).user(username='[email protected]')),
+ dict(username='[email protected]'),
+ )
+ self.assertEqual(
+ User.Encoder().default(bugzilla.Tracker(self.URL).user(email='[email protected]')),
+ dict(emails=['[email protected]']),
+ )
+
+ def test_users(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], users=mocks.USERS):
+ tracker = bugzilla.Tracker(self.URL)
+ self.assertEqual(
+ User.Encoder().default(tracker.user(username='[email protected]')),
+ dict(name='Tim Contributor', username='[email protected]', emails=['[email protected]']),
+ )
+ self.assertEqual(
+ User.Encoder().default(tracker.user(name='Tim Contributor')),
+ dict(name='Tim Contributor', username='[email protected]', emails=['[email protected]']),
+ )
+ self.assertEqual(
+ User.Encoder().default(tracker.user(email='[email protected]')),
+ dict(name='Felix Filer', username='[email protected]', emails=['[email protected]']),
+ )
+
+ def test_link(self):
+ tracker = bugzilla.Tracker(self.URL)
+ self.assertEqual(tracker.issue(1234).link, 'https://bugs.example.com/show_bug.cgi?id=1234')
+ self.assertEqual(
+ tracker.from_string('http://bugs.example.com/show_bug.cgi?id=1234').link,
+ 'https://bugs.example.com/show_bug.cgi?id=1234',
+ )
+ self.assertEqual(tracker.from_string('http://bugs.other.com/show_bug.cgi?id=1234'), None)
+
+ def test_title(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ tracker = bugzilla.Tracker(self.URL)
+ self.assertEqual(tracker.issue(1).title, 'Example issue 1')
+ self.assertEqual(str(tracker.issue(1)), 'https://bugs.example.com/show_bug.cgi?id=1 Example issue 1')
+
+ def test_timestamp(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(bugzilla.Tracker(self.URL).issue(1).timestamp, 1639510960)
+
+ def test_creator(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ User.Encoder().default(bugzilla.Tracker(self.URL).issue(1).creator),
+ dict(name='Felix Filer', username='[email protected]', emails=['[email protected]']),
+ )
+
+ def test_description(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ bugzilla.Tracker(self.URL).issue(1).description,
+ 'An example issue for testing',
+ )
+
+ def test_assignee(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ User.Encoder().default(bugzilla.Tracker(self.URL).issue(1).assignee),
+ dict(name='Tim Contributor', username='[email protected]', emails=['[email protected]']),
+ )
+
+ def test_comments(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ comments = bugzilla.Tracker(self.URL).issue(1).comments
+ self.assertEqual(len(comments), 2)
+ self.assertEqual(comments[0].timestamp, 1639511020)
+ self.assertEqual(comments[0].content, 'Was able to reproduce on version 1.2.3')
+ self.assertEqual(
+ User.Encoder().default(comments[0].user),
+ dict(name='Felix Filer', username='[email protected]', emails=['[email protected]']),
+ )
+
+ def test_watchers(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ User.Encoder().default(bugzilla.Tracker(self.URL).issue(1).watchers), [
+ dict(name='Felix Filer', username='[email protected]', emails=['[email protected]']),
+ dict(name='Tim Contributor', username='[email protected]', emails=['[email protected]']),
+ dict(name='Wilma Watcher', username='[email protected]', emails=['[email protected]']),
+ ],
+ )
+
+ def test_references(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES):
+ tracker = bugzilla.Tracker(self.URL)
+ self.assertEqual(tracker.issue(1).references, [])
+ self.assertEqual(tracker.issue(2).references, [tracker.issue(3)])
+ self.assertEqual(tracker.issue(3).references, [tracker.issue(2)])
+
+ def test_reference_parse(self):
+ with mocks.Bugzilla(self.URL.split('://')[1], issues=mocks.ISSUES) as mock:
+ tracker = bugzilla.Tracker(self.URL)
+ mock.issues[1]['comments'].append(
+ Issue.Comment(
+ user=mocks.USERS['Wilma Watcher'],
+ timestamp=1639539630,
+ content='Is this related to {}/show_bug.cgi?id=2?'.format(self.URL),
+ ),
+ )
+ self.assertEqual(tracker.issue(1).references, [tracker.issue(2)])
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/github_unittest.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/github_unittest.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/github_unittest.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,142 @@
+# Copyright (C) 2021 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 json
+import unittest
+
+from webkitbugspy import Issue, User, github, mocks
+
+
+class TestGitHub(unittest.TestCase):
+ URL = ''
+
+ def test_users(self):
+ with mocks.GitHub(self.URL.split('://')[1], users=mocks.USERS):
+ tracker = github.Tracker(self.URL)
+ self.assertEqual(
+ User.Encoder().default(tracker.user(username='tcontributor')),
+ dict(name='Tim Contributor', username='tcontributor', emails=['[email protected]']),
+ )
+ self.assertEqual(
+ User.Encoder().default(tracker.user(name='Tim Contributor')),
+ dict(name='Tim Contributor', username='tcontributor', emails=['[email protected]']),
+ )
+ with self.assertRaises(RuntimeError):
+ tracker.user(email='[email protected]')
+
+ def test_link(self):
+ tracker = github.Tracker(self.URL)
+ self.assertEqual(tracker.issue(1234).link, 'https://github.example.com/WebKit/WebKit/issues/1234')
+ self.assertEqual(
+ tracker.from_string('http://github.example.com/WebKit/WebKit/issues/1234').link,
+ 'https://github.example.com/WebKit/WebKit/issues/1234',
+ )
+ self.assertEqual(tracker.from_string('https://github.example.com/Apple/Swift/issues/1234'), None)
+
+ def test_title(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ tracker = github.Tracker(self.URL)
+ self.assertEqual(tracker.issue(1).title, 'Example issue 1')
+ self.assertEqual(str(tracker.issue(1)), 'https://github.example.com/WebKit/WebKit/issues/1 Example issue 1')
+
+ def test_timestamp(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(github.Tracker(self.URL).issue(1).timestamp, 1639510960)
+
+ def test_creator(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ User.Encoder().default(github.Tracker(self.URL).issue(1).creator),
+ dict(name='Felix Filer', username='ffiler', emails=['[email protected]']),
+ )
+
+ def test_description(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ github.Tracker(self.URL).issue(1).description,
+ 'An example issue for testing',
+ )
+
+ def test_assignee(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ User.Encoder().default(github.Tracker(self.URL).issue(1).assignee),
+ dict(name='Tim Contributor', username='tcontributor', emails=['[email protected]']),
+ )
+
+ def test_comments(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ comments = github.Tracker(self.URL).issue(1).comments
+ self.assertEqual(len(comments), 2)
+ self.assertEqual(comments[0].timestamp, 1639511020)
+ self.assertEqual(comments[0].content, 'Was able to reproduce on version 1.2.3')
+ self.assertEqual(
+ User.Encoder().default(comments[0].user),
+ dict(name='Felix Filer', username='ffiler', emails=['[email protected]']),
+ )
+
+ def test_watchers(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ self.assertEqual(
+ User.Encoder().default(github.Tracker(self.URL).issue(1).watchers), [
+ dict(name='Felix Filer', username='ffiler', emails=['[email protected]']),
+ dict(name='Tim Contributor', username='tcontributor', emails=['[email protected]']),
+ dict(name='Wilma Watcher', username='wwatcher', emails=['[email protected]']),
+ ],
+ )
+
+ def test_watcher_parse(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES) as mock:
+ tracker = github.Tracker(self.URL)
+ mock.issues[2]['comments'].append(
+ Issue.Comment(
+ user=mocks.USERS['Tim Contributor'],
+ timestamp=1639539630,
+ content='Looks like @ffiler stumbled upon this in #3',
+ ),
+ )
+ self.assertEqual(
+ User.Encoder().default(tracker.issue(2).watchers), [
+ dict(name='Tim Contributor', username='tcontributor', emails=['[email protected]']),
+ dict(name='Wilma Watcher', username='wwatcher', emails=['[email protected]']),
+ dict(name='Felix Filer', username='ffiler', emails=['[email protected]']),
+ ],
+ )
+
+ def test_references(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES):
+ tracker = github.Tracker(self.URL)
+ self.assertEqual(tracker.issue(1).references, [])
+ self.assertEqual(tracker.issue(2).references, [tracker.issue(3)])
+ self.assertEqual(tracker.issue(3).references, [tracker.issue(2)])
+
+ def test_reference_parse(self):
+ with mocks.GitHub(self.URL.split('://')[1], issues=mocks.ISSUES) as mock:
+ tracker = github.Tracker(self.URL)
+ mock.issues[1]['comments'].append(
+ Issue.Comment(
+ user=mocks.USERS['Wilma Watcher'],
+ timestamp=1639539630,
+ content='Is this related to #2?',
+ ),
+ )
+ self.assertEqual(tracker.issue(1).references, [tracker.issue(2)])
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/user_unittest.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/user_unittest.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/user_unittest.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,86 @@
+# Copyright (C) 2021 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 json
+import unittest
+
+from webkitbugspy import User
+
+
+class TestUser(unittest.TestCase):
+ def test_string(self):
+ self.assertEqual(
+ str(User(name='Tim Contributor', username='tcontributor', emails=['[email protected]'])),
+ 'Tim Contributor <tcontributor>',
+ )
+ self.assertEqual(
+ str(User(username='tcontributor', emails=['[email protected]'])),
+ 'tcontributor <[email protected]>',
+ )
+ self.assertEqual(
+ str(User(name='Tim Contributor', emails=['[email protected]'])),
+ 'Tim Contributor <[email protected]>',
+ )
+
+ def test_constructor(self):
+ usr = User('Tim Contributor', 'tcontributor', ['[email protected]'])
+ self.assertEqual(usr.name, 'Tim Contributor')
+ self.assertEqual(usr.username, 'tcontributor')
+ self.assertEqual(usr.emails, ['[email protected]'])
+
+ def test_compare(self):
+ self.assertEqual(User('Tim Contributor', 'tcontributor'), User(username='tcontributor'))
+ self.assertEqual(User('Tim Contributor', emails=['[email protected]']), User('Tim Contributor'))
+ self.assertNotEqual(User('Tim Contributor', 'tcontributor'), User('Tim Contributor'))
+
+ def test_json(self):
+ self.assertEqual(
+ User.Encoder().default(User(name='Tim Contributor', username='tcontributor', emails=['[email protected]'])),
+ dict(name='Tim Contributor', username='tcontributor', emails=['[email protected]']),
+ )
+ self.assertEqual(
+ User.Encoder().default(User(username='tcontributor', emails=['[email protected]'])),
+ dict(username='tcontributor', emails=['[email protected]']),
+ )
+ self.assertEqual(
+ User.Encoder().default(User(name='Tim Contributor', emails=['[email protected]'])),
+ dict(name='Tim Contributor', emails=['[email protected]']),
+ )
+ self.assertEqual(
+ User.Encoder().default(User(name='Tim Contributor', username='tcontributor')),
+ dict(name='Tim Contributor', username='tcontributor'),
+ )
+
+ def test_mapping(self):
+ mapping = User.Mapping()
+ user = mapping.create(name='Tim Contributor', username='tcontributor', emails=['[email protected]'])
+ self.assertEqual(user, mapping['Tim Contributor'])
+ self.assertEqual(user, mapping['tcontributor'])
+ self.assertEqual(user, mapping['[email protected]'])
+
+ mapping.create(name='Tim Contributor', emails=['[email protected]'])
+ self.assertEqual(user, mapping['[email protected]'])
+ self.assertEqual(user.emails, ['[email protected]', '[email protected]'])
+
+ mapping.create(name='Ricky Reviewer', emails=['[email protected]'])
+ with self.assertRaises(RuntimeError):
+ mapping.create(name='Tim Contributor', emails=['[email protected]'])
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tracker.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tracker.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tracker.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,73 @@
+# Copyright (C) 2021 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 re
+
+from .user import User
+
+from webkitcorepy import decorators
+
+
+class Tracker(object):
+ REFERENCE_RE = re.compile(r'((https|http|rdar|radar)://[^\s><,\'\"}{\]\[)(]+[^\s><,\'\"}{\]\[)(\.\?])')
+
+ _trackers = []
+
+ @classmethod
+ def register(cls, tracker):
+ if tracker not in cls._trackers:
+ setattr(cls, str(type(tracker)).split('.')[-2], tracker)
+ cls._trackers.append(tracker)
+ return tracker
+
+ @classmethod
+ def instance(cls):
+ if cls._trackers:
+ return cls._trackers[0]
+ return None
+
+ def __init__(self, users=None):
+ self.users = users or User.Mapping()
+
+ @decorators.hybridmethod
+ def from_string(context, string):
+ if not isinstance(context, type):
+ raise NotImplementedError()
+ for tracker in context._trackers:
+ issue = tracker.from_string(string)
+ if issue:
+ return issue
+ return None
+
+ def user(self, name=None, username=None, email=None):
+ if not name and not username and not email:
+ raise TypeError('No name, username or email defined for user')
+ for key in [name, username, email]:
+ if key and self.users.get(key):
+ return self.users.get(key)
+ return None
+
+ def issue(self, id):
+ raise NotImplementedError()
+
+ def populate(self, issue, member=None):
+ raise NotImplementedError()
Added: trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/user.py (0 => 287686)
--- trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/user.py (rev 0)
+++ trunk/Tools/Scripts/libraries/webkitbugspy/webkitbugspy/user.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -0,0 +1,170 @@
+# Copyright (C) 2021 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 json
+import six
+
+from collections import defaultdict
+from webkitcorepy import string_utils
+
+
+class User(object):
+ class Encoder(json.JSONEncoder):
+
+ def default(self, obj):
+ if isinstance(obj, dict):
+ return {key: self.default(value) for key, value in obj.items()}
+ if isinstance(obj, list):
+ return [self.default(value) for value in obj]
+ if not isinstance(obj, User):
+ return super(User.Encoder, self).default(obj)
+
+ result = {}
+ if obj._name:
+ result['name'] = obj._name
+ if obj.emails:
+ result['emails'] = obj.emails
+ if obj.username:
+ result['username'] = obj.username
+
+ return result
+
+ class Mapping(defaultdict):
+ def __init__(self):
+ super(User.Mapping, self).__init__(lambda: None)
+
+ def add(self, user):
+ return self.create(name=user._name, username=user.username, emails=user.emails)
+
+ def create(self, name=None, username=None, emails=None):
+ matched_key = None
+ user = None
+ for key in [name, username] + (emails or []):
+ if not key:
+ continue
+ candidate = self.get(key)
+
+ if not candidate:
+ continue
+ if user and hash(user) != hash(candidate):
+ raise RuntimeError("'{}' matches '{}', but '{}' already matched '{}'".format(
+ key, candidate, matched_key, user,
+ ))
+ matched_key = key
+ user = candidate
+
+ if user:
+ if name:
+ user._name = name
+ if username:
+ user.username = username
+ for email in emails or []:
+ if email not in user.emails:
+ user.emails.append(email)
+ else:
+ user = User(name=name, username=username, emails=emails)
+
+ for key in [name, username] + (emails or []):
+ self[key] = user
+
+ return user
+
+ def __iter__(self):
+ yielded = set()
+ for user in self.values():
+ if hash(user) in yielded:
+ continue
+ yielded.add(hash(user))
+ yield user
+
+ def __init__(self, name=None, username=None, emails=None):
+ self._name = name
+ self.emails = list(filter(string_utils.decode, emails or []))
+ self.username = username
+ if not self.name:
+ raise TypeError('Not enough arguments to define user')
+
+ @property
+ def name(self):
+ if self._name:
+ return self._name
+ if self.username and isinstance(self.username, six.string_types):
+ return self.username
+ if self.email:
+ return self.email
+ if self.username:
+ return str(self.username)
+ return None
+
+ @property
+ def email(self):
+ if not self.emails:
+ return None
+ return self.emails[0]
+
+ def __hash__(self):
+ if self.username:
+ return hash(self.username)
+ if self._name:
+ return hash(self._name)
+ if self.email:
+ return hash(self.email)
+ return 0
+
+ def __repr__(self):
+ address = None
+ for candidate in [self.username, self.email]:
+ if isinstance(candidate, six.string_types) and candidate != self.name:
+ address = candidate
+ break
+ if not address:
+ return self.name
+ return u'{} <{}>'.format(self.name, address)
+
+ def __cmp__(self, other):
+ if isinstance(other, str):
+ ref_value = other
+ elif isinstance(other, User):
+ ref_value = other.username or self.name
+ else:
+ raise ValueError('Cannot compare {} with {}'.format(User, type(other)))
+ if (self.username or self.name) == ref_value:
+ return 0
+ return 1 if (self.username or self.name) > ref_value else -1
+
+ def __eq__(self, other):
+ return self.__cmp__(other) == 0
+
+ def __ne__(self, other):
+ return self.__cmp__(other) != 0
+
+ def __lt__(self, other):
+ return self.__cmp__(other) < 0
+
+ def __le__(self, other):
+ return self.__cmp__(other) <= 0
+
+ def __gt__(self, other):
+ return self.__cmp__(other) > 0
+
+ def __ge__(self, other):
+ return self.__cmp__(other) >= 0
Modified: trunk/Tools/Scripts/webkitpy/test/main.py (287685 => 287686)
--- trunk/Tools/Scripts/webkitpy/test/main.py 2022-01-06 15:57:49 UTC (rev 287685)
+++ trunk/Tools/Scripts/webkitpy/test/main.py 2022-01-06 16:23:45 UTC (rev 287686)
@@ -63,6 +63,7 @@
tester = Tester()
tester.add_tree(os.path.join(_webkit_root, 'Tools', 'Scripts'), 'webkitpy')
tester.add_tree(os.path.join(_webkit_root, 'Tools', 'Scripts', 'libraries', 'webkitcorepy'), 'webkitcorepy')
+ tester.add_tree(os.path.join(_webkit_root, 'Tools', 'Scripts', 'libraries', 'webkitbugspy'), 'webkitbugspy')
tester.add_tree(os.path.join(_webkit_root, 'Tools', 'Scripts', 'libraries', 'webkitscmpy'), 'webkitscmpy')
tester.add_tree(os.path.join(_webkit_root, 'Tools', 'Scripts', 'libraries', 'webkitflaskpy'), 'webkitflaskpy')
if sys.version_info > (3, 0):