Title: [292937] trunk
Revision
292937
Author
[email protected]
Date
2022-04-15 18:59:43 -0700 (Fri, 15 Apr 2022)

Log Message

[git-webkit] Allow projects to declare alternate remotes
https://bugs.webkit.org/show_bug.cgi?id=239261
<rdar://problem/91654752>

Reviewed by Dewei Zhu.

* Tools/Scripts/libraries/webkitscmpy/setup.py: Bump verison.
* Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py: Ditto.
* Tools/Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py:
(Git.remote): Move logic to remote.Scm.from_url.
* Tools/Scripts/libraries/webkitscmpy/webkitscmpy/program/setup.py:
(Setup.github): Allow user to specify trailing remote name.
(Setup._add_remote): Add a remote or modify exising remote.
(Setup._fork_remote): Determine a remote url based on origin url.
(Setup.git): If the project declares remotes, check if the user is using the righ origin. Warn them
if they are not. Check if the user has access to alternate remotes, if they do, add those remotes
and create forks for them. Fetch all fork remotes. Do not fork repository if origin does not match
declared origin.
* Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py:
(Scm.from_url): Moved logic from local.Git.remote.
* Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/setup_unittest.py:
* metadata/git_config_extension: Add expected remotes.

Canonical link: https://commits.webkit.org/249702@main

Modified Paths

Diff

Modified: trunk/ChangeLog (292936 => 292937)


--- trunk/ChangeLog	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/ChangeLog	2022-04-16 01:59:43 UTC (rev 292937)
@@ -1,3 +1,13 @@
+2022-04-12  Jonathan Bedard  <[email protected]>
+
+        [git-webkit] Allow projects to declare alternate remotes
+        https://bugs.webkit.org/show_bug.cgi?id=239261
+        <rdar://problem/91654752>
+
+        Reviewed by Dewei Zhu.
+
+        * metadata/git_config_extension: Add expected remotes.
+
 2022-04-15  Justin Michaud  <[email protected]>
 
         Add GitHub info to contributors.json

Modified: trunk/Tools/ChangeLog (292936 => 292937)


--- trunk/Tools/ChangeLog	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/Tools/ChangeLog	2022-04-16 01:59:43 UTC (rev 292937)
@@ -1,3 +1,27 @@
+2022-04-12  Jonathan Bedard  <[email protected]>
+
+        [git-webkit] Allow projects to declare alternate remotes
+        https://bugs.webkit.org/show_bug.cgi?id=239261
+        <rdar://problem/91654752>
+
+        Reviewed by Dewei Zhu.
+
+        * Scripts/libraries/webkitscmpy/setup.py: Bump verison.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py: Ditto.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py:
+        (Git.remote): Move logic to remote.Scm.from_url.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/program/setup.py:
+        (Setup.github): Allow user to specify trailing remote name.
+        (Setup._add_remote): Add a remote or modify exising remote.
+        (Setup._fork_remote): Determine a remote url based on origin url.
+        (Setup.git): If the project declares remotes, check if the user is using the righ origin. Warn them
+        if they are not. Check if the user has access to alternate remotes, if they do, add those remotes
+        and create forks for them. Fetch all fork remotes. Do not fork repository if origin does not match
+        declared origin.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py:
+        (Scm.from_url): Moved logic from local.Git.remote.
+        * Scripts/libraries/webkitscmpy/webkitscmpy/test/setup_unittest.py:
+
 2022-04-15  Yusuke Suzuki  <[email protected]>
 
         [JSC] Remove VM& parameter from structure related code including jsDyamicCast

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/setup.py (292936 => 292937)


--- trunk/Tools/Scripts/libraries/webkitscmpy/setup.py	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/setup.py	2022-04-16 01:59:43 UTC (rev 292937)
@@ -29,7 +29,7 @@
 
 setup(
     name='webkitscmpy',
-    version='4.9.3',
+    version='4.10.0',
     description='Library designed to interact with git and svn repositories.',
     long_description=readme(),
     classifiers=[

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py (292936 => 292937)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/__init__.py	2022-04-16 01:59:43 UTC (rev 292937)
@@ -46,7 +46,7 @@
         "Please install webkitcorepy with `pip install webkitcorepy --extra-index-url <package index URL>`"
     )
 
-version = Version(4, 9, 3)
+version = Version(4, 10, 0)
 
 AutoInstall.register(Package('fasteners', Version(0, 15, 0)))
 AutoInstall.register(Package('jinja2', Version(2, 11, 3)))

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


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/local/git.py	2022-04-16 01:59:43 UTC (rev 292937)
@@ -482,18 +482,11 @@
         elif http_match:
             url = ''.format(http_match.group('protocol'), http_match.group('host'), http_match.group('path'))
 
-        if remote.GitHub.is_webserver(url):
-            return remote.GitHub(url, contributors=self.contributors)
-        if 'bitbucket' in url or 'stash' in url:
-            match = re.match(r'(?P<protocol>https?)://(?P<host>.+)/(?P<project>.+)/(?P<repo>.+)', url)
-            return remote.BitBucket(
-                '{}://{}/projects/{}/repos/{}'.format(
-                    match.group('protocol'),
-                    match.group('host'),
-                    match.group('project').upper(),
-                    match.group('repo'),
-                ), contributors=self.contributors,
-            )
+        try:
+            return remote.Scm.from_url(url)
+        except OSError:
+            pass
+
         return None
 
     def _commit_count(self, native_parameter):

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/program/setup.py (292936 => 292937)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/program/setup.py	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/program/setup.py	2022-04-16 01:59:43 UTC (rev 292937)
@@ -20,6 +20,7 @@
 # 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 getpass
 import os
 import requests
 import sys
@@ -26,7 +27,7 @@
 
 from .command import Command
 from requests.auth import HTTPBasicAuth
-from webkitcorepy import arguments, run, Editor, Terminal
+from webkitcorepy import arguments, run, Editor, OutputCapture, Terminal
 from webkitscmpy import log, local, remote
 
 
@@ -35,7 +36,7 @@
     help = 'Configure local settings for the current repository'
 
     @classmethod
-    def github(cls, args, repository, additional_setup=None, **kwargs):
+    def github(cls, args, repository, additional_setup=None, remote=None, **kwargs):
         log.info('Saving GitHub credentials in system credential store...')
         username, access_token = repository.credentials(required=True, validate=True, save_in_keyring=True)
         log.info('GitHub credentials saved via Keyring!')
@@ -45,12 +46,13 @@
         if additional_setup:
             result += additional_setup(args, repository)
 
+        forked_name = '{}{}'.format(repository.name, '-{}'.format(remote) if remote else '')
         log.info('Verifying user owned fork...')
         auth = HTTPBasicAuth(username, access_token)
         response = requests.get('{}/repos/{}/{}'.format(
             repository.api_url,
             username,
-            repository.name,
+            forked_name,
         ), auth=auth, headers=dict(Accept='application/vnd.github.v3+json'))
         if response.status_code == 200:
             log.info("User already owns a fork of '{}'!".format(repository.name))
@@ -57,10 +59,10 @@
             return result
 
         if repository.owner == username or args.defaults or Terminal.choose(
-            "Create a private fork of '{}' belonging to '{}'".format(repository.name, username),
+            "Create a private fork of '{}' belonging to '{}'".format(forked_name, username),
             default='Yes',
         ) == 'No':
-            log.info("Continuing without forking '{}'".format(repository.name))
+            log.info("Continuing without forking '{}'".format(forked_name))
             return 1
 
         response = requests.post('{}/repos/{}/{}/forks'.format(
@@ -69,16 +71,56 @@
             repository.name,
         ), json=dict(
             owner=username,
-            description="{}'s fork of {}".format(username, repository.name),
+            description="{}'s fork of {}{}".format(username, repository.name, ' ({})'.format(remote) if remote else ''),
             private=True,
         ), auth=auth, headers=dict(Accept='application/vnd.github.v3+json'))
         if response.status_code not in (200, 202):
-            sys.stderr.write("Failed to create a fork of '{}' belonging to '{}'\n".format(repository.name, username))
+            sys.stderr.write("Failed to create a fork of '{}' belonging to '{}'\n".format(forked_name, username))
             return 1
-        log.info("Created a private fork of '{}' belonging to '{}'!".format(repository.name, username))
+
+        set_name = response.json().get('name', '')
+        if set_name and set_name != forked_name:
+            response = requests.patch('{}/repos/{}/{}'.format(
+                repository.api_url,
+                username,
+                set_name,
+            ), json=dict(
+                name=forked_name
+            ), auth=auth, headers=dict(Accept='application/vnd.github.v3+json'))
+            if response.status_code not in (200, 202):
+                sys.stderr.write("Fork created with name '{}' belonging to '{}'\n Failed to change name to {}\n".format(set_name, username, forked_name))
+                return 1
+
+        log.info("Created a private fork of '{}' belonging to '{}'!".format(forked_name, username))
         return result
 
     @classmethod
+    def _add_remote(cls, repository, name, url):
+        returncode = run(
+            [repository.executable(), 'remote', 'add', name, url],
+            capture_output=True, cwd=repository.root_path,
+        ).returncode
+        if returncode == 3:
+            returncode = run(
+                [repository.executable(), 'remote', 'set-url', name, url],
+                capture_output=True, cwd=repository.root_path,
+            ).returncode
+        if returncode:
+            sys.stderr.write("Failed to add remote '{}'\n".format(name))
+            return 1
+
+        log.info("Added remote '{}'".format(name))
+        return 0
+
+    @classmethod
+    def _fork_remote(cls, origin, username, name):
+        if '://' in origin:
+            return '{}://{}/{}/{}.git'.format(origin.split(':')[0], origin.split('/')[2], username, name)
+        elif ':' in origin:
+            return '{}:{}/{}.git'.format(origin.split(':')[0], username, name)
+        return None
+
+    @classmethod
     def git(cls, args, repository, additional_setup=None, hooks=None, **kwargs):
         local_config = repository.config()
         global_config = local.Git.config()
@@ -268,50 +310,110 @@
 
         # Only configure GitHub if the URL is a GitHub URL
         rmt = repository.remote()
-        if not isinstance(rmt, remote.GitHub):
-            return result
+        available_remotes = []
+        if isinstance(rmt, remote.GitHub):
+            forking = True
+            username, _ = rmt.credentials(required=True, validate=True, save_in_keyring=True)
+        else:
+            forking = False
+            username = getpass.getuser()
 
-        code = cls.github(args, rmt, **kwargs)
-        result += code
-        if code:
-            return result
+        # Check and configure alternate remotes
+        project_remotes = {}
+        for config_arg, url in repository.config().items():
+            if not config_arg.startswith('webkitscmpy.remotes'):
+                continue
 
-        username, _ = rmt.credentials(required=True, validate=True, save_in_keyring=True)
-        log.info("Adding forked remote as '{}' and 'fork'...".format(username))
-        url = ""
+            for match in [repository.SSH_REMOTE.match(url), repository.HTTP_REMOTE.match(url)]:
+                if not match:
+                    continue
+                project_remotes[config_arg.split('.')[-1]] = [
+                    'https://{}/{}.git'.format(match.group('host'), match.group('path')),
+                    'http://{}/{}.git'.format(match.group('host'), match.group('path')),
+                    'git@{}:{}.git'.format(match.group('host'), match.group('path')),
+                    'ssh://{}:{}.git'.format(match.group('host'), match.group('path')),
+                ]
+                break
+            else:
+                project_remotes[config_arg.split('.')[-1]] = [url]
 
-        if '://' in url:
-            fork_remote = '{}://{}/{}/{}.git'.format(url.split(':')[0], url.split('/')[2], username, rmt.name)
-        elif ':' in url:
-            fork_remote = '{}:{}/{}.git'.format(url.split(':')[0], username, rmt.name)
+        protocol = repository.url().split('://')[0] + '://'
+        if '@' in protocol:
+            protocol = protocol.split('@')[0] + '@'
+        if not project_remotes.get('origin') or repository.url() in project_remotes['origin']:
+            for name, urls in project_remotes.items():
+                if name == 'origin' or not urls:
+                    continue
+
+                # We can check via the remote if the current user has access
+                nw_rmt = None
+                if urls[0].startswith('http'):
+                    try:
+                        nw_rmt = remote.Scm.from_url(urls[0][:-4])
+                        with OutputCapture():
+                            nw_rmt.default_branch
+                    except RuntimeError:
+                        log.info('{} does not have access to {}'.format(username, urls[0]))
+                        continue
+                    except OSError:
+                        pass
+
+                remote_to_add = urls[0]
+                for url in urls:
+                    if url.startswith(protocol):
+                        remote_to_add = url
+                        break
+                if cls._add_remote(repository, name, remote_to_add):
+                    result += 1
+                else:
+                    available_remotes.append(name)
+                if not isinstance(nw_rmt, remote.GitHub):
+                    continue
+                if cls.github(args, nw_rmt, remote=name):
+                    result += 1
+                    continue
+                log.info("Adding forked {remote} remote as '{username}-{remote}' and '{remote}-fork'...".format(
+                    remote=name, username=username,
+                ))
+                for fork_name in ['{}-{}'.format(username, name), '{}-fork'.format(name)]:
+                    if cls._add_remote(repository, fork_name, cls._fork_remote(repository.url(), username, '{}-{}'.format(rmt.name, name))):
+                        result += 1
+                    else:
+                        available_remotes.append(fork_name)
+
         else:
+            warning = '''Checkout using {actual} as origin remote
+Project defines {expected} as its origin remote
+Automation may create pull requests and forks in unexpected locations
+'''.format(actual=repository.url(), expected=project_remotes['origin'][0])
+
+            if forking:
+                forking = Terminal.choose('{}Are you sure you want to set up a fork?\n'.format(warning), default='No')
+            else:
+                sys.stderr.write(warning)
+
+        if not forking:
+            return result
+
+        if cls.github(args, rmt, **kwargs):
             return result + 1
 
-        available_remotes = []
+        log.info("Adding forked remote as '{}' and 'fork'...".format(username))
         for name in [username, 'fork']:
-            returncode = run(
-                [repository.executable(), 'remote', 'add', name, fork_remote],
-                capture_output=True, cwd=repository.root_path,
-            ).returncode
-            if returncode == 3:
-                returncode = run(
-                    [repository.executable(), 'remote', 'set-url', name, fork_remote],
-                    capture_output=True, cwd=repository.root_path,
-                ).returncode
-            if returncode:
-                sys.stderr.write("Failed to add remote '{}'\n".format(name))
+            if cls._add_remote(repository, name, cls._fork_remote(repository.url(), username, rmt.name)):
                 result += 1
             else:
                 available_remotes.append(name)
-                log.info("Added remote '{}'".format(name))
 
-        if 'fork' not in available_remotes:
-            return result
-        log.info("Fetching '{}'".format(fork_remote))
-        return run(
-            [repository.executable(), 'fetch', 'fork'],
-            capture_output=True, cwd=repository.root_path,
-        ).returncode
+        for rem in available_remotes:
+            if 'fork' not in rem:
+                continue
+            log.info("Fetching '{}'".format(rem))
+            result += run(
+                [repository.executable(), 'fetch', rem],
+                capture_output=True, cwd=repository.root_path,
+            ).returncode
+        return result
 
     @classmethod
     def parser(cls, parser, loggers=None):

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


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/remote/scm.py	2022-04-16 01:59:43 UTC (rev 292937)
@@ -20,6 +20,7 @@
 # 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
 import six
 
 from webkitscmpy.scm_base import ScmBase
@@ -58,6 +59,15 @@
     def from_url(cls, url, contributors=None):
         from webkitscmpy import remote
 
+        if 'bitbucket' in url or 'stash' in url:
+            match = re.match(r'(?P<protocol>https?)://(?P<host>.+)/(?P<project>.+)/(?P<repo>.+)', url)
+            url = ''.format(
+                match.group('protocol'),
+                match.group('host'),
+                match.group('project').upper(),
+                match.group('repo'),
+            )
+
         for candidate in [remote.Svn, remote.GitHub, remote.BitBucket]:
             if candidate.is_webserver(url):
                 return candidate(url, contributors=contributors)

Modified: trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/setup_unittest.py (292936 => 292937)


--- trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/setup_unittest.py	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/Tools/Scripts/libraries/webkitscmpy/webkitscmpy/test/setup_unittest.py	2022-04-16 01:59:43 UTC (rev 292937)
@@ -76,7 +76,6 @@
         )
 
     def test_git(self):
-        self.maxDiff = None
         with OutputCapture(level=logging.INFO) as captured, mocks.local.Git(self.path) as repo, \
             mocks.local.Svn(), wkmocks.Environment(EMAIL_ADDRESS=''):
 
@@ -116,6 +115,7 @@
         )
 
     def test_github_checkout(self):
+        self.maxDiff = None
         with OutputCapture(level=logging.INFO) as captured, mocks.remote.GitHub() as remote, \
             MockTerminal.input('n', 'n', '[email protected]', 'n', 'Committer', 's', 'overwrite', 'disabled', '1', 'y'), \
             mocks.local.Git(self.path, remote='https://{}.git'.format(remote.remote)) as repo, \
@@ -180,7 +180,7 @@
 Adding forked remote as 'username' and 'fork'...
 Added remote 'username'
 Added remote 'fork'
-Fetching 'https://github.example.com/username/WebKit.git'
+Fetching 'fork'
 '''.format(repository=self.path),
         )
 

Modified: trunk/metadata/git_config_extension (292936 => 292937)


--- trunk/metadata/git_config_extension	2022-04-16 01:16:56 UTC (rev 292936)
+++ trunk/metadata/git_config_extension	2022-04-16 01:59:43 UTC (rev 292937)
@@ -4,3 +4,6 @@
         pull-request = append
         history = disabled
         update-fork = true
+[webkitscmpy "remotes"]
+        origin = [email protected]:WebKit/WebKit.git
+        apple = [email protected]:apple/WebKit.git
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to