/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to remote.py

  • Committer: Jelmer Vernooij
  • Date: 2018-03-17 17:54:17 UTC
  • mto: (0.200.1859 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180317175417-4ag21da38udunec9
Add tests for memorytree.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007-2012 Jelmer Vernooij <jelmer@samba.org>
 
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from __future__ import absolute_import
 
18
 
 
19
from ... import (
 
20
    config,
 
21
    debug,
 
22
    trace,
 
23
    ui,
 
24
    urlutils,
 
25
    )
 
26
from ...errors import (
 
27
    BzrError,
 
28
    InProcessTransport,
 
29
    InvalidRevisionId,
 
30
    NoSuchFile,
 
31
    NoSuchRevision,
 
32
    NotBranchError,
 
33
    NotLocalUrl,
 
34
    UninitializableFormat,
 
35
    )
 
36
from ...transport import (
 
37
    Transport,
 
38
    )
 
39
 
 
40
from . import (
 
41
    lazy_check_versions,
 
42
    )
 
43
lazy_check_versions()
 
44
 
 
45
from .branch import (
 
46
    GitBranch,
 
47
    GitBranchFormat,
 
48
    GitTags,
 
49
    )
 
50
from .dir import (
 
51
    GitControlDirFormat,
 
52
    GitDir,
 
53
    BareLocalGitControlDirFormat,
 
54
    )
 
55
from .errors import (
 
56
    GitSmartRemoteNotSupported,
 
57
    NoSuchRef,
 
58
    )
 
59
from .mapping import (
 
60
    mapping_registry,
 
61
    )
 
62
from .repository import (
 
63
    GitRepository,
 
64
    )
 
65
from .refs import (
 
66
    branch_name_to_ref,
 
67
    is_peeled,
 
68
    )
 
69
 
 
70
import dulwich
 
71
import dulwich.client
 
72
from dulwich.errors import (
 
73
    GitProtocolError,
 
74
    )
 
75
from dulwich.pack import (
 
76
    Pack,
 
77
    )
 
78
from dulwich.repo import DictRefsContainer
 
79
import os
 
80
import select
 
81
import tempfile
 
82
import urllib
 
83
import urlparse
 
84
 
 
85
# urlparse only supports a limited number of schemes by default
 
86
 
 
87
urlparse.uses_netloc.extend(['git', 'git+ssh'])
 
88
 
 
89
from dulwich.pack import load_pack_index
 
90
 
 
91
 
 
92
# Don't run any tests on GitSmartTransport as it is not intended to be
 
93
# a full implementation of Transport
 
94
def get_test_permutations():
 
95
    return []
 
96
 
 
97
 
 
98
def split_git_url(url):
 
99
    """Split a Git URL.
 
100
 
 
101
    :param url: Git URL
 
102
    :return: Tuple with host, port, username, path.
 
103
    """
 
104
    (scheme, netloc, loc, _, _) = urlparse.urlsplit(url)
 
105
    path = urllib.unquote(loc)
 
106
    if path.startswith("/~"):
 
107
        path = path[1:]
 
108
    (username, hostport) = urllib.splituser(netloc)
 
109
    (host, port) = urllib.splitnport(hostport, None)
 
110
    return (host, port, username, path)
 
111
 
 
112
 
 
113
class RemoteGitError(BzrError):
 
114
 
 
115
    _fmt = "Remote server error: %(msg)s"
 
116
 
 
117
 
 
118
def parse_git_error(url, message):
 
119
    """Parse a remote git server error and return a bzr exception.
 
120
 
 
121
    :param url: URL of the remote repository
 
122
    :param message: Message sent by the remote git server
 
123
    """
 
124
    message = str(message).strip()
 
125
    if message.startswith("Could not find Repository "):
 
126
        return NotBranchError(url, message)
 
127
    if message == "HEAD failed to update":
 
128
        base_url, _ = urlutils.split_segment_parameters(url)
 
129
        raise BzrError(
 
130
            ("Unable to update remote HEAD branch. To update the master "
 
131
             "branch, specify the URL %s,branch=master.") % base_url)
 
132
    # Don't know, just return it to the user as-is
 
133
    return RemoteGitError(message)
 
134
 
 
135
 
 
136
class GitSmartTransport(Transport):
 
137
 
 
138
    def __init__(self, url, _client=None):
 
139
        Transport.__init__(self, url)
 
140
        (self._host, self._port, self._username, self._path) = \
 
141
            split_git_url(url)
 
142
        if 'transport' in debug.debug_flags:
 
143
            trace.mutter('host: %r, user: %r, port: %r, path: %r',
 
144
                         self._host, self._username, self._port, self._path)
 
145
        self._client = _client
 
146
        self._stripped_path = self._path.rsplit(",", 1)[0]
 
147
 
 
148
    def external_url(self):
 
149
        return self.base
 
150
 
 
151
    def has(self, relpath):
 
152
        return False
 
153
 
 
154
    def _get_client(self):
 
155
        raise NotImplementedError(self._get_client)
 
156
 
 
157
    def _get_path(self):
 
158
        return self._stripped_path
 
159
 
 
160
    def get(self, path):
 
161
        raise NoSuchFile(path)
 
162
 
 
163
    def abspath(self, relpath):
 
164
        return urlutils.join(self.base, relpath)
 
165
 
 
166
    def clone(self, offset=None):
 
167
        """See Transport.clone()."""
 
168
        if offset is None:
 
169
            newurl = self.base
 
170
        else:
 
171
            newurl = urlutils.join(self.base, offset)
 
172
 
 
173
        return self.__class__(newurl, self._client)
 
174
 
 
175
 
 
176
class TCPGitSmartTransport(GitSmartTransport):
 
177
 
 
178
    _scheme = 'git'
 
179
 
 
180
    def _get_client(self):
 
181
        if self._client is not None:
 
182
            ret = self._client
 
183
            self._client = None
 
184
            return ret
 
185
        if self._host == '':
 
186
            return dulwich.client.LocalGitClient()
 
187
        return dulwich.client.TCPGitClient(self._host, self._port,
 
188
            report_activity=self._report_activity)
 
189
 
 
190
 
 
191
class SSHSocketWrapper(object):
 
192
 
 
193
    def __init__(self, sock):
 
194
        self.sock = sock
 
195
 
 
196
    def read(self, len=None):
 
197
        return self.sock.recv(len)
 
198
 
 
199
    def write(self, data):
 
200
        return self.sock.write(data)
 
201
 
 
202
    def can_read(self):
 
203
        return len(select.select([self.sock.fileno()], [], [], 0)[0]) > 0
 
204
 
 
205
 
 
206
class DulwichSSHVendor(dulwich.client.SSHVendor):
 
207
 
 
208
    def __init__(self):
 
209
        from ...transport import ssh
 
210
        self.bzr_ssh_vendor = ssh._get_ssh_vendor()
 
211
 
 
212
    def run_command(self, host, command, username=None, port=None):
 
213
        connection = self.bzr_ssh_vendor.connect_ssh(username=username,
 
214
            password=None, port=port, host=host, command=command)
 
215
        (kind, io_object) = connection.get_sock_or_pipes()
 
216
        if kind == 'socket':
 
217
            return SSHSocketWrapper(io_object)
 
218
        else:
 
219
            raise AssertionError("Unknown io object kind %r'" % kind)
 
220
 
 
221
 
 
222
#dulwich.client.get_ssh_vendor = DulwichSSHVendor
 
223
 
 
224
 
 
225
class SSHGitSmartTransport(GitSmartTransport):
 
226
 
 
227
    _scheme = 'git+ssh'
 
228
 
 
229
    def _get_path(self):
 
230
        path = self._stripped_path
 
231
        if path.startswith("/~/"):
 
232
            return path[3:]
 
233
        return path
 
234
 
 
235
    def _get_client(self):
 
236
        if self._client is not None:
 
237
            ret = self._client
 
238
            self._client = None
 
239
            return ret
 
240
        location_config = config.LocationConfig(self.base)
 
241
        client = dulwich.client.SSHGitClient(self._host, self._port, self._username,
 
242
            report_activity=self._report_activity)
 
243
        # Set up alternate pack program paths
 
244
        upload_pack = location_config.get_user_option('git_upload_pack')
 
245
        if upload_pack:
 
246
            client.alternative_paths["upload-pack"] = upload_pack
 
247
        receive_pack = location_config.get_user_option('git_receive_pack')
 
248
        if receive_pack:
 
249
            client.alternative_paths["receive-pack"] = receive_pack
 
250
        return client
 
251
 
 
252
 
 
253
class RemoteGitBranchFormat(GitBranchFormat):
 
254
 
 
255
    def get_format_description(self):
 
256
        return 'Remote Git Branch'
 
257
 
 
258
    @property
 
259
    def _matchingcontroldir(self):
 
260
        return RemoteGitControlDirFormat()
 
261
 
 
262
    def initialize(self, a_controldir, name=None, repository=None,
 
263
                   append_revisions_only=None):
 
264
        raise UninitializableFormat(self)
 
265
 
 
266
 
 
267
class RemoteGitDir(GitDir):
 
268
 
 
269
    def __init__(self, transport, format, client, client_path):
 
270
        self._format = format
 
271
        self.root_transport = transport
 
272
        self.transport = transport
 
273
        self._mode_check_done = None
 
274
        self._client = client
 
275
        self._client_path = client_path
 
276
        self.base = self.root_transport.base
 
277
        self._refs = None
 
278
 
 
279
    @property
 
280
    def _gitrepository_class(self):
 
281
        return RemoteGitRepository
 
282
 
 
283
    def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
 
284
        if progress is None:
 
285
            def progress(text):
 
286
                trace.info("git: %s" % text)
 
287
        def wrap_determine_wants(refs_dict):
 
288
            return determine_wants(remote_refs_dict_to_container(refs_dict))
 
289
        try:
 
290
            refs_dict = self._client.fetch_pack(self._client_path, wrap_determine_wants,
 
291
                graph_walker, pack_data, progress)
 
292
            if refs_dict is None:
 
293
                refs_dict = {}
 
294
            self._refs = remote_refs_dict_to_container(refs_dict)
 
295
            return refs_dict
 
296
        except GitProtocolError, e:
 
297
            raise parse_git_error(self.transport.external_url(), e)
 
298
 
 
299
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
300
        try:
 
301
            return self._client.send_pack(self._client_path, get_changed_refs,
 
302
                generate_pack_contents)
 
303
        except GitProtocolError, e:
 
304
            raise parse_git_error(self.transport.external_url(), e)
 
305
 
 
306
    def _get_default_ref(self):
 
307
        return "refs/heads/master"
 
308
 
 
309
    def destroy_branch(self, name=None):
 
310
        refname = self._get_selected_ref(name)
 
311
        def get_changed_refs(old_refs):
 
312
            ret = dict(old_refs)
 
313
            if not refname in ret:
 
314
                raise NotBranchError(self.user_url)
 
315
            ret[refname] = "00" * 20
 
316
            return ret
 
317
        self.send_pack(get_changed_refs, lambda have, want: [])
 
318
 
 
319
    @property
 
320
    def user_url(self):
 
321
        return self.control_url
 
322
 
 
323
    @property
 
324
    def user_transport(self):
 
325
        return self.root_transport
 
326
 
 
327
    @property
 
328
    def control_url(self):
 
329
        return self.control_transport.base
 
330
 
 
331
    @property
 
332
    def control_transport(self):
 
333
        return self.root_transport
 
334
 
 
335
    def open_repository(self):
 
336
        return RemoteGitRepository(self)
 
337
 
 
338
    def open_branch(self, name=None, unsupported=False,
 
339
            ignore_fallbacks=False, ref=None, possible_transports=None):
 
340
        repo = self.open_repository()
 
341
        refname = self._get_selected_ref(name, ref)
 
342
        return RemoteGitBranch(self, repo, refname)
 
343
 
 
344
    def open_workingtree(self, recommend_upgrade=False):
 
345
        raise NotLocalUrl(self.transport.base)
 
346
 
 
347
    def has_workingtree(self):
 
348
        return False
 
349
 
 
350
    def get_peeled(self, name):
 
351
        return self.get_refs_container().get_peeled(name)
 
352
 
 
353
    def get_refs_container(self):
 
354
        if self._refs is not None:
 
355
            return self._refs
 
356
        refs_dict = self.fetch_pack(lambda x: [], None,
 
357
            lambda x: None, lambda x: trace.mutter("git: %s" % x))
 
358
        self._refs = remote_refs_dict_to_container(refs_dict)
 
359
        return self._refs
 
360
 
 
361
 
 
362
class EmptyObjectStoreIterator(dict):
 
363
 
 
364
    def iterobjects(self):
 
365
        return []
 
366
 
 
367
 
 
368
class TemporaryPackIterator(Pack):
 
369
 
 
370
    def __init__(self, path, resolve_ext_ref):
 
371
        super(TemporaryPackIterator, self).__init__(
 
372
            path, resolve_ext_ref=resolve_ext_ref)
 
373
        self._idx_load = lambda: self._idx_load_or_generate(self._idx_path)
 
374
 
 
375
    def _idx_load_or_generate(self, path):
 
376
        if not os.path.exists(path):
 
377
            pb = ui.ui_factory.nested_progress_bar()
 
378
            try:
 
379
                def report_progress(cur, total):
 
380
                    pb.update("generating index", cur, total)
 
381
                self.data.create_index(path,
 
382
                    progress=report_progress)
 
383
            finally:
 
384
                pb.finished()
 
385
        return load_pack_index(path)
 
386
 
 
387
    def __del__(self):
 
388
        if self._idx is not None:
 
389
            self._idx.close()
 
390
            os.remove(self._idx_path)
 
391
        if self._data is not None:
 
392
            self._data.close()
 
393
            os.remove(self._data_path)
 
394
 
 
395
 
 
396
class BzrGitHttpClient(dulwich.client.HttpGitClient):
 
397
 
 
398
    def __init__(self, transport, *args, **kwargs):
 
399
        self.transport = transport
 
400
        super(BzrGitHttpClient, self).__init__(transport.external_url(), *args, **kwargs)
 
401
        import urllib2
 
402
        self._http_perform = getattr(self.transport, "_perform", urllib2.urlopen)
 
403
 
 
404
    def _perform(self, req):
 
405
        req.accepted_errors = (200, 404)
 
406
        req.follow_redirections = True
 
407
        req.redirected_to = None
 
408
        return self._http_perform(req)
 
409
 
 
410
 
 
411
class RemoteGitControlDirFormat(GitControlDirFormat):
 
412
    """The .git directory control format."""
 
413
 
 
414
    supports_workingtrees = False
 
415
 
 
416
    @classmethod
 
417
    def _known_formats(self):
 
418
        return set([RemoteGitControlDirFormat()])
 
419
 
 
420
    def get_branch_format(self):
 
421
        return RemoteGitBranchFormat()
 
422
 
 
423
    def is_initializable(self):
 
424
        return False
 
425
 
 
426
    def is_supported(self):
 
427
        return True
 
428
 
 
429
    def open(self, transport, _found=None):
 
430
        """Open this directory.
 
431
 
 
432
        """
 
433
        # we dont grok readonly - git isn't integrated with transport.
 
434
        url = transport.base
 
435
        if url.startswith('readonly+'):
 
436
            url = url[len('readonly+'):]
 
437
        scheme = urlparse.urlsplit(transport.external_url())[0]
 
438
        if isinstance(transport, GitSmartTransport):
 
439
            client = transport._get_client()
 
440
            client_path = transport._get_path()
 
441
        elif scheme in ("http", "https"):
 
442
            client = BzrGitHttpClient(transport)
 
443
            client_path, _ = urlutils.split_segment_parameters(transport._path)
 
444
        elif scheme == 'file':
 
445
            client = dulwich.client.LocalGitClient()
 
446
            client_path = transport.local_abspath('.')
 
447
        else:
 
448
            raise NotBranchError(transport.base)
 
449
        if not _found:
 
450
            pass # TODO(jelmer): Actually probe for something
 
451
        return RemoteGitDir(transport, self, client, client_path)
 
452
 
 
453
    def get_format_description(self):
 
454
        return "Remote Git Repository"
 
455
 
 
456
    def initialize_on_transport(self, transport):
 
457
        raise UninitializableFormat(self)
 
458
 
 
459
    def supports_transport(self, transport):
 
460
        try:
 
461
            external_url = transport.external_url()
 
462
        except InProcessTransport:
 
463
            raise NotBranchError(path=transport.base)
 
464
        return (external_url.startswith("http:") or
 
465
                external_url.startswith("https:") or
 
466
                external_url.startswith("git+") or
 
467
                external_url.startswith("git:"))
 
468
 
 
469
 
 
470
class RemoteGitRepository(GitRepository):
 
471
 
 
472
    @property
 
473
    def user_url(self):
 
474
        return self.control_url
 
475
 
 
476
    def get_parent_map(self, revids):
 
477
        raise GitSmartRemoteNotSupported(self.get_parent_map, self)
 
478
 
 
479
    def fetch_pack(self, determine_wants, graph_walker, pack_data,
 
480
                   progress=None):
 
481
        return self.controldir.fetch_pack(determine_wants, graph_walker,
 
482
                                          pack_data, progress)
 
483
 
 
484
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
485
        return self.controldir.send_pack(get_changed_refs, generate_pack_contents)
 
486
 
 
487
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
 
488
                      progress=None):
 
489
        fd, path = tempfile.mkstemp(suffix=".pack")
 
490
        try:
 
491
            self.fetch_pack(determine_wants, graph_walker,
 
492
                lambda x: os.write(fd, x), progress)
 
493
        finally:
 
494
            os.close(fd)
 
495
        if os.path.getsize(path) == 0:
 
496
            return EmptyObjectStoreIterator()
 
497
        return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
 
498
 
 
499
    def lookup_bzr_revision_id(self, bzr_revid):
 
500
        # This won't work for any round-tripped bzr revisions, but it's a start..
 
501
        try:
 
502
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
 
503
        except InvalidRevisionId:
 
504
            raise NoSuchRevision(self, bzr_revid)
 
505
 
 
506
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
 
507
        """Lookup a revision id.
 
508
 
 
509
        """
 
510
        if mapping is None:
 
511
            mapping = self.get_mapping()
 
512
        # Not really an easy way to parse foreign revids here..
 
513
        return mapping.revision_id_foreign_to_bzr(foreign_revid)
 
514
 
 
515
    def revision_tree(self, revid):
 
516
        raise GitSmartRemoteNotSupported(self.revision_tree, self)
 
517
 
 
518
    def get_revisions(self, revids):
 
519
        raise GitSmartRemoteNotSupported(self.get_revisions, self)
 
520
 
 
521
    def has_revisions(self, revids):
 
522
        raise GitSmartRemoteNotSupported(self.get_revisions, self)
 
523
 
 
524
 
 
525
class RemoteGitTagDict(GitTags):
 
526
 
 
527
    def set_tag(self, name, revid):
 
528
        # FIXME: Not supported yet, should do a push of a new ref
 
529
        raise NotImplementedError(self.set_tag)
 
530
 
 
531
 
 
532
class RemoteGitBranch(GitBranch):
 
533
 
 
534
    def __init__(self, controldir, repository, name):
 
535
        self._sha = None
 
536
        super(RemoteGitBranch, self).__init__(controldir, repository, name,
 
537
                RemoteGitBranchFormat())
 
538
 
 
539
    def last_revision_info(self):
 
540
        raise GitSmartRemoteNotSupported(self.last_revision_info, self)
 
541
 
 
542
    @property
 
543
    def user_url(self):
 
544
        return self.control_url
 
545
 
 
546
    @property
 
547
    def control_url(self):
 
548
        return self.base
 
549
 
 
550
    def revision_id_to_revno(self, revision_id):
 
551
        raise GitSmartRemoteNotSupported(self.revision_id_to_revno, self)
 
552
 
 
553
    def last_revision(self):
 
554
        return self.lookup_foreign_revision_id(self.head)
 
555
 
 
556
    @property
 
557
    def head(self):
 
558
        if self._sha is not None:
 
559
            return self._sha
 
560
        refs = self.controldir.get_refs_container()
 
561
        name = branch_name_to_ref(self.name)
 
562
        try:
 
563
            self._sha = refs[name]
 
564
        except KeyError:
 
565
            raise NoSuchRef(name, self.repository.user_url, refs)
 
566
        return self._sha
 
567
 
 
568
    def _synchronize_history(self, destination, revision_id):
 
569
        """See Branch._synchronize_history()."""
 
570
        destination.generate_revision_history(self.last_revision())
 
571
 
 
572
    def _get_parent_location(self):
 
573
        return None
 
574
 
 
575
    def get_push_location(self):
 
576
        return None
 
577
 
 
578
    def set_push_location(self, url):
 
579
        pass
 
580
 
 
581
 
 
582
def remote_refs_dict_to_container(refs_dict):
 
583
    base = {}
 
584
    peeled = {}
 
585
    for k, v in refs_dict.iteritems():
 
586
        if is_peeled(k):
 
587
            peeled[k[:-3]] = v
 
588
        else:
 
589
            base[k] = v
 
590
            peeled[k] = v
 
591
    ret = DictRefsContainer(base)
 
592
    ret._peeled = peeled
 
593
    return ret