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