/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

More work on roundtrip push support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
 
1
# Copyright (C) 2008-2010 Jelmer Vernooij <jelmer@samba.org>
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
56
56
from bzrlib.revisiontree import (
57
57
    RevisionTree,
58
58
    )
 
59
from bzrlib.testament import (
 
60
    StrictTestament3,
 
61
    )
59
62
from bzrlib.tsort import (
60
63
    topo_sort,
61
64
    )
65
68
 
66
69
from bzrlib.plugins.git.mapping import (
67
70
    DEFAULT_FILE_MODE,
68
 
    inventory_to_tree_and_blobs,
69
71
    mode_is_executable,
70
72
    mode_kind,
71
 
    squash_revision,
72
73
    warn_unusual_mode,
73
74
    )
74
75
from bzrlib.plugins.git.object_store import (
75
76
    BazaarObjectStore,
76
77
    LRUTreeCache,
 
78
    _tree_to_objects,
77
79
    )
78
80
from bzrlib.plugins.git.remote import (
79
81
    RemoteGitRepository,
87
89
 
88
90
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha), 
89
91
        base_inv, parent_id, revision_id,
90
 
        parent_invs, lookup_object, (base_mode, mode), store_updater):
 
92
        parent_invs, lookup_object, (base_mode, mode), store_updater,
 
93
        lookup_file_id):
91
94
    """Import a git blob object into a bzr repository.
92
95
 
93
96
    :param texts: VersionedFiles to add to
95
98
    :param blob: A git blob
96
99
    :return: Inventory delta for this file
97
100
    """
 
101
    if mapping.is_control_file(path):
 
102
        return []
98
103
    if base_hexsha == hexsha and base_mode == mode:
99
104
        # If nothing has changed since the base revision, we're done
100
105
        return []
101
 
    file_id = mapping.generate_file_id(path)
 
106
    file_id = lookup_file_id(path)
102
107
    if stat.S_ISLNK(mode):
103
108
        cls = InventoryLink
104
109
    else:
105
110
        cls = InventoryFile
106
111
    ie = cls(file_id, name.decode("utf-8"), parent_id)
107
 
    ie.executable = mode_is_executable(mode)
 
112
    if ie.kind == "file":
 
113
        ie.executable = mode_is_executable(mode)
108
114
    if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
109
115
        base_ie = base_inv[base_inv.path2id(path)]
110
116
        ie.text_size = base_ie.text_size
111
117
        ie.text_sha1 = base_ie.text_sha1
112
 
        ie.symlink_target = base_ie.symlink_target
 
118
        if ie.kind == "symlink":
 
119
            ie.symlink_target = base_ie.symlink_target
113
120
        if ie.executable == base_ie.executable:
114
121
            ie.revision = base_ie.revision
115
122
        else:
119
126
        if ie.kind == "symlink":
120
127
            ie.revision = None
121
128
            ie.symlink_target = blob.data
122
 
            ie.text_size = None
123
 
            ie.text_sha1 = None
124
129
        else:
125
130
            ie.text_size = sum(imap(len, blob.chunked))
126
131
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
127
132
    # Check what revision we should store
128
133
    parent_keys = []
129
 
    for pinv in parent_invs[1:]:
 
134
    for pinv in parent_invs:
130
135
        try:
131
136
            pie = pinv[file_id]
132
137
        except NoSuchId:
133
138
            continue
134
 
        if pie.text_sha1 == ie.text_sha1 and pie.executable == ie.executable and pie.symlink_target == ie.symlink_target:
 
139
        if (pie.text_sha1 == ie.text_sha1 and
 
140
            pie.executable == ie.executable and
 
141
            pie.symlink_target == ie.symlink_target):
135
142
            # found a revision in one of the parents to use
136
143
            ie.revision = pie.revision
137
144
            break
138
 
        parent_keys.append((file_id, pie.revision))
 
145
        parent_key = (file_id, pie.revision)
 
146
        if not parent_key in parent_keys:
 
147
            parent_keys.append(parent_key)
139
148
    if ie.revision is None:
140
149
        # Need to store a new revision
141
150
        ie.revision = revision_id
144
153
            chunks = []
145
154
        else: 
146
155
            chunks = blob.chunked
147
 
        texts.insert_record_stream([ChunkedContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, chunks)])
 
156
        texts.insert_record_stream([
 
157
            ChunkedContentFactory((file_id, ie.revision),
 
158
                tuple(parent_keys), ie.text_sha1, chunks)])
148
159
    invdelta = []
149
160
    if base_hexsha is not None:
150
 
        old_path = path # Renames are not supported yet
 
161
        old_path = path.decode("utf-8") # Renames are not supported yet
151
162
        if stat.S_ISDIR(base_mode):
152
163
            invdelta.extend(remove_disappeared_children(base_inv, old_path,
153
164
                lookup_object(base_hexsha), [], lookup_object))
154
165
    else:
155
166
        old_path = None
156
 
    invdelta.append((old_path, path, file_id, ie))
 
167
    new_path = path.decode("utf-8")
 
168
    invdelta.append((old_path, new_path, file_id, ie))
157
169
    if base_hexsha != hexsha:
158
 
        store_updater.add_object(blob, ie)
 
170
        store_updater.add_object(blob, ie, path)
159
171
    return invdelta
160
172
 
161
173
 
166
178
 
167
179
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
168
180
    base_inv, parent_id, revision_id, parent_invs, lookup_object,
169
 
    (base_mode, mode), store_updater):
 
181
    (base_mode, mode), store_updater, lookup_file_id):
170
182
    if base_hexsha == hexsha and base_mode == mode:
171
183
        return [], {}
172
 
    file_id = mapping.generate_file_id(path)
 
184
    file_id = lookup_file_id(path)
173
185
    ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
174
186
    ie.revision = revision_id
175
187
    if base_hexsha is None:
177
189
    else:
178
190
        oldpath = path
179
191
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
180
 
    texts.insert_record_stream([ChunkedContentFactory((file_id, ie.revision), (), None, [])])
 
192
    texts.insert_record_stream([
 
193
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
181
194
    invdelta = [(oldpath, path, file_id, ie)]
182
195
    return invdelta, {}
183
196
 
184
197
 
185
198
def remove_disappeared_children(base_inv, path, base_tree, existing_children,
186
199
        lookup_object):
 
200
    """Generate an inventory delta for removed children.
 
201
 
 
202
    :param base_inv: Base inventory against which to generate the 
 
203
        inventory delta.
 
204
    :param path: Path to process (unicode)
 
205
    :param base_tree: Git Tree base object
 
206
    :param existing_children: Children that still exist
 
207
    :param lookup_object: Lookup a git object by its SHA1
 
208
    :return: Inventory delta, as list
 
209
    """
 
210
    assert type(path) is unicode
187
211
    ret = []
188
212
    for name, mode, hexsha in base_tree.iteritems():
189
213
        if name in existing_children:
190
214
            continue
191
215
        c_path = posixpath.join(path, name.decode("utf-8"))
192
 
        ret.append((c_path, None, base_inv.path2id(c_path), None))
 
216
        file_id = base_inv.path2id(c_path)
 
217
        assert file_id is not None
 
218
        ret.append((c_path, None, file_id, None))
193
219
        if stat.S_ISDIR(mode):
194
220
            ret.extend(remove_disappeared_children(
195
221
                base_inv, c_path, lookup_object(hexsha), [], lookup_object))
198
224
 
199
225
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
200
226
        base_inv, parent_id, revision_id, parent_invs,
201
 
    lookup_object, (base_mode, mode), store_updater, allow_submodules=False):
 
227
        lookup_object, (base_mode, mode), store_updater,
 
228
        lookup_file_id, allow_submodules=False):
202
229
    """Import a git tree object into a bzr repository.
203
230
 
204
231
    :param texts: VersionedFiles object to add to
205
 
    :param path: Path in the tree
 
232
    :param path: Path in the tree (str)
 
233
    :param name: Name of the tree (str)
206
234
    :param tree: A git tree object
207
235
    :param base_inv: Base inventory against which to return inventory delta
208
236
    :return: Inventory delta for this subtree
209
237
    """
 
238
    assert type(path) is str
 
239
    assert type(name) is str
210
240
    if base_hexsha == hexsha and base_mode == mode:
211
241
        # If nothing has changed since the base revision, we're done
212
242
        return [], {}
213
243
    invdelta = []
214
 
    file_id = mapping.generate_file_id(path)
 
244
    file_id = lookup_file_id(path)
215
245
    # We just have to hope this is indeed utf-8:
216
246
    ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
217
247
    tree = lookup_object(hexsha)
220
250
        old_path = None # Newly appeared here
221
251
    else:
222
252
        base_tree = lookup_object(base_hexsha)
223
 
        old_path = path # Renames aren't supported yet
 
253
        old_path = path.decode("utf-8") # Renames aren't supported yet
 
254
    new_path = path.decode("utf-8")
224
255
    if base_tree is None or type(base_tree) is not Tree:
225
256
        ie.revision = revision_id
226
 
        invdelta.append((old_path, path, ie.file_id, ie))
227
 
        texts.insert_record_stream([ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
 
257
        invdelta.append((old_path, new_path, ie.file_id, ie))
 
258
        texts.insert_record_stream([
 
259
            ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
228
260
    # Remember for next time
229
261
    existing_children = set()
230
262
    child_modes = {}
241
273
            child_base_hexsha = None
242
274
            child_base_mode = 0
243
275
        if stat.S_ISDIR(child_mode):
244
 
            subinvdelta, grandchildmodes = import_git_tree(
245
 
                    texts, mapping, child_path, name,
246
 
                    (child_base_hexsha, child_hexsha),
247
 
                    base_inv, file_id, revision_id, parent_invs, lookup_object,
248
 
                    (child_base_mode, child_mode), store_updater,
249
 
                    allow_submodules=allow_submodules)
 
276
            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)
250
281
        elif S_ISGITLINK(child_mode): # submodule
251
282
            if not allow_submodules:
252
283
                raise SubmodulesRequireSubtrees()
253
 
            subinvdelta, grandchildmodes = import_git_submodule(
254
 
                    texts, mapping, child_path, name,
255
 
                    (child_base_hexsha, child_hexsha),
256
 
                    base_inv, file_id, revision_id, parent_invs, lookup_object,
257
 
                    (child_base_mode, child_mode), store_updater)
 
284
            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)
258
288
        else:
259
 
            subinvdelta = import_git_blob(texts, mapping,
260
 
                    child_path, name, (child_base_hexsha, child_hexsha),
261
 
                    base_inv, file_id, revision_id, parent_invs, lookup_object,
262
 
                    (child_base_mode, child_mode), store_updater)
 
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)
263
293
            grandchildmodes = {}
264
294
        child_modes.update(grandchildmodes)
265
295
        invdelta.extend(subinvdelta)
268
298
            child_modes[child_path] = child_mode
269
299
    # Remove any children that have disappeared
270
300
    if base_tree is not None and type(base_tree) is Tree:
271
 
        invdelta.extend(remove_disappeared_children(base_inv, old_path, 
 
301
        invdelta.extend(remove_disappeared_children(base_inv, old_path,
272
302
            base_tree, existing_children, lookup_object))
273
 
    store_updater.add_object(tree, ie)
 
303
    store_updater.add_object(tree, ie, path)
274
304
    return invdelta, child_modes
275
305
 
276
306
 
 
307
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
 
308
    o, rev, ret_tree, parent_trees, mapping, unusual_modes):
 
309
    new_unusual_modes = mapping.export_unusual_file_modes(rev)
 
310
    if new_unusual_modes != unusual_modes:
 
311
        raise AssertionError("unusual modes don't match: %r != %r" % (
 
312
            unusual_modes, new_unusual_modes))
 
313
    # Verify that we can reconstruct the commit properly
 
314
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True)
 
315
    if rec_o != o:
 
316
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
 
317
            rec_o, o))
 
318
    diff = []
 
319
    new_objs = {}
 
320
    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):
 
322
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
 
323
        new_objs[path] = obj
 
324
        if obj.id != old_obj_id:
 
325
            diff.append((path, lookup_object(old_obj_id), obj))
 
326
    for (path, old_obj, new_obj) in diff:
 
327
        while (old_obj.type_name == "tree" and
 
328
               new_obj.type_name == "tree" and
 
329
               sorted(old_obj) == sorted(new_obj)):
 
330
            for name in old_obj:
 
331
                if old_obj[name][0] != new_obj[name][0]:
 
332
                    raise AssertionError("Modes for %s differ: %o != %o" %
 
333
                        (path, old_obj[name][0], new_obj[name][0]))
 
334
                if old_obj[name][1] != new_obj[name][1]:
 
335
                    # Found a differing child, delve deeper
 
336
                    path = posixpath.join(path, name)
 
337
                    old_obj = lookup_object(old_obj[name][1])
 
338
                    new_obj = new_objs[path]
 
339
                    break
 
340
        raise AssertionError("objects differ for %s: %r != %r" % (path,
 
341
            old_obj, new_obj))
 
342
 
 
343
 
277
344
def import_git_commit(repo, mapping, head, lookup_object,
278
345
                      target_git_object_retriever, trees_cache):
279
346
    o = lookup_object(head)
280
 
    rev = mapping.import_commit(o)
 
347
    rev, roundtrip_revid, verifiers = mapping.import_commit(o,
 
348
            lambda x: target_git_object_retriever.lookup_git_sha(x)[1][0])
281
349
    # We have to do this here, since we have to walk the tree and
282
350
    # we need to make sure to import the blobs / trees with the right
283
351
    # path; this may involve adding them more than once.
291
359
        base_tree = lookup_object(o.parents[0]).tree
292
360
        base_mode = stat.S_IFDIR
293
361
    store_updater = target_git_object_retriever._get_updater(rev)
294
 
    store_updater.add_object(o, None)
 
362
    fileid_map = mapping.get_fileid_map(lookup_object, o.tree)
295
363
    inv_delta, unusual_modes = import_git_tree(repo.texts,
296
 
            mapping, "", u"", (base_tree, o.tree), base_inv, 
 
364
            mapping, "", "", (base_tree, o.tree), base_inv,
297
365
            None, rev.revision_id, [p.inventory for p in parent_trees],
298
366
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
 
367
            fileid_map.lookup_file_id,
299
368
            allow_submodules=getattr(repo._format, "supports_tree_reference", False))
300
 
    store_updater.finish()
301
369
    if unusual_modes != {}:
302
370
        for path, mode in unusual_modes.iteritems():
303
371
            warn_unusual_mode(rev.foreign_revid, path, mode)
308
376
        basis_id = NULL_REVISION
309
377
        base_inv = None
310
378
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
311
 
              inv_delta, rev.revision_id, rev.parent_ids,
312
 
              base_inv)
313
 
    trees_cache.add(RevisionTree(repo, inv, rev.revision_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
 
386
        if calculated_verifiers != verifiers:
 
387
            trace.mutter("Testament SHA1 %r for %r did not match %r.",
 
388
                         calculated_verifiers["testament3-sha1"],
 
389
                         rev.revision_id, verifiers["testament3-sha1"])
 
390
            rev.revision_id = original_revid
 
391
    store_updater.add_object(o, calculated_verifiers, None)
 
392
    store_updater.finish()
 
393
    ret_tree = RevisionTree(repo, inv, rev.revision_id)
 
394
    trees_cache.add(ret_tree)
314
395
    repo.add_revision(rev.revision_id, rev)
315
396
    if "verify" in debug.debug_flags:
316
 
        new_unusual_modes = mapping.export_unusual_file_modes(rev)
317
 
        if new_unusual_modes != unusual_modes:
318
 
            raise AssertionError("unusual modes don't match: %r != %r" % (unusual_modes, new_unusual_modes))
319
 
        objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping, unusual_modes)
320
 
        for newsha1, newobj, path in objs:
321
 
            assert path is not None
322
 
            if path == "":
323
 
                oldsha1 = o.tree
324
 
            else:
325
 
                (oldmode, oldsha1) = tree_lookup_path(lookup_object, o.tree, path)
326
 
            if oldsha1 != newsha1:
327
 
                raise AssertionError("%r != %r in %s" % (oldsha1, newsha1, path))
 
397
        verify_commit_reconstruction(target_git_object_retriever, 
 
398
            lookup_object, o, rev, ret_tree, parent_trees, mapping,
 
399
            unusual_modes)
328
400
 
329
401
 
330
402
def import_git_objects(repo, mapping, object_iter,
356
428
        except KeyError:
357
429
            continue
358
430
        if isinstance(o, Commit):
359
 
            rev = mapping.import_commit(o)
360
 
            if repo.has_revision(rev.revision_id):
 
431
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
 
432
                lambda x: None)
 
433
            if (repo.has_revision(rev.revision_id) or
 
434
                (roundtrip_revid and repo.has_revision(roundtrip_revid))):
361
435
                continue
362
 
            squash_revision(repo, rev)
363
436
            graph.append((o.id, o.parents))
364
437
            heads.extend([p for p in o.parents if p not in checked])
365
438
        elif isinstance(o, Tag):
388
461
                        pb.update("fetching revisions", offset+i,
389
462
                                  len(revision_ids))
390
463
                    import_git_commit(repo, mapping, head, lookup_object,
391
 
                                      target_git_object_retriever,
392
 
                                      trees_cache)
 
464
                        target_git_object_retriever, trees_cache)
393
465
                    last_imported = head
394
466
            except:
395
467
                repo.abort_write_group()
418
490
        """See InterRepository.copy_content."""
419
491
        self.fetch(revision_id, pb, find_ghosts=False)
420
492
 
421
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
422
 
        mapping=None, fetch_spec=None):
423
 
        self.fetch_refs(revision_id=revision_id, pb=pb,
424
 
            find_ghosts=find_ghosts, mapping=mapping, fetch_spec=fetch_spec)
425
 
 
426
493
 
427
494
class InterGitNonGitRepository(InterGitRepository):
428
495
    """Base InterRepository that copies revisions from a Git into a non-Git
429
496
    repository."""
430
497
 
431
 
    def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
 
498
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
499
        """Fetch objects from a remote server.
 
500
 
 
501
        :param determine_wants: determine_wants callback
 
502
        :param mapping: BzrGitMapping to use
 
503
        :param pb: Optional progress bar
 
504
        :param limit: Maximum number of commits to import.
 
505
        :return: Tuple with pack hint, last imported revision id and remote refs
 
506
        """
 
507
        raise NotImplementedError(self.fetch_objects)
 
508
 
 
509
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
432
510
              mapping=None, fetch_spec=None):
433
511
        if mapping is None:
434
512
            mapping = self.source.get_mapping()
438
516
            interesting_heads = fetch_spec.heads
439
517
        else:
440
518
            interesting_heads = None
441
 
        self._refs = {}
442
519
        def determine_wants(refs):
443
 
            self._refs = refs
444
520
            if interesting_heads is None:
445
521
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
446
522
            else:
447
 
                ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
448
 
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
449
 
        (pack_hint, _) = self.fetch_objects(determine_wants, mapping, pb)
 
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)
450
526
        if pack_hint is not None and self.target._format.pack_compresses:
451
527
            self.target.pack(hint=pack_hint)
452
 
        if interesting_heads is not None:
453
 
            present_interesting_heads = self.target.has_revisions(interesting_heads)
454
 
            missing_interesting_heads = set(interesting_heads) - present_interesting_heads
455
 
            if missing_interesting_heads:
456
 
                raise AssertionError("Missing interesting heads: %r" % missing_interesting_heads)
457
 
        return self._refs
 
528
        return remote_refs
458
529
 
459
530
 
460
531
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
468
539
        pb.update(text, 0, 0)
469
540
 
470
541
 
 
542
class DetermineWantsRecorder(object):
 
543
 
 
544
    def __init__(self, actual):
 
545
        self.actual = actual
 
546
        self.wants = []
 
547
        self.remote_refs = {}
 
548
 
 
549
    def __call__(self, refs):
 
550
        self.remote_refs = refs
 
551
        self.wants = self.actual(refs)
 
552
        return self.wants
 
553
 
 
554
 
471
555
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
472
556
    """InterRepository that copies revisions from a remote Git into a non-Git
473
557
    repository."""
481
565
        return set(all_revs) - all_parents
482
566
 
483
567
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
568
        """See `InterGitNonGitRepository`."""
484
569
        def progress(text):
485
570
            report_git_progress(pb, text)
486
571
        store = BazaarObjectStore(self.target, mapping)
489
574
            heads = self.get_target_heads()
490
575
            graph_walker = store.get_graph_walker(
491
576
                    [store._lookup_revision_sha1(head) for head in heads])
492
 
            recorded_wants = []
493
 
 
494
 
            def record_determine_wants(heads):
495
 
                wants = determine_wants(heads)
496
 
                recorded_wants.extend(wants)
497
 
                return wants
 
577
            wants_recorder = DetermineWantsRecorder(determine_wants)
498
578
 
499
579
            create_pb = None
500
580
            if pb is None:
501
581
                create_pb = pb = ui.ui_factory.nested_progress_bar()
502
582
            try:
503
583
                objects_iter = self.source.fetch_objects(
504
 
                            record_determine_wants, graph_walker,
505
 
                            store.get_raw, progress)
506
 
                return import_git_objects(self.target, mapping,
507
 
                    objects_iter, store, recorded_wants, pb, limit)
 
584
                    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)
 
588
                return (pack_hint, last_rev, wants_recorder.remote_refs)
508
589
            finally:
509
590
                if create_pb:
510
591
                    create_pb.finished()
514
595
    @staticmethod
515
596
    def is_compatible(source, target):
516
597
        """Be compatible with GitRepository."""
517
 
        # FIXME: Also check target uses VersionedFile
518
598
        return (isinstance(source, RemoteGitRepository) and
519
599
                target.supports_rich_root() and
520
 
                not isinstance(target, GitRepository))
 
600
                not isinstance(target, GitRepository) and
 
601
                target.texts is not None)
521
602
 
522
603
 
523
604
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
525
606
    repository."""
526
607
 
527
608
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
528
 
        """Fetch objects.
529
 
        """
530
 
        wants = determine_wants(self.source._git.get_refs())
 
609
        """See `InterGitNonGitRepository`."""
 
610
        remote_refs = self.source._git.get_refs()
 
611
        wants = determine_wants(remote_refs)
531
612
        create_pb = None
532
613
        if pb is None:
533
614
            create_pb = pb = ui.ui_factory.nested_progress_bar()
535
616
        try:
536
617
            self.target.lock_write()
537
618
            try:
538
 
                return import_git_objects(self.target, mapping,
 
619
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
539
620
                    self.source._git.object_store,
540
621
                    target_git_object_retriever, wants, pb, limit)
 
622
                return (pack_hint, last_rev, remote_refs)
541
623
            finally:
542
624
                self.target.unlock()
543
625
        finally:
547
629
    @staticmethod
548
630
    def is_compatible(source, target):
549
631
        """Be compatible with GitRepository."""
550
 
        # FIXME: Also check target uses VersionedFile
551
632
        return (isinstance(source, LocalGitRepository) and
552
633
                target.supports_rich_root() and
553
 
                not isinstance(target, GitRepository))
 
634
                not isinstance(target, GitRepository) and
 
635
                target.texts is not None)
554
636
 
555
637
 
556
638
class InterGitGitRepository(InterGitRepository):
562
644
        graphwalker = self.target._git.get_graph_walker()
563
645
        if (isinstance(self.source, LocalGitRepository) and
564
646
            isinstance(self.target, LocalGitRepository)):
565
 
            return self.source._git.fetch(self.target._git, determine_wants,
 
647
            refs = self.source._git.fetch(self.target._git, determine_wants,
566
648
                progress)
 
649
            return (None, None, refs)
567
650
        elif (isinstance(self.source, LocalGitRepository) and
568
651
              isinstance(self.target, RemoteGitRepository)):
569
652
            raise NotImplementedError
571
654
              isinstance(self.target, LocalGitRepository)):
572
655
            f, commit = self.target._git.object_store.add_thin_pack()
573
656
            try:
574
 
                refs = self.source._git.fetch_pack(determine_wants,
575
 
                    graphwalker, f.write, progress)
 
657
                refs = self.source.bzrdir.root_transport.fetch_pack(
 
658
                    determine_wants, graphwalker, f.write, progress)
576
659
                commit()
577
 
                return refs
 
660
                return (None, None, refs)
578
661
            except:
579
662
                f.close()
580
663
                raise
581
664
        else:
582
665
            raise AssertionError
583
666
 
584
 
    def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
 
667
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
585
668
              mapping=None, fetch_spec=None, branches=None):
586
669
        if mapping is None:
587
670
            mapping = self.source.get_mapping()
596
679
            determine_wants = r.object_store.determine_wants_all
597
680
        else:
598
681
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
599
 
        return self.fetch_objects(determine_wants, mapping)[0]
600
 
 
 
682
        self.fetch_objects(determine_wants, mapping)
601
683
 
602
684
    @staticmethod
603
685
    def is_compatible(source, target):