/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
    )
67
70
    DEFAULT_FILE_MODE,
68
71
    mode_is_executable,
69
72
    mode_kind,
70
 
    squash_revision,
71
73
    warn_unusual_mode,
72
74
    )
73
75
from bzrlib.plugins.git.object_store import (
96
98
    :param blob: A git blob
97
99
    :return: Inventory delta for this file
98
100
    """
 
101
    if mapping.is_control_file(path):
 
102
        return []
99
103
    if base_hexsha == hexsha and base_mode == mode:
100
104
        # If nothing has changed since the base revision, we're done
101
105
        return []
105
109
    else:
106
110
        cls = InventoryFile
107
111
    ie = cls(file_id, name.decode("utf-8"), parent_id)
108
 
    ie.executable = mode_is_executable(mode)
 
112
    if ie.kind == "file":
 
113
        ie.executable = mode_is_executable(mode)
109
114
    if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
110
115
        base_ie = base_inv[base_inv.path2id(path)]
111
116
        ie.text_size = base_ie.text_size
112
117
        ie.text_sha1 = base_ie.text_sha1
113
 
        ie.symlink_target = base_ie.symlink_target
 
118
        if ie.kind == "symlink":
 
119
            ie.symlink_target = base_ie.symlink_target
114
120
        if ie.executable == base_ie.executable:
115
121
            ie.revision = base_ie.revision
116
122
        else:
120
126
        if ie.kind == "symlink":
121
127
            ie.revision = None
122
128
            ie.symlink_target = blob.data
123
 
            ie.text_size = None
124
 
            ie.text_sha1 = None
125
129
        else:
126
130
            ie.text_size = sum(imap(len, blob.chunked))
127
131
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
132
136
            pie = pinv[file_id]
133
137
        except NoSuchId:
134
138
            continue
135
 
        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):
136
142
            # found a revision in one of the parents to use
137
143
            ie.revision = pie.revision
138
144
            break
147
153
            chunks = []
148
154
        else: 
149
155
            chunks = blob.chunked
150
 
        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)])
151
159
    invdelta = []
152
160
    if base_hexsha is not None:
153
 
        old_path = path # Renames are not supported yet
 
161
        old_path = path.decode("utf-8") # Renames are not supported yet
154
162
        if stat.S_ISDIR(base_mode):
155
163
            invdelta.extend(remove_disappeared_children(base_inv, old_path,
156
164
                lookup_object(base_hexsha), [], lookup_object))
157
165
    else:
158
166
        old_path = None
159
 
    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))
160
169
    if base_hexsha != hexsha:
161
 
        store_updater.add_object(blob, ie)
 
170
        store_updater.add_object(blob, ie, path)
162
171
    return invdelta
163
172
 
164
173
 
180
189
    else:
181
190
        oldpath = path
182
191
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
183
 
    texts.insert_record_stream([ChunkedContentFactory((file_id, ie.revision), (), None, [])])
 
192
    texts.insert_record_stream([
 
193
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
184
194
    invdelta = [(oldpath, path, file_id, ie)]
185
195
    return invdelta, {}
186
196
 
187
197
 
188
198
def remove_disappeared_children(base_inv, path, base_tree, existing_children,
189
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
190
211
    ret = []
191
212
    for name, mode, hexsha in base_tree.iteritems():
192
213
        if name in existing_children:
193
214
            continue
194
215
        c_path = posixpath.join(path, name.decode("utf-8"))
195
 
        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))
196
219
        if stat.S_ISDIR(mode):
197
220
            ret.extend(remove_disappeared_children(
198
221
                base_inv, c_path, lookup_object(hexsha), [], lookup_object))
206
229
    """Import a git tree object into a bzr repository.
207
230
 
208
231
    :param texts: VersionedFiles object to add to
209
 
    :param path: Path in the tree
 
232
    :param path: Path in the tree (str)
 
233
    :param name: Name of the tree (str)
210
234
    :param tree: A git tree object
211
235
    :param base_inv: Base inventory against which to return inventory delta
212
236
    :return: Inventory delta for this subtree
213
237
    """
 
238
    assert type(path) is str
 
239
    assert type(name) is str
214
240
    if base_hexsha == hexsha and base_mode == mode:
215
241
        # If nothing has changed since the base revision, we're done
216
242
        return [], {}
224
250
        old_path = None # Newly appeared here
225
251
    else:
226
252
        base_tree = lookup_object(base_hexsha)
227
 
        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")
228
255
    if base_tree is None or type(base_tree) is not Tree:
229
256
        ie.revision = revision_id
230
 
        invdelta.append((old_path, path, ie.file_id, ie))
231
 
        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, [])])
232
260
    # Remember for next time
233
261
    existing_children = set()
234
262
    child_modes = {}
245
273
            child_base_hexsha = None
246
274
            child_base_mode = 0
247
275
        if stat.S_ISDIR(child_mode):
248
 
            subinvdelta, grandchildmodes = import_git_tree(
249
 
                    texts, mapping, child_path, name,
250
 
                    (child_base_hexsha, child_hexsha),
251
 
                    base_inv, file_id, revision_id, parent_invs, lookup_object,
252
 
                    (child_base_mode, child_mode), store_updater, 
253
 
                    lookup_file_id, 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)
254
281
        elif S_ISGITLINK(child_mode): # submodule
255
282
            if not allow_submodules:
256
283
                raise SubmodulesRequireSubtrees()
257
 
            subinvdelta, grandchildmodes = import_git_submodule(
258
 
                    texts, mapping, child_path, name,
259
 
                    (child_base_hexsha, child_hexsha),
260
 
                    base_inv, file_id, revision_id, parent_invs, lookup_object,
261
 
                    (child_base_mode, child_mode), store_updater,
262
 
                    lookup_file_id)
 
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)
263
288
        else:
264
 
            subinvdelta = import_git_blob(texts, mapping,
265
 
                    child_path, name, (child_base_hexsha, child_hexsha),
266
 
                    base_inv, file_id, revision_id, parent_invs, lookup_object,
267
 
                    (child_base_mode, child_mode), store_updater,
268
 
                    lookup_file_id)
 
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)
269
293
            grandchildmodes = {}
270
294
        child_modes.update(grandchildmodes)
271
295
        invdelta.extend(subinvdelta)
274
298
            child_modes[child_path] = child_mode
275
299
    # Remove any children that have disappeared
276
300
    if base_tree is not None and type(base_tree) is Tree:
277
 
        invdelta.extend(remove_disappeared_children(base_inv, old_path, 
 
301
        invdelta.extend(remove_disappeared_children(base_inv, old_path,
278
302
            base_tree, existing_children, lookup_object))
279
 
    store_updater.add_object(tree, ie)
 
303
    store_updater.add_object(tree, ie, path)
280
304
    return invdelta, child_modes
281
305
 
282
306
 
287
311
        raise AssertionError("unusual modes don't match: %r != %r" % (
288
312
            unusual_modes, new_unusual_modes))
289
313
    # Verify that we can reconstruct the commit properly
290
 
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree)
 
314
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True)
291
315
    if rec_o != o:
292
316
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
293
317
            rec_o, o))
294
318
    diff = []
295
319
    new_objs = {}
296
320
    for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
297
 
        target_git_object_retriever._cache.idmap, unusual_modes):
 
321
        target_git_object_retriever._cache.idmap, unusual_modes, mapping.BZR_DUMMY_FILE):
298
322
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
299
323
        new_objs[path] = obj
300
324
        if obj.id != old_obj_id:
305
329
               sorted(old_obj) == sorted(new_obj)):
306
330
            for name in old_obj:
307
331
                if old_obj[name][0] != new_obj[name][0]:
308
 
                    raise AssertionError("Modes for %s differ: %o != %o" % (path, 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]))
309
334
                if old_obj[name][1] != new_obj[name][1]:
310
335
                    # Found a differing child, delve deeper
311
336
                    path = posixpath.join(path, name)
319
344
def import_git_commit(repo, mapping, head, lookup_object,
320
345
                      target_git_object_retriever, trees_cache):
321
346
    o = lookup_object(head)
322
 
    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])
323
349
    # We have to do this here, since we have to walk the tree and
324
350
    # we need to make sure to import the blobs / trees with the right
325
351
    # path; this may involve adding them more than once.
333
359
        base_tree = lookup_object(o.parents[0]).tree
334
360
        base_mode = stat.S_IFDIR
335
361
    store_updater = target_git_object_retriever._get_updater(rev)
336
 
    store_updater.add_object(o, None)
 
362
    fileid_map = mapping.get_fileid_map(lookup_object, o.tree)
337
363
    inv_delta, unusual_modes = import_git_tree(repo.texts,
338
 
            mapping, "", u"", (base_tree, o.tree), base_inv, 
 
364
            mapping, "", "", (base_tree, o.tree), base_inv,
339
365
            None, rev.revision_id, [p.inventory for p in parent_trees],
340
366
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
341
 
            mapping.generate_file_id,
 
367
            fileid_map.lookup_file_id,
342
368
            allow_submodules=getattr(repo._format, "supports_tree_reference", False))
343
 
    store_updater.finish()
344
369
    if unusual_modes != {}:
345
370
        for path, mode in unusual_modes.iteritems():
346
371
            warn_unusual_mode(rev.foreign_revid, path, mode)
351
376
        basis_id = NULL_REVISION
352
377
        base_inv = None
353
378
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
354
 
              inv_delta, rev.revision_id, rev.parent_ids,
355
 
              base_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()
356
393
    ret_tree = RevisionTree(repo, inv, rev.revision_id)
357
394
    trees_cache.add(ret_tree)
358
395
    repo.add_revision(rev.revision_id, rev)
391
428
        except KeyError:
392
429
            continue
393
430
        if isinstance(o, Commit):
394
 
            rev = mapping.import_commit(o)
395
 
            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))):
396
435
                continue
397
 
            squash_revision(repo, rev)
398
436
            graph.append((o.id, o.parents))
399
437
            heads.extend([p for p in o.parents if p not in checked])
400
438
        elif isinstance(o, Tag):
423
461
                        pb.update("fetching revisions", offset+i,
424
462
                                  len(revision_ids))
425
463
                    import_git_commit(repo, mapping, head, lookup_object,
426
 
                                      target_git_object_retriever,
427
 
                                      trees_cache)
 
464
                        target_git_object_retriever, trees_cache)
428
465
                    last_imported = head
429
466
            except:
430
467
                repo.abort_write_group()
453
490
        """See InterRepository.copy_content."""
454
491
        self.fetch(revision_id, pb, find_ghosts=False)
455
492
 
456
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
457
 
        mapping=None, fetch_spec=None):
458
 
        self.fetch_refs(revision_id=revision_id, pb=pb,
459
 
            find_ghosts=find_ghosts, mapping=mapping, fetch_spec=fetch_spec)
460
 
 
461
493
 
462
494
class InterGitNonGitRepository(InterGitRepository):
463
495
    """Base InterRepository that copies revisions from a Git into a non-Git
464
496
    repository."""
465
497
 
466
 
    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,
467
510
              mapping=None, fetch_spec=None):
468
511
        if mapping is None:
469
512
            mapping = self.source.get_mapping()
473
516
            interesting_heads = fetch_spec.heads
474
517
        else:
475
518
            interesting_heads = None
476
 
        self._refs = {}
477
519
        def determine_wants(refs):
478
 
            self._refs = refs
479
520
            if interesting_heads is None:
480
521
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
481
522
            else:
482
 
                ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
483
 
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
484
 
        (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)
485
526
        if pack_hint is not None and self.target._format.pack_compresses:
486
527
            self.target.pack(hint=pack_hint)
487
 
        if interesting_heads is not None:
488
 
            present_interesting_heads = self.target.has_revisions(interesting_heads)
489
 
            missing_interesting_heads = set(interesting_heads) - present_interesting_heads
490
 
            if missing_interesting_heads:
491
 
                raise AssertionError("Missing interesting heads: %r" % missing_interesting_heads)
492
 
        return self._refs
 
528
        return remote_refs
493
529
 
494
530
 
495
531
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
503
539
        pb.update(text, 0, 0)
504
540
 
505
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
 
506
555
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
507
556
    """InterRepository that copies revisions from a remote Git into a non-Git
508
557
    repository."""
516
565
        return set(all_revs) - all_parents
517
566
 
518
567
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
568
        """See `InterGitNonGitRepository`."""
519
569
        def progress(text):
520
570
            report_git_progress(pb, text)
521
571
        store = BazaarObjectStore(self.target, mapping)
524
574
            heads = self.get_target_heads()
525
575
            graph_walker = store.get_graph_walker(
526
576
                    [store._lookup_revision_sha1(head) for head in heads])
527
 
            recorded_wants = []
528
 
 
529
 
            def record_determine_wants(heads):
530
 
                wants = determine_wants(heads)
531
 
                recorded_wants.extend(wants)
532
 
                return wants
 
577
            wants_recorder = DetermineWantsRecorder(determine_wants)
533
578
 
534
579
            create_pb = None
535
580
            if pb is None:
536
581
                create_pb = pb = ui.ui_factory.nested_progress_bar()
537
582
            try:
538
583
                objects_iter = self.source.fetch_objects(
539
 
                            record_determine_wants, graph_walker,
540
 
                            store.get_raw, progress)
541
 
                return import_git_objects(self.target, mapping,
542
 
                    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)
543
589
            finally:
544
590
                if create_pb:
545
591
                    create_pb.finished()
560
606
    repository."""
561
607
 
562
608
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
563
 
        """Fetch objects.
564
 
        """
565
 
        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)
566
612
        create_pb = None
567
613
        if pb is None:
568
614
            create_pb = pb = ui.ui_factory.nested_progress_bar()
570
616
        try:
571
617
            self.target.lock_write()
572
618
            try:
573
 
                return import_git_objects(self.target, mapping,
 
619
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
574
620
                    self.source._git.object_store,
575
621
                    target_git_object_retriever, wants, pb, limit)
 
622
                return (pack_hint, last_rev, remote_refs)
576
623
            finally:
577
624
                self.target.unlock()
578
625
        finally:
597
644
        graphwalker = self.target._git.get_graph_walker()
598
645
        if (isinstance(self.source, LocalGitRepository) and
599
646
            isinstance(self.target, LocalGitRepository)):
600
 
            return self.source._git.fetch(self.target._git, determine_wants,
 
647
            refs = self.source._git.fetch(self.target._git, determine_wants,
601
648
                progress)
 
649
            return (None, None, refs)
602
650
        elif (isinstance(self.source, LocalGitRepository) and
603
651
              isinstance(self.target, RemoteGitRepository)):
604
652
            raise NotImplementedError
606
654
              isinstance(self.target, LocalGitRepository)):
607
655
            f, commit = self.target._git.object_store.add_thin_pack()
608
656
            try:
609
 
                refs = self.source._git.fetch_pack(determine_wants,
610
 
                    graphwalker, f.write, progress)
 
657
                refs = self.source.bzrdir.root_transport.fetch_pack(
 
658
                    determine_wants, graphwalker, f.write, progress)
611
659
                commit()
612
 
                return refs
 
660
                return (None, None, refs)
613
661
            except:
614
662
                f.close()
615
663
                raise
616
664
        else:
617
665
            raise AssertionError
618
666
 
619
 
    def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
 
667
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
620
668
              mapping=None, fetch_spec=None, branches=None):
621
669
        if mapping is None:
622
670
            mapping = self.source.get_mapping()
631
679
            determine_wants = r.object_store.determine_wants_all
632
680
        else:
633
681
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
634
 
        return self.fetch_objects(determine_wants, mapping)[0]
635
 
 
 
682
        self.fetch_objects(determine_wants, mapping)
636
683
 
637
684
    @staticmethod
638
685
    def is_compatible(source, target):