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