/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

Raise SettingFileIdUnsupported

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007,2012 Canonical Ltd
 
2
# Copyright (C) 2009-2012 Jelmer Vernooij <jelmer@samba.org>
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
 
 
18
"""An adapter between a Git Branch and a Bazaar Branch"""
 
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
from cStringIO import StringIO
 
23
from collections import defaultdict
 
24
 
 
25
from dulwich.objects import (
 
26
    ZERO_SHA,
 
27
    )
 
28
from dulwich.repo import check_ref_format
 
29
 
 
30
from ... import (
 
31
    branch,
 
32
    config,
 
33
    controldir,
 
34
    errors,
 
35
    repository as _mod_repository,
 
36
    revision,
 
37
    tag,
 
38
    transport,
 
39
    urlutils,
 
40
    )
 
41
from ...decorators import (
 
42
    needs_read_lock,
 
43
    )
 
44
from ...revision import (
 
45
    NULL_REVISION,
 
46
    )
 
47
from ...trace import (
 
48
    is_quiet,
 
49
    mutter,
 
50
    warning,
 
51
    )
 
52
 
 
53
from .config import (
 
54
    GitBranchConfig,
 
55
    GitBranchStack,
 
56
    )
 
57
from .errors import (
 
58
    NoPushSupport,
 
59
    NoSuchRef,
 
60
    )
 
61
from .refs import (
 
62
    is_tag,
 
63
    ref_to_branch_name,
 
64
    ref_to_tag_name,
 
65
    tag_name_to_ref,
 
66
    )
 
67
from .unpeel_map import (
 
68
    UnpeelMap,
 
69
    )
 
70
 
 
71
from ...foreign import ForeignBranch
 
72
 
 
73
 
 
74
class GitPullResult(branch.PullResult):
 
75
    """Result of a pull from a Git branch."""
 
76
 
 
77
    def _lookup_revno(self, revid):
 
78
        assert isinstance(revid, str), "was %r" % revid
 
79
        # Try in source branch first, it'll be faster
 
80
        self.target_branch.lock_read()
 
81
        try:
 
82
            return self.target_branch.revision_id_to_revno(revid)
 
83
        finally:
 
84
            self.target_branch.unlock()
 
85
 
 
86
    @property
 
87
    def old_revno(self):
 
88
        return self._lookup_revno(self.old_revid)
 
89
 
 
90
    @property
 
91
    def new_revno(self):
 
92
        return self._lookup_revno(self.new_revid)
 
93
 
 
94
 
 
95
class GitTags(tag.BasicTags):
 
96
    """Ref-based tag dictionary."""
 
97
 
 
98
    def __init__(self, branch):
 
99
        self.branch = branch
 
100
        self.repository = branch.repository
 
101
 
 
102
    def get_refs_container(self):
 
103
        raise NotImplementedError(self.get_refs_container)
 
104
 
 
105
    def _iter_tag_refs(self, refs):
 
106
        """Iterate over the tag refs.
 
107
 
 
108
        :param refs: Refs dictionary (name -> git sha1)
 
109
        :return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
 
110
        """
 
111
        for k, unpeeled in refs.as_dict().iteritems():
 
112
            try:
 
113
                tag_name = ref_to_tag_name(k)
 
114
            except (ValueError, UnicodeDecodeError):
 
115
                continue
 
116
            peeled = refs.get_peeled(k)
 
117
            if peeled is None:
 
118
                peeled = self.repository.controldir._git.object_store.peel_sha(unpeeled).id
 
119
            assert type(tag_name) is unicode
 
120
            yield (tag_name, peeled, unpeeled,
 
121
                   self.branch.lookup_foreign_revision_id(peeled))
 
122
 
 
123
    def _merge_to_remote_git(self, target_repo, new_refs, overwrite=False):
 
124
        updates = {}
 
125
        conflicts = []
 
126
        def get_changed_refs(old_refs):
 
127
            ret = dict(old_refs)
 
128
            for k, v in new_refs.iteritems():
 
129
                if not is_tag(k):
 
130
                    continue
 
131
                name = ref_to_tag_name(k)
 
132
                if old_refs.get(k) == v:
 
133
                    pass
 
134
                elif overwrite or not k in old_refs:
 
135
                    ret[k] = v
 
136
                    updates[name] = target_repo.lookup_foreign_revision_id(v)
 
137
                else:
 
138
                    conflicts.append((name, v, old_refs[k]))
 
139
            return ret
 
140
        target_repo.controldir.send_pack(get_changed_refs, lambda have, want: [])
 
141
        return updates, conflicts
 
142
 
 
143
    def _merge_to_local_git(self, target_repo, refs, overwrite=False):
 
144
        conflicts = []
 
145
        updates = {}
 
146
        for k, unpeeled in refs.as_dict().iteritems():
 
147
            if not is_tag(k):
 
148
                continue
 
149
            name = ref_to_tag_name(k)
 
150
            peeled = self.repository.controldir.get_peeled(k)
 
151
            if target_repo._git.refs.get(k) == unpeeled:
 
152
                pass
 
153
            elif overwrite or not k in target_repo._git.refs:
 
154
                target_repo._git.refs[k] = unpeeled or peeled
 
155
                updates[name] = target_repo.lookup_foreign_revision_id(peeled)
 
156
            else:
 
157
                conflicts.append((name, peeled, target_repo._git.refs[k]))
 
158
        return updates, conflicts
 
159
 
 
160
    def _merge_to_git(self, to_tags, refs, overwrite=False):
 
161
        target_repo = to_tags.repository
 
162
        if self.repository.has_same_location(target_repo):
 
163
            return {}, []
 
164
        if getattr(target_repo, "_git", None):
 
165
            return self._merge_to_local_git(target_repo, refs, overwrite)
 
166
        else:
 
167
            return self._merge_to_remote_git(target_repo, refs, overwrite)
 
168
 
 
169
    def _merge_to_non_git(self, to_tags, refs, overwrite=False):
 
170
        unpeeled_map = defaultdict(set)
 
171
        conflicts = []
 
172
        updates = {}
 
173
        result = dict(to_tags.get_tag_dict())
 
174
        for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
 
175
            if unpeeled is not None:
 
176
                unpeeled_map[peeled].add(unpeeled)
 
177
            if result.get(n) == bzr_revid:
 
178
                pass
 
179
            elif n not in result or overwrite:
 
180
                result[n] = bzr_revid
 
181
                updates[n] = bzr_revid
 
182
            else:
 
183
                conflicts.append((n, result[n], bzr_revid))
 
184
        to_tags._set_tag_dict(result)
 
185
        if len(unpeeled_map) > 0:
 
186
            map_file = UnpeelMap.from_repository(to_tags.branch.repository)
 
187
            map_file.update(unpeeled_map)
 
188
            map_file.save_in_repository(to_tags.branch.repository)
 
189
        return updates, conflicts
 
190
 
 
191
    def merge_to(self, to_tags, overwrite=False, ignore_master=False,
 
192
                 source_refs=None):
 
193
        """See Tags.merge_to."""
 
194
        if source_refs is None:
 
195
            source_refs = self.get_refs_container()
 
196
        if self == to_tags:
 
197
            return {}, []
 
198
        if isinstance(to_tags, GitTags):
 
199
            return self._merge_to_git(to_tags, source_refs,
 
200
                                      overwrite=overwrite)
 
201
        else:
 
202
            if ignore_master:
 
203
                master = None
 
204
            else:
 
205
                master = to_tags.branch.get_master_branch()
 
206
            updates, conflicts = self._merge_to_non_git(to_tags, source_refs,
 
207
                                              overwrite=overwrite)
 
208
            if master is not None:
 
209
                extra_updates, extra_conflicts = self.merge_to(
 
210
                    master.tags, overwrite=overwrite,
 
211
                                           source_refs=source_refs,
 
212
                                           ignore_master=ignore_master)
 
213
                updates.update(extra_updates)
 
214
                conflicts += extra_conflicts
 
215
            return updates, conflicts
 
216
 
 
217
    def get_tag_dict(self):
 
218
        ret = {}
 
219
        refs = self.get_refs_container()
 
220
        for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
 
221
            ret[name] = bzr_revid
 
222
        return ret
 
223
 
 
224
 
 
225
class LocalGitTagDict(GitTags):
 
226
    """Dictionary with tags in a local repository."""
 
227
 
 
228
    def __init__(self, branch):
 
229
        super(LocalGitTagDict, self).__init__(branch)
 
230
        self.refs = self.repository.controldir._git.refs
 
231
 
 
232
    def get_refs_container(self):
 
233
        return self.refs
 
234
 
 
235
    def _set_tag_dict(self, to_dict):
 
236
        extra = set(self.refs.allkeys())
 
237
        for k, revid in to_dict.iteritems():
 
238
            name = tag_name_to_ref(k)
 
239
            if name in extra:
 
240
                extra.remove(name)
 
241
            self.set_tag(k, revid)
 
242
        for name in extra:
 
243
            if is_tag(name):
 
244
                del self.repository._git[name]
 
245
 
 
246
    def set_tag(self, name, revid):
 
247
        try:
 
248
            git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
 
249
        except errors.NoSuchRevision:
 
250
            raise errors.GhostTagsNotSupported(self)
 
251
        self.refs[tag_name_to_ref(name)] = git_sha
 
252
 
 
253
 
 
254
class DictTagDict(tag.BasicTags):
 
255
 
 
256
    def __init__(self, branch, tags):
 
257
        super(DictTagDict, self).__init__(branch)
 
258
        self._tags = tags
 
259
 
 
260
    def get_tag_dict(self):
 
261
        return self._tags
 
262
 
 
263
 
 
264
class GitSymrefBranchFormat(branch.BranchFormat):
 
265
 
 
266
    def get_format_description(self):
 
267
        return 'Git Symbolic Reference Branch'
 
268
 
 
269
    def network_name(self):
 
270
        return "git"
 
271
 
 
272
    def get_reference(self, controldir, name=None):
 
273
        return controldir.get_branch_reference(name)
 
274
 
 
275
    def set_reference(self, controldir, name, target):
 
276
        return controldir.set_branch_reference(target, name)
 
277
 
 
278
 
 
279
class GitBranchFormat(branch.BranchFormat):
 
280
 
 
281
    def get_format_description(self):
 
282
        return 'Git Branch'
 
283
 
 
284
    def network_name(self):
 
285
        return "git"
 
286
 
 
287
    def supports_tags(self):
 
288
        return True
 
289
 
 
290
    def supports_leaving_lock(self):
 
291
        return False
 
292
 
 
293
    def supports_tags_referencing_ghosts(self):
 
294
        return False
 
295
 
 
296
    def tags_are_versioned(self):
 
297
        return False
 
298
 
 
299
    @property
 
300
    def _matchingbzrdir(self):
 
301
        from .dir import LocalGitControlDirFormat
 
302
        return LocalGitControlDirFormat()
 
303
 
 
304
    def get_foreign_tests_branch_factory(self):
 
305
        from .tests.test_branch import ForeignTestsBranchFactory
 
306
        return ForeignTestsBranchFactory()
 
307
 
 
308
    def make_tags(self, branch):
 
309
        try:
 
310
            return branch.tags
 
311
        except AttributeError:
 
312
            pass
 
313
        if getattr(branch.repository, "_git", None) is None:
 
314
            from .remote import RemoteGitTagDict
 
315
            return RemoteGitTagDict(branch)
 
316
        else:
 
317
            return LocalGitTagDict(branch)
 
318
 
 
319
    def initialize(self, a_controldir, name=None, repository=None,
 
320
                   append_revisions_only=None):
 
321
        from .dir import LocalGitDir
 
322
        if not isinstance(a_controldir, LocalGitDir):
 
323
            raise errors.IncompatibleFormat(self, a_controldir._format)
 
324
        return a_controldir.create_branch(repository=repository, name=name,
 
325
            append_revisions_only=append_revisions_only)
 
326
 
 
327
 
 
328
class GitReadLock(object):
 
329
 
 
330
    def __init__(self, unlock):
 
331
        self.unlock = unlock
 
332
 
 
333
 
 
334
class GitWriteLock(object):
 
335
 
 
336
    def __init__(self, unlock):
 
337
        self.branch_token = None
 
338
        self.unlock = unlock
 
339
 
 
340
 
 
341
class GitBranch(ForeignBranch):
 
342
    """An adapter to git repositories for bzr Branch objects."""
 
343
 
 
344
    @property
 
345
    def control_transport(self):
 
346
        return self.controldir.control_transport
 
347
 
 
348
    def __init__(self, controldir, repository, ref):
 
349
        self.base = controldir.root_transport.base
 
350
        self.repository = repository
 
351
        self._format = GitBranchFormat()
 
352
        self.controldir = controldir
 
353
        self._lock_mode = None
 
354
        self._lock_count = 0
 
355
        super(GitBranch, self).__init__(repository.get_mapping())
 
356
        self.ref = ref
 
357
        try:
 
358
            self.name = ref_to_branch_name(ref)
 
359
        except ValueError:
 
360
            self.name = None
 
361
        self._head = None
 
362
 
 
363
    def _get_checkout_format(self, lightweight=False):
 
364
        """Return the most suitable metadir for a checkout of this branch.
 
365
        Weaves are used if this branch's repository uses weaves.
 
366
        """
 
367
        return controldir.format_registry.make_controldir("default")
 
368
 
 
369
    def get_child_submit_format(self):
 
370
        """Return the preferred format of submissions to this branch."""
 
371
        ret = self.get_config_stack().get("child_submit_format")
 
372
        if ret is not None:
 
373
            return ret
 
374
        return "git"
 
375
 
 
376
    def get_config(self):
 
377
        return GitBranchConfig(self)
 
378
 
 
379
    def get_config_stack(self):
 
380
        return GitBranchStack(self)
 
381
 
 
382
    def _get_nick(self, local=False, possible_master_transports=None):
 
383
        """Find the nick name for this branch.
 
384
 
 
385
        :return: Branch nick
 
386
        """
 
387
        cs = self.repository._git.get_config_stack()
 
388
        try:
 
389
            return cs.get(("branch", self.name), "nick")
 
390
        except KeyError:
 
391
            pass
 
392
        return self.name.encode('utf-8') or "HEAD"
 
393
 
 
394
    def _set_nick(self, nick):
 
395
        cf = self.repository._git.get_config()
 
396
        cf.set(("branch", self.name), "nick", nick)
 
397
        f = StringIO()
 
398
        cf.write_to_file(f)
 
399
        self.controldir.control_transport.put_bytes('config', f.getvalue())
 
400
 
 
401
    nick = property(_get_nick, _set_nick)
 
402
 
 
403
    def __repr__(self):
 
404
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
 
405
            self.name)
 
406
 
 
407
    def generate_revision_history(self, revid, old_revid=None):
 
408
        if revid == NULL_REVISION:
 
409
            newhead = ZERO_SHA
 
410
        else:
 
411
            # FIXME: Check that old_revid is in the ancestry of revid
 
412
            newhead, self.mapping = self.repository.lookup_bzr_revision_id(revid)
 
413
            if self.mapping is None:
 
414
                raise AssertionError
 
415
        self._set_head(newhead)
 
416
 
 
417
    def lock_write(self, token=None):
 
418
        if token is not None:
 
419
            raise errors.TokenLockingNotSupported(self)
 
420
        if self._lock_mode:
 
421
            if self._lock_mode == 'r':
 
422
                raise errors.ReadOnlyError(self)
 
423
            self._lock_count += 1
 
424
        else:
 
425
            self._lock_mode = 'w'
 
426
            self._lock_count = 1
 
427
        self.repository.lock_write()
 
428
        return GitWriteLock(self.unlock)
 
429
 
 
430
    def leave_lock_in_place(self):
 
431
        raise NotImplementedError(self.leave_lock_in_place)
 
432
 
 
433
    def dont_leave_lock_in_place(self):
 
434
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
435
 
 
436
    def get_stacked_on_url(self):
 
437
        # Git doesn't do stacking (yet...)
 
438
        raise branch.UnstackableBranchFormat(self._format, self.base)
 
439
 
 
440
    def get_parent(self):
 
441
        """See Branch.get_parent()."""
 
442
        # FIXME: Set "origin" url from .git/config ?
 
443
        return None
 
444
 
 
445
    def set_parent(self, url):
 
446
        # FIXME: Set "origin" url in .git/config ?
 
447
        pass
 
448
 
 
449
    def break_lock(self):
 
450
        raise NotImplementedError(self.break_lock)
 
451
 
 
452
    def lock_read(self):
 
453
        if self._lock_mode:
 
454
            assert self._lock_mode in ('r', 'w')
 
455
            self._lock_count += 1
 
456
        else:
 
457
            self._lock_mode = 'r'
 
458
            self._lock_count = 1
 
459
        self.repository.lock_read()
 
460
        return GitReadLock(self.unlock)
 
461
 
 
462
    def peek_lock_mode(self):
 
463
        return self._lock_mode
 
464
 
 
465
    def is_locked(self):
 
466
        return (self._lock_mode is not None)
 
467
 
 
468
    def unlock(self):
 
469
        """See Branch.unlock()."""
 
470
        self._lock_count -= 1
 
471
        if self._lock_count == 0:
 
472
            self._lock_mode = None
 
473
            self._clear_cached_state()
 
474
        self.repository.unlock()
 
475
 
 
476
    def get_physical_lock_status(self):
 
477
        return False
 
478
 
 
479
    @needs_read_lock
 
480
    def last_revision(self):
 
481
        # perhaps should escape this ?
 
482
        if self.head is None:
 
483
            return revision.NULL_REVISION
 
484
        return self.lookup_foreign_revision_id(self.head)
 
485
 
 
486
    def _basic_push(self, target, overwrite=False, stop_revision=None):
 
487
        return branch.InterBranch.get(self, target)._basic_push(
 
488
            overwrite, stop_revision)
 
489
 
 
490
    def lookup_foreign_revision_id(self, foreign_revid):
 
491
        return self.repository.lookup_foreign_revision_id(foreign_revid,
 
492
            self.mapping)
 
493
 
 
494
    def lookup_bzr_revision_id(self, revid):
 
495
        return self.repository.lookup_bzr_revision_id(
 
496
            revid, mapping=self.mapping)
 
497
 
 
498
 
 
499
class LocalGitBranch(GitBranch):
 
500
    """A local Git branch."""
 
501
 
 
502
    def __init__(self, controldir, repository, ref):
 
503
        super(LocalGitBranch, self).__init__(controldir, repository, ref)
 
504
        refs = controldir.get_refs_container()
 
505
        if not (ref in refs or "HEAD" in refs):
 
506
            raise errors.NotBranchError(self.base)
 
507
 
 
508
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
 
509
        accelerator_tree=None, hardlink=False):
 
510
        if lightweight:
 
511
            t = transport.get_transport(to_location)
 
512
            t.ensure_base()
 
513
            format = self._get_checkout_format(lightweight=True)
 
514
            checkout = format.initialize_on_transport(t)
 
515
            from breezy.bzr.branch import BranchReferenceFormat
 
516
            from_branch = BranchReferenceFormat().initialize(checkout, self)
 
517
            tree = checkout.create_workingtree(revision_id,
 
518
                from_branch=from_branch, hardlink=hardlink)
 
519
            return tree
 
520
        else:
 
521
            return self._create_heavyweight_checkout(to_location, revision_id,
 
522
                hardlink)
 
523
 
 
524
    def _create_heavyweight_checkout(self, to_location, revision_id=None,
 
525
                                     hardlink=False):
 
526
        """Create a new heavyweight checkout of this branch.
 
527
 
 
528
        :param to_location: URL of location to create the new checkout in.
 
529
        :param revision_id: Revision that should be the tip of the checkout.
 
530
        :param hardlink: Whether to hardlink
 
531
        :return: WorkingTree object of checkout.
 
532
        """
 
533
        checkout_branch = controldir.ControlDir.create_branch_convenience(
 
534
            to_location, force_new_tree=False,
 
535
            format=self._get_checkout_format(lightweight=False))
 
536
        checkout = checkout_branch.controldir
 
537
        checkout_branch.bind(self)
 
538
        # pull up to the specified revision_id to set the initial
 
539
        # branch tip correctly, and seed it with history.
 
540
        checkout_branch.pull(self, stop_revision=revision_id)
 
541
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
 
542
 
 
543
    def fetch(self, from_branch, last_revision=None, limit=None):
 
544
        return branch.InterBranch.get(from_branch, self).fetch(
 
545
            stop_revision=last_revision, limit=limit)
 
546
 
 
547
    def _gen_revision_history(self):
 
548
        if self.head is None:
 
549
            return []
 
550
        graph = self.repository.get_graph()
 
551
        ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
 
552
            (revision.NULL_REVISION, )))
 
553
        ret.reverse()
 
554
        return ret
 
555
 
 
556
    def _get_head(self):
 
557
        try:
 
558
            return self.repository._git.refs[self.ref or "HEAD"]
 
559
        except KeyError:
 
560
            return None
 
561
 
 
562
    def _read_last_revision_info(self):
 
563
        last_revid = self.last_revision()
 
564
        graph = self.repository.get_graph()
 
565
        revno = graph.find_distance_to_null(last_revid,
 
566
            [(revision.NULL_REVISION, 0)])
 
567
        return revno, last_revid
 
568
 
 
569
    def set_last_revision_info(self, revno, revision_id):
 
570
        self.set_last_revision(revision_id)
 
571
        self._last_revision_info_cache = revno, revision_id
 
572
 
 
573
    def set_last_revision(self, revid):
 
574
        if not revid or not isinstance(revid, basestring):
 
575
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
 
576
        if revid == NULL_REVISION:
 
577
            newhead = ZERO_SHA
 
578
        else:
 
579
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
 
580
            if self.mapping is None:
 
581
                raise AssertionError
 
582
        self._set_head(newhead)
 
583
 
 
584
    def _set_head(self, value):
 
585
        self._head = value
 
586
        self.repository._git.refs[self.ref or "HEAD"] = self._head
 
587
        self._clear_cached_state()
 
588
 
 
589
    head = property(_get_head, _set_head)
 
590
 
 
591
    def get_push_location(self):
 
592
        """See Branch.get_push_location."""
 
593
        push_loc = self.get_config_stack().get('push_location')
 
594
        return push_loc
 
595
 
 
596
    def set_push_location(self, location):
 
597
        """See Branch.set_push_location."""
 
598
        self.get_config().set_user_option('push_location', location,
 
599
                                          store=config.STORE_LOCATION)
 
600
 
 
601
    def supports_tags(self):
 
602
        return True
 
603
 
 
604
 
 
605
def _quick_lookup_revno(local_branch, remote_branch, revid):
 
606
    assert isinstance(revid, str), "was %r" % revid
 
607
    # Try in source branch first, it'll be faster
 
608
    local_branch.lock_read()
 
609
    try:
 
610
        try:
 
611
            return local_branch.revision_id_to_revno(revid)
 
612
        except errors.NoSuchRevision:
 
613
            graph = local_branch.repository.get_graph()
 
614
            try:
 
615
                return graph.find_distance_to_null(revid,
 
616
                    [(revision.NULL_REVISION, 0)])
 
617
            except errors.GhostRevisionsHaveNoRevno:
 
618
                # FIXME: Check using graph.find_distance_to_null() ?
 
619
                remote_branch.lock_read()
 
620
                try:
 
621
                    return remote_branch.revision_id_to_revno(revid)
 
622
                finally:
 
623
                    remote_branch.unlock()
 
624
    finally:
 
625
        local_branch.unlock()
 
626
 
 
627
 
 
628
class GitBranchPullResult(branch.PullResult):
 
629
 
 
630
    def __init__(self):
 
631
        super(GitBranchPullResult, self).__init__()
 
632
        self.new_git_head = None
 
633
        self._old_revno = None
 
634
        self._new_revno = None
 
635
 
 
636
    def report(self, to_file):
 
637
        if not is_quiet():
 
638
            if self.old_revid == self.new_revid:
 
639
                to_file.write('No revisions to pull.\n')
 
640
            elif self.new_git_head is not None:
 
641
                to_file.write('Now on revision %d (git sha: %s).\n' %
 
642
                        (self.new_revno, self.new_git_head))
 
643
            else:
 
644
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
 
645
        self._show_tag_conficts(to_file)
 
646
 
 
647
    def _lookup_revno(self, revid):
 
648
        return _quick_lookup_revno(self.target_branch, self.source_branch,
 
649
            revid)
 
650
 
 
651
    def _get_old_revno(self):
 
652
        if self._old_revno is not None:
 
653
            return self._old_revno
 
654
        return self._lookup_revno(self.old_revid)
 
655
 
 
656
    def _set_old_revno(self, revno):
 
657
        self._old_revno = revno
 
658
 
 
659
    old_revno = property(_get_old_revno, _set_old_revno)
 
660
 
 
661
    def _get_new_revno(self):
 
662
        if self._new_revno is not None:
 
663
            return self._new_revno
 
664
        return self._lookup_revno(self.new_revid)
 
665
 
 
666
    def _set_new_revno(self, revno):
 
667
        self._new_revno = revno
 
668
 
 
669
    new_revno = property(_get_new_revno, _set_new_revno)
 
670
 
 
671
 
 
672
class GitBranchPushResult(branch.BranchPushResult):
 
673
 
 
674
    def _lookup_revno(self, revid):
 
675
        return _quick_lookup_revno(self.source_branch, self.target_branch,
 
676
            revid)
 
677
 
 
678
    @property
 
679
    def old_revno(self):
 
680
        return self._lookup_revno(self.old_revid)
 
681
 
 
682
    @property
 
683
    def new_revno(self):
 
684
        new_original_revno = getattr(self, "new_original_revno", None)
 
685
        if new_original_revno:
 
686
            return new_original_revno
 
687
        if getattr(self, "new_original_revid", None) is not None:
 
688
            return self._lookup_revno(self.new_original_revid)
 
689
        return self._lookup_revno(self.new_revid)
 
690
 
 
691
 
 
692
class InterFromGitBranch(branch.GenericInterBranch):
 
693
    """InterBranch implementation that pulls from Git into bzr."""
 
694
 
 
695
    @staticmethod
 
696
    def _get_branch_formats_to_test():
 
697
        try:
 
698
            default_format = branch.format_registry.get_default()
 
699
        except AttributeError:
 
700
            default_format = branch.BranchFormat._default_format
 
701
        return [
 
702
            (GitBranchFormat(), GitBranchFormat()),
 
703
            (GitBranchFormat(), default_format)]
 
704
 
 
705
    @classmethod
 
706
    def _get_interrepo(self, source, target):
 
707
        return _mod_repository.InterRepository.get(source.repository, target.repository)
 
708
 
 
709
    @classmethod
 
710
    def is_compatible(cls, source, target):
 
711
        if not isinstance(source, GitBranch):
 
712
            return False
 
713
        if isinstance(target, GitBranch):
 
714
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
 
715
            return False
 
716
        if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
 
717
            # fetch_objects is necessary for this to work
 
718
            return False
 
719
        return True
 
720
 
 
721
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
 
722
        self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
 
723
 
 
724
    def fetch_objects(self, stop_revision, fetch_tags, limit=None):
 
725
        interrepo = self._get_interrepo(self.source, self.target)
 
726
        if fetch_tags is None:
 
727
            c = self.source.get_config_stack()
 
728
            fetch_tags = c.get('branch.fetch_tags')
 
729
        def determine_wants(heads):
 
730
            if self.source.ref is not None and not self.source.ref in heads:
 
731
                raise NoSuchRef(self.source.ref, self.source.user_url, heads.keys())
 
732
 
 
733
            if stop_revision is None:
 
734
                if self.source.ref is not None:
 
735
                    head = heads[self.source.ref]
 
736
                else:
 
737
                    head = heads["HEAD"]
 
738
                self._last_revid = self.source.lookup_foreign_revision_id(head)
 
739
            else:
 
740
                self._last_revid = stop_revision
 
741
            real = interrepo.get_determine_wants_revids(
 
742
                [self._last_revid], include_tags=fetch_tags)
 
743
            return real(heads)
 
744
        pack_hint, head, refs = interrepo.fetch_objects(
 
745
            determine_wants, self.source.mapping, limit=limit)
 
746
        if (pack_hint is not None and
 
747
            self.target.repository._format.pack_compresses):
 
748
            self.target.repository.pack(hint=pack_hint)
 
749
        return head, refs
 
750
 
 
751
    def _update_revisions(self, stop_revision=None, overwrite=False):
 
752
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
 
753
        if overwrite:
 
754
            prev_last_revid = None
 
755
        else:
 
756
            prev_last_revid = self.target.last_revision()
 
757
        self.target.generate_revision_history(self._last_revid,
 
758
            prev_last_revid, self.source)
 
759
        return head, refs
 
760
 
 
761
    def _basic_pull(self, stop_revision, overwrite, run_hooks,
 
762
              _override_hook_target, _hook_master):
 
763
        result = GitBranchPullResult()
 
764
        result.source_branch = self.source
 
765
        if _override_hook_target is None:
 
766
            result.target_branch = self.target
 
767
        else:
 
768
            result.target_branch = _override_hook_target
 
769
        self.source.lock_read()
 
770
        try:
 
771
            self.target.lock_write()
 
772
            try:
 
773
                # We assume that during 'pull' the target repository is closer than
 
774
                # the source one.
 
775
                (result.old_revno, result.old_revid) = \
 
776
                    self.target.last_revision_info()
 
777
                result.new_git_head, remote_refs = self._update_revisions(
 
778
                    stop_revision, overwrite=overwrite)
 
779
                tags_ret  = self.source.tags.merge_to(
 
780
                        self.target.tags, overwrite, ignore_master=True)
 
781
                if isinstance(tags_ret, tuple):
 
782
                    result.tag_updates, result.tag_conflicts = tags_ret
 
783
                else:
 
784
                    result.tag_conflicts = tags_ret
 
785
                (result.new_revno, result.new_revid) = \
 
786
                    self.target.last_revision_info()
 
787
                if _hook_master:
 
788
                    result.master_branch = _hook_master
 
789
                    result.local_branch = result.target_branch
 
790
                else:
 
791
                    result.master_branch = result.target_branch
 
792
                    result.local_branch = None
 
793
                if run_hooks:
 
794
                    for hook in branch.Branch.hooks['post_pull']:
 
795
                        hook(result)
 
796
                return result
 
797
            finally:
 
798
                self.target.unlock()
 
799
        finally:
 
800
            self.source.unlock()
 
801
 
 
802
    def pull(self, overwrite=False, stop_revision=None,
 
803
             possible_transports=None, _hook_master=None, run_hooks=True,
 
804
             _override_hook_target=None, local=False):
 
805
        """See Branch.pull.
 
806
 
 
807
        :param _hook_master: Private parameter - set the branch to
 
808
            be supplied as the master to pull hooks.
 
809
        :param run_hooks: Private parameter - if false, this branch
 
810
            is being called because it's the master of the primary branch,
 
811
            so it should not run its hooks.
 
812
        :param _override_hook_target: Private parameter - set the branch to be
 
813
            supplied as the target_branch to pull hooks.
 
814
        """
 
815
        # This type of branch can't be bound.
 
816
        bound_location = self.target.get_bound_location()
 
817
        if local and not bound_location:
 
818
            raise errors.LocalRequiresBoundBranch()
 
819
        master_branch = None
 
820
        source_is_master = False
 
821
        self.source.lock_read()
 
822
        if bound_location:
 
823
            # bound_location comes from a config file, some care has to be
 
824
            # taken to relate it to source.user_url
 
825
            normalized = urlutils.normalize_url(bound_location)
 
826
            try:
 
827
                relpath = self.source.user_transport.relpath(normalized)
 
828
                source_is_master = (relpath == '')
 
829
            except (errors.PathNotChild, urlutils.InvalidURL):
 
830
                source_is_master = False
 
831
        if not local and bound_location and not source_is_master:
 
832
            # not pulling from master, so we need to update master.
 
833
            master_branch = self.target.get_master_branch(possible_transports)
 
834
            master_branch.lock_write()
 
835
        try:
 
836
            try:
 
837
                if master_branch:
 
838
                    # pull from source into master.
 
839
                    master_branch.pull(self.source, overwrite, stop_revision,
 
840
                        run_hooks=False)
 
841
                result = self._basic_pull(stop_revision, overwrite, run_hooks,
 
842
                    _override_hook_target, _hook_master=master_branch)
 
843
            finally:
 
844
                self.source.unlock()
 
845
        finally:
 
846
            if master_branch:
 
847
                master_branch.unlock()
 
848
        return result
 
849
 
 
850
    def _basic_push(self, overwrite=False, stop_revision=None):
 
851
        result = branch.BranchPushResult()
 
852
        result.source_branch = self.source
 
853
        result.target_branch = self.target
 
854
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
855
        result.new_git_head, remote_refs = self._update_revisions(
 
856
            stop_revision, overwrite=overwrite)
 
857
        tags_ret = self.source.tags.merge_to(self.target.tags,
 
858
            overwrite)
 
859
        if isinstance(tags_ret, tuple):
 
860
            (result.tag_updates, result.tag_conflicts) = tags_ret
 
861
        else:
 
862
            result.tag_conflicts = tags_ret
 
863
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
864
        return result
 
865
 
 
866
 
 
867
class InterGitBranch(branch.GenericInterBranch):
 
868
    """InterBranch implementation that pulls between Git branches."""
 
869
 
 
870
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
 
871
        raise NotImplementedError(self.fetch)
 
872
 
 
873
 
 
874
class InterLocalGitRemoteGitBranch(InterGitBranch):
 
875
    """InterBranch that copies from a local to a remote git branch."""
 
876
 
 
877
    @staticmethod
 
878
    def _get_branch_formats_to_test():
 
879
        # FIXME
 
880
        return []
 
881
 
 
882
    @classmethod
 
883
    def is_compatible(self, source, target):
 
884
        from .remote import RemoteGitBranch
 
885
        return (isinstance(source, LocalGitBranch) and
 
886
                isinstance(target, RemoteGitBranch))
 
887
 
 
888
    def _basic_push(self, overwrite=False, stop_revision=None):
 
889
        result = GitBranchPushResult()
 
890
        result.source_branch = self.source
 
891
        result.target_branch = self.target
 
892
        if stop_revision is None:
 
893
            stop_revision = self.source.last_revision()
 
894
        # FIXME: Check for diverged branches
 
895
        def get_changed_refs(old_refs):
 
896
            old_ref = old_refs.get(self.target.ref, ZERO_SHA)
 
897
            result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
 
898
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
 
899
            result.new_revid = stop_revision
 
900
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
 
901
                refs[tag_name_to_ref(name)] = sha
 
902
            return refs
 
903
        self.target.repository.send_pack(get_changed_refs,
 
904
            self.source.repository._git.object_store.generate_pack_contents)
 
905
        return result
 
906
 
 
907
 
 
908
class InterGitLocalGitBranch(InterGitBranch):
 
909
    """InterBranch that copies from a remote to a local git branch."""
 
910
 
 
911
    @staticmethod
 
912
    def _get_branch_formats_to_test():
 
913
        # FIXME
 
914
        return []
 
915
 
 
916
    @classmethod
 
917
    def is_compatible(self, source, target):
 
918
        return (isinstance(source, GitBranch) and
 
919
                isinstance(target, LocalGitBranch))
 
920
 
 
921
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
 
922
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
 
923
            self.target.repository)
 
924
        if stop_revision is None:
 
925
            stop_revision = self.source.last_revision()
 
926
        determine_wants = interrepo.get_determine_wants_revids(
 
927
            [stop_revision], include_tags=fetch_tags)
 
928
        interrepo.fetch_objects(determine_wants, limit=limit)
 
929
 
 
930
    def _basic_push(self, overwrite=False, stop_revision=None):
 
931
        result = GitBranchPushResult()
 
932
        result.source_branch = self.source
 
933
        result.target_branch = self.target
 
934
        result.old_revid = self.target.last_revision()
 
935
        refs, stop_revision = self.update_refs(stop_revision)
 
936
        self.target.generate_revision_history(stop_revision, result.old_revid)
 
937
        tags_ret = self.source.tags.merge_to(self.target.tags,
 
938
            source_refs=refs, overwrite=overwrite)
 
939
        if isinstance(tags_ret, tuple):
 
940
            (result.tag_updates, result.tag_conflicts) = tags_ret
 
941
        else:
 
942
            result.tag_conflicts = tags_ret
 
943
        result.new_revid = self.target.last_revision()
 
944
        return result
 
945
 
 
946
    def update_refs(self, stop_revision=None):
 
947
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
 
948
            self.target.repository)
 
949
        if stop_revision is None:
 
950
            refs = interrepo.fetch(branches=["HEAD"])
 
951
            stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
 
952
        else:
 
953
            refs = interrepo.fetch(revision_id=stop_revision)
 
954
        return refs, stop_revision
 
955
 
 
956
    def pull(self, stop_revision=None, overwrite=False,
 
957
        possible_transports=None, run_hooks=True,local=False):
 
958
        # This type of branch can't be bound.
 
959
        if local:
 
960
            raise errors.LocalRequiresBoundBranch()
 
961
        result = GitPullResult()
 
962
        result.source_branch = self.source
 
963
        result.target_branch = self.target
 
964
        self.source.lock_read()
 
965
        try:
 
966
            self.target.lock_write()
 
967
            try:
 
968
                result.old_revid = self.target.last_revision()
 
969
                refs, stop_revision = self.update_refs(stop_revision)
 
970
                self.target.generate_revision_history(stop_revision, result.old_revid)
 
971
                tags_ret = self.source.tags.merge_to(self.target.tags,
 
972
                    overwrite=overwrite, source_refs=refs)
 
973
                if isinstance(tags_ret, tuple):
 
974
                    (result.tag_updates, result.tag_conflicts) = tags_ret
 
975
                else:
 
976
                    result.tag_conflicts = tags_ret
 
977
                result.new_revid = self.target.last_revision()
 
978
                result.local_branch = None
 
979
                result.master_branch = result.target_branch
 
980
                if run_hooks:
 
981
                    for hook in branch.Branch.hooks['post_pull']:
 
982
                        hook(result)
 
983
            finally:
 
984
                self.target.unlock()
 
985
        finally:
 
986
            self.source.unlock()
 
987
        return result
 
988
 
 
989
 
 
990
class InterToGitBranch(branch.GenericInterBranch):
 
991
    """InterBranch implementation that pulls into a Git branch."""
 
992
 
 
993
    def __init__(self, source, target):
 
994
        super(InterToGitBranch, self).__init__(source, target)
 
995
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
 
996
                                           target.repository)
 
997
 
 
998
    @staticmethod
 
999
    def _get_branch_formats_to_test():
 
1000
        try:
 
1001
            default_format = branch.format_registry.get_default()
 
1002
        except AttributeError:
 
1003
            default_format = branch.BranchFormat._default_format
 
1004
        return [(default_format, GitBranchFormat())]
 
1005
 
 
1006
    @classmethod
 
1007
    def is_compatible(self, source, target):
 
1008
        return (not isinstance(source, GitBranch) and
 
1009
                isinstance(target, GitBranch))
 
1010
 
 
1011
    def _get_new_refs(self, stop_revision=None, fetch_tags=None):
 
1012
        assert self.source.is_locked()
 
1013
        if stop_revision is None:
 
1014
            (stop_revno, stop_revision) = self.source.last_revision_info()
 
1015
        else:
 
1016
            stop_revno = self.source.revision_id_to_revno(stop_revision)
 
1017
        assert type(stop_revision) is str
 
1018
        main_ref = self.target.ref or "refs/heads/master"
 
1019
        refs = { main_ref: (None, stop_revision) }
 
1020
        if fetch_tags is None:
 
1021
            c = self.source.get_config_stack()
 
1022
            fetch_tags = c.get('branch.fetch_tags')
 
1023
        for name, revid in self.source.tags.get_tag_dict().iteritems():
 
1024
            if self.source.repository.has_revision(revid):
 
1025
                ref = tag_name_to_ref(name)
 
1026
                if not check_ref_format(ref):
 
1027
                    warning("skipping tag with invalid characters %s (%s)",
 
1028
                        name, ref)
 
1029
                    continue
 
1030
                if fetch_tags:
 
1031
                    # FIXME: Skip tags that are not in the ancestry
 
1032
                    refs[ref] = (None, revid)
 
1033
        return refs, main_ref, (stop_revno, stop_revision)
 
1034
 
 
1035
    def _update_refs(self, result, old_refs, new_refs, overwrite):
 
1036
        mutter("updating refs. old refs: %r, new refs: %r",
 
1037
               old_refs, new_refs)
 
1038
        result.tag_updates = {}
 
1039
        result.tag_conflicts = []
 
1040
        ret = dict(old_refs)
 
1041
        def ref_equals(refs, ref, git_sha, revid):
 
1042
            try:
 
1043
                value = refs[ref]
 
1044
            except KeyError:
 
1045
                return False
 
1046
            if (value[0] is not None and
 
1047
                git_sha is not None and
 
1048
                value[0] == git_sha):
 
1049
                return True
 
1050
            if (value[1] is not None and
 
1051
                revid is not None and
 
1052
                value[1] == revid):
 
1053
                return True
 
1054
            # FIXME: If one side only has the git sha available and the other only
 
1055
            # has the bzr revid, then this will cause us to show a tag as updated
 
1056
            # that hasn't actually been updated.
 
1057
            return False
 
1058
        # FIXME: Check for diverged branches
 
1059
        for ref, (git_sha, revid) in new_refs.iteritems():
 
1060
            if ref_equals(ret, ref, git_sha, revid):
 
1061
                # Already up to date
 
1062
                if git_sha is None:
 
1063
                    git_sha = old_refs[ref][0]
 
1064
                if revid is None:
 
1065
                    revid = old_refs[ref][1]
 
1066
                ret[ref] = new_refs[ref] = (git_sha, revid)
 
1067
            elif ref not in ret or overwrite:
 
1068
                try:
 
1069
                    tag_name = ref_to_tag_name(ref)
 
1070
                except ValueError:
 
1071
                    pass
 
1072
                else:
 
1073
                    result.tag_updates[tag_name] = revid
 
1074
                ret[ref] = (git_sha, revid)
 
1075
            else:
 
1076
                # FIXME: Check diverged
 
1077
                diverged = False
 
1078
                if diverged:
 
1079
                    try:
 
1080
                        name = ref_to_tag_name(ref)
 
1081
                    except ValueError:
 
1082
                        pass
 
1083
                    else:
 
1084
                        result.tag_conflicts.append((name, revid, ret[name][1]))
 
1085
                else:
 
1086
                    ret[ref] = (git_sha, revid)
 
1087
        return ret
 
1088
 
 
1089
    def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
 
1090
        assert limit is None
 
1091
        if stop_revision is None:
 
1092
            stop_revision = self.source.last_revision()
 
1093
        ret = []
 
1094
        if fetch_tags:
 
1095
            for k, v in self.source.tags.get_tag_dict().iteritems():
 
1096
                ret.append((None, v))
 
1097
        ret.append((None, stop_revision))
 
1098
        self.interrepo.fetch_objects(ret, lossy=lossy)
 
1099
 
 
1100
    def pull(self, overwrite=False, stop_revision=None, local=False,
 
1101
             possible_transports=None, run_hooks=True):
 
1102
        result = GitBranchPullResult()
 
1103
        result.source_branch = self.source
 
1104
        result.target_branch = self.target
 
1105
        self.source.lock_read()
 
1106
        try:
 
1107
            self.target.lock_write()
 
1108
            try:
 
1109
                new_refs, main_ref, stop_revinfo = self._get_new_refs(
 
1110
                    stop_revision)
 
1111
                def update_refs(old_refs):
 
1112
                    return self._update_refs(result, old_refs, new_refs, overwrite)
 
1113
                try:
 
1114
                    result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
 
1115
                        update_refs, lossy=False)
 
1116
                except NoPushSupport:
 
1117
                    raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1118
                (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
 
1119
                if result.old_revid is None:
 
1120
                    result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
 
1121
                result.new_revid = new_refs[main_ref][1]
 
1122
                result.local_branch = None
 
1123
                result.master_branch = self.target
 
1124
                if run_hooks:
 
1125
                    for hook in branch.Branch.hooks['post_pull']:
 
1126
                        hook(result)
 
1127
            finally:
 
1128
                self.target.unlock()
 
1129
        finally:
 
1130
            self.source.unlock()
 
1131
        return result
 
1132
 
 
1133
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
1134
             _override_hook_source_branch=None):
 
1135
        result = GitBranchPushResult()
 
1136
        result.source_branch = self.source
 
1137
        result.target_branch = self.target
 
1138
        result.local_branch = None
 
1139
        result.master_branch = result.target_branch
 
1140
        self.source.lock_read()
 
1141
        try:
 
1142
            new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
 
1143
            def update_refs(old_refs):
 
1144
                return self._update_refs(result, old_refs, new_refs, overwrite)
 
1145
            try:
 
1146
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
 
1147
                    update_refs, lossy=lossy)
 
1148
            except NoPushSupport:
 
1149
                raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1150
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
 
1151
            if result.old_revid is None:
 
1152
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
 
1153
            result.new_revid = new_refs[main_ref][1]
 
1154
            (result.new_original_revno, result.new_original_revid) = stop_revinfo
 
1155
            for hook in branch.Branch.hooks['post_push']:
 
1156
                hook(result)
 
1157
        finally:
 
1158
            self.source.unlock()
 
1159
        return result
 
1160
 
 
1161
 
 
1162
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
 
1163
branch.InterBranch.register_optimiser(InterFromGitBranch)
 
1164
branch.InterBranch.register_optimiser(InterToGitBranch)
 
1165
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)