/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
1
# Copyright (C) 2007-2018 Jelmer Vernooij <jelmer@jelmer.uk>
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
0.358.1 by Jelmer Vernooij
Fix FSF address.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
16
0.358.3 by Jelmer Vernooij
Enable absolute import.
17
"""Remote dirs, repositories and branches."""
18
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
19
import gzip
7404.5.3 by Jelmer Vernooij
Reuse connections.
20
from io import BytesIO
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
21
import re
22
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
23
from .. import (
0.200.596 by Jelmer Vernooij
Import RemoteGitBranch._get_config().
24
    config,
0.200.707 by Jelmer Vernooij
Add debug routines.
25
    debug,
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
26
    errors,
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
27
    osutils,
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
28
    trace,
0.200.333 by Jelmer Vernooij
Support progress reporting when creating index.
29
    ui,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
30
    urlutils,
31
    )
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
32
from ..push import (
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
33
    PushResult,
34
    )
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
35
from ..errors import (
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
36
    AlreadyBranchError,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
37
    BzrError,
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
38
    DivergedBranches,
0.200.1412 by Jelmer Vernooij
Implement GitControlDirFormat.supports_transport.
39
    InProcessTransport,
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
40
    InvalidRevisionId,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
41
    NoSuchFile,
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
42
    NoSuchRevision,
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
43
    NoSuchTag,
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
44
    NotBranchError,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
45
    NotLocalUrl,
7103.1.2 by Jelmer Vernooij
Handle PermissionDenied.
46
    PermissionDenied,
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
47
    UninitializableFormat,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
48
    )
7484.1.2 by Jelmer Vernooij
Add some tests.
49
from ..revision import NULL_REVISION
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
50
from ..revisiontree import RevisionTree
51
from ..transport import (
0.200.292 by Jelmer Vernooij
Fix formatting.
52
    Transport,
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
53
    register_urlparse_netloc_protocol,
0.200.292 by Jelmer Vernooij
Fix formatting.
54
    )
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
55
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
56
from . import (
0.200.292 by Jelmer Vernooij
Fix formatting.
57
    lazy_check_versions,
7359.1.1 by Jelmer Vernooij
Only set user agent for GitHub.
58
    is_github_url,
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
59
    user_agent_for_github,
0.200.292 by Jelmer Vernooij
Fix formatting.
60
    )
0.200.200 by Jelmer Vernooij
Register lazily where possible.
61
lazy_check_versions()
62
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
63
from .branch import (
0.200.292 by Jelmer Vernooij
Fix formatting.
64
    GitBranch,
0.295.1 by Jelmer Vernooij
Split up branch formats.
65
    GitBranchFormat,
0.403.3 by Jelmer Vernooij
Test RemoteGitDir.push_branch.
66
    GitBranchPushResult,
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
67
    GitTags,
0.406.2 by Jelmer Vernooij
Add tests.
68
    _quick_lookup_revno,
0.200.292 by Jelmer Vernooij
Fix formatting.
69
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
70
from .dir import (
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
71
    GitControlDirFormat,
72
    GitDir,
73
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
74
from .errors import (
0.200.319 by Jelmer Vernooij
Print proper error when trying unsupported operations against a git server.
75
    GitSmartRemoteNotSupported,
0.200.292 by Jelmer Vernooij
Fix formatting.
76
    NoSuchRef,
77
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
78
from .mapping import (
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
79
    mapping_registry,
80
    )
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
81
from .object_store import (
82
    get_object_store,
83
    )
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
84
from .push import (
85
    remote_divergence,
86
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
87
from .repository import (
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
88
    GitRepository,
7290.20.3 by Jelmer Vernooij
Fix tests for git/full history branches.
89
    GitRepositoryFormat,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
90
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
91
from .refs import (
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
92
    branch_name_to_ref,
0.200.1487 by Jelmer Vernooij
Use peeling.
93
    is_peeled,
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
94
    ref_to_tag_name,
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
95
    tag_name_to_ref,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
96
    )
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
97
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
98
import dulwich
99
import dulwich.client
0.200.292 by Jelmer Vernooij
Fix formatting.
100
from dulwich.errors import (
101
    GitProtocolError,
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
102
    HangupException,
0.200.292 by Jelmer Vernooij
Fix formatting.
103
    )
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
104
from dulwich.pack import (
105
    Pack,
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
106
    pack_objects_to_data,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
107
    )
0.403.3 by Jelmer Vernooij
Test RemoteGitDir.push_branch.
108
from dulwich.protocol import ZERO_SHA
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
109
from dulwich.refs import (
110
    DictRefsContainer,
111
    SYMREF,
112
    )
113
from dulwich.repo import (
114
    NotGitRepository,
115
    )
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
116
import os
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
117
import select
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
118
import tempfile
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
119
7479.2.1 by Jelmer Vernooij
Drop python2 support.
120
import urllib.parse as urlparse
121
from urllib.parse import splituser
0.200.1555 by Jelmer Vernooij
Remove segment parameters for http smart transports.
122
123
# urlparse only supports a limited number of schemes by default
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
124
register_urlparse_netloc_protocol('git')
125
register_urlparse_netloc_protocol('git+ssh')
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
126
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
127
from dulwich.pack import load_pack_index
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
128
0.200.143 by Jelmer Vernooij
Reoncile InterGitRepository objects.
129
0.406.1 by Jelmer Vernooij
Properly lookup revnos for brz-git push result.
130
class GitPushResult(PushResult):
131
132
    def _lookup_revno(self, revid):
0.406.2 by Jelmer Vernooij
Add tests.
133
        try:
134
            return _quick_lookup_revno(self.source_branch, self.target_branch,
7143.15.2 by Jelmer Vernooij
Run autopep8.
135
                                       revid)
0.406.2 by Jelmer Vernooij
Add tests.
136
        except GitSmartRemoteNotSupported:
137
            return None
0.406.1 by Jelmer Vernooij
Properly lookup revnos for brz-git push result.
138
139
    @property
140
    def old_revno(self):
141
        return self._lookup_revno(self.old_revid)
142
143
    @property
144
    def new_revno(self):
145
        return self._lookup_revno(self.new_revid)
146
147
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
148
# Don't run any tests on GitSmartTransport as it is not intended to be
0.200.181 by Jelmer Vernooij
Support setting tags.
149
# a full implementation of Transport
150
def get_test_permutations():
151
    return []
152
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
153
0.200.708 by Jelmer Vernooij
Factor out URL parsing.
154
def split_git_url(url):
0.200.709 by Jelmer Vernooij
When unpacking URLs, strip leftmost slash to match gits behaviour.
155
    """Split a Git URL.
156
157
    :param url: Git URL
158
    :return: Tuple with host, port, username, path.
159
    """
7290.38.1 by Jelmer Vernooij
Backport python3.8 support patch to breezy 3.0.
160
    parsed_url = urlparse.urlparse(url)
161
    path = urlparse.unquote(parsed_url.path)
0.246.2 by Jelmer Vernooij
Improve the fix dealing with git repo's in home directories.
162
    if path.startswith("/~"):
0.200.709 by Jelmer Vernooij
When unpacking URLs, strip leftmost slash to match gits behaviour.
163
        path = path[1:]
7290.38.1 by Jelmer Vernooij
Backport python3.8 support patch to breezy 3.0.
164
    return ((parsed_url.hostname or '', parsed_url.port, parsed_url.username, path))
0.200.708 by Jelmer Vernooij
Factor out URL parsing.
165
166
0.200.1562 by Jelmer Vernooij
Add separate exception for remote errors.
167
class RemoteGitError(BzrError):
168
0.290.1 by Jelmer Vernooij
Avoid 'message' argument in RemoteGitError; apparently it breaks some versions of Python.
169
    _fmt = "Remote server error: %(msg)s"
0.200.1562 by Jelmer Vernooij
Add separate exception for remote errors.
170
171
7103.1.1 by Jelmer Vernooij
Improved error parsing for Git branches.
172
class HeadUpdateFailed(BzrError):
173
174
    _fmt = ("Unable to update remote HEAD branch. To update the master "
175
            "branch, specify the URL %(base_url)s,branch=master.")
176
177
    def __init__(self, base_url):
178
        super(HeadUpdateFailed, self).__init__()
179
        self.base_url = base_url
180
181
0.200.1275 by Jelmer Vernooij
recognize missing repositories
182
def parse_git_error(url, message):
183
    """Parse a remote git server error and return a bzr exception.
184
185
    :param url: URL of the remote repository
186
    :param message: Message sent by the remote git server
187
    """
188
    message = str(message).strip()
7143.15.2 by Jelmer Vernooij
Run autopep8.
189
    if (message.startswith("Could not find Repository ")
190
        or message == 'Repository not found.'
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
191
            or (message.startswith('Repository ') and
192
                message.endswith(' not found.'))):
0.200.1275 by Jelmer Vernooij
recognize missing repositories
193
        return NotBranchError(url, message)
0.200.1563 by Jelmer Vernooij
Improve error message.
194
    if message == "HEAD failed to update":
7441.1.1 by Jelmer Vernooij
Add strip_segment_parameters function.
195
        base_url = urlutils.strip_segment_parameters(url)
7103.1.1 by Jelmer Vernooij
Improved error parsing for Git branches.
196
        return HeadUpdateFailed(base_url)
7103.1.2 by Jelmer Vernooij
Handle PermissionDenied.
197
    if message.startswith('access denied or repository not exported:'):
7428.1.2 by Jelmer Vernooij
Don't require head whitespace.
198
        extra, path = message.split(':', 1)
199
        return PermissionDenied(path.strip(), extra)
7131.7.4 by Jelmer Vernooij
Don't use GitLab string.
200
    if message.endswith('You are not allowed to push code to this project.'):
7131.7.2 by Jelmer Vernooij
Handle github PermissionDenied.
201
        return PermissionDenied(url, message)
7131.7.3 by Jelmer Vernooij
Handle one more error.
202
    if message.endswith(' does not appear to be a git repository'):
203
        return NotBranchError(url, message)
7379.1.1 by Jelmer Vernooij
Handle invalid repository name on GitHub.
204
    if re.match('(.+) is not a valid repository name',
205
                message.splitlines()[0]):
206
        return NotBranchError(url, message)
7131.7.2 by Jelmer Vernooij
Handle github PermissionDenied.
207
    m = re.match(r'Permission to ([^ ]+) denied to ([^ ]+)\.', message)
208
    if m:
209
        return PermissionDenied(m.group(1), 'denied to %s' % m.group(2))
0.200.1275 by Jelmer Vernooij
recognize missing repositories
210
    # Don't know, just return it to the user as-is
0.200.1562 by Jelmer Vernooij
Add separate exception for remote errors.
211
    return RemoteGitError(message)
0.200.1275 by Jelmer Vernooij
recognize missing repositories
212
213
7490.29.12 by Jelmer Vernooij
Parse stderr from remote git servers when they hang up.
214
def parse_git_hangup(url, e):
215
    """Parse the error lines from a git servers stderr on hangup.
216
217
    :param url: URL of the remote repository
218
    :param e: A HangupException
219
    """
220
    stderr_lines = getattr(e, 'stderr_lines', None)
221
    if not stderr_lines:
222
        return e
223
    interesting_lines = [
224
        line for line in stderr_lines
7490.49.4 by Jelmer Vernooij
Fix more tests.
225
        if line and line.replace(b'=', b'')]
7490.29.12 by Jelmer Vernooij
Parse stderr from remote git servers when they hang up.
226
    if len(interesting_lines) == 1:
227
        interesting_line = interesting_lines[0]
7490.49.4 by Jelmer Vernooij
Fix more tests.
228
        return parse_git_error(
229
            url, interesting_line.decode('utf-8', 'surrogateescape'))
230
    return RemoteGitError(
231
        b'\n'.join(stderr_lines).decode('utf-8', 'surrogateescape'))
7490.29.12 by Jelmer Vernooij
Parse stderr from remote git servers when they hang up.
232
233
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
234
class GitSmartTransport(Transport):
235
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
236
    def __init__(self, url, _client=None):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
237
        Transport.__init__(self, url)
0.200.708 by Jelmer Vernooij
Factor out URL parsing.
238
        (self._host, self._port, self._username, self._path) = \
239
            split_git_url(url)
0.200.707 by Jelmer Vernooij
Add debug routines.
240
        if 'transport' in debug.debug_flags:
241
            trace.mutter('host: %r, user: %r, port: %r, path: %r',
242
                         self._host, self._username, self._port, self._path)
0.200.166 by Jelmer Vernooij
don't reuse client objects.
243
        self._client = _client
0.200.1464 by Jelmer Vernooij
Warn about ignoring path segment parameters when using bzr 2.4.
244
        self._stripped_path = self._path.rsplit(",", 1)[0]
0.200.166 by Jelmer Vernooij
don't reuse client objects.
245
0.200.543 by Jelmer Vernooij
Implement GitSmartTransport.external_url().
246
    def external_url(self):
247
        return self.base
248
0.200.238 by Jelmer Vernooij
Import Transport.has().
249
    def has(self, relpath):
250
        return False
251
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
252
    def _get_client(self):
0.200.307 by Jelmer Vernooij
Support git+ssh.
253
        raise NotImplementedError(self._get_client)
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
254
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
255
    def _get_path(self):
0.200.1464 by Jelmer Vernooij
Warn about ignoring path segment parameters when using bzr 2.4.
256
        return self._stripped_path
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
257
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
258
    def get(self, path):
259
        raise NoSuchFile(path)
260
0.200.160 by Jelmer Vernooij
Implement abspath.
261
    def abspath(self, relpath):
262
        return urlutils.join(self.base, relpath)
263
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
264
    def clone(self, offset=None):
265
        """See Transport.clone()."""
266
        if offset is None:
267
            newurl = self.base
268
        else:
269
            newurl = urlutils.join(self.base, offset)
270
0.200.307 by Jelmer Vernooij
Support git+ssh.
271
        return self.__class__(newurl, self._client)
272
273
274
class TCPGitSmartTransport(GitSmartTransport):
275
0.200.332 by Jelmer Vernooij
Support activity reporting.
276
    _scheme = 'git'
277
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
278
    def _get_client(self):
0.200.307 by Jelmer Vernooij
Support git+ssh.
279
        if self._client is not None:
280
            ret = self._client
281
            self._client = None
282
            return ret
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
283
        if self._host == '':
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
284
            # return dulwich.client.LocalGitClient()
285
            return dulwich.client.SubprocessGitClient()
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
286
        return dulwich.client.TCPGitClient(
287
            self._host, self._port, report_activity=self._report_activity)
0.200.307 by Jelmer Vernooij
Support git+ssh.
288
289
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
290
class SSHSocketWrapper(object):
291
292
    def __init__(self, sock):
293
        self.sock = sock
294
295
    def read(self, len=None):
296
        return self.sock.recv(len)
297
298
    def write(self, data):
299
        return self.sock.write(data)
300
301
    def can_read(self):
302
        return len(select.select([self.sock.fileno()], [], [], 0)[0]) > 0
303
304
305
class DulwichSSHVendor(dulwich.client.SSHVendor):
306
307
    def __init__(self):
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
308
        from ..transport import ssh
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
309
        self.bzr_ssh_vendor = ssh._get_ssh_vendor()
310
311
    def run_command(self, host, command, username=None, port=None):
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
312
        connection = self.bzr_ssh_vendor.connect_ssh(
313
            username=username, password=None, port=port, host=host,
314
            command=command)
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
315
        (kind, io_object) = connection.get_sock_or_pipes()
316
        if kind == 'socket':
317
            return SSHSocketWrapper(io_object)
318
        else:
319
            raise AssertionError("Unknown io object kind %r'" % kind)
320
321
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
322
# dulwich.client.get_ssh_vendor = DulwichSSHVendor
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
323
324
0.200.307 by Jelmer Vernooij
Support git+ssh.
325
class SSHGitSmartTransport(GitSmartTransport):
326
0.200.332 by Jelmer Vernooij
Support activity reporting.
327
    _scheme = 'git+ssh'
328
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
329
    def _get_path(self):
0.200.1464 by Jelmer Vernooij
Warn about ignoring path segment parameters when using bzr 2.4.
330
        path = self._stripped_path
0.200.1318 by Jelmer Vernooij
Strip segment parameters where necessary.
331
        if path.startswith("/~/"):
332
            return path[3:]
333
        return path
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
334
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
335
    def _get_client(self):
0.200.307 by Jelmer Vernooij
Support git+ssh.
336
        if self._client is not None:
337
            ret = self._client
338
            self._client = None
339
            return ret
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
340
        location_config = config.LocationConfig(self.base)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
341
        client = dulwich.client.SSHGitClient(
342
            self._host, self._port, self._username,
343
            report_activity=self._report_activity)
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
344
        # Set up alternate pack program paths
345
        upload_pack = location_config.get_user_option('git_upload_pack')
346
        if upload_pack:
0.200.949 by Jelmer Vernooij
merge support for specifying alternative paths for git executables.
347
            client.alternative_paths["upload-pack"] = upload_pack
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
348
        receive_pack = location_config.get_user_option('git_receive_pack')
349
        if receive_pack:
0.200.949 by Jelmer Vernooij
merge support for specifying alternative paths for git executables.
350
            client.alternative_paths["receive-pack"] = receive_pack
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
351
        return client
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
352
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
353
0.295.1 by Jelmer Vernooij
Split up branch formats.
354
class RemoteGitBranchFormat(GitBranchFormat):
355
356
    def get_format_description(self):
357
        return 'Remote Git Branch'
358
359
    @property
360
    def _matchingcontroldir(self):
361
        return RemoteGitControlDirFormat()
362
0.295.2 by Jelmer Vernooij
Make RemoteGitBranchFormat uninitializeable.
363
    def initialize(self, a_controldir, name=None, repository=None,
364
                   append_revisions_only=None):
365
        raise UninitializableFormat(self)
366
0.295.1 by Jelmer Vernooij
Split up branch formats.
367
0.407.1 by Jelmer Vernooij
Improve progress reporting.
368
class DefaultProgressReporter(object):
369
370
    _GIT_PROGRESS_PARTIAL_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
371
    _GIT_PROGRESS_TOTAL_RE = re.compile(r"(.*?): (\d+)")
372
373
    def __init__(self, pb):
374
        self.pb = pb
375
376
    def progress(self, text):
7018.3.2 by Jelmer Vernooij
Fix some git tests.
377
        text = text.rstrip(b"\r\n")
378
        text = text.decode('utf-8')
7131.7.1 by Jelmer Vernooij
Handle permission denied by GitLab.
379
        if text.lower().startswith('error: '):
7018.3.2 by Jelmer Vernooij
Fix some git tests.
380
            trace.show_error('git: %s', text[len(b'error: '):])
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
381
        else:
0.407.1 by Jelmer Vernooij
Improve progress reporting.
382
            trace.mutter("git: %s", text)
383
            g = self._GIT_PROGRESS_PARTIAL_RE.match(text)
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
384
            if g is not None:
0.407.1 by Jelmer Vernooij
Improve progress reporting.
385
                (text, pct, current, total) = g.groups()
386
                self.pb.update(text, int(current), int(total))
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
387
            else:
0.407.1 by Jelmer Vernooij
Improve progress reporting.
388
                g = self._GIT_PROGRESS_TOTAL_RE.match(text)
389
                if g is not None:
390
                    (text, total) = g.groups()
391
                    self.pb.update(text, None, int(total))
392
                else:
393
                    trace.note("%s", text)
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
394
395
0.200.148 by Jelmer Vernooij
Share more infrastructure between LocalGitDir and RemoteGitDir.
396
class RemoteGitDir(GitDir):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
397
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
398
    def __init__(self, transport, format, client, client_path):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
399
        self._format = format
400
        self.root_transport = transport
401
        self.transport = transport
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
402
        self._mode_check_done = None
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
403
        self._client = client
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
404
        self._client_path = client_path
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
405
        self.base = self.root_transport.base
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
406
        self._refs = None
0.200.1335 by Jelmer Vernooij
Move _get_client.
407
0.322.1 by Jelmer Vernooij
Fix access of remote git branches.
408
    @property
409
    def _gitrepository_class(self):
410
        return RemoteGitRepository
411
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
412
    def archive(self, format, committish, write_data, progress=None,
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
413
                write_error=None, subdirs=None, prefix=None):
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
414
        if progress is None:
415
            pb = ui.ui_factory.nested_progress_bar()
416
            progress = DefaultProgressReporter(pb).progress
417
        else:
418
            pb = None
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
419
        def progress_wrapper(message):
420
            if message.startswith(b"fatal: Unknown archive format \'"):
421
                format = message.strip()[len(b"fatal: Unknown archive format '"):-1]
422
                raise errors.NoSuchExportFormat(format.decode('ascii'))
423
            return progress(message)
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
424
        try:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
425
            self._client.archive(
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
426
                self._client_path, committish, write_data, progress_wrapper,
427
                write_error,
428
                format=(format.encode('ascii') if format else None),
429
                subdirs=subdirs,
430
                prefix=(prefix.encode('utf-8') if prefix else None))
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
431
        except GitProtocolError as e:
432
            raise parse_git_error(self.transport.external_url(), e)
7490.29.12 by Jelmer Vernooij
Parse stderr from remote git servers when they hang up.
433
        except HangupException as e:
434
            raise parse_git_hangup(self.transport.external_url(), e)
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
435
        finally:
436
            if pb is not None:
437
                pb.finished()
438
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
439
    def fetch_pack(self, determine_wants, graph_walker, pack_data,
440
                   progress=None):
0.200.1335 by Jelmer Vernooij
Move _get_client.
441
        if progress is None:
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
442
            pb = ui.ui_factory.nested_progress_bar()
0.407.1 by Jelmer Vernooij
Improve progress reporting.
443
            progress = DefaultProgressReporter(pb).progress
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
444
        else:
445
            pb = None
0.200.1335 by Jelmer Vernooij
Move _get_client.
446
        try:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
447
            result = self._client.fetch_pack(
448
                self._client_path, determine_wants, graph_walker, pack_data,
449
                progress)
0.376.1 by Jelmer Vernooij
Add tests for remote operations.
450
            if result.refs is None:
451
                result.refs = {}
7143.15.2 by Jelmer Vernooij
Run autopep8.
452
            self._refs = remote_refs_dict_to_container(
453
                result.refs, result.symrefs)
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
454
            return result
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
455
        except GitProtocolError as e:
0.200.1335 by Jelmer Vernooij
Move _get_client.
456
            raise parse_git_error(self.transport.external_url(), e)
7490.29.12 by Jelmer Vernooij
Parse stderr from remote git servers when they hang up.
457
        except HangupException as e:
458
            raise parse_git_hangup(self.transport.external_url(), e)
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
459
        finally:
460
            if pb is not None:
461
                pb.finished()
0.200.1335 by Jelmer Vernooij
Move _get_client.
462
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
463
    def send_pack(self, get_changed_refs, generate_pack_data, progress=None):
464
        if progress is None:
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
465
            pb = ui.ui_factory.nested_progress_bar()
0.407.1 by Jelmer Vernooij
Improve progress reporting.
466
            progress = DefaultProgressReporter(pb).progress
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
467
        else:
468
            pb = None
7143.15.2 by Jelmer Vernooij
Run autopep8.
469
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
470
        def get_changed_refs_wrapper(remote_refs):
7484.1.2 by Jelmer Vernooij
Add some tests.
471
            if self._refs is not None:
472
                update_refs_container(self._refs, remote_refs)
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
473
            return get_changed_refs(remote_refs)
0.200.1335 by Jelmer Vernooij
Move _get_client.
474
        try:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
475
            return self._client.send_pack(
476
                self._client_path, get_changed_refs_wrapper,
477
                generate_pack_data, progress)
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
478
        except GitProtocolError as e:
0.200.1335 by Jelmer Vernooij
Move _get_client.
479
            raise parse_git_error(self.transport.external_url(), e)
7490.29.12 by Jelmer Vernooij
Parse stderr from remote git servers when they hang up.
480
        except HangupException as e:
481
            raise parse_git_hangup(self.transport.external_url(), e)
0.405.1 by Jelmer Vernooij
Use same logic for interpreting progress reports everywhere.
482
        finally:
483
            if pb is not None:
484
                pb.finished()
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
485
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
486
    def create_branch(self, name=None, repository=None,
487
                      append_revisions_only=None, ref=None):
488
        refname = self._get_selected_ref(name, ref)
489
        if refname != b'HEAD' and refname in self.get_refs_container():
490
            raise AlreadyBranchError(self.user_url)
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
491
        ref_chain, unused_sha = self.get_refs_container().follow(
7484.1.2 by Jelmer Vernooij
Add some tests.
492
            self._get_selected_ref(name))
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
493
        if ref_chain and ref_chain[0] == b'HEAD':
494
            refname = ref_chain[1]
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
495
        repo = self.open_repository()
496
        return RemoteGitBranch(self, repo, refname)
497
0.200.1393 by Jelmer Vernooij
Implement removal of remote branches.
498
    def destroy_branch(self, name=None):
499
        refname = self._get_selected_ref(name)
7143.15.2 by Jelmer Vernooij
Run autopep8.
500
0.200.1393 by Jelmer Vernooij
Implement removal of remote branches.
501
        def get_changed_refs(old_refs):
7240.3.1 by Jelmer Vernooij
When sending refs to a remote server, don't send a copy of the old refs.
502
            ret = {}
7240.3.2 by Jelmer Vernooij
Fix tests.
503
            if refname not in old_refs:
0.200.1395 by Jelmer Vernooij
Fix error reporting.
504
                raise NotBranchError(self.user_url)
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
505
            ret[refname] = dulwich.client.ZERO_SHA
0.200.1393 by Jelmer Vernooij
Implement removal of remote branches.
506
            return ret
7143.15.2 by Jelmer Vernooij
Run autopep8.
507
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
508
        def generate_pack_data(have, want, ofs_delta=False):
509
            return pack_objects_to_data([])
510
        self.send_pack(get_changed_refs, generate_pack_data)
0.200.1393 by Jelmer Vernooij
Implement removal of remote branches.
511
0.200.1068 by Jelmer Vernooij
Implement user_url/control_url.
512
    @property
513
    def user_url(self):
514
        return self.control_url
515
0.200.1314 by Jelmer Vernooij
Provide RemoteGitDir.user_transport.
516
    @property
517
    def user_transport(self):
518
        return self.root_transport
519
0.200.1395 by Jelmer Vernooij
Fix error reporting.
520
    @property
521
    def control_url(self):
522
        return self.control_transport.base
523
524
    @property
525
    def control_transport(self):
526
        return self.root_transport
527
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
528
    def open_repository(self):
0.200.1415 by Jelmer Vernooij
Fix lock files for remote directories.
529
        return RemoteGitRepository(self)
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
530
7142.3.1 by Jelmer Vernooij
Support .nick on remote branches and fix get_branch_reference.
531
    def get_branch_reference(self, name=None):
532
        ref = branch_name_to_ref(name)
533
        val = self.get_refs_container().read_ref(ref)
534
        if val.startswith(SYMREF):
535
            return val[len(SYMREF):]
536
        return None
537
0.200.1310 by Jelmer Vernooij
Add _get_selected_ref method.
538
    def open_branch(self, name=None, unsupported=False,
7143.15.2 by Jelmer Vernooij
Run autopep8.
539
                    ignore_fallbacks=False, ref=None, possible_transports=None,
540
                    nascent_ok=False):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
541
        repo = self.open_repository()
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
542
        ref = self._get_selected_ref(name, ref)
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
543
        try:
544
            if not nascent_ok and ref not in self.get_refs_container():
7143.16.10 by Jelmer Vernooij
Fix E128.
545
                raise NotBranchError(
546
                    self.root_transport.base, controldir=self)
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
547
        except NotGitRepository:
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
548
            raise NotBranchError(self.root_transport.base,
7143.15.2 by Jelmer Vernooij
Run autopep8.
549
                                 controldir=self)
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
550
        ref_chain, unused_sha = self.get_refs_container().follow(ref)
551
        return RemoteGitBranch(self, repo, ref_chain[-1])
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
552
0.200.662 by Jelmer Vernooij
Deal with recommend_upgrade argument to open_workingtree.
553
    def open_workingtree(self, recommend_upgrade=False):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
554
        raise NotLocalUrl(self.transport.base)
555
0.310.4 by Jelmer Vernooij
Implement RemoteControlDir.has_workingtree.
556
    def has_workingtree(self):
557
        return False
558
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
559
    def get_peeled(self, name):
560
        return self.get_refs_container().get_peeled(name)
561
0.200.1487 by Jelmer Vernooij
Use peeling.
562
    def get_refs_container(self):
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
563
        if self._refs is not None:
564
            return self._refs
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
565
        result = self.fetch_pack(lambda x: None, None,
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
566
                                 lambda x: None,
567
                                 lambda x: trace.mutter("git: %s" % x))
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
568
        self._refs = remote_refs_dict_to_container(
7143.15.2 by Jelmer Vernooij
Run autopep8.
569
            result.refs, result.symrefs)
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
570
        return self._refs
571
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
572
    def push_branch(self, source, revision_id=None, overwrite=False,
573
                    remember=False, create_prefix=False, lossy=False,
7490.4.1 by Jelmer Vernooij
Add tag_selector support in GitRemoteDir.
574
                    name=None, tag_selector=None):
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
575
        """Push the source branch into this ControlDir."""
576
        if revision_id is None:
577
            # No revision supplied by the user, default to the branch
578
            # revision
579
            revision_id = source.last_revision()
580
0.406.1 by Jelmer Vernooij
Properly lookup revnos for brz-git push result.
581
        push_result = GitPushResult()
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
582
        push_result.workingtree_updated = None
583
        push_result.master_branch = None
584
        push_result.source_branch = source
585
        push_result.stacked_on = None
586
        push_result.branch_push_result = None
587
        repo = self.find_repository()
588
        refname = self._get_selected_ref(name)
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
589
        ref_chain, old_sha = self.get_refs_container().follow(refname)
590
        if ref_chain:
591
            actual_refname = ref_chain[-1]
592
        else:
593
            actual_refname = refname
0.407.1 by Jelmer Vernooij
Improve progress reporting.
594
        if isinstance(source, GitBranch) and lossy:
595
            raise errors.LossyPushToSameVCS(source.controldir, self)
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
596
        source_store = get_object_store(source.repository)
7289.1.2 by Jelmer Vernooij
Fix pushing of tags as part of nascent git branches.
597
        fetch_tags = source.get_config_stack().get('branch.fetch_tags')
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
598
        def get_changed_refs(remote_refs):
7484.1.2 by Jelmer Vernooij
Add some tests.
599
            if self._refs is not None:
600
                update_refs_container(self._refs, remote_refs)
7289.1.2 by Jelmer Vernooij
Fix pushing of tags as part of nascent git branches.
601
            ret = {}
602
            # TODO(jelmer): Unpeel if necessary
603
            push_result.new_original_revid = revision_id
604
            if lossy:
605
                new_sha = source_store._lookup_revision_sha1(revision_id)
606
            else:
607
                try:
608
                    new_sha = repo.lookup_bzr_revision_id(revision_id)[0]
609
                except errors.NoSuchRevision:
610
                    raise errors.NoRoundtrippingSupport(
611
                        source, self.open_branch(name=name, nascent_ok=True))
612
            if not overwrite:
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
613
                if remote_divergence(old_sha, new_sha, source_store):
7289.1.2 by Jelmer Vernooij
Fix pushing of tags as part of nascent git branches.
614
                    raise DivergedBranches(
615
                        source, self.open_branch(name, nascent_ok=True))
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
616
            ret[actual_refname] = new_sha
7289.1.2 by Jelmer Vernooij
Fix pushing of tags as part of nascent git branches.
617
            if fetch_tags:
7479.2.1 by Jelmer Vernooij
Drop python2 support.
618
                for tagname, revid in source.tags.get_tag_dict().items():
7490.4.1 by Jelmer Vernooij
Add tag_selector support in GitRemoteDir.
619
                    if tag_selector and not tag_selector(tagname):
620
                        continue
7289.1.2 by Jelmer Vernooij
Fix pushing of tags as part of nascent git branches.
621
                    if lossy:
7489.1.1 by Jelmer Vernooij
Ignore ghost tags when pushing to a remote git repo.
622
                        try:
623
                            new_sha = source_store._lookup_revision_sha1(revid)
624
                        except KeyError:
625
                            if source.repository.has_revision(revid):
626
                                raise
7289.1.2 by Jelmer Vernooij
Fix pushing of tags as part of nascent git branches.
627
                    else:
628
                        try:
629
                            new_sha = repo.lookup_bzr_revision_id(revid)[0]
630
                        except errors.NoSuchRevision:
631
                            continue
7289.1.5 by Jelmer Vernooij
Fix flake8 warning.
632
                    ret[tag_name_to_ref(tagname)] = new_sha
7289.1.2 by Jelmer Vernooij
Fix pushing of tags as part of nascent git branches.
633
            return ret
0.403.3 by Jelmer Vernooij
Test RemoteGitDir.push_branch.
634
        with source_store.lock_read():
7490.26.2 by Jelmer Vernooij
More shallow work.
635
            def generate_pack_data(have, want, progress=None,
636
                                   ofs_delta=True):
637
                git_repo = getattr(source.repository, '_git', None)
638
                if git_repo:
639
                    shallow = git_repo.get_shallow()
640
                else:
641
                    shallow = None
642
                if lossy:
643
                    return source_store.generate_lossy_pack_data(
644
                        have, want, shallow=shallow,
645
                        progress=progress, ofs_delta=ofs_delta)
646
                elif shallow:
647
                    return source_store.generate_pack_data(
648
                        have, want, shallow=shallow,
649
                        progress=progress, ofs_delta=ofs_delta)
650
                else:
651
                    return source_store.generate_pack_data(
652
                        have, want, progress=progress, ofs_delta=ofs_delta)
0.403.3 by Jelmer Vernooij
Test RemoteGitDir.push_branch.
653
            new_refs = self.send_pack(get_changed_refs, generate_pack_data)
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
654
        push_result.new_revid = repo.lookup_foreign_revision_id(
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
655
            new_refs[actual_refname])
7484.1.2 by Jelmer Vernooij
Add some tests.
656
        if old_sha is not None:
657
            push_result.old_revid = repo.lookup_foreign_revision_id(old_sha)
658
        else:
659
            push_result.old_revid = NULL_REVISION
660
        if self._refs is not None:
661
            update_refs_container(self._refs, new_refs)
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
662
        push_result.target_branch = self.open_branch(name)
7484.1.2 by Jelmer Vernooij
Add some tests.
663
        if old_sha is not None:
0.403.3 by Jelmer Vernooij
Test RemoteGitDir.push_branch.
664
            push_result.branch_push_result = GitBranchPushResult()
665
            push_result.branch_push_result.source_branch = source
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
666
            push_result.branch_push_result.target_branch = (
667
                push_result.target_branch)
0.403.3 by Jelmer Vernooij
Test RemoteGitDir.push_branch.
668
            push_result.branch_push_result.local_branch = None
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
669
            push_result.branch_push_result.master_branch = (
670
                push_result.target_branch)
0.403.3 by Jelmer Vernooij
Test RemoteGitDir.push_branch.
671
            push_result.branch_push_result.old_revid = push_result.old_revid
672
            push_result.branch_push_result.new_revid = push_result.new_revid
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
673
            push_result.branch_push_result.new_original_revid = (
674
                push_result.new_original_revid)
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
675
        if source.get_push_location() is None or remember:
676
            source.set_push_location(push_result.target_branch.base)
677
        return push_result
678
0.409.1 by Jelmer Vernooij
Don't probe for commondir over remote transport.
679
    def _find_commondir(self):
680
        # There is no way to find the commondir, if there is any.
681
        return self
682
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
683
0.225.2 by Jelmer Vernooij
Handle situation when repository is already up to date during pull.
684
class EmptyObjectStoreIterator(dict):
685
686
    def iterobjects(self):
687
        return []
688
689
0.200.218 by Jelmer Vernooij
Simplify TemporaryPack implementation.
690
class TemporaryPackIterator(Pack):
691
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
692
    def __init__(self, path, resolve_ext_ref):
0.279.1 by William Grant
Support thin packs in fetch_pack and send_pack, since dulwich now handles them properly.
693
        super(TemporaryPackIterator, self).__init__(
694
            path, resolve_ext_ref=resolve_ext_ref)
0.278.2 by William Grant
Also override _idx_load rather than index, to be a bit cleaner.
695
        self._idx_load = lambda: self._idx_load_or_generate(self._idx_path)
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
696
0.278.2 by William Grant
Also override _idx_load rather than index, to be a bit cleaner.
697
    def _idx_load_or_generate(self, path):
698
        if not os.path.exists(path):
7143.22.2 by Jelmer Vernooij
use more context libs for progress bars.
699
            with ui.ui_factory.nested_progress_bar() as pb:
0.278.2 by William Grant
Also override _idx_load rather than index, to be a bit cleaner.
700
                def report_progress(cur, total):
701
                    pb.update("generating index", cur, total)
7143.22.3 by Jelmer Vernooij
merge trunk.
702
                self.data.create_index(path, progress=report_progress)
0.278.2 by William Grant
Also override _idx_load rather than index, to be a bit cleaner.
703
        return load_pack_index(path)
0.200.205 by Jelmer Vernooij
Fix remote fetching.
704
705
    def __del__(self):
0.200.611 by Jelmer Vernooij
Merge warning fix from Naoki.
706
        if self._idx is not None:
0.241.1 by Naoki INADA
Fix can't delete tempfile on Windows
707
            self._idx.close()
708
            os.remove(self._idx_path)
0.200.611 by Jelmer Vernooij
Merge warning fix from Naoki.
709
        if self._data is not None:
0.241.1 by Naoki INADA
Fix can't delete tempfile on Windows
710
            self._data.close()
711
            os.remove(self._data_path)
0.200.205 by Jelmer Vernooij
Fix remote fetching.
712
713
0.200.1337 by Jelmer Vernooij
Re-use http connection if possible.
714
class BzrGitHttpClient(dulwich.client.HttpGitClient):
715
716
    def __init__(self, transport, *args, **kwargs):
717
        self.transport = transport
7268.10.2 by Jelmer Vernooij
Strip username.
718
        url = urlutils.URL.from_string(transport.external_url())
719
        url.user = url.quoted_user = None
720
        url.password = url.quoted_password = None
7441.1.1 by Jelmer Vernooij
Add strip_segment_parameters function.
721
        url = urlutils.strip_segment_parameters(str(url))
7371.3.2 by Jelmer Vernooij
Fix URL parsing for Git.
722
        super(BzrGitHttpClient, self).__init__(url, *args, **kwargs)
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
723
724
    def _http_request(self, url, headers=None, data=None,
725
                      allow_compression=False):
726
        """Perform HTTP request.
727
728
        :param url: Request URL.
729
        :param headers: Optional custom headers to override defaults.
730
        :param data: Request data.
731
        :param allow_compression: Allow GZipped communication.
732
        :return: Tuple (`response`, `read`), where response is an `urllib3`
7140.1.1 by Jelmer Vernooij
Rollback https://code.launchpad.net/~jelmer/brz/python3-git-fix-http/+merge/356238
733
            response object with additional `content_type` and
734
            `redirect_location` properties, and `read` is a consumable read
735
            method for the response data.
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
736
        """
7359.1.1 by Jelmer Vernooij
Only set user agent for GitHub.
737
        if is_github_url(url):
738
            headers['User-agent'] = user_agent_for_github()
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
739
        headers["Pragma"] = "no-cache"
740
        if allow_compression:
741
            headers["Accept-Encoding"] = "gzip"
742
        else:
743
            headers["Accept-Encoding"] = "identity"
744
7296.2.2 by Jelmer Vernooij
Add a urllib3-like interface.
745
        response = self.transport.request(
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
746
            ('GET' if data is None else 'POST'),
7320.1.1 by Jelmer Vernooij
Fix git http support.
747
            url,
7296.2.2 by Jelmer Vernooij
Add a urllib3-like interface.
748
            body=data,
749
            headers=headers, retries=8)
750
751
        if response.status == 404:
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
752
            raise NotGitRepository()
7296.2.2 by Jelmer Vernooij
Add a urllib3-like interface.
753
        elif response.status != 200:
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
754
            raise GitProtocolError("unexpected http resp %d for %s" %
7490.14.1 by Jelmer Vernooij
Various git fixes.
755
                                   (response.status, url))
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
756
757
        # TODO: Optimization available by adding `preload_content=False` to the
758
        # request and just passing the `read` method on instead of going via
759
        # `BytesIO`, if we can guarantee that the entire response is consumed
760
        # before issuing the next to still allow for connection reuse from the
761
        # pool.
762
        if response.getheader("Content-Encoding") == "gzip":
7404.5.3 by Jelmer Vernooij
Reuse connections.
763
            read = gzip.GzipFile(fileobj=BytesIO(response.read())).read
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
764
        else:
765
            read = response.read
766
767
        class WrapResponse(object):
768
769
            def __init__(self, response):
770
                self._response = response
7320.1.1 by Jelmer Vernooij
Fix git http support.
771
                self.status = response.status
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
772
                self.content_type = response.getheader("Content-Type")
7320.1.1 by Jelmer Vernooij
Fix git http support.
773
                self.redirect_location = response._actual.geturl()
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
774
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
775
            def readlines(self):
776
                return self._response.readlines()
777
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
778
            def close(self):
7320.1.1 by Jelmer Vernooij
Fix git http support.
779
                pass
0.409.2 by Jelmer Vernooij
call out to HTTP transport rather than creating new connection.
780
781
        return WrapResponse(response), read
0.200.1337 by Jelmer Vernooij
Re-use http connection if possible.
782
783
7371.3.2 by Jelmer Vernooij
Fix URL parsing for Git.
784
def _git_url_and_path_from_transport(external_url):
7441.1.1 by Jelmer Vernooij
Add strip_segment_parameters function.
785
    url = urlutils.strip_segment_parameters(external_url)
7371.3.2 by Jelmer Vernooij
Fix URL parsing for Git.
786
    return urlparse.urlsplit(url)
787
788
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
789
class RemoteGitControlDirFormat(GitControlDirFormat):
790
    """The .git directory control format."""
791
792
    supports_workingtrees = False
793
794
    @classmethod
795
    def _known_formats(self):
796
        return set([RemoteGitControlDirFormat()])
797
0.295.1 by Jelmer Vernooij
Split up branch formats.
798
    def get_branch_format(self):
799
        return RemoteGitBranchFormat()
800
7290.20.3 by Jelmer Vernooij
Fix tests for git/full history branches.
801
    @property
802
    def repository_format(self):
803
        return GitRepositoryFormat()
804
0.200.1413 by Jelmer Vernooij
Fix is_initializable()
805
    def is_initializable(self):
806
        return False
807
808
    def is_supported(self):
809
        return True
810
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
811
    def open(self, transport, _found=None):
812
        """Open this directory.
813
814
        """
7371.3.2 by Jelmer Vernooij
Fix URL parsing for Git.
815
        split_url = _git_url_and_path_from_transport(transport.external_url())
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
816
        if isinstance(transport, GitSmartTransport):
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
817
            client = transport._get_client()
7371.3.2 by Jelmer Vernooij
Fix URL parsing for Git.
818
        elif split_url.scheme in ("http", "https"):
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
819
            client = BzrGitHttpClient(transport)
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
820
        elif split_url.scheme in ('file', ):
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
821
            client = dulwich.client.LocalGitClient()
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
822
        else:
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
823
            raise NotBranchError(transport.base)
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
824
        if not _found:
7143.15.2 by Jelmer Vernooij
Run autopep8.
825
            pass  # TODO(jelmer): Actually probe for something
7371.3.2 by Jelmer Vernooij
Fix URL parsing for Git.
826
        return RemoteGitDir(transport, self, client, split_url.path)
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
827
828
    def get_format_description(self):
829
        return "Remote Git Repository"
830
831
    def initialize_on_transport(self, transport):
832
        raise UninitializableFormat(self)
833
0.200.1412 by Jelmer Vernooij
Implement GitControlDirFormat.supports_transport.
834
    def supports_transport(self, transport):
835
        try:
836
            external_url = transport.external_url()
837
        except InProcessTransport:
838
            raise NotBranchError(path=transport.base)
7143.15.2 by Jelmer Vernooij
Run autopep8.
839
        return (external_url.startswith("http:")
840
                or external_url.startswith("https:")
841
                or external_url.startswith("git+")
842
                or external_url.startswith("git:"))
0.200.1412 by Jelmer Vernooij
Implement GitControlDirFormat.supports_transport.
843
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
844
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
845
class GitRemoteRevisionTree(RevisionTree):
846
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
847
    def archive(self, format, name, root=None, subdir=None, force_mtime=None):
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
848
        """Create an archive of this tree.
849
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
850
        :param format: Format name (e.g. 'tar')
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
851
        :param name: target file name
852
        :param root: Root directory name (or None)
853
        :param subdir: Subdirectory to export (or None)
854
        :return: Iterator over archive chunks
855
        """
856
        commit = self._repository.lookup_bzr_revision_id(
857
            self.get_revision_id())[0]
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
858
        f = tempfile.SpooledTemporaryFile()
859
        # git-upload-archive(1) generaly only supports refs. So let's see if we
860
        # can find one.
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
861
        reverse_refs = {
7143.15.2 by Jelmer Vernooij
Run autopep8.
862
            v: k for (k, v) in
863
            self._repository.controldir.get_refs_container().as_dict().items()}
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
864
        try:
865
            committish = reverse_refs[commit]
866
        except KeyError:
867
            # No? Maybe the user has uploadArchive.allowUnreachable enabled.
868
            # Let's hope for the best.
869
            committish = commit
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
870
        self._repository.archive(
7143.15.2 by Jelmer Vernooij
Run autopep8.
871
            format, committish, f.write,
872
            subdirs=([subdir] if subdir else None),
873
            prefix=(root + '/') if root else '')
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
874
        f.seek(0)
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
875
        return osutils.file_iterator(f)
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
876
7192.5.1 by Jelmer Vernooij
Remove more file ids.
877
    def is_versioned(self, path):
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
878
        raise GitSmartRemoteNotSupported(self.is_versioned, self)
879
880
    def has_filename(self, path):
881
        raise GitSmartRemoteNotSupported(self.has_filename, self)
882
7192.5.1 by Jelmer Vernooij
Remove more file ids.
883
    def get_file_text(self, path):
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
884
        raise GitSmartRemoteNotSupported(self.get_file_text, self)
885
7413.4.4 by Jelmer Vernooij
'Implement' RevisionTree.list_files.
886
    def list_files(self, include_root=False, from_dir=None, recursive=True):
887
        raise GitSmartRemoteNotSupported(self.list_files, self)
888
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
889
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
890
class RemoteGitRepository(GitRepository):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
891
7254.5.1 by Jelmer Vernooij
Add supports_random_access attribute to repositories.
892
    supports_random_access = False
893
0.200.319 by Jelmer Vernooij
Print proper error when trying unsupported operations against a git server.
894
    @property
0.200.1068 by Jelmer Vernooij
Implement user_url/control_url.
895
    def user_url(self):
896
        return self.control_url
897
0.200.1288 by Jelmer Vernooij
Properly raise GitRemoteNotSupported from RemoteGitRepository.
898
    def get_parent_map(self, revids):
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
899
        raise GitSmartRemoteNotSupported(self.get_parent_map, self)
0.200.319 by Jelmer Vernooij
Print proper error when trying unsupported operations against a git server.
900
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
901
    def archive(self, *args, **kwargs):
902
        return self.controldir.archive(*args, **kwargs)
903
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
904
    def fetch_pack(self, determine_wants, graph_walker, pack_data,
0.200.155 by Jelmer Vernooij
Fix formatting, remove catch-all for exceptions when opening local repositories.
905
                   progress=None):
7143.2.1 by Jelmer Vernooij
Don't hardcode the list of supported archive formats.
906
        return self.controldir.fetch_pack(
7143.16.8 by Jelmer Vernooij
Fix E126
907
            determine_wants, graph_walker, pack_data, progress)
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
908
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
909
    def send_pack(self, get_changed_refs, generate_pack_data):
910
        return self.controldir.send_pack(get_changed_refs, generate_pack_data)
0.200.427 by Jelmer Vernooij
make send_pack accessible.
911
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
912
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
913
                      progress=None):
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
914
        fd, path = tempfile.mkstemp(suffix=".pack")
0.200.1299 by Jelmer Vernooij
Make sure file gets closed.
915
        try:
916
            self.fetch_pack(determine_wants, graph_walker,
7143.15.2 by Jelmer Vernooij
Run autopep8.
917
                            lambda x: os.write(fd, x), progress)
0.200.1299 by Jelmer Vernooij
Make sure file gets closed.
918
        finally:
919
            os.close(fd)
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
920
        if os.path.getsize(path) == 0:
0.225.2 by Jelmer Vernooij
Handle situation when repository is already up to date during pull.
921
            return EmptyObjectStoreIterator()
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
922
        return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
923
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
924
    def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
925
        # This won't work for any round-tripped bzr revisions, but it's a
926
        # start..
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
927
        try:
928
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
929
        except InvalidRevisionId:
930
            raise NoSuchRevision(self, bzr_revid)
931
0.252.48 by Jelmer Vernooij
Implement lookup_foreign_revision for remote branches.
932
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
933
        """Lookup a revision id.
934
935
        """
936
        if mapping is None:
937
            mapping = self.get_mapping()
938
        # Not really an easy way to parse foreign revids here..
939
        return mapping.revision_id_foreign_to_bzr(foreign_revid)
940
0.200.1446 by Jelmer Vernooij
Add stub for RemoteGitRepository.revision_tree.
941
    def revision_tree(self, revid):
6968.4.1 by Jelmer Vernooij
Add support for exporting archives in Git.
942
        return GitRemoteRevisionTree(self, revid)
0.200.1446 by Jelmer Vernooij
Add stub for RemoteGitRepository.revision_tree.
943
0.200.1481 by Jelmer Vernooij
'Implement' RemoteGitRepository.get_revisions.
944
    def get_revisions(self, revids):
945
        raise GitSmartRemoteNotSupported(self.get_revisions, self)
946
0.200.1557 by Jelmer Vernooij
Implement RemoteGitRepository.has_revisions.
947
    def has_revisions(self, revids):
948
        raise GitSmartRemoteNotSupported(self.get_revisions, self)
949
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
950
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
951
class RemoteGitTagDict(GitTags):
0.228.3 by Jelmer Vernooij
Fix tags when fetching from remotes.
952
953
    def set_tag(self, name, revid):
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
954
        sha = self.branch.lookup_bzr_revision_id(revid)[0]
955
        self._set_ref(name, sha)
956
957
    def delete_tag(self, name):
958
        self._set_ref(name, dulwich.client.ZERO_SHA)
959
960
    def _set_ref(self, name, sha):
961
        ref = tag_name_to_ref(name)
7143.15.2 by Jelmer Vernooij
Run autopep8.
962
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
963
        def get_changed_refs(old_refs):
7240.3.1 by Jelmer Vernooij
When sending refs to a remote server, don't send a copy of the old refs.
964
            ret = {}
7240.3.2 by Jelmer Vernooij
Fix tests.
965
            if sha == dulwich.client.ZERO_SHA and ref not in old_refs:
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
966
                raise NoSuchTag(name)
967
            ret[ref] = sha
968
            return ret
7143.15.2 by Jelmer Vernooij
Run autopep8.
969
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
970
        def generate_pack_data(have, want, ofs_delta=False):
971
            return pack_objects_to_data([])
972
        self.repository.send_pack(get_changed_refs, generate_pack_data)
0.228.3 by Jelmer Vernooij
Fix tags when fetching from remotes.
973
974
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
975
class RemoteGitBranch(GitBranch):
976
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
977
    def __init__(self, controldir, repository, name):
0.200.919 by Jelmer Vernooij
Simplify ref handling in remote.py.
978
        self._sha = None
0.295.1 by Jelmer Vernooij
Split up branch formats.
979
        super(RemoteGitBranch, self).__init__(controldir, repository, name,
7143.15.2 by Jelmer Vernooij
Run autopep8.
980
                                              RemoteGitBranchFormat())
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
981
0.200.1317 by Jelmer Vernooij
Avoid NotImplementedError.
982
    def last_revision_info(self):
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
983
        raise GitSmartRemoteNotSupported(self.last_revision_info, self)
0.200.1317 by Jelmer Vernooij
Avoid NotImplementedError.
984
0.200.1068 by Jelmer Vernooij
Implement user_url/control_url.
985
    @property
986
    def user_url(self):
987
        return self.control_url
988
989
    @property
990
    def control_url(self):
991
        return self.base
992
0.200.1436 by Jelmer Vernooij
Raise UnsupportedOperation for `Branch.revision_id_to_dotted_revno`,
993
    def revision_id_to_revno(self, revision_id):
994
        raise GitSmartRemoteNotSupported(self.revision_id_to_revno, self)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
995
996
    def last_revision(self):
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
997
        return self.lookup_foreign_revision_id(self.head)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
998
999
    @property
1000
    def head(self):
0.200.919 by Jelmer Vernooij
Simplify ref handling in remote.py.
1001
        if self._sha is not None:
1002
            return self._sha
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
1003
        refs = self.controldir.get_refs_container()
0.200.1561 by Jelmer Vernooij
Some fixes for colocated branch handling.
1004
        name = branch_name_to_ref(self.name)
0.200.1386 by Jelmer Vernooij
Friendlier message if HEAD is not found.
1005
        try:
1006
            self._sha = refs[name]
1007
        except KeyError:
1008
            raise NoSuchRef(name, self.repository.user_url, refs)
0.200.919 by Jelmer Vernooij
Simplify ref handling in remote.py.
1009
        return self._sha
0.200.141 by Jelmer Vernooij
Separate out local and remote fetching.
1010
0.200.169 by Jelmer Vernooij
Fix branch cloning.
1011
    def _synchronize_history(self, destination, revision_id):
1012
        """See Branch._synchronize_history()."""
7143.12.1 by Jelmer Vernooij
Support cloning revisions referenced only by an annotated tag.
1013
        if revision_id is None:
1014
            revision_id = self.last_revision()
1015
        destination.generate_revision_history(revision_id)
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1016
0.289.1 by Jelmer Vernooij
No parent location for remote repos.
1017
    def _get_parent_location(self):
1018
        return None
1019
0.200.499 by Jelmer Vernooij
Implement RemoteBranch.{get,set}_push_location.
1020
    def get_push_location(self):
1021
        return None
1022
1023
    def set_push_location(self, url):
1024
        pass
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
1025
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
1026
    def _iter_tag_refs(self):
1027
        """Iterate over the tag refs.
1028
1029
        :param refs: Refs dictionary (name -> git sha1)
1030
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
1031
        """
1032
        refs = self.controldir.get_refs_container()
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
1033
        for ref_name, unpeeled in refs.as_dict().items():
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
1034
            try:
1035
                tag_name = ref_to_tag_name(ref_name)
1036
            except (ValueError, UnicodeDecodeError):
1037
                continue
1038
            peeled = refs.get_peeled(ref_name)
1039
            if peeled is None:
7058.4.36 by Jelmer Vernooij
Fix peeled error.
1040
                # Let's just hope it's a commit
1041
                peeled = unpeeled
7479.2.1 by Jelmer Vernooij
Drop python2 support.
1042
            if not isinstance(tag_name, str):
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
1043
                raise TypeError(tag_name)
1044
            yield (ref_name, tag_name, peeled, unpeeled)
1045
7131.12.1 by Jelmer Vernooij
Support uncommit on remote git branches.
1046
    def set_last_revision_info(self, revno, revid):
1047
        self.generate_revision_history(revid)
1048
1049
    def generate_revision_history(self, revision_id, last_rev=None,
1050
                                  other_branch=None):
1051
        sha = self.lookup_bzr_revision_id(revision_id)[0]
1052
        def get_changed_refs(old_refs):
1053
            return {self.ref: sha}
1054
        def generate_pack_data(have, want, ofs_delta=False):
1055
            return pack_objects_to_data([])
1056
        self.repository.send_pack(get_changed_refs, generate_pack_data)
1057
        self._sha = sha
1058
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
1059
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
1060
def remote_refs_dict_to_container(refs_dict, symrefs_dict={}):
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
1061
    base = {}
1062
    peeled = {}
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
1063
    for k, v in refs_dict.items():
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
1064
        if is_peeled(k):
1065
            peeled[k[:-3]] = v
1066
        else:
1067
            base[k] = v
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
1068
    for name, target in symrefs_dict.items():
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
1069
        base[name] = SYMREF + target
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
1070
    ret = DictRefsContainer(base)
1071
    ret._peeled = peeled
1072
    return ret
7484.1.1 by Jelmer Vernooij
Follow symrefs when pushing to git repositories.
1073
1074
1075
def update_refs_container(container, refs_dict):
1076
    peeled = {}
1077
    base = {}
1078
    for k, v in refs_dict.items():
1079
        if is_peeled(k):
1080
            peeled[k[:-3]] = v
1081
        else:
1082
            base[k] = v
1083
    container._peeled = peeled
1084
    container._refs.update(base)