Diff
Modified: trunk/Tools/ChangeLog (289249 => 289250)
--- trunk/Tools/ChangeLog 2022-02-08 01:13:23 UTC (rev 289249)
+++ trunk/Tools/ChangeLog 2022-02-08 01:13:32 UTC (rev 289250)
@@ -1,5 +1,37 @@
2022-02-07 Jonathan Bedard <[email protected]>
+ [webkitscmpy] Adopt webkitbugspy for GitHub issues (Part 2)
+ https://bugs.webkit.org/show_bug.cgi?id=235899
+ <rdar://problem/88280520>
+
+ Reviewed by Dewei Zhu.
+
+ * Scripts/libraries/webkitscmpy/setup.py: Add webkitbugspy dependency.
+ * Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py: Ditto.
+ * Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py:
+ (GitHub): Build on top of webkitbugspy's mock GitHub server.
+ (GitHub.__init__): Pass mock environment to base class.
+ (GitHub.request): Let webkitbugspy handle issues.
+ (GitHub.__enter__): Deleted.
+ (GitHub.__exit__): Deleted.
+ (GitHub._users): Deleted.
+ * Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py:
+ (GitHub.PRGenerator.PullRequest): Linked issue should be an "issue" object.
+ (GitHub.PRGenerator.create): Ditto.
+ (GitHub.PRGenerator.update): Ditto.
+ (GitHub.PRGenerator._contributor): Leverage webkitbugpy to retrieve information
+ about unknown contributors.
+ (GitHub.PRGenerator.comment): Leverage webkitbugspy to create comments.
+ (GitHub.PRGenerator.comments): Leverage webkitbugspy to retrieve comments.
+ (GitHub.__init__): Construct a tracker, populate it's user mapping.
+ (GitHub.credentials): Leverage webkitbugspy to retrieve credentials.
+ * Scripts/libraries/webkitscmpy/webkitscmpy/test/land_unittest.py:
+ (TestLandGitHub.webserver): Create a mock issue.
+ * Scripts/libraries/webkitscmpy/webkitscmpy/test/pull_request_unittest.py:
+ (TestNetworkPullRequestGitHub.webserver): Create a mock issue.
+
+2022-02-07 Jonathan Bedard <[email protected]>
+
[webkitscmpy] Adopt webkitbugspy for GitHub issues (Part 1)
https://bugs.webkit.org/show_bug.cgi?id=235899
<rdar://problem/88280520>
Modified: trunk/Tools/Scripts/libraries/webkitscmpy/setup.py (289249 => 289250)
--- trunk/Tools/Scripts/libraries/webkitscmpy/setup.py 2022-02-08 01:13:23 UTC (rev 289249)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/setup.py 2022-02-08 01:13:32 UTC (rev 289250)
@@ -29,7 +29,7 @@
setup(
name='webkitscmpy',
- version='3.2.0',
+ version='4.0.0',
description='Library designed to interact with git and svn repositories.',
long_description=readme(),
classifiers=[
@@ -58,7 +58,7 @@
'webkitscmpy.test',
],
scripts=['git-webkit'],
- install_requires=['fasteners', 'inspect2', 'jinja2', 'monotonic', 'webkitcorepy', 'xmltodict'],
+ install_requires=['fasteners', 'inspect2', 'jinja2', 'monotonic', 'webkitcorepy', 'webkitbugspy', 'xmltodict'],
include_package_data=True,
zip_safe=False,
)
Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py (289249 => 289250)
--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py 2022-02-08 01:13:23 UTC (rev 289249)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py 2022-02-08 01:13:32 UTC (rev 289250)
@@ -46,7 +46,7 @@
"Please install webkitcorepy with `pip install webkitcorepy --extra-index-url <package index URL>`"
)
-version = Version(3, 2, 0)
+version = Version(4, 0, 0)
AutoInstall.register(Package('fasteners', Version(0, 15, 0)))
AutoInstall.register(Package('jinja2', Version(2, 11, 3)))
@@ -53,6 +53,7 @@
AutoInstall.register(Package('monotonic', Version(1, 5)))
AutoInstall.register(Package('xmltodict', Version(0, 11, 0)))
AutoInstall.register(Package('markupsafe', Version(1, 1, 1), pypi_name='MarkupSafe'))
+AutoInstall.register(Package('webkitbugspy', Version(0, 3, 1)), local=True)
if sys.version_info < (3, 0):
AutoInstall.register(Package('inspect2', Version(0, 1, 2)))
Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py (289249 => 289250)
--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py 2022-02-08 01:13:23 UTC (rev 289249)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/mocks/remote/git_hub.py 2022-02-08 01:13:32 UTC (rev 289250)
@@ -24,16 +24,17 @@
import time
import json as jsonlib
+from webkitbugspy import mocks as bmocks
from webkitcorepy import mocks
from webkitscmpy import Commit, remote as scmremote
-class GitHub(mocks.Requests):
+class GitHub(bmocks.GitHub):
top = None
def __init__(
self, remote='github.example.com/WebKit/WebKit', datafile=None,
- default_branch='main', git_svn=False,
+ default_branch='main', git_svn=False, environment=None,
):
if not scmremote.GitHub.is_webserver('https://{}'.format(remote)):
raise ValueError('"{}" is not a valid GitHub remote'.format(remote))
@@ -41,13 +42,8 @@
self.default_branch = default_branch
self.remote = remote
self.forks = []
- 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))
+ super(GitHub, self).__init__(remote, environment=environment)
with open(datafile or os.path.join(os.path.dirname(os.path.dirname(__file__)), 'git-repo.json')) as file:
self.commits = jsonlib.load(file)
@@ -60,32 +56,7 @@
self.head = self.commits[self.default_branch][-1]
self.tags = {}
self.pull_requests = []
- self.issues = dict()
- self.users = dict()
- self._environment = None
- def __enter__(self):
- prefix = self.remote.split('/')[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 commit(self, ref):
if ref in self.commits:
return self.commits[ref][-1]
@@ -284,15 +255,6 @@
), url=""
)
- def _users(self, url, username):
- user = self.users.get(username)
- if not user:
- return mocks.Response.create404(url)
- return mocks.Response.fromJson(dict(
- name=user.name,
- email=user.email,
- ), url=""
-
def request(self, method, url, data="" params=None, auth=None, json=None, **kwargs):
from datetime import datetime, timedelta
@@ -416,11 +378,18 @@
pr['user'] = dict(login=auth.username)
pr['_links'] = dict(issue=dict(href=''.format(self.api_remote, pr['number'])))
self.pull_requests.append(pr)
- if int(pr['number']) not in self.issues:
- self.issues[int(pr['number'])] = dict(
+ if pr['number'] not in self.issues:
+ self.issues[pr['number']] = dict(
+ creator=self.users.create(username=pr['user']['login']),
+ timestamp=time.time(),
+ assignee=None,
comments=[],
- assignees=[],
)
+ self.issues[pr['number']].update(dict(
+ title=pr['title'],
+ opened=pr['state'] == 'open',
+ description=pr['body'],
+ ))
return mocks.Response.fromJson(pr, url=""
# Update specifically
@@ -433,30 +402,11 @@
if existing is None:
return mocks.Response.create404(url)
self.pull_requests[existing].update(pr)
+ self.issues[number].update(dict(
+ title=self.pull_requests[existing]['title'],
+ opened=self.pull_requests[existing]['state'] == 'open',
+ description=self.pull_requests[existing]['body'],
+ ))
return mocks.Response.fromJson(self.pull_requests[existing], url=""
- # Access user
- if method == 'GET' and stripped_url.startswith('{}/users'.format(self.api_remote.split('/')[0])):
- return self._users(url, stripped_url.split('/')[-1])
-
- # Access underlying issue
- if stripped_url.startswith('{}/issues/'.format(self.api_remote)):
- number = int(stripped_url.split('/')[5])
- issue = self.issues.get(number, dict(comments=[]))
- if method == 'GET' and stripped_url.split('/')[6] == 'comments':
- return mocks.Response.fromJson(issue['comments'], url=""
- if method == 'POST' and stripped_url.split('/')[6] == 'comments':
- self.issues[number] = issue
- now = datetime.utcfromtimestamp(int(time.time()) - timedelta(hours=7).seconds).strftime('%Y-%m-%dT%H:%M:%SZ')
- self.issues[number]['comments'].append(dict(
- user=dict(login=auth.username),
- created_at=now, updated_at=now,
- body=json.get('body', ''),
- ))
- return mocks.Response.fromJson(issue['comments'], url=""
- if method == 'POST' and stripped_url.split('/')[6] == 'assignees':
- self.issues[number]['assignees'] = {'login': name for name in json.get('assignees', [])}
- return mocks.Response.fromJson(issue['assignees'], url=""
- return mocks.Response.create404(url)
-
- return mocks.Response.create404(url)
+ return super(GitHub, self).request(method, url, data="" params=params, auth=auth, json=json, **kwargs)
Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py (289249 => 289250)
--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py 2022-02-08 01:13:23 UTC (rev 289249)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/git_hub.py 2022-02-08 01:13:32 UTC (rev 289250)
@@ -29,6 +29,8 @@
from datetime import datetime
from requests.auth import HTTPBasicAuth
+from webkitbugspy import User
+from webkitbugspy.github import Tracker
from webkitcorepy import decorators
from webkitscmpy import Commit, Contributor, PullRequest
from webkitscmpy.remote.scm import Scm
@@ -43,6 +45,7 @@
def PullRequest(self, data):
if not data:
return None
+ issue_ref = data.get('_links', {}).get('issue', {}).get('href')
return PullRequest(
number=data['number'],
title=data.get('title'),
@@ -56,7 +59,7 @@
).get(data.get('state'), None),
generator=self,
metadata=dict(
- issue=data.get('_links', {}).get('issue', {}).get('href'),
+ issue=self.repository.tracker.from_string(issue_ref) if issue_ref else None,
), url=''.format(self.repository.url, data['number']),
)
@@ -107,14 +110,8 @@
return None
result = self.PullRequest(response.json())
- # FIXME: Move this to bug tracking library
issue = result._metadata.get('issue')
- if not issue or requests.post(
- '{}/assignees'.format(issue),
- auth=HTTPBasicAuth(*self.repository.credentials()),
- headers=dict(Accept='application/vnd.github.v3+json'),
- json=dict(assignees=[user]),
- ).status_code // 100 != 2:
+ if not issue or not issue.tracker or not issue.assign(issue.tracker.me()):
sys.stderr.write("Failed to assign '{}' to '{}'\n".format(result, user))
return result
@@ -164,21 +161,16 @@
closed=False,
).get(data.get('state'), None)
pull_request.generator = self
+ issue_ref = data.get('_links', {}).get('issue', {}).get('href')
pull_request._metadata = dict(
- issue=data.get('_links', {}).get('issue', {}).get('href'),
+ issue=self.repository.tracker.from_string(issue_ref) if issue_ref else None,
)
- # FIXME: Move this to bug tracking library
assignees = [node.get('login') for node in data.get('assignees', []) if node.get('login')]
if user not in assignees:
issue = pull_request._metadata.get('issue')
- if not issue or requests.post(
- '{}/assignees'.format(issue),
- auth=HTTPBasicAuth(*self.repository.credentials()),
- headers=dict(Accept='application/vnd.github.v3+json'),
- json=dict(assignees=assignees + [user]),
- ).status_code // 100 != 2:
- sys.stderr.write("Failed to assign '{}' to '{}'\n".format(pull_request, user))
+ if not issue or not issue.tracker or not issue.assign(issue.tracker.me()):
+ sys.stderr.write("Failed to assign '{}' to '{}'\n".format(result, user))
return pull_request
@@ -187,18 +179,11 @@
if result:
return result
- response = requests.get(
- '{api_url}/users/{username}'.format(
- api_url=self.repository.api_url,
- username=username,
- ), auth=HTTPBasicAuth(*self.repository.credentials(required=True)),
- headers=dict(Accept='application/vnd.github.v3+json'),
- )
- if response.status_code // 100 != 2:
- return Contributor(username)
-
- data = ""
- result = self.repository.contributors.create(data.get('name', username) or username, data.get('email'))
+ found = self.repository.tracker.user(username=username)
+ if found:
+ result = self.repository.contributors.create(found.name, found.email)
+ else:
+ result = self.repository.contributors.create(username)
result.github = username
self.repository.contributors[username] = result
return result
@@ -235,14 +220,7 @@
issue = pull_request._metadata.get('issue')
if not issue:
raise self.repository.Exception('Failed to find issue underlying pull-request')
- response = requests.post(
- '{}/comments'.format(issue),
- auth=HTTPBasicAuth(*self.repository.credentials(required=True)),
- headers=dict(Accept='application/vnd.github.v3+json'),
- json=dict(body=content),
- )
- if response.status_code // 100 != 2:
- sys.stderr.write("Failed to add comment to '{}'\n".format(pull_request))
+ issue.add_comment(content)
def comments(self, pull_request):
issue = pull_request._metadata.get('issue')
@@ -255,23 +233,11 @@
issue = pull_request._metadata.get('issue')
if not issue:
raise self.repository.Exception('Failed to find issue underlying pull-request')
- response = requests.get(
- '{}/comments'.format(issue),
- auth=HTTPBasicAuth(*self.repository.credentials()),
- headers=dict(Accept='application/vnd.github.v3+json'),
- )
- for node in response.json() if response.status_code // 100 == 2 else []:
- user = node.get('user', {}).get('login')
- if not user:
- 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()))
-
+ for comment in issue.comments:
yield PullRequest.Comment(
- author=self._contributor(user),
- timestamp=tm,
- content=node.get('body'),
+ author=self._contributor(comment.user.username),
+ timestamp=comment.timestamp,
+ content=comment.content,
)
@@ -300,30 +266,15 @@
)
self.pull_requests = self.PRGenerator(self)
+ users = User.Mapping()
+ for contributor in contributors or []:
+ if contributor.github:
+ users.create(contributor.name, contributor.github, contributor.emails)
+ self.tracker = Tracker(url, users=users)
def credentials(self, required=True):
- # FIXME: Should use webkitbugspy's impelementation
- hostname = self.url.split('/')[2]
- args = dict(
- url=""
- required=required,
- name=self.url.split('/')[2].replace('.', '_').upper(),
- prompt='''GitHub's API
-Please go to https://{host}/settings/tokens/new and generate a new 'Personal access token' via 'Developer settings'
-with 'repo' and 'workflow' access and appropriate 'Expiration' for your {host} user'''.format(host=hostname),
- key_name='token',
- )
+ return self.tracker.credentials(required=required)
- username, token = webkitcorepy.credentials(**args)
- if username and '@' in username:
- sys.stderr.write(
- "Provided username contains an '@' symbol. Please make sure to enter your GitHub username, not an email associated with the account\n")
- webkitcorepy.delete_credentials(url="" name=args['name'])
- username, token = webkitcorepy.credentials(**args)
- if username and '@' in username:
- raise ValueError("GitHub usernames cannot have '@' in them")
- return username, token
-
@property
def is_git(self):
return True
Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/land_unittest.py (289249 => 289250)
--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/land_unittest.py 2022-02-08 01:13:23 UTC (rev 289249)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/land_unittest.py 2022-02-08 01:13:32 UTC (rev 289250)
@@ -209,15 +209,19 @@
@classmethod
def webserver(cls, approved=None):
result = mocks.remote.GitHub()
- result.users = dict(
- rreviewer=Contributor('Ricky Reviewer', ['[email protected]'], github='rreviewer'),
- tcontributor=Contributor('Tim Contributor', ['[email protected]'], github='tcontributor'),
- )
+ result.users.create('Ricky Reviewer', 'rreviewer', ['[email protected]'])
+ result.users.create('Tim Contributor', 'tcontributor', ['[email protected]'])
result.issues = {
1: dict(
+ number=1,
+ opened=True,
+ title='Example Change',
+ description='?',
+ creator=result.users.create(name='Tim Contributor', username='tcontributor'),
+ timestamp=1639536160,
+ assignee=None,
comments=[],
- assignees=[],
- )
+ ),
}
result.pull_requests = [dict(
number=1,
Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/pull_request_unittest.py (289249 => 289250)
--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/pull_request_unittest.py 2022-02-08 01:13:23 UTC (rev 289249)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/pull_request_unittest.py 2022-02-08 01:13:32 UTC (rev 289250)
@@ -25,6 +25,7 @@
import sys
import unittest
+from webkitbugspy import User
from webkitcorepy import OutputCapture, testing, log as wcplog
from webkitcorepy.mocks import Terminal as MockTerminal
from webkitscmpy import Contributor, Commit, PullRequest, local, program, mocks, remote, log as wsplog
@@ -620,17 +621,21 @@
@classmethod
def webserver(cls):
result = mocks.remote.GitHub()
- result.users = dict(
- ereviewer=Contributor('Eager Reviewer', ['[email protected]'], github='ereviewer'),
- rreviewer=Contributor('Reluctant Reviewer', ['[email protected]'], github='rreviewer'),
- sreviewer=Contributor('Suspicious Reviewer', ['[email protected]'], github='sreviewer'),
- tcontributor=Contributor('Tim Contributor', ['[email protected]']),
- )
+ result.users.create('Eager Reviewer', 'ereviewer', ['[email protected]'])
+ result.users.create('Reluctant Reviewer', 'rreviewer', ['[email protected]'])
+ result.users.create('Suspicious Reviewer', 'sreviewer', ['[email protected]'])
+ result.users.create('Tim Contributor', 'tcontributor', ['[email protected]'])
result.issues = {
1: dict(
+ number=1,
+ opened=True,
+ title='Example Change',
+ description='?',
+ creator=result.users.create(name='Tim Contributor', username='tcontributor'),
+ timestamp=1639536160,
+ assignee=None,
comments=[],
- assignees=[],
- )
+ ),
}
result.pull_requests = [dict(
number=1,