/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

Reduce number of round trips when fetching from Git.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
    StringIO,
19
19
    )
20
20
import dulwich as git
 
21
from dulwich.client import (
 
22
    SimpleFetchGraphWalker,
 
23
    )
21
24
from dulwich.objects import (
22
25
    Commit,
23
26
    Tag,
24
 
    S_ISGITLINK,
25
27
    )
26
28
from dulwich.object_store import (
27
29
    tree_lookup_path,
65
67
from bzrlib.plugins.git.mapping import (
66
68
    DEFAULT_FILE_MODE,
67
69
    inventory_to_tree_and_blobs,
68
 
    mode_is_executable,
69
 
    squash_revision,
70
70
    text_to_blob,
71
 
    warn_unusual_mode,
72
71
    )
73
72
from bzrlib.plugins.git.object_store import (
74
73
    BazaarObjectStore,
83
82
    )
84
83
 
85
84
 
 
85
class BzrFetchGraphWalker(object):
 
86
    """GraphWalker implementation that uses a Bazaar repository."""
 
87
 
 
88
    def __init__(self, repository, mapping):
 
89
        self.repository = repository
 
90
        self.mapping = mapping
 
91
        self.done = set()
 
92
        self.heads = set(repository.all_revision_ids())
 
93
        self.parents = {}
 
94
 
 
95
    def __iter__(self):
 
96
        return iter(self.next, None)
 
97
 
 
98
    def ack(self, sha):
 
99
        revid = self.mapping.revision_id_foreign_to_bzr(sha)
 
100
        self.remove(revid)
 
101
 
 
102
    def remove(self, revid):
 
103
        self.done.add(revid)
 
104
        if revid in self.heads:
 
105
            self.heads.remove(revid)
 
106
        if revid in self.parents:
 
107
            for p in self.parents[revid]:
 
108
                self.remove(p)
 
109
 
 
110
    def next(self):
 
111
        while self.heads:
 
112
            ret = self.heads.pop()
 
113
            ps = self.repository.get_parent_map([ret])[ret]
 
114
            self.parents[ret] = ps
 
115
            self.heads.update([p for p in ps if not p in self.done])
 
116
            try:
 
117
                self.done.add(ret)
 
118
                return self.mapping.revision_id_bzr_to_foreign(ret)[0]
 
119
            except InvalidRevisionId:
 
120
                pass
 
121
        return None
 
122
 
 
123
 
86
124
def import_git_blob(texts, mapping, path, hexsha, base_inv, parent_id, 
87
125
    revision_id, parent_invs, shagitmap, lookup_object, executable, symlink):
88
126
    """Import a git blob object into a bzr repository.
100
138
    # We just have to hope this is indeed utf-8:
101
139
    ie = cls(file_id, urlutils.basename(path).decode("utf-8"), parent_id)
102
140
    ie.executable = executable
 
141
    ie.text_id = hexsha
103
142
    # See if this has changed at all
104
143
    try:
105
144
        base_ie = base_inv[file_id]
107
146
        base_ie = None
108
147
        base_sha = None
109
148
    else:
 
149
        base_sha = base_ie.text_id
110
150
        try:
111
 
            base_sha = shagitmap.lookup_blob(file_id, base_ie.revision)
 
151
            if base_sha is None:
 
152
                base_sha = shagitmap.lookup_blob(file_id, base_ie.revision)
112
153
        except KeyError:
113
154
            base_sha = None
114
155
        else:
116
157
                and base_ie.kind == ie.kind):
117
158
                # If nothing has changed since the base revision, we're done
118
159
                return [], []
119
 
    if base_sha == hexsha and base_ie.kind == ie.kind:
 
160
    if base_sha == hexsha:
120
161
        ie.text_size = base_ie.text_size
121
162
        ie.text_sha1 = base_ie.text_sha1
122
163
        ie.symlink_target = base_ie.symlink_target
123
 
        if ie.executable == base_ie.executable:
124
 
            ie.revision = base_ie.revision
125
 
        else:
126
 
            blob = lookup_object(hexsha)
 
164
        ie.revision = base_ie.revision
127
165
    else:
128
166
        blob = lookup_object(hexsha)
129
167
        if ie.kind == "symlink":
130
 
            ie.revision = None
131
168
            ie.symlink_target = blob.data
132
169
            ie.text_size = None
133
170
            ie.text_sha1 = None
146
183
                pie = pinv[file_id]
147
184
            except NoSuchId:
148
185
                continue
149
 
        if pie.text_sha1 == ie.text_sha1 and pie.executable == ie.executable and pie.symlink_target == ie.symlink_target:
 
186
        if pie.text_sha1 == ie.text_sha1:
150
187
            # found a revision in one of the parents to use
151
188
            ie.revision = pie.revision
152
189
            break
164
201
        old_path = base_inv.id2path(file_id)
165
202
    else:
166
203
        old_path = None
167
 
    invdelta = [(old_path, path, file_id, ie)]
168
 
    invdelta.extend(remove_disappeared_children(base_inv, base_ie, []))
169
 
    return (invdelta, shamap)
170
 
 
171
 
 
172
 
def import_git_submodule(texts, mapping, path, hexsha, base_inv, parent_id, 
173
 
    revision_id, parent_invs, shagitmap, lookup_object):
174
 
    raise NotImplementedError(import_git_submodule)
175
 
 
176
 
 
177
 
def remove_disappeared_children(base_inv, base_ie, existing_children):
178
 
    if base_ie is None or base_ie.kind != 'directory':
179
 
        return []
180
 
    ret = []
181
 
    deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
182
 
    while deletable:
183
 
        ie = deletable.pop()
184
 
        ret.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
185
 
        if ie.kind == "directory":
186
 
            deletable.extend(ie.children.values())
187
 
    return ret
 
204
    return ([(old_path, path, file_id, ie)], shamap)
188
205
 
189
206
 
190
207
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id, 
202
219
    # We just have to hope this is indeed utf-8:
203
220
    ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")), 
204
221
        parent_id)
 
222
    ie.text_id = hexsha
205
223
    try:
206
224
        base_ie = base_inv[file_id]
207
225
    except NoSuchId:
211
229
        texts.add_lines((file_id, ie.revision), (), [])
212
230
        invdelta.append((None, path, file_id, ie))
213
231
    else:
 
232
        base_sha = base_ie.text_id
214
233
        # See if this has changed at all
215
234
        try:
216
 
            base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
 
235
            if base_sha is None:
 
236
                base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
217
237
        except KeyError:
218
238
            pass
219
239
        else:
220
240
            if base_sha == hexsha:
221
241
                # If nothing has changed since the base revision, we're done
222
242
                return [], {}, []
223
 
        if base_ie.kind != "directory":
224
 
            ie.revision = revision_id
225
 
            texts.add_lines((ie.file_id, ie.revision), (), [])
226
 
            invdelta.append((base_inv.id2path(ie.file_id), path, ie.file_id, ie))
227
243
    # Remember for next time
228
244
    existing_children = set()
229
245
    child_modes = {}
234
250
        existing_children.add(basename)
235
251
        child_path = osutils.pathjoin(path, name)
236
252
        if stat.S_ISDIR(mode):
237
 
            subinvdelta, grandchildmodes, subshamap = import_git_tree(
238
 
                    texts, mapping, child_path, child_hexsha, base_inv, 
239
 
                    file_id, revision_id, parent_invs, shagitmap, lookup_object)
240
 
            invdelta.extend(subinvdelta)
241
 
            child_modes.update(grandchildmodes)
242
 
            shamap.extend(subshamap)
243
 
        elif S_ISGITLINK(mode): # submodule
244
 
            subinvdelta, grandchildmodes, subshamap = import_git_submodule(
245
 
                    texts, mapping, child_path, child_hexsha, base_inv,
246
 
                    file_id, revision_id, parent_invs, shagitmap, lookup_object)
 
253
            subinvdelta, grandchildmodes, subshamap = import_git_tree(texts, 
 
254
                    mapping, child_path, child_hexsha, base_inv, file_id, 
 
255
                    revision_id, parent_invs, shagitmap, lookup_object)
247
256
            invdelta.extend(subinvdelta)
248
257
            child_modes.update(grandchildmodes)
249
258
            shamap.extend(subshamap)
250
259
        else:
 
260
            fs_mode = stat.S_IMODE(mode)
 
261
            symlink = stat.S_ISLNK(mode)
251
262
            subinvdelta, subshamap = import_git_blob(texts, mapping, 
252
263
                    child_path, child_hexsha, base_inv, file_id, revision_id, 
253
264
                    parent_invs, shagitmap, lookup_object, 
254
 
                    mode_is_executable(mode), stat.S_ISLNK(mode))
 
265
                    bool(fs_mode & 0111), symlink)
255
266
            invdelta.extend(subinvdelta)
256
267
            shamap.extend(subshamap)
257
268
        if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
258
269
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
259
270
            child_modes[child_path] = mode
260
271
    # Remove any children that have disappeared
261
 
    invdelta.extend(remove_disappeared_children(base_inv, base_ie, existing_children))
 
272
    if base_ie is not None:
 
273
        deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
 
274
        while deletable:
 
275
            ie = deletable.pop()
 
276
            invdelta.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
 
277
            if ie.kind == "directory":
 
278
                deletable.extend(ie.children.values())
262
279
    shamap.append((hexsha, "tree", (file_id, revision_id)))
263
280
    return invdelta, child_modes, shamap
264
281
 
267
284
        heads, pb=None):
268
285
    """Import a set of git objects into a bzr repository.
269
286
 
270
 
    :param repo: Target Bazaar repository
 
287
    :param repo: Bazaar repository
271
288
    :param mapping: Mapping to use
272
289
    :param object_iter: Iterator over Git objects.
273
290
    """
274
 
    def lookup_object(sha):
275
 
        try:
276
 
            return object_iter[sha]
277
 
        except KeyError:
278
 
            return target_git_object_retriever[sha]
279
291
    # TODO: a more (memory-)efficient implementation of this
280
292
    graph = []
281
293
    root_trees = {}
290
302
        head = heads.pop()
291
303
        assert isinstance(head, str)
292
304
        try:
293
 
            o = lookup_object(head)
 
305
            o = object_iter[head]
294
306
        except KeyError:
295
307
            continue
296
308
        if isinstance(o, Commit):
297
309
            rev = mapping.import_commit(o)
298
310
            if repo.has_revision(rev.revision_id):
299
311
                continue
300
 
            squash_revision(repo, rev)
301
312
            root_trees[rev.revision_id] = o.tree
302
313
            revisions[rev.revision_id] = rev
303
314
            graph.append((rev.revision_id, rev.parent_ids))
318
329
        # We have to do this here, since we have to walk the tree and 
319
330
        # we need to make sure to import the blobs / trees with the right 
320
331
        # path; this may involve adding them more than once.
 
332
        def lookup_object(sha):
 
333
            try:
 
334
                return object_iter[sha]
 
335
            except KeyError:
 
336
                return target_git_object_retriever[sha]
321
337
        parent_invs = []
322
338
        for parent_id in rev.parent_ids:
323
339
            try:
335
351
                parent_invs, target_git_object_retriever._idmap, lookup_object)
336
352
        target_git_object_retriever._idmap.add_entries(shamap)
337
353
        if unusual_modes != {}:
338
 
            for path, mode in unusual_modes.iteritems():
339
 
                warn_unusual_mode(rev.foreign_revid, path, mode)
340
 
            mapping.import_unusual_file_modes(rev, unusual_modes)
 
354
            ret = "unusual modes: \n"
 
355
            for item in unusual_modes.iteritems():
 
356
                ret += "\t%s: %o\n" % item
 
357
            raise AssertionError(ret)
341
358
        try:
342
359
            basis_id = rev.parent_ids[0]
343
360
        except IndexError:
347
364
        parent_invs_cache[rev.revision_id] = inv
348
365
        repo.add_revision(rev.revision_id, rev)
349
366
        if "verify" in debug.debug_flags:
350
 
            new_unusual_modes = mapping.export_unusual_file_modes(rev)
351
 
            if new_unusual_modes != unusual_modes:
352
 
                raise AssertionError("unusual modes don't match: %r != %r" % (unusual_modes, new_unusual_modes))
353
 
            objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping, unusual_modes)
 
367
            objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping)
354
368
            for sha1, newobj, path in objs:
355
369
                assert path is not None
356
370
                oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
357
 
                if oldobj != newobj:
358
 
                    raise AssertionError("%r != %r in %s" % (oldobj, newobj, path))
 
371
                assert oldobj == newobj, "%r != %r in %s" % (oldobj, newobj, path)
359
372
 
360
373
    target_git_object_retriever._idmap.commit()
361
374
 
398
411
            if interesting_heads is None:
399
412
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
400
413
            else:
401
 
                ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
 
414
                ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid != NULL_REVISION]
402
415
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
403
416
        self.fetch_objects(determine_wants, mapping, pb)
404
417
        return self._refs
405
418
 
406
419
 
 
420
 
407
421
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
408
422
    """InterRepository that copies revisions from a remote Git into a non-Git 
409
423
    repository."""
411
425
    def fetch_objects(self, determine_wants, mapping, pb=None):
412
426
        def progress(text):
413
427
            pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
414
 
        store = BazaarObjectStore(self.target, mapping)
415
 
        self.target.lock_write()
416
 
        try:
417
 
            heads = self.target.get_graph().heads(self.target.all_revision_ids())
418
 
            graph_walker = store.get_graph_walker(
419
 
                    [store._lookup_revision_sha1(head) for head in heads])
420
 
            recorded_wants = []
 
428
        graph_walker = BzrFetchGraphWalker(self.target, mapping)
 
429
        create_pb = None
 
430
        if pb is None:
 
431
            create_pb = pb = ui.ui_factory.nested_progress_bar()
 
432
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
 
433
        recorded_wants = []
421
434
 
422
 
            def record_determine_wants(heads):
423
 
                wants = determine_wants(heads)
424
 
                recorded_wants.extend(wants)
425
 
                return wants
 
435
        def record_determine_wants(heads):
 
436
            wants = determine_wants(heads)
 
437
            recorded_wants.extend(wants)
 
438
            return wants
426
439
        
427
 
            create_pb = None
428
 
            if pb is None:
429
 
                create_pb = pb = ui.ui_factory.nested_progress_bar()
 
440
        try:
 
441
            self.target.lock_write()
430
442
            try:
431
443
                self.target.start_write_group()
432
444
                try:
433
445
                    objects_iter = self.source.fetch_objects(
434
 
                                record_determine_wants, graph_walker, 
435
 
                                store.get_raw, progress)
 
446
                                record_determine_wants, 
 
447
                                graph_walker, 
 
448
                                target_git_object_retriever.get_raw, 
 
449
                                progress)
436
450
                    import_git_objects(self.target, mapping, objects_iter, 
437
 
                            store, recorded_wants, pb)
 
451
                            target_git_object_retriever, recorded_wants, pb)
438
452
                finally:
439
453
                    self.target.commit_write_group()
440
454
            finally:
441
 
                if create_pb:
442
 
                    create_pb.finished()
 
455
                self.target.unlock()
443
456
        finally:
444
 
            self.target.unlock()
 
457
            if create_pb:
 
458
                create_pb.finished()
445
459
 
446
460
    @staticmethod
447
461
    def is_compatible(source, target):
453
467
 
454
468
 
455
469
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
456
 
    """InterRepository that copies revisions from a local Git into a non-Git 
 
470
    """InterRepository that copies revisions from a remote Git into a non-Git 
457
471
    repository."""
458
472
 
459
473
    def fetch_objects(self, determine_wants, mapping, pb=None):
508
522
        else:
509
523
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
510
524
 
511
 
        graphwalker = r.get_graph_walker()
 
525
        graphwalker = SimpleFetchGraphWalker(r.heads().values(), r.get_parents)
512
526
        f, commit = r.object_store.add_thin_pack()
513
527
        try:
514
528
            refs = self.source.fetch_pack(determine_wants, graphwalker,