|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +from ...exceptions import ResourceNotFoundError |
| 4 | +from ..service import register_target, RepositoryService |
| 5 | + |
| 6 | +from gerritclient import client |
| 7 | +from gerritclient.error import HTTPError |
| 8 | + |
| 9 | +@register_target('gerrit', 'gerrit') |
| 10 | +class GerritService(RepositoryService): |
| 11 | + fqdn = 'review.gerrithub.io' |
| 12 | + auth_type = 'basic' |
| 13 | + ssh_port = 29418 |
| 14 | + _max_nested_namespaces = 99 |
| 15 | + _min_nested_namespaces = 0 |
| 16 | + ro_suffix = '' |
| 17 | + |
| 18 | + def create_connection(self): |
| 19 | + self.connection = client.connect(self.url_ro, auth_type=self.auth_type, |
| 20 | + username=self._username, password=self._privatekey) |
| 21 | + self._session = self.connection.session |
| 22 | + |
| 23 | + def connect(self): |
| 24 | + if not hasattr(self, 'connection'): |
| 25 | + self.create_connection() |
| 26 | + self.server_client = client.get_client('server', connection=self.connection) |
| 27 | + self.project_client = client.get_client('project', connection=self.connection) |
| 28 | + self.change_client = client.get_client('change', connection=self.connection) |
| 29 | + |
| 30 | + try: |
| 31 | + self.server_client.get_version() |
| 32 | + except HTTPError as err: |
| 33 | + if not self._username or not self._privatekey: |
| 34 | + raise ConnectionError('Could not connect to Gerrit. ' |
| 35 | + 'Please configure .gitconfig ' |
| 36 | + 'with your gerrit username and HTTP password.') from err |
| 37 | + else: |
| 38 | + raise ConnectionError('Could not connect to Gerrit. ' |
| 39 | + 'Please check your configuration and try again.') from err |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def get_auth_token(self, login, password, prompt=None): |
| 43 | + # HTTP password is used as auth token |
| 44 | + return password |
| 45 | + |
| 46 | + def load_configuration(self, c, hc=[]): |
| 47 | + super(GerritService, self).load_configuration(c, hc) |
| 48 | + self.ssh_port = c.get('ssh-port', self.ssh_port) |
| 49 | + self.auth_type = c.get('auth-type', self.auth_type) |
| 50 | + self.ro_suffix = c.get('ro-suffix', self.ro_suffix) |
| 51 | + |
| 52 | + @property |
| 53 | + def session(self): |
| 54 | + if not hasattr(self, '_session'): |
| 55 | + self.create_connection() |
| 56 | + return self._session |
| 57 | + |
| 58 | + @property |
| 59 | + def git_user(self): |
| 60 | + return self._username |
| 61 | + |
| 62 | + @property |
| 63 | + def url_ro(self): |
| 64 | + '''Property that returns the HTTP URL of the service''' |
| 65 | + return self.build_url(self) + self.ro_suffix |
| 66 | + |
| 67 | + @property |
| 68 | + def url_rw(self): |
| 69 | + return 'ssh://{}@{}:{}'.format(self.git_user, self.ssh_url, self.ssh_port) |
| 70 | + |
| 71 | + def repo_name(self, namespace, repo): |
| 72 | + if namespace: |
| 73 | + return '{}/{}'.format(namespace, repo) |
| 74 | + else: |
| 75 | + return repo |
| 76 | + |
| 77 | + def get_repository(self, namespace, repo): |
| 78 | + if namespace is not None: |
| 79 | + return self.project_client.get_by_name(self.repo_name(namespace, repo)) |
| 80 | + else: |
| 81 | + return self.project_client.get_by_name(repo) |
| 82 | + |
| 83 | + def get_project_default_branch(self, project): |
| 84 | + branches = self.project_client.get_branches(project['name']) |
| 85 | + for branch in branches: |
| 86 | + if branch['ref'] == 'HEAD': |
| 87 | + return branch['revision'] |
| 88 | + |
| 89 | + def is_repository_empty(self, project): |
| 90 | + # There is no way to find out if repository is empty, so always return False |
| 91 | + return False |
| 92 | + |
| 93 | + def get_parent_project_url(self, namespace, repo, rw=True): |
| 94 | + # Gerrit parent project concept is quite different from other services, |
| 95 | + # so it is better to always return None here |
| 96 | + return None |
| 97 | + |
| 98 | + def request_create(self, onto_user, onto_repo, from_branch, onto_branch=None, title=None, description=None, auto_slug=False, edit=None): |
| 99 | + from_branch = from_branch or self.repository.active_branch.name |
| 100 | + onto_branch = onto_branch or 'HEAD:refs/for/' + from_branch |
| 101 | + remote = self.repository.remote(self.name) |
| 102 | + info, lines = self.push(remote, onto_branch) |
| 103 | + new_changes = [] |
| 104 | + new_changes_lines = False |
| 105 | + for line in lines: |
| 106 | + if line.startswith('remote:'): |
| 107 | + line = line[len('remote:'):].strip() |
| 108 | + |
| 109 | + if 'New Changes' in line: |
| 110 | + new_changes_lines = True |
| 111 | + |
| 112 | + if new_changes_lines and self.fqdn in line: |
| 113 | + url = line.split(' ')[0] |
| 114 | + new_changes.append(url) |
| 115 | + |
| 116 | + if len(new_changes) > 0: |
| 117 | + yield '{}' |
| 118 | + yield ['Created new review request of `{local}` onto `{project}:{remote}`'.format( |
| 119 | + local = from_branch, |
| 120 | + project = '/'.join([onto_user, onto_repo]), |
| 121 | + remote = onto_branch |
| 122 | + )] |
| 123 | + for url in new_changes: |
| 124 | + yield ['with changeset {} available at {}'.format(url, url.split('/')[-1])] |
| 125 | + else: |
| 126 | + yield '{}' |
| 127 | + yield ['Review request of `{local}` was not created'.format( |
| 128 | + local = from_branch |
| 129 | + )] |
| 130 | + for element in info: |
| 131 | + yield ['{} -> {}: {}'.format(element.local_ref, element.remote_ref_string, element.summary)] |
| 132 | + |
| 133 | + def request_fetch(self, user, repo, request, pull=False, force=False): |
| 134 | + if 'refs/changes/' not in request: |
| 135 | + if '/' in request: |
| 136 | + change_id, patch_set = request.split('/') |
| 137 | + else: |
| 138 | + change_id = request |
| 139 | + change = self.change_client.get_all(['change: {}'.format(change_id)], ['CURRENT_REVISION'])[0] |
| 140 | + current_patchset = change['revisions'][change['current_revision']] |
| 141 | + patch_set = current_patchset['_number'] |
| 142 | + |
| 143 | + if change_id[0] == 'I': |
| 144 | + change_id = str(self.change_client.get_by_id(request)['_number']) |
| 145 | + |
| 146 | + request = 'refs/changes/{}/{}/{}'.format(change_id[-2:], change_id, patch_set) |
| 147 | + else: |
| 148 | + change_id = request.split('/')[3] |
| 149 | + |
| 150 | + try: |
| 151 | + remote = self.repository.remote(self.name) |
| 152 | + except ValueError as err: |
| 153 | + raise Exception('Remote "{remote}" is not setup. Please run `git {remote} add`'.format(remote=self.name)) |
| 154 | + local_branch_name = 'requests/{}/{}'.format(self.name, change_id) |
| 155 | + self.fetch(remote, request, local_branch_name, force=force) |
| 156 | + |
| 157 | + return local_branch_name |
| 158 | + |
| 159 | + def request_list(self, user, repo): |
| 160 | + project = self.repo_name(user, repo) |
| 161 | + changes = self.change_client.get_all(['project:{} status:open'.format(project)]) |
| 162 | + |
| 163 | + yield "{}\t{}\t{:<60}\t{}" |
| 164 | + yield ['id', 'branch', 'subject', 'url'] |
| 165 | + for change in changes: |
| 166 | + yield [change['_number'], change['branch'], change['subject'], '{}/{}'.format(self.url_ro, change['_number'])] |
0 commit comments