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

ImproveĀ errorĀ message.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
    Commit,
19
19
    Tag,
20
20
    Tree,
 
21
    S_IFGITLINK,
21
22
    S_ISGITLINK,
 
23
    ZERO_SHA,
22
24
    )
23
25
from dulwich.object_store import (
24
26
    tree_lookup_path,
25
27
    )
 
28
from dulwich.walk import Walker
26
29
from itertools import (
27
30
    imap,
28
31
    )
32
35
 
33
36
from bzrlib import (
34
37
    debug,
 
38
    errors,
35
39
    osutils,
36
40
    trace,
37
41
    ui,
53
57
from bzrlib.revision import (
54
58
    NULL_REVISION,
55
59
    )
56
 
from bzrlib.revisiontree import (
57
 
    RevisionTree,
58
 
    )
 
60
from bzrlib.revisiontree import InventoryRevisionTree
59
61
from bzrlib.testament import (
60
62
    StrictTestament3,
61
63
    )
66
68
    ChunkedContentFactory,
67
69
    )
68
70
 
 
71
from bzrlib.plugins.git.errors import (
 
72
    NotCommitError,
 
73
    )
69
74
from bzrlib.plugins.git.mapping import (
70
75
    DEFAULT_FILE_MODE,
71
76
    mode_is_executable,
77
82
    LRUTreeCache,
78
83
    _tree_to_objects,
79
84
    )
 
85
from bzrlib.plugins.git.refs import (
 
86
    is_tag,
 
87
    )
80
88
from bzrlib.plugins.git.remote import (
81
89
    RemoteGitRepository,
82
90
    )
125
133
        blob = lookup_object(hexsha)
126
134
        if ie.kind == "symlink":
127
135
            ie.revision = None
128
 
            ie.symlink_target = blob.data
 
136
            ie.symlink_target = blob.data.decode("utf-8")
129
137
        else:
130
138
            ie.text_size = sum(imap(len, blob.chunked))
131
139
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
151
159
        assert ie.revision is not None
152
160
        if ie.kind == 'symlink':
153
161
            chunks = []
154
 
        else: 
 
162
        else:
155
163
            chunks = blob.chunked
156
164
        texts.insert_record_stream([
157
165
            ChunkedContentFactory((file_id, ie.revision),
172
180
 
173
181
 
174
182
class SubmodulesRequireSubtrees(BzrError):
175
 
    _fmt = """The repository you are fetching from contains submodules. To continue, upgrade your Bazaar repository to a format that supports nested trees, such as 'development-subtree'."""
 
183
    _fmt = ("The repository you are fetching from contains submodules. "
 
184
            "To continue, upgrade your Bazaar repository to a format that "
 
185
            "supports nested trees, such as 'development-subtree'.")
176
186
    internal = False
177
187
 
178
188
 
179
189
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
180
190
    base_inv, parent_id, revision_id, parent_invs, lookup_object,
181
191
    (base_mode, mode), store_updater, lookup_file_id):
 
192
    """Import a git submodule."""
182
193
    if base_hexsha == hexsha and base_mode == mode:
183
194
        return [], {}
184
195
    file_id = lookup_file_id(path)
 
196
    invdelta = []
185
197
    ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
186
198
    ie.revision = revision_id
187
 
    if base_hexsha is None:
188
 
        oldpath = None
 
199
    if base_hexsha is not None:
 
200
        old_path = path.decode("utf-8") # Renames are not supported yet
 
201
        if stat.S_ISDIR(base_mode):
 
202
            invdelta.extend(remove_disappeared_children(base_inv, old_path,
 
203
                lookup_object(base_hexsha), [], lookup_object))
189
204
    else:
190
 
        oldpath = path
 
205
        old_path = None
191
206
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
192
207
    texts.insert_record_stream([
193
208
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
194
 
    invdelta = [(oldpath, path, file_id, ie)]
 
209
    invdelta.append((old_path, path, file_id, ie))
195
210
    return invdelta, {}
196
211
 
197
212
 
260
275
    # Remember for next time
261
276
    existing_children = set()
262
277
    child_modes = {}
263
 
    for child_mode, name, child_hexsha in tree.entries():
 
278
    for name, child_mode, child_hexsha in tree.iteritems():
264
279
        existing_children.add(name)
265
280
        child_path = posixpath.join(path, name)
266
281
        if type(base_tree) is Tree:
275
290
        if stat.S_ISDIR(child_mode):
276
291
            subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
277
292
                child_path, name, (child_base_hexsha, child_hexsha), base_inv,
278
 
                file_id, revision_id, parent_invs, lookup_object, 
 
293
                file_id, revision_id, parent_invs, lookup_object,
279
294
                (child_base_mode, child_mode), store_updater, lookup_file_id,
280
295
                allow_submodules=allow_submodules)
281
296
        elif S_ISGITLINK(child_mode): # submodule
286
301
                file_id, revision_id, parent_invs, lookup_object,
287
302
                (child_base_mode, child_mode), store_updater, lookup_file_id)
288
303
        else:
289
 
            subinvdelta = import_git_blob(texts, mapping, child_path, name,
290
 
                (child_base_hexsha, child_hexsha), base_inv, file_id,
291
 
                revision_id, parent_invs, lookup_object,
292
 
                (child_base_mode, child_mode), store_updater, lookup_file_id)
 
304
            if not mapping.is_special_file(name):
 
305
                subinvdelta = import_git_blob(texts, mapping, child_path, name,
 
306
                    (child_base_hexsha, child_hexsha), base_inv, file_id,
 
307
                    revision_id, parent_invs, lookup_object,
 
308
                    (child_base_mode, child_mode), store_updater, lookup_file_id)
 
309
            else:
 
310
                subinvdelta = []
293
311
            grandchildmodes = {}
294
312
        child_modes.update(grandchildmodes)
295
313
        invdelta.extend(subinvdelta)
296
314
        if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
297
 
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
 
315
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111,
 
316
                        S_IFGITLINK):
298
317
            child_modes[child_path] = child_mode
299
318
    # Remove any children that have disappeared
300
319
    if base_tree is not None and type(base_tree) is Tree:
305
324
 
306
325
 
307
326
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
308
 
    o, rev, ret_tree, parent_trees, mapping, unusual_modes):
 
327
    o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
309
328
    new_unusual_modes = mapping.export_unusual_file_modes(rev)
310
329
    if new_unusual_modes != unusual_modes:
311
330
        raise AssertionError("unusual modes don't match: %r != %r" % (
312
331
            unusual_modes, new_unusual_modes))
313
332
    # Verify that we can reconstruct the commit properly
314
 
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True)
 
333
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
 
334
        verifiers)
315
335
    if rec_o != o:
316
336
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
317
337
            rec_o, o))
318
338
    diff = []
319
339
    new_objs = {}
320
340
    for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
321
 
        target_git_object_retriever._cache.idmap, unusual_modes, mapping.BZR_DUMMY_FILE):
 
341
        target_git_object_retriever._cache.idmap, unusual_modes,
 
342
        mapping.BZR_DUMMY_FILE):
322
343
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
323
344
        new_objs[path] = obj
324
345
        if obj.id != old_obj_id:
341
362
            old_obj, new_obj))
342
363
 
343
364
 
 
365
def ensure_inventories_in_repo(repo, trees):
 
366
    real_inv_vf = repo.inventories.without_fallbacks()
 
367
    for t in trees:
 
368
        revid = t.get_revision_id()
 
369
        if not real_inv_vf.get_parent_map([(revid, )]):
 
370
            repo.add_inventory(revid, t.inventory, t.get_parent_ids())
 
371
 
 
372
 
344
373
def import_git_commit(repo, mapping, head, lookup_object,
345
374
                      target_git_object_retriever, trees_cache):
346
375
    o = lookup_object(head)
347
 
    rev, roundtrip_revid, verifiers = mapping.import_commit(o,
348
 
            lambda x: target_git_object_retriever.lookup_git_sha(x)[1][0])
 
376
    # Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
 
377
    # were bzr roundtripped revisions they would be specified in the
 
378
    # roundtrip data.
 
379
    rev, roundtrip_revid, verifiers = mapping.import_commit(
 
380
        o, mapping.revision_id_foreign_to_bzr)
 
381
    if roundtrip_revid is not None:
 
382
        original_revid = rev.revision_id
 
383
        rev.revision_id = roundtrip_revid
349
384
    # We have to do this here, since we have to walk the tree and
350
385
    # we need to make sure to import the blobs / trees with the right
351
386
    # path; this may involve adding them more than once.
352
387
    parent_trees = trees_cache.revision_trees(rev.parent_ids)
 
388
    ensure_inventories_in_repo(repo, parent_trees)
353
389
    if parent_trees == []:
354
390
        base_inv = Inventory(root_id=None)
355
391
        base_tree = None
359
395
        base_tree = lookup_object(o.parents[0]).tree
360
396
        base_mode = stat.S_IFDIR
361
397
    store_updater = target_git_object_retriever._get_updater(rev)
362
 
    fileid_map = mapping.get_fileid_map(lookup_object, o.tree)
 
398
    tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
363
399
    inv_delta, unusual_modes = import_git_tree(repo.texts,
364
400
            mapping, "", "", (base_tree, o.tree), base_inv,
365
401
            None, rev.revision_id, [p.inventory for p in parent_trees],
366
402
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
367
 
            fileid_map.lookup_file_id,
368
 
            allow_submodules=getattr(repo._format, "supports_tree_reference", False))
 
403
            tree_supplement.lookup_file_id,
 
404
            allow_submodules=getattr(repo._format, "supports_tree_reference",
 
405
                False))
369
406
    if unusual_modes != {}:
370
407
        for path, mode in unusual_modes.iteritems():
371
408
            warn_unusual_mode(rev.foreign_revid, path, mode)
377
414
        base_inv = None
378
415
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
379
416
              inv_delta, rev.revision_id, rev.parent_ids, base_inv)
380
 
    # FIXME: Check verifiers
381
 
    testament = StrictTestament3(rev, inv)
382
 
    calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
383
 
    if roundtrip_revid is not None:
384
 
        original_revid = rev.revision_id
385
 
        rev.revision_id = roundtrip_revid
 
417
    ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
418
    # Check verifiers
 
419
    if verifiers and roundtrip_revid is not None:
 
420
        testament = StrictTestament3(rev, ret_tree)
 
421
        calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
386
422
        if calculated_verifiers != verifiers:
387
423
            trace.mutter("Testament SHA1 %r for %r did not match %r.",
388
424
                         calculated_verifiers["testament3-sha1"],
389
425
                         rev.revision_id, verifiers["testament3-sha1"])
390
426
            rev.revision_id = original_revid
 
427
            rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
428
              inv_delta, rev.revision_id, rev.parent_ids, base_inv)
 
429
            ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
430
    else:
 
431
        calculated_verifiers = {}
391
432
    store_updater.add_object(o, calculated_verifiers, None)
392
433
    store_updater.finish()
393
 
    ret_tree = RevisionTree(repo, inv, rev.revision_id)
394
434
    trees_cache.add(ret_tree)
395
435
    repo.add_revision(rev.revision_id, rev)
396
436
    if "verify" in debug.debug_flags:
397
437
        verify_commit_reconstruction(target_git_object_retriever, 
398
438
            lookup_object, o, rev, ret_tree, parent_trees, mapping,
399
 
            unusual_modes)
 
439
            unusual_modes, verifiers)
400
440
 
401
441
 
402
442
def import_git_objects(repo, mapping, object_iter,
422
462
        if pb is not None:
423
463
            pb.update("finding revisions to fetch", len(graph), None)
424
464
        head = heads.pop()
425
 
        assert isinstance(head, str)
 
465
        if head == ZERO_SHA:
 
466
            continue
 
467
        assert isinstance(head, str), "head is %r" % (head,)
426
468
        try:
427
469
            o = lookup_object(head)
428
470
        except KeyError:
429
471
            continue
430
472
        if isinstance(o, Commit):
431
473
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
432
 
                lambda x: None)
 
474
                mapping.revision_id_foreign_to_bzr)
433
475
            if (repo.has_revision(rev.revision_id) or
434
476
                (roundtrip_revid and repo.has_revision(roundtrip_revid))):
435
477
                continue
478
520
    return pack_hints, last_imported
479
521
 
480
522
 
481
 
class InterGitRepository(InterRepository):
 
523
class InterFromGitRepository(InterRepository):
482
524
 
483
525
    _matching_repo_format = GitRepositoryFormat()
484
526
 
 
527
    def _target_has_shas(self, shas):
 
528
        raise NotImplementedError(self._target_has_shas)
 
529
 
 
530
    def get_determine_wants_heads(self, wants, include_tags=False):
 
531
        raise NotImplementedError(self.get_determine_wants_heads)
 
532
 
 
533
    def determine_wants_all(self, refs):
 
534
        raise NotImplementedError(self.determine_wants_all)
 
535
 
485
536
    @staticmethod
486
537
    def _get_repo_format_to_test():
487
538
        return None
488
539
 
489
 
    def copy_content(self, revision_id=None, pb=None):
 
540
    def copy_content(self, revision_id=None):
490
541
        """See InterRepository.copy_content."""
491
 
        self.fetch(revision_id, pb, find_ghosts=False)
492
 
 
493
 
 
494
 
class InterGitNonGitRepository(InterGitRepository):
 
542
        self.fetch(revision_id, find_ghosts=False)
 
543
 
 
544
    def search_missing_revision_ids(self,
 
545
            find_ghosts=True, revision_ids=None, if_present_ids=None,
 
546
            limit=None):
 
547
        git_shas = []
 
548
        todo = []
 
549
        if revision_ids:
 
550
            todo.extend(revision_ids)
 
551
        if if_present_ids:
 
552
            todo.extend(revision_ids)
 
553
        for revid in revision_ids:
 
554
            if revid == NULL_REVISION:
 
555
                continue
 
556
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
557
            git_shas.append(git_sha)
 
558
        walker = Walker(self.source._git.object_store,
 
559
            include=git_shas, exclude=[sha for sha in self.target.bzrdir.get_refs_container().as_dict().values() if sha != ZERO_SHA])
 
560
        missing_revids = set()
 
561
        for entry in walker:
 
562
            missing_revids.add(self.source.lookup_foreign_revision_id(entry.commit.id))
 
563
        return self.source.revision_ids_to_search_result(missing_revids)
 
564
 
 
565
 
 
566
class InterGitNonGitRepository(InterFromGitRepository):
495
567
    """Base InterRepository that copies revisions from a Git into a non-Git
496
568
    repository."""
497
569
 
498
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
570
    def _target_has_shas(self, shas):
 
571
        revids = {}
 
572
        for sha in shas:
 
573
            try:
 
574
                revid = self.source.lookup_foreign_revision_id(sha)
 
575
            except NotCommitError:
 
576
                # Commit is definitely not present
 
577
                continue
 
578
            else:
 
579
                revids[revid] = sha
 
580
        return set([revids[r] for r in self.target.has_revisions(revids)])
 
581
 
 
582
    def determine_wants_all(self, refs):
 
583
        potential = set()
 
584
        for k, v in refs.as_dict().iteritems():
 
585
            # For non-git target repositories, only worry about peeled
 
586
            if v == ZERO_SHA:
 
587
                continue
 
588
            potential.add(self.source.bzrdir.get_peeled(k))
 
589
        return list(potential - self._target_has_shas(potential))
 
590
 
 
591
    def get_determine_wants_heads(self, wants, include_tags=False):
 
592
        wants = set(wants)
 
593
        def determine_wants(refs):
 
594
            potential = set(wants)
 
595
            if include_tags:
 
596
                for k, unpeeled in refs.as_dict().iteritems():
 
597
                    if not is_tag(k):
 
598
                        continue
 
599
                    if unpeeled == ZERO_SHA:
 
600
                        continue
 
601
                    potential.add(self.source.bzrdir.get_peeled(k))
 
602
            return list(potential - self._target_has_shas(potential))
 
603
        return determine_wants
 
604
 
 
605
    def get_determine_wants_revids(self, revids, include_tags=False):
 
606
        wants = set()
 
607
        for revid in set(revids):
 
608
            if self.target.has_revision(revid):
 
609
                continue
 
610
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
611
            wants.add(git_sha)
 
612
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
 
613
 
 
614
    def fetch_objects(self, determine_wants, mapping, limit=None):
499
615
        """Fetch objects from a remote server.
500
616
 
501
617
        :param determine_wants: determine_wants callback
502
618
        :param mapping: BzrGitMapping to use
503
 
        :param pb: Optional progress bar
504
619
        :param limit: Maximum number of commits to import.
505
620
        :return: Tuple with pack hint, last imported revision id and remote refs
506
621
        """
507
622
        raise NotImplementedError(self.fetch_objects)
508
623
 
509
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
624
    def fetch(self, revision_id=None, find_ghosts=False,
510
625
              mapping=None, fetch_spec=None):
511
626
        if mapping is None:
512
627
            mapping = self.source.get_mapping()
513
628
        if revision_id is not None:
514
629
            interesting_heads = [revision_id]
515
630
        elif fetch_spec is not None:
516
 
            interesting_heads = fetch_spec.heads
 
631
            recipe = fetch_spec.get_recipe()
 
632
            if recipe[0] in ("search", "proxy-search"):
 
633
                interesting_heads = recipe[1]
 
634
            else:
 
635
                raise AssertionError("Unsupported search result type %s" %
 
636
                        recipe[0])
517
637
        else:
518
638
            interesting_heads = None
519
 
        def determine_wants(refs):
520
 
            if interesting_heads is None:
521
 
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
522
 
            else:
523
 
                ret = [self.source.lookup_bzr_revision_id(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
524
 
            return [rev for rev in ret if not self.target.has_revision(self.source.lookup_foreign_revision_id(rev))]
525
 
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants, mapping, pb)
 
639
 
 
640
        if interesting_heads is not None:
 
641
            determine_wants = self.get_determine_wants_revids(
 
642
                interesting_heads, include_tags=False)
 
643
        else:
 
644
            determine_wants = self.determine_wants_all
 
645
 
 
646
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
 
647
            mapping)
526
648
        if pack_hint is not None and self.target._format.pack_compresses:
527
649
            self.target.pack(hint=pack_hint)
528
650
        return remote_refs
564
686
        map(all_parents.update, parent_map.itervalues())
565
687
        return set(all_revs) - all_parents
566
688
 
567
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
689
    def fetch_objects(self, determine_wants, mapping, limit=None):
568
690
        """See `InterGitNonGitRepository`."""
569
 
        def progress(text):
570
 
            report_git_progress(pb, text)
571
691
        store = BazaarObjectStore(self.target, mapping)
572
 
        self.target.lock_write()
 
692
        store.lock_write()
573
693
        try:
574
694
            heads = self.get_target_heads()
575
695
            graph_walker = store.get_graph_walker(
576
696
                    [store._lookup_revision_sha1(head) for head in heads])
577
697
            wants_recorder = DetermineWantsRecorder(determine_wants)
578
698
 
579
 
            create_pb = None
580
 
            if pb is None:
581
 
                create_pb = pb = ui.ui_factory.nested_progress_bar()
 
699
            pb = ui.ui_factory.nested_progress_bar()
582
700
            try:
583
701
                objects_iter = self.source.fetch_objects(
584
702
                    wants_recorder, graph_walker, store.get_raw,
585
 
                    progress)
586
 
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
587
 
                    objects_iter, store, wants_recorder.wants, pb, limit)
 
703
                    progress=lambda text: report_git_progress(pb, text))
 
704
                trace.mutter("Importing %d new revisions",
 
705
                             len(wants_recorder.wants))
 
706
                (pack_hint, last_rev) = import_git_objects(self.target,
 
707
                    mapping, objects_iter, store, wants_recorder.wants, pb,
 
708
                    limit)
588
709
                return (pack_hint, last_rev, wants_recorder.remote_refs)
589
710
            finally:
590
 
                if create_pb:
591
 
                    create_pb.finished()
 
711
                pb.finished()
592
712
        finally:
593
 
            self.target.unlock()
 
713
            store.unlock()
594
714
 
595
715
    @staticmethod
596
716
    def is_compatible(source, target):
597
717
        """Be compatible with GitRepository."""
598
 
        return (isinstance(source, RemoteGitRepository) and
599
 
                target.supports_rich_root() and
600
 
                not isinstance(target, GitRepository) and
601
 
                target.texts is not None)
 
718
        if not isinstance(source, RemoteGitRepository):
 
719
            return False
 
720
        if not target.supports_rich_root():
 
721
            return False
 
722
        if isinstance(target, GitRepository):
 
723
            return False
 
724
        if not getattr(target._format, "supports_full_versioned_files", True):
 
725
            return False
 
726
        return True
602
727
 
603
728
 
604
729
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
605
730
    """InterRepository that copies revisions from a local Git into a non-Git
606
731
    repository."""
607
732
 
608
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
733
    def fetch_objects(self, determine_wants, mapping, limit=None):
609
734
        """See `InterGitNonGitRepository`."""
610
 
        remote_refs = self.source._git.get_refs()
 
735
        remote_refs = self.source.bzrdir.get_refs_container()
611
736
        wants = determine_wants(remote_refs)
612
737
        create_pb = None
613
 
        if pb is None:
614
 
            create_pb = pb = ui.ui_factory.nested_progress_bar()
 
738
        pb = ui.ui_factory.nested_progress_bar()
615
739
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
616
740
        try:
617
 
            self.target.lock_write()
 
741
            target_git_object_retriever.lock_write()
618
742
            try:
619
 
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
620
 
                    self.source._git.object_store,
 
743
                (pack_hint, last_rev) = import_git_objects(self.target,
 
744
                    mapping, self.source._git.object_store,
621
745
                    target_git_object_retriever, wants, pb, limit)
622
746
                return (pack_hint, last_rev, remote_refs)
623
747
            finally:
624
 
                self.target.unlock()
 
748
                target_git_object_retriever.unlock()
625
749
        finally:
626
 
            if create_pb:
627
 
                create_pb.finished()
 
750
            pb.finished()
628
751
 
629
752
    @staticmethod
630
753
    def is_compatible(source, target):
631
754
        """Be compatible with GitRepository."""
632
 
        return (isinstance(source, LocalGitRepository) and
633
 
                target.supports_rich_root() and
634
 
                not isinstance(target, GitRepository) and
635
 
                target.texts is not None)
636
 
 
637
 
 
638
 
class InterGitGitRepository(InterGitRepository):
 
755
        if not isinstance(source, LocalGitRepository):
 
756
            return False
 
757
        if not target.supports_rich_root():
 
758
            return False
 
759
        if isinstance(target, GitRepository):
 
760
            return False
 
761
        if not getattr(target._format, "supports_full_versioned_files", True):
 
762
            return False
 
763
        return True
 
764
 
 
765
 
 
766
class InterGitGitRepository(InterFromGitRepository):
639
767
    """InterRepository that copies between Git repositories."""
640
768
 
641
 
    def fetch_objects(self, determine_wants, mapping, pb=None):
642
 
        def progress(text):
643
 
            trace.note("git: %s", text)
 
769
    def fetch_refs(self, update_refs, lossy=False):
 
770
        if lossy:
 
771
            raise errors.LossyPushToSameVCS(self.source, self.target)
 
772
        old_refs = self.target.bzrdir.get_refs_container()
 
773
        ref_changes = {}
 
774
        def determine_wants(heads):
 
775
            old_refs = dict([(k, (v, None)) for (k, v) in heads.as_dict().iteritems()])
 
776
            new_refs = update_refs(old_refs)
 
777
            ref_changes.update(new_refs)
 
778
            return [sha1 for (sha1, bzr_revid) in new_refs.itervalues()]
 
779
        self.fetch_objects(determine_wants)
 
780
        for k, (git_sha, bzr_revid) in ref_changes.iteritems():
 
781
            self.target._git.refs[k] = git_sha
 
782
        new_refs = self.target.bzrdir.get_refs_container()
 
783
        return None, old_refs, new_refs
 
784
 
 
785
    def fetch_objects(self, determine_wants, mapping=None, limit=None):
644
786
        graphwalker = self.target._git.get_graph_walker()
645
787
        if (isinstance(self.source, LocalGitRepository) and
646
788
            isinstance(self.target, LocalGitRepository)):
647
 
            refs = self.source._git.fetch(self.target._git, determine_wants,
648
 
                progress)
 
789
            def wrap_determine_wants(refs):
 
790
                return determine_wants(self.source._git.refs)
 
791
            pb = ui.ui_factory.nested_progress_bar()
 
792
            try:
 
793
                refs = self.source._git.fetch(self.target._git, wrap_determine_wants,
 
794
                    lambda text: report_git_progress(pb, text))
 
795
            finally:
 
796
                pb.finished()
649
797
            return (None, None, refs)
650
798
        elif (isinstance(self.source, LocalGitRepository) and
651
799
              isinstance(self.target, RemoteGitRepository)):
652
800
            raise NotImplementedError
653
801
        elif (isinstance(self.source, RemoteGitRepository) and
654
802
              isinstance(self.target, LocalGitRepository)):
655
 
            f, commit = self.target._git.object_store.add_thin_pack()
 
803
            pb = ui.ui_factory.nested_progress_bar()
656
804
            try:
657
 
                refs = self.source.bzrdir.root_transport.fetch_pack(
658
 
                    determine_wants, graphwalker, f.write, progress)
659
 
                commit()
660
 
                return (None, None, refs)
661
 
            except:
662
 
                f.close()
663
 
                raise
 
805
                f, commit = self.target._git.object_store.add_pack()
 
806
                try:
 
807
                    refs = self.source.bzrdir.fetch_pack(
 
808
                        determine_wants, graphwalker, f.write,
 
809
                        lambda text: report_git_progress(pb, text))
 
810
                    commit()
 
811
                    return (None, None, refs)
 
812
                except:
 
813
                    f.close()
 
814
                    raise
 
815
            finally:
 
816
                pb.finished()
664
817
        else:
665
 
            raise AssertionError
666
 
 
667
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
668
 
              mapping=None, fetch_spec=None, branches=None):
 
818
            raise AssertionError("fetching between %r and %r not supported" %
 
819
                    (self.source, self.target))
 
820
 
 
821
    def _target_has_shas(self, shas):
 
822
        return set([sha for sha in shas if sha in self.target._git.object_store])
 
823
 
 
824
    def fetch(self, revision_id=None, find_ghosts=False,
 
825
              mapping=None, fetch_spec=None, branches=None, limit=None):
669
826
        if mapping is None:
670
827
            mapping = self.source.get_mapping()
671
828
        r = self.target._git
672
829
        if revision_id is not None:
673
 
            args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]
 
830
            args = [self.source.lookup_bzr_revision_id(revision_id)[0]]
674
831
        elif fetch_spec is not None:
675
 
            args = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in fetch_spec.heads]
 
832
            recipe = fetch_spec.get_recipe()
 
833
            if recipe[0] in ("search", "proxy-search"):
 
834
                heads = recipe[1]
 
835
            else:
 
836
                raise AssertionError(
 
837
                    "Unsupported search result type %s" % recipe[0])
 
838
            args = [self.source.lookup_bzr_revision_id(revid)[0] for revid in heads]
676
839
        if branches is not None:
677
 
            determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store]
 
840
            determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store and x[y] != ZERO_SHA]
678
841
        elif fetch_spec is None and revision_id is None:
679
 
            determine_wants = r.object_store.determine_wants_all
 
842
            determine_wants = self.determine_wants_all
680
843
        else:
681
 
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
682
 
        self.fetch_objects(determine_wants, mapping)
 
844
            determine_wants = lambda x: [y for y in args if not y in r.object_store and y != ZERO_SHA]
 
845
        wants_recorder = DetermineWantsRecorder(determine_wants)
 
846
        self.fetch_objects(wants_recorder, mapping)
 
847
        return wants_recorder.remote_refs
683
848
 
684
849
    @staticmethod
685
850
    def is_compatible(source, target):
686
851
        """Be compatible with GitRepository."""
687
852
        return (isinstance(source, GitRepository) and
688
853
                isinstance(target, GitRepository))
 
854
 
 
855
    def get_determine_wants_revids(self, revids, include_tags=False):
 
856
        wants = set()
 
857
        for revid in set(revids):
 
858
            if self.target.has_revision(revid):
 
859
                continue
 
860
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
861
            wants.add(git_sha)
 
862
        return self.get_determine_wants_heads(wants,
 
863
            include_tags=include_tags)
 
864
 
 
865
    def determine_wants_all(self, refs):
 
866
        potential = set([v for v in refs.as_dict().values() if not v == ZERO_SHA])
 
867
        return list(potential - self._target_has_shas(potential))
 
868
 
 
869
    def get_determine_wants_heads(self, wants, include_tags=False):
 
870
        wants = set(wants)
 
871
        def determine_wants(refs):
 
872
            potential = set(wants)
 
873
            if include_tags:
 
874
                for k, unpeeled in refs.as_dict().iteritems():
 
875
                    if not is_tag(k):
 
876
                        continue
 
877
                    if unpeeled == ZERO_SHA:
 
878
                        continue
 
879
                    potential.add(unpeeled)
 
880
            return list(potential - self._target_has_shas(potential))
 
881
        return determine_wants
 
882
 
 
883