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