/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

Add 'github:' directory service.

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
            if v == ZERO_SHA:
 
593
                continue
 
594
            potential.add(self.source.bzrdir.get_peeled(k))
 
595
        return list(potential - self._target_has_shas(potential))
 
596
 
 
597
    def get_determine_wants_heads(self, wants, include_tags=False):
 
598
        wants = set(wants)
 
599
        def determine_wants(refs):
 
600
            potential = set(wants)
 
601
            if include_tags:
 
602
                for k, unpeeled in refs.as_dict().iteritems():
 
603
                    if not is_tag(k):
 
604
                        continue
 
605
                    if unpeeled == ZERO_SHA:
 
606
                        continue
 
607
                    potential.add(self.source.bzrdir.get_peeled(k))
 
608
            return list(potential - self._target_has_shas(potential))
 
609
        return determine_wants
 
610
 
 
611
    def get_determine_wants_revids(self, revids, include_tags=False):
 
612
        wants = set()
 
613
        for revid in set(revids):
 
614
            if self.target.has_revision(revid):
 
615
                continue
 
616
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
617
            wants.add(git_sha)
 
618
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
 
619
 
 
620
    def fetch_objects(self, determine_wants, mapping, limit=None):
499
621
        """Fetch objects from a remote server.
500
622
 
501
623
        :param determine_wants: determine_wants callback
502
624
        :param mapping: BzrGitMapping to use
503
 
        :param pb: Optional progress bar
504
625
        :param limit: Maximum number of commits to import.
505
626
        :return: Tuple with pack hint, last imported revision id and remote refs
506
627
        """
507
628
        raise NotImplementedError(self.fetch_objects)
508
629
 
509
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
630
    def fetch(self, revision_id=None, find_ghosts=False,
510
631
              mapping=None, fetch_spec=None):
511
632
        if mapping is None:
512
633
            mapping = self.source.get_mapping()
513
634
        if revision_id is not None:
514
635
            interesting_heads = [revision_id]
515
636
        elif fetch_spec is not None:
516
 
            interesting_heads = fetch_spec.heads
 
637
            recipe = fetch_spec.get_recipe()
 
638
            if recipe[0] in ("search", "proxy-search"):
 
639
                interesting_heads = recipe[1]
 
640
            else:
 
641
                raise AssertionError("Unsupported search result type %s" %
 
642
                        recipe[0])
517
643
        else:
518
644
            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)
 
645
 
 
646
        if interesting_heads is not None:
 
647
            determine_wants = self.get_determine_wants_revids(
 
648
                interesting_heads, include_tags=False)
 
649
        else:
 
650
            determine_wants = self.determine_wants_all
 
651
 
 
652
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
 
653
            mapping)
526
654
        if pack_hint is not None and self.target._format.pack_compresses:
527
655
            self.target.pack(hint=pack_hint)
528
656
        return remote_refs
564
692
        map(all_parents.update, parent_map.itervalues())
565
693
        return set(all_revs) - all_parents
566
694
 
567
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
695
    def fetch_objects(self, determine_wants, mapping, limit=None):
568
696
        """See `InterGitNonGitRepository`."""
569
 
        def progress(text):
570
 
            report_git_progress(pb, text)
571
697
        store = BazaarObjectStore(self.target, mapping)
572
 
        self.target.lock_write()
 
698
        store.lock_write()
573
699
        try:
574
700
            heads = self.get_target_heads()
575
701
            graph_walker = store.get_graph_walker(
576
702
                    [store._lookup_revision_sha1(head) for head in heads])
577
703
            wants_recorder = DetermineWantsRecorder(determine_wants)
578
704
 
579
 
            create_pb = None
580
 
            if pb is None:
581
 
                create_pb = pb = ui.ui_factory.nested_progress_bar()
 
705
            pb = ui.ui_factory.nested_progress_bar()
582
706
            try:
583
707
                objects_iter = self.source.fetch_objects(
584
708
                    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)
 
709
                    progress=lambda text: report_git_progress(pb, text))
 
710
                trace.mutter("Importing %d new revisions",
 
711
                             len(wants_recorder.wants))
 
712
                (pack_hint, last_rev) = import_git_objects(self.target,
 
713
                    mapping, objects_iter, store, wants_recorder.wants, pb,
 
714
                    limit)
588
715
                return (pack_hint, last_rev, wants_recorder.remote_refs)
589
716
            finally:
590
 
                if create_pb:
591
 
                    create_pb.finished()
 
717
                pb.finished()
592
718
        finally:
593
 
            self.target.unlock()
 
719
            store.unlock()
594
720
 
595
721
    @staticmethod
596
722
    def is_compatible(source, target):
597
723
        """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)
 
724
        if not isinstance(source, RemoteGitRepository):
 
725
            return False
 
726
        if not target.supports_rich_root():
 
727
            return False
 
728
        if isinstance(target, GitRepository):
 
729
            return False
 
730
        if not getattr(target._format, "supports_full_versioned_files", True):
 
731
            return False
 
732
        return True
602
733
 
603
734
 
604
735
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
605
736
    """InterRepository that copies revisions from a local Git into a non-Git
606
737
    repository."""
607
738
 
608
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
739
    def fetch_objects(self, determine_wants, mapping, limit=None):
609
740
        """See `InterGitNonGitRepository`."""
610
 
        remote_refs = self.source._git.get_refs()
 
741
        remote_refs = self.source.bzrdir.get_refs_container()
611
742
        wants = determine_wants(remote_refs)
612
743
        create_pb = None
613
 
        if pb is None:
614
 
            create_pb = pb = ui.ui_factory.nested_progress_bar()
 
744
        pb = ui.ui_factory.nested_progress_bar()
615
745
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
616
746
        try:
617
 
            self.target.lock_write()
 
747
            target_git_object_retriever.lock_write()
618
748
            try:
619
 
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
620
 
                    self.source._git.object_store,
 
749
                (pack_hint, last_rev) = import_git_objects(self.target,
 
750
                    mapping, self.source._git.object_store,
621
751
                    target_git_object_retriever, wants, pb, limit)
622
752
                return (pack_hint, last_rev, remote_refs)
623
753
            finally:
624
 
                self.target.unlock()
 
754
                target_git_object_retriever.unlock()
625
755
        finally:
626
 
            if create_pb:
627
 
                create_pb.finished()
 
756
            pb.finished()
628
757
 
629
758
    @staticmethod
630
759
    def is_compatible(source, target):
631
760
        """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):
 
761
        if not isinstance(source, LocalGitRepository):
 
762
            return False
 
763
        if not target.supports_rich_root():
 
764
            return False
 
765
        if isinstance(target, GitRepository):
 
766
            return False
 
767
        if not getattr(target._format, "supports_full_versioned_files", True):
 
768
            return False
 
769
        return True
 
770
 
 
771
 
 
772
class InterGitGitRepository(InterFromGitRepository):
639
773
    """InterRepository that copies between Git repositories."""
640
774
 
641
 
    def fetch_objects(self, determine_wants, mapping, pb=None):
642
 
        def progress(text):
643
 
            trace.note("git: %s", text)
 
775
    def fetch_refs(self, update_refs, lossy=False):
 
776
        if lossy:
 
777
            raise errors.LossyPushToSameVCS(self.source, self.target)
 
778
        old_refs = self.target.bzrdir.get_refs_container()
 
779
        ref_changes = {}
 
780
        def determine_wants(heads):
 
781
            old_refs = dict([(k, (v, None)) for (k, v) in heads.as_dict().iteritems()])
 
782
            new_refs = update_refs(old_refs)
 
783
            ref_changes.update(new_refs)
 
784
            return [sha1 for (sha1, bzr_revid) in new_refs.itervalues()]
 
785
        self.fetch_objects(determine_wants)
 
786
        for k, (git_sha, bzr_revid) in ref_changes.iteritems():
 
787
            self.target._git.refs[k] = git_sha
 
788
        new_refs = self.target.bzrdir.get_refs_container()
 
789
        return None, old_refs, new_refs
 
790
 
 
791
    def fetch_objects(self, determine_wants, mapping=None, limit=None):
644
792
        graphwalker = self.target._git.get_graph_walker()
645
793
        if (isinstance(self.source, LocalGitRepository) and
646
794
            isinstance(self.target, LocalGitRepository)):
647
 
            refs = self.source._git.fetch(self.target._git, determine_wants,
648
 
                progress)
 
795
            def wrap_determine_wants(refs):
 
796
                return determine_wants(self.source._git.refs)
 
797
            pb = ui.ui_factory.nested_progress_bar()
 
798
            try:
 
799
                refs = self.source._git.fetch(self.target._git, wrap_determine_wants,
 
800
                    lambda text: report_git_progress(pb, text))
 
801
            finally:
 
802
                pb.finished()
649
803
            return (None, None, refs)
650
804
        elif (isinstance(self.source, LocalGitRepository) and
651
805
              isinstance(self.target, RemoteGitRepository)):
652
806
            raise NotImplementedError
653
807
        elif (isinstance(self.source, RemoteGitRepository) and
654
808
              isinstance(self.target, LocalGitRepository)):
655
 
            f, commit = self.target._git.object_store.add_thin_pack()
 
809
            pb = ui.ui_factory.nested_progress_bar()
656
810
            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
 
811
                f, commit = self.target._git.object_store.add_pack()
 
812
                try:
 
813
                    refs = self.source.bzrdir.fetch_pack(
 
814
                        determine_wants, graphwalker, f.write,
 
815
                        lambda text: report_git_progress(pb, text))
 
816
                    commit()
 
817
                    return (None, None, refs)
 
818
                except:
 
819
                    f.close()
 
820
                    raise
 
821
            finally:
 
822
                pb.finished()
664
823
        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):
 
824
            raise AssertionError("fetching between %r and %r not supported" %
 
825
                    (self.source, self.target))
 
826
 
 
827
    def _target_has_shas(self, shas):
 
828
        return set([sha for sha in shas if sha in self.target._git.object_store])
 
829
 
 
830
    def fetch(self, revision_id=None, find_ghosts=False,
 
831
              mapping=None, fetch_spec=None, branches=None, limit=None):
669
832
        if mapping is None:
670
833
            mapping = self.source.get_mapping()
671
834
        r = self.target._git
672
835
        if revision_id is not None:
673
 
            args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]
 
836
            args = [self.source.lookup_bzr_revision_id(revision_id)[0]]
674
837
        elif fetch_spec is not None:
675
 
            args = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in fetch_spec.heads]
 
838
            recipe = fetch_spec.get_recipe()
 
839
            if recipe[0] in ("search", "proxy-search"):
 
840
                heads = recipe[1]
 
841
            else:
 
842
                raise AssertionError(
 
843
                    "Unsupported search result type %s" % recipe[0])
 
844
            args = [self.source.lookup_bzr_revision_id(revid)[0] for revid in heads]
676
845
        if branches is not None:
677
 
            determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store]
 
846
            determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store and x[y] != ZERO_SHA]
678
847
        elif fetch_spec is None and revision_id is None:
679
 
            determine_wants = r.object_store.determine_wants_all
 
848
            determine_wants = self.determine_wants_all
680
849
        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)
 
850
            determine_wants = lambda x: [y for y in args if not y in r.object_store and y != ZERO_SHA]
 
851
        wants_recorder = DetermineWantsRecorder(determine_wants)
 
852
        self.fetch_objects(wants_recorder, mapping)
 
853
        return wants_recorder.remote_refs
683
854
 
684
855
    @staticmethod
685
856
    def is_compatible(source, target):
686
857
        """Be compatible with GitRepository."""
687
858
        return (isinstance(source, GitRepository) and
688
859
                isinstance(target, GitRepository))
 
860
 
 
861
    def get_determine_wants_revids(self, revids, include_tags=False):
 
862
        wants = set()
 
863
        for revid in set(revids):
 
864
            if self.target.has_revision(revid):
 
865
                continue
 
866
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
867
            wants.add(git_sha)
 
868
        return self.get_determine_wants_heads(wants,
 
869
            include_tags=include_tags)
 
870
 
 
871
    def determine_wants_all(self, refs):
 
872
        potential = set([v for v in refs.as_dict().values() if not v == ZERO_SHA])
 
873
        return list(potential - self._target_has_shas(potential))
 
874
 
 
875
    def get_determine_wants_heads(self, wants, include_tags=False):
 
876
        wants = set(wants)
 
877
        def determine_wants(refs):
 
878
            potential = set(wants)
 
879
            if include_tags:
 
880
                for k, unpeeled in refs.as_dict().iteritems():
 
881
                    if not is_tag(k):
 
882
                        continue
 
883
                    if unpeeled == ZERO_SHA:
 
884
                        continue
 
885
                    potential.add(unpeeled)
 
886
            return list(potential - self._target_has_shas(potential))
 
887
        return determine_wants
 
888
 
 
889