~jelmer/bzr-git/index-based

« back to all changes in this revision

Viewing changes to branch.py

  • Committer: Jelmer Vernooij
  • Date: 2010-06-23 19:07:06 UTC
  • mfrom: (677.7.182 trunk)
  • Revision ID: jelmer@samba.org-20100623190706-t2mqoj2o304ni80f
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2007 Canonical Ltd
2
 
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
 
2
# Copyright (C) 2009-2010 Jelmer Vernooij <jelmer@samba.org>
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
5
5
# it under the terms of the GNU General Public License as published by
40
40
    mutter,
41
41
    )
42
42
 
43
 
from bzrlib.plugins.git import (
44
 
    get_rich_root_format,
45
 
    )
46
43
from bzrlib.plugins.git.config import (
47
44
    GitBranchConfig,
48
45
    )
50
47
    NoPushSupport,
51
48
    NoSuchRef,
52
49
    )
 
50
from bzrlib.plugins.git.refs import (
 
51
    branch_name_to_ref,
 
52
    ref_to_branch_name,
 
53
    extract_tags,
 
54
    tag_name_to_ref,
 
55
    )
53
56
 
54
57
from bzrlib.foreign import ForeignBranch
55
58
 
56
59
 
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
 
    """
63
 
    ret = {}
64
 
    for k,v in refs.iteritems():
65
 
        if k.startswith("refs/tags/") and not k.endswith("^{}"):
66
 
            v = refs.get(k+"^{}", v)
67
 
            ret[k[len("refs/tags/"):]] = v
68
 
    return ret
69
 
 
70
 
 
71
 
def branch_name_to_ref(name, default=None):
72
 
    """Map a branch name to a ref.
73
 
 
74
 
    :param name: Branch name
75
 
    :return: ref string
76
 
    """
77
 
    if name is None:
78
 
        return default
79
 
    if name == "HEAD":
80
 
        return "HEAD"
81
 
    if not name.startswith("refs/"):
82
 
        return "refs/heads/%s" % name
83
 
    else:
84
 
        return name
85
 
 
86
 
 
87
 
def ref_to_branch_name(ref):
88
 
    """Map a ref to a branch name
89
 
 
90
 
    :param ref: Ref
91
 
    :return: A branch name
92
 
    """
93
 
    if ref == "HEAD":
94
 
        return "HEAD"
95
 
    if ref.startswith("refs/heads/"):
96
 
        return ref[len("refs/heads/"):]
97
 
    raise ValueError("unable to map ref %s back to branch name")
98
 
 
99
 
 
100
60
class GitPullResult(branch.PullResult):
101
61
 
102
62
    def _lookup_revno(self, revid):
135
95
                mutter("Tag %s points at object %r that is not a commit, "
136
96
                       "ignoring", k, obj)
137
97
                continue
138
 
            ret[k] = self.branch.mapping.revision_id_foreign_to_bzr(v)
 
98
            ret[k] = self.branch.lookup_foreign_revision_id(v)
139
99
        return ret
140
100
 
141
101
    def _set_tag_dict(self, to_dict):
142
102
        extra = set(self.repository._git.get_refs().keys())
143
103
        for k, revid in to_dict.iteritems():
144
 
            name = "refs/tags/%s" % k
 
104
            name = tag_name_to_ref(k)
145
105
            if name in extra:
146
106
                extra.remove(name)
147
107
            self.set_tag(k, revid)
150
110
                del self.repository._git[name]
151
111
        
152
112
    def set_tag(self, name, revid):
153
 
        self.repository._git.refs["refs/tags/%s" % name], _ = \
 
113
        self.repository._git.refs[tag_name_to_ref(name)], _ = \
154
114
            self.branch.mapping.revision_id_bzr_to_foreign(revid)
155
115
 
156
116
 
187
147
            return LocalGitTagDict(branch)
188
148
 
189
149
 
 
150
class GitReadLock(object):
 
151
 
 
152
    def __init__(self, unlock):
 
153
        self.unlock = unlock
 
154
 
 
155
 
 
156
class GitWriteLock(object):
 
157
 
 
158
    def __init__(self, unlock):
 
159
        self.unlock = unlock
 
160
 
 
161
 
190
162
class GitBranch(ForeignBranch):
191
163
    """An adapter to git repositories for bzr Branch objects."""
192
164
 
207
179
        """Return the most suitable metadir for a checkout of this branch.
208
180
        Weaves are used if this branch's repository uses weaves.
209
181
        """
210
 
        return get_rich_root_format()
 
182
        return bzrdir.format_registry.make_bzrdir("default")
211
183
 
212
184
    def get_child_submit_format(self):
213
185
        """Return the preferred format of submissions to this branch."""
221
193
 
222
194
        :return: Branch nick
223
195
        """
224
 
        return self.name
 
196
        return self.name or "HEAD"
225
197
 
226
198
    def _set_nick(self, nick):
227
199
        raise NotImplementedError
230
202
 
231
203
    def __repr__(self):
232
204
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
233
 
            self.ref)
 
205
            self.ref or "HEAD")
234
206
 
235
207
    def generate_revision_history(self, revid, old_revid=None):
236
208
        # FIXME: Check that old_revid is in the ancestry of revid
239
211
 
240
212
    def lock_write(self):
241
213
        self.control_files.lock_write()
 
214
        return GitWriteLock(self.unlock)
242
215
 
243
216
    def get_stacked_on_url(self):
244
217
        # Git doesn't do stacking (yet...)
255
228
 
256
229
    def lock_read(self):
257
230
        self.control_files.lock_read()
 
231
        return GitReadLock(self.unlock)
258
232
 
259
233
    def is_locked(self):
260
234
        return self.control_files.is_locked()
270
244
        # perhaps should escape this ?
271
245
        if self.head is None:
272
246
            return revision.NULL_REVISION
273
 
        return self.mapping.revision_id_foreign_to_bzr(self.head)
 
247
        return self.lookup_foreign_revision_id(self.head)
274
248
 
275
249
    def _basic_push(self, target, overwrite=False, stop_revision=None):
276
250
        return branch.InterBranch.get(self, target)._basic_push(
277
251
            overwrite, stop_revision)
278
252
 
 
253
    def lookup_foreign_revision_id(self, foreign_revid):
 
254
        return self.repository.lookup_foreign_revision_id(foreign_revid, 
 
255
            self.mapping)
 
256
 
279
257
 
280
258
class LocalGitBranch(GitBranch):
281
259
    """A local Git branch."""
283
261
    def __init__(self, bzrdir, repository, name, lockfiles, tagsdict=None):
284
262
        super(LocalGitBranch, self).__init__(bzrdir, repository, name, 
285
263
              lockfiles, tagsdict)
286
 
        if not name in repository._git.get_refs().keys():
 
264
        refs = repository._git.get_refs()
 
265
        if not (name in refs.keys() or "HEAD" in refs.keys()):
287
266
            raise errors.NotBranchError(self.base)
288
267
 
289
268
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
312
291
        :return: WorkingTree object of checkout.
313
292
        """
314
293
        checkout_branch = bzrdir.BzrDir.create_branch_convenience(
315
 
            to_location, force_new_tree=False, format=get_rich_root_format())
 
294
            to_location, force_new_tree=False)
316
295
        checkout = checkout_branch.bzrdir
317
296
        checkout_branch.bind(self)
318
297
        # pull up to the specified revision_id to set the initial
330
309
 
331
310
    def _get_head(self):
332
311
        try:
333
 
            return self.repository._git.ref(self.ref)
 
312
            return self.repository._git.ref(self.ref or "HEAD")
334
313
        except KeyError:
335
314
            return None
336
315
 
338
317
        self.set_last_revision(revid)
339
318
 
340
319
    def set_last_revision(self, revid):
341
 
        (newhead, self.mapping) = self.mapping.revision_id_bzr_to_foreign(
342
 
                revid)
 
320
        (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
343
321
        self.head = newhead
344
322
 
345
323
    def _set_head(self, value):
346
324
        self._head = value
347
 
        self.repository._git.refs[self.ref] = self._head
 
325
        self.repository._git.refs[self.ref or "HEAD"] = self._head
348
326
        self._clear_cached_state()
349
327
 
350
328
    head = property(_get_head, _set_head)
364
342
 
365
343
    def supports_tags(self):
366
344
        return True
367
 
 
 
345
    
368
346
 
369
347
class GitBranchPullResult(branch.PullResult):
370
348
 
 
349
    def __init__(self):
 
350
        super(GitBranchPullResult, self).__init__()
 
351
        self.new_git_head = None
 
352
        self._old_revno = None
 
353
        self._new_revno = None
 
354
 
371
355
    def report(self, to_file):
372
356
        if not is_quiet():
373
357
            if self.old_revid == self.new_revid:
379
363
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
380
364
        self._show_tag_conficts(to_file)
381
365
 
 
366
    def _lookup_revno(self, revid):
 
367
        assert isinstance(revid, str), "was %r" % revid
 
368
        # Try in source branch first, it'll be faster
 
369
        try:
 
370
            return self.source_branch.revision_id_to_revno(revid)
 
371
        except errors.NoSuchRevision:
 
372
            # FIXME: Check using graph.find_distance_to_null() ?
 
373
            return self.target_branch.revision_id_to_revno(revid)
 
374
 
 
375
    def _get_old_revno(self):
 
376
        if self._old_revno is not None:
 
377
            return self._old_revno
 
378
        return self._lookup_revno(self.old_revid)
 
379
 
 
380
    def _set_old_revno(self, revno):
 
381
        self._old_revno = revno
 
382
 
 
383
    old_revno = property(_get_old_revno, _set_old_revno)
 
384
 
 
385
    def _get_new_revno(self):
 
386
        if self._new_revno is not None:
 
387
            return self._new_revno
 
388
        return self._lookup_revno(self.new_revid)
 
389
 
 
390
    def _set_new_revno(self, revno):
 
391
        self._new_revno = revno
 
392
    
 
393
    new_revno = property(_get_new_revno, _set_new_revno)
 
394
 
382
395
 
383
396
class GitBranchPushResult(branch.BranchPushResult):
384
397
 
424
437
        """
425
438
        interrepo = self._get_interrepo(self.source, self.target)
426
439
        def determine_wants(heads):
427
 
            if not self.source.ref in heads:
 
440
            if self.source.ref is not None and not self.source.ref in heads:
428
441
                raise NoSuchRef(self.source.ref, heads.keys())
429
442
            if stop_revision is not None:
430
443
                self._last_revid = stop_revision
431
444
                head, mapping = self.source.repository.lookup_bzr_revision_id(
432
445
                    stop_revision)
433
446
            else:
434
 
                head = heads[self.source.ref]
435
 
                self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(
436
 
                    head)
 
447
                if self.source.ref is not None:
 
448
                    head = heads[self.source.ref]
 
449
                else:
 
450
                    head = heads["HEAD"]
 
451
                self._last_revid = self.source.lookup_foreign_revision_id(head)
437
452
            if self.target.repository.has_revision(self._last_revid):
438
453
                return []
439
454
            return [head]
440
455
        pack_hint, head = interrepo.fetch_objects(
441
456
            determine_wants, self.source.mapping, limit=limit)
442
 
        if pack_hint is not None and self.target.repository._format.pack_compresses:
 
457
        if (pack_hint is not None and
 
458
            self.target.repository._format.pack_compresses):
443
459
            self.target.repository.pack(hint=pack_hint)
444
460
        if head is not None:
445
 
            self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(head)
 
461
            self._last_revid = self.source.lookup_foreign_revision_id(head)
446
462
        if overwrite:
447
463
            prev_last_revid = None
448
464
        else:
534
550
                isinstance(target, RemoteGitBranch))
535
551
 
536
552
    def _basic_push(self, overwrite=False, stop_revision=None):
 
553
        from dulwich.protocol import ZERO_SHA
537
554
        result = GitBranchPushResult()
538
555
        result.source_branch = self.source
539
556
        result.target_branch = self.target
541
558
            stop_revision = self.source.last_revision()
542
559
        # FIXME: Check for diverged branches
543
560
        def get_changed_refs(old_refs):
544
 
            result.old_revid = self.target.mapping.revision_id_foreign_to_bzr(old_refs.get(self.target.ref, "0" * 40))
 
561
            result.old_revid = self.target.lookup_foreign_revision_id(old_refs.get(self.target.ref, ZERO_SHA))
545
562
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
546
563
            result.new_revid = stop_revision
547
564
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
548
 
                refs["refs/tags/%s" % name] = sha
 
565
                refs[tag_name_to_ref(name)] = sha
549
566
            return refs
550
567
        self.target.repository.send_pack(get_changed_refs,
551
568
            self.source.repository._git.object_store.generate_pack_contents)
574
591
 
575
592
    def update_tags(self, refs):
576
593
        for name, v in extract_tags(refs).iteritems():
577
 
            revid = self.target.mapping.revision_id_foreign_to_bzr(v)
 
594
            revid = self.target.lookup_foreign_revision_id(v)
578
595
            self.target.tags.set_tag(name, revid)
579
596
 
580
597
    def update_refs(self, stop_revision=None):
582
599
            self.target.repository)
583
600
        if stop_revision is None:
584
601
            refs = interrepo.fetch_refs(branches=["HEAD"])
585
 
            stop_revision = self.target.mapping.revision_id_foreign_to_bzr(refs["HEAD"])
 
602
            stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
586
603
        else:
587
604
            refs = interrepo.fetch_refs(revision_id=stop_revision)
588
605
        return refs, stop_revision
618
635
    def update_revisions(self, *args, **kwargs):
619
636
        raise NoPushSupport()
620
637
 
621
 
    def push(self, overwrite=True, stop_revision=None,
 
638
    def _get_new_refs(self, stop_revision=None):
 
639
        if stop_revision is None:
 
640
            stop_revision = self.source.last_revision()
 
641
        main_ref = self.target.ref or "refs/heads/master"
 
642
        refs = { main_ref: stop_revision }
 
643
        for name, revid in self.source.tags.get_tag_dict().iteritems():
 
644
            if self.source.repository.has_revision(revid):
 
645
                refs[tag_name_to_ref(name)] = revid
 
646
        return refs, main_ref
 
647
 
 
648
    def pull(self, overwrite=False, stop_revision=None, local=False,
 
649
             possible_transports=None):
 
650
        from dulwich.protocol import ZERO_SHA
 
651
        result = GitBranchPullResult()
 
652
        result.source_branch = self.source
 
653
        result.target_branch = self.target
 
654
        # FIXME: Check for diverged branches
 
655
        old_refs = self.target.repository._git.get_refs()
 
656
        refs = dict(old_refs)
 
657
        new_refs, main_ref = self._get_new_refs(stop_revision)
 
658
        refs.update(new_refs)
 
659
        self.target.repository.fetch_refs(self.source.repository, refs)
 
660
        result.old_revid = self.target.lookup_foreign_revision_id(
 
661
            old_refs.get(main_ref, ZERO_SHA))
 
662
        result.new_revid = refs[main_ref]
 
663
        return result
 
664
 
 
665
    def push(self, overwrite=False, stop_revision=None,
622
666
             _override_hook_source_branch=None):
623
 
        raise NoPushSupport()
 
667
        from dulwich.protocol import ZERO_SHA
 
668
        result = GitBranchPushResult()
 
669
        result.source_branch = self.source
 
670
        result.target_branch = self.target
 
671
        # FIXME: Check for diverged branches
 
672
        old_refs = self.target.repository._git.get_refs()
 
673
        refs = dict(old_refs)
 
674
        new_refs, main_ref = self._get_new_refs(stop_revision)
 
675
        refs.update(new_refs)
 
676
        self.target.repository.fetch_refs(self.source.repository, refs)
 
677
        result.old_revid = self.target.lookup_foreign_revision_id(
 
678
            old_refs.get(main_ref, ZERO_SHA))
 
679
        result.new_revid = refs[main_ref]
 
680
        return result
624
681
 
625
682
    def lossy_push(self, stop_revision=None):
 
683
        from dulwich.protocol import ZERO_SHA
626
684
        result = GitBranchPushResult()
627
685
        result.source_branch = self.source
628
686
        result.target_branch = self.target
629
 
        if stop_revision is None:
630
 
            stop_revision = self.source.last_revision()
631
687
        # FIXME: Check for diverged branches
632
 
        refs = { self.target.ref: stop_revision }
633
 
        for name, revid in self.source.tags.get_tag_dict().iteritems():
634
 
            if self.source.repository.has_revision(revid):
635
 
                refs["refs/tags/%s" % name] = revid
636
 
        revidmap, old_refs, new_refs = self.target.repository.dfetch_refs(
 
688
        refs, main_ref = self._get_new_refs(stop_revision)
 
689
        result.revidmap, old_refs, new_refs = self.target.repository.dfetch_refs(
637
690
            self.source.repository, refs)
638
 
        result.old_revid = self.target.mapping.revision_id_foreign_to_bzr(
639
 
            old_refs.get(self.target.ref, "0" * 40))
640
 
        result.new_revid = self.target.mapping.revision_id_foreign_to_bzr(
641
 
            new_refs[self.target.ref])
642
 
        result.revidmap = revidmap
 
691
        result.old_revid = self.target.lookup_foreign_revision_id(
 
692
            old_refs.get(self.target.ref, ZERO_SHA))
 
693
        result.new_revid = self.target.lookup_foreign_revision_id(
 
694
            new_refs[main_ref])
643
695
        return result
644
696
 
645
697