/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 formatting.

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,
52
51
    NoSuchRef,
53
52
    )
54
53
 
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):
 
54
from bzrlib.foreign import ForeignBranch
 
55
 
 
56
 
 
57
def extract_tags(refs):
 
58
    """Extract the tags from a refs dictionary.
 
59
 
 
60
    :param refs: Refs to extract the tags from.
 
61
    :return: Dictionary mapping tag names to SHA1s.
 
62
    """
65
63
    ret = {}
66
64
    for k,v in refs.iteritems():
67
65
        if k.startswith("refs/tags/") and not k.endswith("^{}"):
68
66
            v = refs.get(k+"^{}", v)
69
 
            ret[k[len("refs/tags/"):]] = mapping.revision_id_foreign_to_bzr(v)
 
67
            ret[k[len("refs/tags/"):]] = v
70
68
    return ret
71
69
 
72
70
 
 
71
def branch_name_to_ref(name):
 
72
    """Map a branch name to a ref.
 
73
 
 
74
    :param name: Branch name
 
75
    :return: ref string
 
76
    """
 
77
    if name is None or name == "HEAD":
 
78
        return "HEAD"
 
79
    if not name.startswith("refs/"):
 
80
        return "refs/heads/%s" % name
 
81
    else:
 
82
        return name
 
83
 
 
84
 
 
85
def ref_to_branch_name(ref):
 
86
    """Map a ref to a branch name
 
87
 
 
88
    :param ref: Ref
 
89
    :return: A branch name
 
90
    """
 
91
    if ref == "HEAD":
 
92
        return "HEAD"
 
93
    if ref.startswith("refs/heads/"):
 
94
        return ref[len("refs/heads/"):]
 
95
    raise ValueError("unable to map ref %s back to branch name")
 
96
 
 
97
 
73
98
class GitPullResult(branch.PullResult):
74
99
 
75
100
    def _lookup_revno(self, revid):
95
120
 
96
121
    def get_tag_dict(self):
97
122
        ret = {}
98
 
        for k,v in self.repository._git.refs.as_dict("refs/tags").iteritems():
99
 
            obj = self.repository._git.get_object(v)
 
123
        for k,v in extract_tags(self.repository._git.get_refs()).iteritems():
 
124
            try:
 
125
                obj = self.repository._git[v]
 
126
            except KeyError:
 
127
                mutter("Tag %s points at unknown object %s, ignoring", v, obj)
 
128
                continue
100
129
            while isinstance(obj, Tag):
101
130
                v = obj.object[1]
102
 
                obj = self.repository._git.get_object(v)
 
131
                obj = self.repository._git[v]
103
132
            if not isinstance(obj, Commit):
104
133
                mutter("Tag %s points at object %r that is not a commit, "
105
134
                       "ignoring", k, obj)
107
136
            ret[k] = self.branch.mapping.revision_id_foreign_to_bzr(v)
108
137
        return ret
109
138
 
 
139
    def _set_tag_dict(self, to_dict):
 
140
        extra = set(self.repository._git.get_refs().keys())
 
141
        for k, revid in to_dict.iteritems():
 
142
            name = "refs/tags/%s" % k
 
143
            if name in extra:
 
144
                extra.remove(name)
 
145
            self.set_tag(k, revid)
 
146
        for name in extra:
 
147
            if name.startswith("refs/tags/"):
 
148
                del self.repository._git[name]
 
149
        
110
150
    def set_tag(self, name, revid):
111
151
        self.repository._git.refs["refs/tags/%s" % name], _ = \
112
152
            self.branch.mapping.revision_id_bzr_to_foreign(revid)
113
153
 
114
154
 
 
155
class DictTagDict(LocalGitTagDict):
 
156
 
 
157
    def __init__(self, branch, tags):
 
158
        super(DictTagDict, self).__init__(branch)
 
159
        self._tags = tags
 
160
 
 
161
    def get_tag_dict(self):
 
162
        return self._tags
 
163
 
 
164
 
115
165
class GitBranchFormat(branch.BranchFormat):
116
166
 
117
167
    def get_format_description(self):
118
168
        return 'Git Branch'
119
169
 
 
170
    def network_name(self):
 
171
        return "git"
 
172
 
120
173
    def supports_tags(self):
121
174
        return True
122
175
 
 
176
    def get_foreign_tests_branch_factory(self):
 
177
        from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
 
178
        return ForeignTestsBranchFactory()
 
179
 
123
180
    def make_tags(self, branch):
124
181
        if getattr(branch.repository, "get_refs", None) is not None:
125
182
            from bzrlib.plugins.git.remote import RemoteGitTagDict
131
188
class GitBranch(ForeignBranch):
132
189
    """An adapter to git repositories for bzr Branch objects."""
133
190
 
134
 
    def __init__(self, bzrdir, repository, name, lockfiles):
 
191
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
135
192
        self.repository = repository
136
193
        self._format = GitBranchFormat()
137
194
        self.control_files = lockfiles
138
195
        self.bzrdir = bzrdir
139
196
        super(GitBranch, self).__init__(repository.get_mapping())
140
 
        self.name = name
 
197
        if tagsdict is not None:
 
198
            self.tags = DictTagDict(self, tagsdict)
 
199
        self.ref = ref
 
200
        self.name = ref_to_branch_name(ref)
141
201
        self._head = None
142
 
        self.base = bzrdir.transport.base
 
202
        self.base = bzrdir.root_transport.base
 
203
 
 
204
    def _get_checkout_format(self):
 
205
        """Return the most suitable metadir for a checkout of this branch.
 
206
        Weaves are used if this branch's repository uses weaves.
 
207
        """
 
208
        return get_rich_root_format()
 
209
 
 
210
    def get_child_submit_format(self):
 
211
        """Return the preferred format of submissions to this branch."""
 
212
        ret = self.get_config().get_user_option("child_submit_format")
 
213
        if ret is not None:
 
214
            return ret
 
215
        return "git"
143
216
 
144
217
    def _get_nick(self, local=False, possible_master_transports=None):
145
218
        """Find the nick name for this branch.
154
227
    nick = property(_get_nick, _set_nick)
155
228
 
156
229
    def __repr__(self):
157
 
        return "%s(%r, %r)" % (self.__class__.__name__, self.repository.base, self.name)
 
230
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
 
231
            self.ref)
158
232
 
159
233
    def generate_revision_history(self, revid, old_revid=None):
160
234
        # FIXME: Check that old_revid is in the ancestry of revid
166
240
 
167
241
    def get_stacked_on_url(self):
168
242
        # Git doesn't do stacking (yet...)
169
 
        return None
 
243
        raise errors.UnstackableBranchFormat(self._format, self.base)
170
244
 
171
245
    def get_parent(self):
172
246
        """See Branch.get_parent()."""
200
274
        return branch.InterBranch.get(self, target)._basic_push(
201
275
            overwrite, stop_revision)
202
276
 
203
 
 
 
277
 
204
278
class LocalGitBranch(GitBranch):
205
279
    """A local Git branch."""
206
280
 
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
 
281
    def __init__(self, bzrdir, repository, name, lockfiles, tagsdict=None):
 
282
        super(LocalGitBranch, self).__init__(bzrdir, repository, name, 
 
283
              lockfiles, tagsdict)
 
284
        if not name in repository._git.get_refs().keys():
 
285
            raise errors.NotBranchError(self.base)
214
286
 
215
287
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
216
288
        accelerator_tree=None, hardlink=False):
219
291
            t.ensure_base()
220
292
            format = self._get_checkout_format()
221
293
            checkout = format.initialize_on_transport(t)
222
 
            from_branch = branch.BranchReferenceFormat().initialize(checkout, 
 
294
            from_branch = branch.BranchReferenceFormat().initialize(checkout,
223
295
                self)
224
296
            tree = checkout.create_workingtree(revision_id,
225
297
                from_branch=from_branch, hardlink=hardlink)
228
300
            return self._create_heavyweight_checkout(to_location, revision_id,
229
301
            hardlink)
230
302
 
231
 
    def _create_heavyweight_checkout(self, to_location, revision_id=None, 
 
303
    def _create_heavyweight_checkout(self, to_location, revision_id=None,
232
304
                                     hardlink=False):
233
305
        """Create a new heavyweight checkout of this branch.
234
306
 
241
313
            to_location, force_new_tree=False, format=get_rich_root_format())
242
314
        checkout = checkout_branch.bzrdir
243
315
        checkout_branch.bind(self)
244
 
        # pull up to the specified revision_id to set the initial 
 
316
        # pull up to the specified revision_id to set the initial
245
317
        # branch tip correctly, and seed it with history.
246
318
        checkout_branch.pull(self, stop_revision=revision_id)
247
319
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
256
328
 
257
329
    def _get_head(self):
258
330
        try:
259
 
            return self.repository._git.ref(self.name)
 
331
            return self.repository._git.ref(self.ref)
260
332
        except KeyError:
261
333
            return None
262
334
 
270
342
 
271
343
    def _set_head(self, value):
272
344
        self._head = value
273
 
        self.repository._git.refs[self.name] = self._head
 
345
        self.repository._git.refs[self.ref] = self._head
274
346
        self._clear_cached_state()
275
347
 
276
348
    head = property(_get_head, _set_head)
298
370
        if not is_quiet():
299
371
            if self.old_revid == self.new_revid:
300
372
                to_file.write('No revisions to pull.\n')
301
 
            else:
302
 
                to_file.write('Now on revision %d (git sha: %s).\n' % 
 
373
            elif self.new_git_head is not None:
 
374
                to_file.write('Now on revision %d (git sha: %s).\n' %
303
375
                        (self.new_revno, self.new_git_head))
 
376
            else:
 
377
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
304
378
        self._show_tag_conficts(to_file)
305
379
 
306
380
 
328
402
    """InterBranch implementation that pulls from Git into bzr."""
329
403
 
330
404
    @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
 
405
    def _get_interrepo(self, source, target):
 
406
        return repository.InterRepository.get(source.repository,
 
407
            target.repository)
 
408
 
 
409
    @classmethod
 
410
    def is_compatible(cls, source, target):
 
411
        return (isinstance(source, GitBranch) and
 
412
                not isinstance(target, GitBranch) and
 
413
                (getattr(cls._get_interrepo(source, target), "fetch_objects", None) is not None))
 
414
 
 
415
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
416
        graph=None, limit=None):
 
417
        """Like InterBranch.update_revisions(), but with additions.
 
418
 
 
419
        Compared to the `update_revisions()` below, this function takes a
 
420
        `limit` argument that limits how many git commits will be converted
 
421
        and returns the new git head.
 
422
        """
 
423
        interrepo = self._get_interrepo(self.source, self.target)
342
424
        def determine_wants(heads):
343
 
            if not self.source.name in heads:
344
 
                raise NoSuchRef(self.source.name, heads.keys())
 
425
            if not self.source.ref in heads:
 
426
                raise NoSuchRef(self.source.ref, heads.keys())
345
427
            if stop_revision is not None:
346
428
                self._last_revid = stop_revision
347
 
                self._head, mapping = self.source.repository.lookup_git_revid(
 
429
                head, mapping = self.source.repository.lookup_bzr_revision_id(
348
430
                    stop_revision)
349
431
            else:
350
 
                self._head = heads[self.source.name]
351
 
                self._last_revid = \
352
 
                    self.source.mapping.revision_id_foreign_to_bzr(self._head)
 
432
                head = heads[self.source.ref]
 
433
                self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(
 
434
                    head)
353
435
            if self.target.repository.has_revision(self._last_revid):
354
436
                return []
355
 
            return [self._head]
356
 
        interrepo.fetch_objects(determine_wants, self.source.mapping)
 
437
            return [head]
 
438
        pack_hint, head = interrepo.fetch_objects(
 
439
            determine_wants, self.source.mapping, limit=limit)
 
440
        if pack_hint is not None and self.target.repository._format.pack_compresses:
 
441
            self.target.repository.pack(hint=pack_hint)
 
442
        if head is not None:
 
443
            self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(head)
357
444
        if overwrite:
358
445
            prev_last_revid = None
359
446
        else:
360
447
            prev_last_revid = self.target.last_revision()
361
 
        self.target.generate_revision_history(self._last_revid, prev_last_revid)
 
448
        self.target.generate_revision_history(self._last_revid,
 
449
            prev_last_revid)
 
450
        return head
 
451
 
 
452
    def update_revisions(self, stop_revision=None, overwrite=False,
 
453
                         graph=None):
 
454
        """See InterBranch.update_revisions()."""
 
455
        self._update_revisions(stop_revision, overwrite, graph)
362
456
 
363
457
    def pull(self, overwrite=False, stop_revision=None,
364
458
             possible_transports=None, _hook_master=None, run_hooks=True,
365
 
             _override_hook_target=None, local=False):
 
459
             _override_hook_target=None, local=False, limit=None):
366
460
        """See Branch.pull.
367
461
 
368
462
        :param _hook_master: Private parameter - set the branch to
372
466
            so it should not run its hooks.
373
467
        :param _override_hook_target: Private parameter - set the branch to be
374
468
            supplied as the target_branch to pull hooks.
 
469
        :param limit: Only import this many revisons.  `None`, the default,
 
470
            means import all revisions.
375
471
        """
376
472
        # This type of branch can't be bound.
377
473
        if local:
387
483
            # We assume that during 'pull' the target repository is closer than
388
484
            # the source one.
389
485
            graph = self.target.repository.get_graph(self.source.repository)
390
 
            result.old_revno, result.old_revid = \
 
486
            (result.old_revno, result.old_revid) = \
391
487
                self.target.last_revision_info()
392
 
            self.update_revisions(stop_revision, overwrite=overwrite, 
393
 
                graph=graph)
394
 
            result.new_git_head = self._head
 
488
            result.new_git_head = self._update_revisions(
 
489
                stop_revision, overwrite=overwrite, graph=graph, limit=limit)
395
490
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
396
491
                overwrite)
397
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
492
            (result.new_revno, result.new_revid) = \
 
493
                self.target.last_revision_info()
398
494
            if _hook_master:
399
495
                result.master_branch = _hook_master
400
496
                result.local_branch = result.target_branch
414
510
        result.target_branch = self.target
415
511
        graph = self.target.repository.get_graph(self.source.repository)
416
512
        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
 
513
        result.new_git_head = self._update_revisions(
 
514
            stop_revision, overwrite=overwrite, graph=graph)
420
515
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
421
516
            overwrite)
422
517
        result.new_revno, result.new_revid = self.target.last_revision_info()
433
528
    @classmethod
434
529
    def is_compatible(self, source, target):
435
530
        from bzrlib.plugins.git.remote import RemoteGitBranch
436
 
        return (isinstance(source, LocalGitBranch) and 
 
531
        return (isinstance(source, LocalGitBranch) and
437
532
                isinstance(target, RemoteGitBranch))
438
533
 
439
534
    def _basic_push(self, overwrite=False, stop_revision=None):
445
540
        # FIXME: Check for diverged branches
446
541
        def get_changed_refs(old_refs):
447
542
            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] }
 
543
            refs = { "refs/heads/master": self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
449
544
            result.new_revid = stop_revision
450
545
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
451
546
                refs["refs/tags/%s" % name] = sha
452
547
            return refs
453
 
        self.target.repository.send_pack(get_changed_refs, 
454
 
                self.source.repository._git.object_store.generate_pack_contents)
 
548
        self.target.repository.send_pack(get_changed_refs,
 
549
            self.source.repository._git.object_store.generate_pack_contents)
455
550
        return result
456
551
 
457
552
 
461
556
    @classmethod
462
557
    def is_compatible(self, source, target):
463
558
        from bzrlib.plugins.git.remote import RemoteGitBranch
464
 
        return (isinstance(source, RemoteGitBranch) and 
 
559
        return (isinstance(source, RemoteGitBranch) and
465
560
                isinstance(target, LocalGitBranch))
466
561
 
467
562
    def _basic_push(self, overwrite=False, stop_revision=None):
476
571
        return result
477
572
 
478
573
    def update_tags(self, refs):
479
 
        for name, revid in extract_tags(refs, self.target.mapping).iteritems():
 
574
        for name, v in extract_tags(refs).iteritems():
 
575
            revid = self.target.mapping.revision_id_foreign_to_bzr(v)
480
576
            self.target.tags.set_tag(name, revid)
481
577
 
482
578
    def update_refs(self, stop_revision=None):
483
 
        interrepo = repository.InterRepository.get(self.source.repository, 
 
579
        interrepo = repository.InterRepository.get(self.source.repository,
484
580
            self.target.repository)
485
581
        if stop_revision is None:
486
582
            refs = interrepo.fetch_refs(branches=["HEAD"])
489
585
            refs = interrepo.fetch_refs(revision_id=stop_revision)
490
586
        return refs, stop_revision
491
587
 
492
 
    def pull(self, stop_revision=None, overwrite=False, 
493
 
        possible_transports=None, local=False):
 
588
    def pull(self, stop_revision=None, overwrite=False,
 
589
        possible_transports=None, run_hooks=True,local=False):
494
590
        # This type of branch can't be bound.
495
591
        if local:
496
592
            raise errors.LocalRequiresBoundBranch()
504
600
        result.new_revid = self.target.last_revision()
505
601
        return result
506
602
 
507
 
    
 
603
 
508
604
class InterToGitBranch(branch.InterBranch):
509
605
    """InterBranch implementation that pulls from Git into bzr."""
510
606
 
 
607
    @staticmethod
 
608
    def _get_branch_formats_to_test():
 
609
        return None, None
 
610
 
511
611
    @classmethod
512
612
    def is_compatible(self, source, target):
513
 
        return (not isinstance(source, GitBranch) and 
 
613
        return (not isinstance(source, GitBranch) and
514
614
                isinstance(target, GitBranch))
515
615
 
516
616
    def update_revisions(self, *args, **kwargs):
517
617
        raise NoPushSupport()
518
618
 
519
 
    def push(self, overwrite=True, stop_revision=None, 
 
619
    def push(self, overwrite=True, stop_revision=None,
520
620
             _override_hook_source_branch=None):
521
621
        raise NoPushSupport()
522
622
 
524
624
        result = GitBranchPushResult()
525
625
        result.source_branch = self.source
526
626
        result.target_branch = self.target
527
 
        result.old_revid = self.target.last_revision()
 
627
        try:
 
628
            result.old_revid = self.target.last_revision()
 
629
        except NoSuchRef:
 
630
            result.old_revid = revision.NULL_REVISION
528
631
        if stop_revision is None:
529
632
            stop_revision = self.source.last_revision()
530
633
        # FIXME: Check for diverged branches