/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

Merge changes to avoid inventories.

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