/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 branch.py

Fix compatibility with newer versions of Dulwich.

Show diffs side-by-side

added added

removed removed

Lines of Context:
27
27
    bzrdir,
28
28
    config,
29
29
    errors,
30
 
    foreign,
31
30
    repository,
32
31
    revision,
33
32
    tag,
51
50
    NoPushSupport,
52
51
    NoSuchRef,
53
52
    )
54
 
 
55
 
try:
56
 
    from bzrlib.foreign import ForeignBranch
57
 
except ImportError:
58
 
    class ForeignBranch(branch.Branch):
59
 
        def __init__(self, mapping):
60
 
            self.mapping = mapping
61
 
            super(ForeignBranch, self).__init__()
62
 
 
63
 
 
64
 
def extract_tags(refs, mapping):
65
 
    ret = {}
66
 
    for k,v in refs.iteritems():
67
 
        if k.startswith("refs/tags/") and not k.endswith("^{}"):
68
 
            v = refs.get(k+"^{}", v)
69
 
            ret[k[len("refs/tags/"):]] = mapping.revision_id_foreign_to_bzr(v)
70
 
    return ret
 
53
from bzrlib.plugins.git.refs import (
 
54
    ref_to_branch_name,
 
55
    extract_tags,
 
56
    tag_name_to_ref,
 
57
    )
 
58
 
 
59
from bzrlib.foreign import ForeignBranch
71
60
 
72
61
 
73
62
class GitPullResult(branch.PullResult):
95
84
 
96
85
    def get_tag_dict(self):
97
86
        ret = {}
98
 
        for k,v in self.repository._git.refs.as_dict("refs/tags").iteritems():
99
 
            obj = self.repository._git.get_object(v)
 
87
        for k,v in extract_tags(self.repository._git.get_refs()).iteritems():
 
88
            try:
 
89
                obj = self.repository._git[v]
 
90
            except KeyError:
 
91
                mutter("Tag %s points at unknown object %s, ignoring", v, obj)
 
92
                continue
100
93
            while isinstance(obj, Tag):
101
94
                v = obj.object[1]
102
 
                obj = self.repository._git.get_object(v)
 
95
                obj = self.repository._git[v]
103
96
            if not isinstance(obj, Commit):
104
97
                mutter("Tag %s points at object %r that is not a commit, "
105
98
                       "ignoring", k, obj)
107
100
            ret[k] = self.branch.mapping.revision_id_foreign_to_bzr(v)
108
101
        return ret
109
102
 
 
103
    def _set_tag_dict(self, to_dict):
 
104
        extra = set(self.repository._git.get_refs().keys())
 
105
        for k, revid in to_dict.iteritems():
 
106
            name = tag_name_to_ref(k)
 
107
            if name in extra:
 
108
                extra.remove(name)
 
109
            self.set_tag(k, revid)
 
110
        for name in extra:
 
111
            if name.startswith("refs/tags/"):
 
112
                del self.repository._git[name]
 
113
        
110
114
    def set_tag(self, name, revid):
111
 
        self.repository._git.refs["refs/tags/%s" % name], _ = \
 
115
        self.repository._git.refs[tag_name_to_ref(name)], _ = \
112
116
            self.branch.mapping.revision_id_bzr_to_foreign(revid)
113
117
 
114
118
 
 
119
class DictTagDict(LocalGitTagDict):
 
120
 
 
121
    def __init__(self, branch, tags):
 
122
        super(DictTagDict, self).__init__(branch)
 
123
        self._tags = tags
 
124
 
 
125
    def get_tag_dict(self):
 
126
        return self._tags
 
127
 
 
128
 
115
129
class GitBranchFormat(branch.BranchFormat):
116
130
 
117
131
    def get_format_description(self):
118
132
        return 'Git Branch'
119
133
 
 
134
    def network_name(self):
 
135
        return "git"
 
136
 
120
137
    def supports_tags(self):
121
138
        return True
122
139
 
 
140
    def get_foreign_tests_branch_factory(self):
 
141
        from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
 
142
        return ForeignTestsBranchFactory()
 
143
 
123
144
    def make_tags(self, branch):
124
145
        if getattr(branch.repository, "get_refs", None) is not None:
125
146
            from bzrlib.plugins.git.remote import RemoteGitTagDict
131
152
class GitBranch(ForeignBranch):
132
153
    """An adapter to git repositories for bzr Branch objects."""
133
154
 
134
 
    def __init__(self, bzrdir, repository, name, lockfiles):
 
155
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
135
156
        self.repository = repository
136
157
        self._format = GitBranchFormat()
137
158
        self.control_files = lockfiles
138
159
        self.bzrdir = bzrdir
139
160
        super(GitBranch, self).__init__(repository.get_mapping())
140
 
        self.name = name
 
161
        if tagsdict is not None:
 
162
            self.tags = DictTagDict(self, tagsdict)
 
163
        self.ref = ref
 
164
        self.name = ref_to_branch_name(ref)
141
165
        self._head = None
142
 
        self.base = bzrdir.transport.base
 
166
        self.base = bzrdir.root_transport.base
 
167
 
 
168
    def _get_checkout_format(self):
 
169
        """Return the most suitable metadir for a checkout of this branch.
 
170
        Weaves are used if this branch's repository uses weaves.
 
171
        """
 
172
        return get_rich_root_format()
 
173
 
 
174
    def get_child_submit_format(self):
 
175
        """Return the preferred format of submissions to this branch."""
 
176
        ret = self.get_config().get_user_option("child_submit_format")
 
177
        if ret is not None:
 
178
            return ret
 
179
        return "git"
143
180
 
144
181
    def _get_nick(self, local=False, possible_master_transports=None):
145
182
        """Find the nick name for this branch.
154
191
    nick = property(_get_nick, _set_nick)
155
192
 
156
193
    def __repr__(self):
157
 
        return "%s(%r, %r)" % (self.__class__.__name__, self.repository.base, self.name)
 
194
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
 
195
            self.ref)
158
196
 
159
197
    def generate_revision_history(self, revid, old_revid=None):
160
198
        # FIXME: Check that old_revid is in the ancestry of revid
166
204
 
167
205
    def get_stacked_on_url(self):
168
206
        # Git doesn't do stacking (yet...)
169
 
        return None
 
207
        raise errors.UnstackableBranchFormat(self._format, self.base)
170
208
 
171
209
    def get_parent(self):
172
210
        """See Branch.get_parent()."""
200
238
        return branch.InterBranch.get(self, target)._basic_push(
201
239
            overwrite, stop_revision)
202
240
 
203
 
 
 
241
 
204
242
class LocalGitBranch(GitBranch):
205
243
    """A local Git branch."""
206
244
 
207
 
    def _get_checkout_format(self):
208
 
        """Return the most suitable metadir for a checkout of this branch.
209
 
        Weaves are used if this branch's repository uses weaves.
210
 
        """
211
 
        format = self.repository.bzrdir.checkout_metadir()
212
 
        format.set_branch_format(self._format)
213
 
        return format
 
245
    def __init__(self, bzrdir, repository, name, lockfiles, tagsdict=None):
 
246
        super(LocalGitBranch, self).__init__(bzrdir, repository, name, 
 
247
              lockfiles, tagsdict)
 
248
        if not name in repository._git.get_refs().keys():
 
249
            raise errors.NotBranchError(self.base)
214
250
 
215
251
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
216
252
        accelerator_tree=None, hardlink=False):
219
255
            t.ensure_base()
220
256
            format = self._get_checkout_format()
221
257
            checkout = format.initialize_on_transport(t)
222
 
            from_branch = branch.BranchReferenceFormat().initialize(checkout, 
 
258
            from_branch = branch.BranchReferenceFormat().initialize(checkout,
223
259
                self)
224
260
            tree = checkout.create_workingtree(revision_id,
225
261
                from_branch=from_branch, hardlink=hardlink)
228
264
            return self._create_heavyweight_checkout(to_location, revision_id,
229
265
            hardlink)
230
266
 
231
 
    def _create_heavyweight_checkout(self, to_location, revision_id=None, 
 
267
    def _create_heavyweight_checkout(self, to_location, revision_id=None,
232
268
                                     hardlink=False):
233
269
        """Create a new heavyweight checkout of this branch.
234
270
 
241
277
            to_location, force_new_tree=False, format=get_rich_root_format())
242
278
        checkout = checkout_branch.bzrdir
243
279
        checkout_branch.bind(self)
244
 
        # pull up to the specified revision_id to set the initial 
 
280
        # pull up to the specified revision_id to set the initial
245
281
        # branch tip correctly, and seed it with history.
246
282
        checkout_branch.pull(self, stop_revision=revision_id)
247
283
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
256
292
 
257
293
    def _get_head(self):
258
294
        try:
259
 
            return self.repository._git.ref(self.name)
 
295
            return self.repository._git.ref(self.ref)
260
296
        except KeyError:
261
297
            return None
262
298
 
264
300
        self.set_last_revision(revid)
265
301
 
266
302
    def set_last_revision(self, revid):
267
 
        (newhead, self.mapping) = self.mapping.revision_id_bzr_to_foreign(
268
 
                revid)
 
303
        (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
269
304
        self.head = newhead
270
305
 
271
306
    def _set_head(self, value):
272
307
        self._head = value
273
 
        self.repository._git.refs[self.name] = self._head
 
308
        self.repository._git.refs[self.ref] = self._head
274
309
        self._clear_cached_state()
275
310
 
276
311
    head = property(_get_head, _set_head)
298
333
        if not is_quiet():
299
334
            if self.old_revid == self.new_revid:
300
335
                to_file.write('No revisions to pull.\n')
301
 
            else:
302
 
                to_file.write('Now on revision %d (git sha: %s).\n' % 
 
336
            elif self.new_git_head is not None:
 
337
                to_file.write('Now on revision %d (git sha: %s).\n' %
303
338
                        (self.new_revno, self.new_git_head))
 
339
            else:
 
340
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
304
341
        self._show_tag_conficts(to_file)
305
342
 
306
343
 
328
365
    """InterBranch implementation that pulls from Git into bzr."""
329
366
 
330
367
    @classmethod
331
 
    def is_compatible(self, source, target):
332
 
        return (isinstance(source, GitBranch) and 
333
 
                not isinstance(target, GitBranch))
334
 
 
335
 
    def update_revisions(self, stop_revision=None, overwrite=False,
336
 
        graph=None):
337
 
        """See InterBranch.update_revisions()."""
338
 
        interrepo = repository.InterRepository.get(self.source.repository, 
339
 
            self.target.repository)
340
 
        self._head = None
341
 
        self._last_revid = None
 
368
    def _get_interrepo(self, source, target):
 
369
        return repository.InterRepository.get(source.repository,
 
370
            target.repository)
 
371
 
 
372
    @classmethod
 
373
    def is_compatible(cls, source, target):
 
374
        return (isinstance(source, GitBranch) and
 
375
                not isinstance(target, GitBranch) and
 
376
                (getattr(cls._get_interrepo(source, target), "fetch_objects", None) is not None))
 
377
 
 
378
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
379
        graph=None, limit=None):
 
380
        """Like InterBranch.update_revisions(), but with additions.
 
381
 
 
382
        Compared to the `update_revisions()` below, this function takes a
 
383
        `limit` argument that limits how many git commits will be converted
 
384
        and returns the new git head.
 
385
        """
 
386
        interrepo = self._get_interrepo(self.source, self.target)
342
387
        def determine_wants(heads):
343
 
            if not self.source.name in heads:
344
 
                raise NoSuchRef(self.source.name, heads.keys())
 
388
            if not self.source.ref in heads:
 
389
                raise NoSuchRef(self.source.ref, heads.keys())
345
390
            if stop_revision is not None:
346
391
                self._last_revid = stop_revision
347
 
                self._head, mapping = self.source.repository.lookup_git_revid(
 
392
                head, mapping = self.source.repository.lookup_bzr_revision_id(
348
393
                    stop_revision)
349
394
            else:
350
 
                self._head = heads[self.source.name]
351
 
                self._last_revid = \
352
 
                    self.source.mapping.revision_id_foreign_to_bzr(self._head)
 
395
                head = heads[self.source.ref]
 
396
                self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(
 
397
                    head)
353
398
            if self.target.repository.has_revision(self._last_revid):
354
399
                return []
355
 
            return [self._head]
356
 
        interrepo.fetch_objects(determine_wants, self.source.mapping)
 
400
            return [head]
 
401
        pack_hint, head = interrepo.fetch_objects(
 
402
            determine_wants, self.source.mapping, limit=limit)
 
403
        if pack_hint is not None and self.target.repository._format.pack_compresses:
 
404
            self.target.repository.pack(hint=pack_hint)
 
405
        if head is not None:
 
406
            self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(head)
357
407
        if overwrite:
358
408
            prev_last_revid = None
359
409
        else:
360
410
            prev_last_revid = self.target.last_revision()
361
 
        self.target.generate_revision_history(self._last_revid, prev_last_revid)
 
411
        self.target.generate_revision_history(self._last_revid,
 
412
            prev_last_revid)
 
413
        return head
 
414
 
 
415
    def update_revisions(self, stop_revision=None, overwrite=False,
 
416
                         graph=None):
 
417
        """See InterBranch.update_revisions()."""
 
418
        self._update_revisions(stop_revision, overwrite, graph)
362
419
 
363
420
    def pull(self, overwrite=False, stop_revision=None,
364
421
             possible_transports=None, _hook_master=None, run_hooks=True,
365
 
             _override_hook_target=None, local=False):
 
422
             _override_hook_target=None, local=False, limit=None):
366
423
        """See Branch.pull.
367
424
 
368
425
        :param _hook_master: Private parameter - set the branch to
372
429
            so it should not run its hooks.
373
430
        :param _override_hook_target: Private parameter - set the branch to be
374
431
            supplied as the target_branch to pull hooks.
 
432
        :param limit: Only import this many revisons.  `None`, the default,
 
433
            means import all revisions.
375
434
        """
376
435
        # This type of branch can't be bound.
377
436
        if local:
387
446
            # We assume that during 'pull' the target repository is closer than
388
447
            # the source one.
389
448
            graph = self.target.repository.get_graph(self.source.repository)
390
 
            result.old_revno, result.old_revid = \
 
449
            (result.old_revno, result.old_revid) = \
391
450
                self.target.last_revision_info()
392
 
            self.update_revisions(stop_revision, overwrite=overwrite, 
393
 
                graph=graph)
394
 
            result.new_git_head = self._head
 
451
            result.new_git_head = self._update_revisions(
 
452
                stop_revision, overwrite=overwrite, graph=graph, limit=limit)
395
453
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
396
454
                overwrite)
397
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
455
            (result.new_revno, result.new_revid) = \
 
456
                self.target.last_revision_info()
398
457
            if _hook_master:
399
458
                result.master_branch = _hook_master
400
459
                result.local_branch = result.target_branch
414
473
        result.target_branch = self.target
415
474
        graph = self.target.repository.get_graph(self.source.repository)
416
475
        result.old_revno, result.old_revid = self.target.last_revision_info()
417
 
        self.update_revisions(stop_revision, overwrite=overwrite, 
418
 
            graph=graph)
419
 
        result.new_git_head = self._head
 
476
        result.new_git_head = self._update_revisions(
 
477
            stop_revision, overwrite=overwrite, graph=graph)
420
478
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
421
479
            overwrite)
422
480
        result.new_revno, result.new_revid = self.target.last_revision_info()
433
491
    @classmethod
434
492
    def is_compatible(self, source, target):
435
493
        from bzrlib.plugins.git.remote import RemoteGitBranch
436
 
        return (isinstance(source, LocalGitBranch) and 
 
494
        return (isinstance(source, LocalGitBranch) and
437
495
                isinstance(target, RemoteGitBranch))
438
496
 
439
497
    def _basic_push(self, overwrite=False, stop_revision=None):
 
498
        from dulwich.protocol import ZERO_SHA
440
499
        result = GitBranchPushResult()
441
500
        result.source_branch = self.source
442
501
        result.target_branch = self.target
444
503
            stop_revision = self.source.last_revision()
445
504
        # FIXME: Check for diverged branches
446
505
        def get_changed_refs(old_refs):
447
 
            result.old_revid = self.target.mapping.revision_id_foreign_to_bzr(old_refs.get("refs/heads/master", "0" * 40))
448
 
            refs = { "refs/heads/master": self.source.repository.lookup_git_revid(stop_revision)[0] }
 
506
            result.old_revid = self.target.mapping.revision_id_foreign_to_bzr(old_refs.get(self.target.ref, ZERO_SHA))
 
507
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
449
508
            result.new_revid = stop_revision
450
509
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
451
 
                refs["refs/tags/%s" % name] = sha
 
510
                refs[tag_name_to_ref(name)] = sha
452
511
            return refs
453
 
        self.target.repository.send_pack(get_changed_refs, 
454
 
                self.source.repository._git.object_store.generate_pack_contents)
 
512
        self.target.repository.send_pack(get_changed_refs,
 
513
            self.source.repository._git.object_store.generate_pack_contents)
455
514
        return result
456
515
 
457
516
 
461
520
    @classmethod
462
521
    def is_compatible(self, source, target):
463
522
        from bzrlib.plugins.git.remote import RemoteGitBranch
464
 
        return (isinstance(source, RemoteGitBranch) and 
 
523
        return (isinstance(source, RemoteGitBranch) and
465
524
                isinstance(target, LocalGitBranch))
466
525
 
467
526
    def _basic_push(self, overwrite=False, stop_revision=None):
476
535
        return result
477
536
 
478
537
    def update_tags(self, refs):
479
 
        for name, revid in extract_tags(refs, self.target.mapping).iteritems():
 
538
        for name, v in extract_tags(refs).iteritems():
 
539
            revid = self.target.mapping.revision_id_foreign_to_bzr(v)
480
540
            self.target.tags.set_tag(name, revid)
481
541
 
482
542
    def update_refs(self, stop_revision=None):
483
 
        interrepo = repository.InterRepository.get(self.source.repository, 
 
543
        interrepo = repository.InterRepository.get(self.source.repository,
484
544
            self.target.repository)
485
545
        if stop_revision is None:
486
546
            refs = interrepo.fetch_refs(branches=["HEAD"])
489
549
            refs = interrepo.fetch_refs(revision_id=stop_revision)
490
550
        return refs, stop_revision
491
551
 
492
 
    def pull(self, stop_revision=None, overwrite=False, 
493
 
        possible_transports=None, local=False):
 
552
    def pull(self, stop_revision=None, overwrite=False,
 
553
        possible_transports=None, run_hooks=True,local=False):
494
554
        # This type of branch can't be bound.
495
555
        if local:
496
556
            raise errors.LocalRequiresBoundBranch()
504
564
        result.new_revid = self.target.last_revision()
505
565
        return result
506
566
 
507
 
    
 
567
 
508
568
class InterToGitBranch(branch.InterBranch):
509
569
    """InterBranch implementation that pulls from Git into bzr."""
510
570
 
 
571
    @staticmethod
 
572
    def _get_branch_formats_to_test():
 
573
        return None, None
 
574
 
511
575
    @classmethod
512
576
    def is_compatible(self, source, target):
513
 
        return (not isinstance(source, GitBranch) and 
 
577
        return (not isinstance(source, GitBranch) and
514
578
                isinstance(target, GitBranch))
515
579
 
516
580
    def update_revisions(self, *args, **kwargs):
517
581
        raise NoPushSupport()
518
582
 
519
 
    def push(self, overwrite=True, stop_revision=None, 
 
583
    def push(self, overwrite=True, stop_revision=None,
520
584
             _override_hook_source_branch=None):
521
585
        raise NoPushSupport()
522
586
 
523
587
    def lossy_push(self, stop_revision=None):
 
588
        from dulwich.protocol import ZERO_SHA
524
589
        result = GitBranchPushResult()
525
590
        result.source_branch = self.source
526
591
        result.target_branch = self.target
527
 
        result.old_revid = self.target.last_revision()
528
592
        if stop_revision is None:
529
593
            stop_revision = self.source.last_revision()
530
594
        # FIXME: Check for diverged branches
531
 
        refs = { "refs/heads/master": stop_revision }
 
595
        refs = { self.target.ref: stop_revision }
532
596
        for name, revid in self.source.tags.get_tag_dict().iteritems():
533
597
            if self.source.repository.has_revision(revid):
534
 
                refs["refs/tags/%s" % name] = revid
535
 
        revidmap, new_refs = self.target.repository.dfetch_refs(
 
598
                refs[tag_name_to_ref(name)] = revid
 
599
        revidmap, old_refs, new_refs = self.target.repository.dfetch_refs(
536
600
            self.source.repository, refs)
537
 
        if revidmap != {}:
538
 
            self.target.generate_revision_history(revidmap[stop_revision])
539
 
            result.new_revid = revidmap[stop_revision]
540
 
        else:
541
 
            result.new_revid = result.old_revid
 
601
        result.old_revid = self.target.mapping.revision_id_foreign_to_bzr(
 
602
            old_refs.get(self.target.ref, ZERO_SHA))
 
603
        result.new_revid = self.target.mapping.revision_id_foreign_to_bzr(
 
604
            new_refs[self.target.ref])
542
605
        result.revidmap = revidmap
543
606
        return result
544
607