/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-31 17:39:57 UTC
  • mto: (0.200.1908 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180331173957-gij9lwydf25aisat
Fix typo.

Show diffs side-by-side

added added

removed removed

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