/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

Fix access to native git repositories.

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