/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 object_store.py

More work on roundtrip push support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
 
19
19
from dulwich.objects import (
20
20
    Blob,
 
21
    Commit,
21
22
    Tree,
22
23
    sha_to_hex,
23
24
    )
35
36
from bzrlib.revision import (
36
37
    NULL_REVISION,
37
38
    )
 
39
from bzrlib.testament import(
 
40
    StrictTestament3,
 
41
    )
38
42
 
39
43
from bzrlib.plugins.git.mapping import (
40
44
    default_mapping,
43
47
    mapping_registry,
44
48
    symlink_to_blob,
45
49
    )
46
 
from bzrlib.plugins.git.shamap import (
 
50
from bzrlib.plugins.git.cache import (
47
51
    from_repository as cache_from_repository,
48
52
    )
49
53
 
50
54
import posixpath
 
55
import stat
51
56
 
52
57
 
53
58
def get_object_store(repo, mapping=None):
70
75
        self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
71
76
            after_cleanup_size=None, compute_size=approx_tree_size)
72
77
 
73
 
    def revision_tree(self, revid):            
 
78
    def revision_tree(self, revid):
74
79
        try:
75
 
            return self._cache[revid] 
 
80
            tree = self._cache[revid]
76
81
        except KeyError:
77
82
            tree = self.repository.revision_tree(revid)
78
83
            self.add(tree)
79
 
            return tree
 
84
        assert tree.get_revision_id() == tree.inventory.revision_id
 
85
        return tree
80
86
 
81
87
    def iter_revision_trees(self, revids):
82
 
        trees = dict([(k, self._cache.get(k)) for k in revids]) 
83
 
        for tree in self.repository.revision_trees(
84
 
                [r for r, v in trees.iteritems() if v is None]):
 
88
        trees = {}
 
89
        todo = []
 
90
        for revid in revids:
 
91
            try:
 
92
                tree = self._cache[revid]
 
93
            except KeyError:
 
94
                todo.append(revid)
 
95
            else:
 
96
                assert tree.get_revision_id() == revid
 
97
                assert tree.inventory.revision_id == revid
 
98
                trees[revid] = tree
 
99
        for tree in self.repository.revision_trees(todo):
85
100
            trees[tree.get_revision_id()] = tree
86
101
            self.add(tree)
87
102
        return (trees[r] for r in revids)
93
108
        self._cache.add(tree.get_revision_id(), tree)
94
109
 
95
110
 
 
111
def _find_missing_bzr_revids(get_parent_map, want, have):
 
112
    """Find the revisions that have to be pushed.
 
113
 
 
114
    :param get_parent_map: Function that returns the parents for a sequence
 
115
        of revisions.
 
116
    :param want: Revisions the target wants
 
117
    :param have: Revisions the target already has
 
118
    :return: Set of revisions to fetch
 
119
    """
 
120
    pending = want - have
 
121
    processed = set()
 
122
    todo = set()
 
123
    while pending:
 
124
        processed.update(pending)
 
125
        next_map = get_parent_map(pending)
 
126
        next_pending = set()
 
127
        for item in next_map.iteritems():
 
128
            if item[0] in have:
 
129
                continue
 
130
            todo.add(item[0])
 
131
            next_pending.update(p for p in item[1] if p not in processed)
 
132
        pending = next_pending
 
133
    if NULL_REVISION in todo:
 
134
        todo.remove(NULL_REVISION)
 
135
    return todo
 
136
 
 
137
 
96
138
def _check_expected_sha(expected_sha, object):
97
139
    """Check whether an object matches an expected SHA.
98
140
 
114
156
            expected_sha))
115
157
 
116
158
 
117
 
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes):
 
159
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
 
160
                     dummy_file_name=None):
118
161
    """Iterate over the objects that were introduced in a revision.
119
162
 
120
163
    :param idmap: id map
121
 
    :param unusual_modes: Unusual file modes
 
164
    :param parent_trees: Parent revision trees
 
165
    :param unusual_modes: Unusual file modes dictionary
 
166
    :param dummy_file_name: File name to use for dummy files
 
167
        in empty directories. None to skip empty directories
122
168
    :return: Yields (path, object, ie) entries
123
169
    """
124
170
    new_trees = {}
143
189
                    pie.symlink_target == ie.symlink_target):
144
190
                    return pie
145
191
        raise KeyError
 
192
 
 
193
    # Find all the changed blobs
146
194
    for (file_id, path, changed_content, versioned, parent, name, kind,
147
195
         executable) in tree.iter_changes(base_tree):
148
196
        if kind[1] == "file":
149
197
            ie = tree.inventory[file_id]
150
198
            if changed_content:
151
 
                
152
199
                try:
153
200
                    pie = find_unchanged_parent_ie(ie, other_parent_trees)
154
201
                except KeyError:
155
202
                    pass
156
203
                else:
157
 
                    shamap[ie.file_id] = idmap.lookup_blob_id(
158
 
                        pie.file_id, pie.revision)
 
204
                    try:
 
205
                        shamap[ie.file_id] = idmap.lookup_blob_id(
 
206
                            pie.file_id, pie.revision)
 
207
                    except KeyError:
 
208
                        # no-change merge ?
 
209
                        blob = Blob()
 
210
                        blob.data = tree.get_file_text(ie.file_id)
 
211
                        shamap[ie.file_id] = blob.id
159
212
            if not file_id in shamap:
160
213
                new_blobs.append((path[1], ie))
161
214
            new_trees[posixpath.dirname(path[1])] = parent[1]
171
224
            new_trees[posixpath.dirname(path[1])] = parent[1]
172
225
        elif kind[1] not in (None, "directory"):
173
226
            raise AssertionError(kind[1])
174
 
        if path[0] is not None:
 
227
        if (path[0] not in (None, "") and
 
228
            parent[0] in tree.inventory and
 
229
            tree.inventory[parent[0]].kind == "directory"):
 
230
            # Removal
175
231
            new_trees[posixpath.dirname(path[0])] = parent[0]
176
232
    
 
233
    # Fetch contents of the blobs that were changed
177
234
    for (path, ie), chunks in tree.iter_files_bytes(
178
235
        [(ie.file_id, (path, ie)) for (path, ie) in new_blobs]):
179
236
        obj = Blob()
184
241
    for path in unusual_modes:
185
242
        parent_path = posixpath.dirname(path)
186
243
        new_trees[parent_path] = tree.path2id(parent_path)
187
 
    
 
244
 
188
245
    trees = {}
189
246
    while new_trees:
190
247
        items = new_trees.items()
191
248
        new_trees = {}
192
249
        for path, file_id in items:
193
 
            try:
194
 
                parent_id = tree.inventory[file_id].parent_id
195
 
            except errors.NoSuchId:
196
 
                # Directory was removed recursively perhaps ?
197
 
                continue
 
250
            parent_id = tree.inventory[file_id].parent_id
198
251
            if parent_id is not None:
199
252
                parent_path = urlutils.dirname(path)
200
253
                new_trees[parent_path] = parent_id
216
269
            elif ie.kind == "directory":
217
270
                # Not all cache backends store the tree information, 
218
271
                # calculate again from scratch
219
 
                ret = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
 
272
                ret = directory_to_tree(ie, ie_to_hexsha, unusual_modes,
 
273
                    dummy_file_name)
220
274
                if ret is None:
221
275
                    return ret
222
276
                return ret.id
226
280
    for path in sorted(trees.keys(), reverse=True):
227
281
        ie = tree.inventory[trees[path]]
228
282
        assert ie.kind == "directory"
229
 
        obj = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
 
283
        obj = directory_to_tree(ie, ie_to_hexsha, unusual_modes,
 
284
            dummy_file_name)
230
285
        if obj is not None:
231
286
            yield path, obj, ie
232
287
            shamap[ie.file_id] = obj.id
287
342
        self._update_sha_map()
288
343
        return iter(self._cache.idmap.sha1s())
289
344
 
290
 
    def _reconstruct_commit(self, rev, tree_sha):
 
345
    def _reconstruct_commit(self, rev, tree_sha, roundtrip, verifiers):
 
346
        """Reconstruct a Commit object.
 
347
 
 
348
        :param rev: Revision object
 
349
        :param tree_sha: SHA1 of the root tree object
 
350
        :param roundtrip: Whether or not to roundtrip bzr metadata
 
351
        :param verifiers: Verifiers for the commits
 
352
        :return: Commit object
 
353
        """
291
354
        def parent_lookup(revid):
292
355
            try:
293
356
                return self._lookup_revision_sha1(revid)
294
357
            except errors.NoSuchRevision:
295
 
                trace.warning("Ignoring ghost parent %s", revid)
296
358
                return None
297
 
        return self.mapping.export_commit(rev, tree_sha, parent_lookup)
298
 
 
299
 
    def _revision_to_objects(self, rev, tree):
 
359
        return self.mapping.export_commit(rev, tree_sha, parent_lookup,
 
360
            roundtrip, verifiers)
 
361
 
 
362
    def _create_fileid_map_blob(self, inv):
 
363
        # FIXME: This can probably be a lot more efficient, 
 
364
        # not all files necessarily have to be processed.
 
365
        file_ids = {}
 
366
        for (path, ie) in inv.iter_entries():
 
367
            if self.mapping.generate_file_id(path) != ie.file_id:
 
368
                file_ids[path] = ie.file_id
 
369
        return self.mapping.export_fileid_map(file_ids)
 
370
 
 
371
    def _revision_to_objects(self, rev, tree, roundtrip):
 
372
        """Convert a revision to a set of git objects.
 
373
 
 
374
        :param rev: Bazaar revision object
 
375
        :param tree: Bazaar revision tree
 
376
        :param roundtrip: Whether to roundtrip all Bazaar revision data
 
377
        """
300
378
        unusual_modes = extract_unusual_modes(rev)
301
379
        present_parents = self.repository.has_revisions(rev.parent_ids)
302
380
        parent_trees = self.tree_cache.revision_trees(
303
381
            [p for p in rev.parent_ids if p in present_parents])
304
 
        tree_sha = None
 
382
        root_tree = None
305
383
        for path, obj, ie in _tree_to_objects(tree, parent_trees,
306
 
                self._cache.idmap, unusual_modes):
307
 
            yield path, obj, ie
 
384
                self._cache.idmap, unusual_modes, self.mapping.BZR_DUMMY_FILE):
308
385
            if path == "":
309
 
                tree_sha = obj.id
310
 
        if tree_sha is None:
 
386
                root_tree = obj
 
387
                root_ie = ie
 
388
                # Don't yield just yet
 
389
            else:
 
390
                yield path, obj, ie
 
391
        if root_tree is None:
311
392
            # Pointless commit - get the tree sha elsewhere
312
393
            if not rev.parent_ids:
313
 
                tree_sha = Tree().id
 
394
                root_tree = Tree()
314
395
            else:
315
396
                base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
316
 
                tree_sha = self[base_sha1].tree
317
 
        commit_obj = self._reconstruct_commit(rev, tree_sha)
 
397
                root_tree = self[self[base_sha1].tree]
 
398
            root_ie = tree.inventory.root
 
399
        if roundtrip and self.mapping.BZR_FILE_IDS_FILE is not None:
 
400
            b = self._create_fileid_map_blob(tree.inventory)
 
401
            if b is not None:
 
402
                root_tree[self.mapping.BZR_FILE_IDS_FILE] = ((stat.S_IFREG | 0644), b.id)
 
403
                yield self.mapping.BZR_FILE_IDS_FILE, b, None
 
404
        yield "", root_tree, root_ie
 
405
        if roundtrip:
 
406
            testament3 = StrictTestament3(rev, tree.inventory)
 
407
            verifiers = { "testament3-sha1": testament3.as_sha1() }
 
408
        else:
 
409
            verifiers = {}
 
410
        commit_obj = self._reconstruct_commit(rev, root_tree.id,
 
411
            roundtrip=roundtrip, verifiers=verifiers)
318
412
        try:
319
413
            foreign_revid, mapping = mapping_registry.parse_revision_id(
320
414
                rev.revision_id)
331
425
        rev = self.repository.get_revision(revid)
332
426
        tree = self.tree_cache.revision_tree(rev.revision_id)
333
427
        updater = self._get_updater(rev)
334
 
        for path, obj, ie in self._revision_to_objects(rev, tree):
335
 
            updater.add_object(obj, ie)
 
428
        for path, obj, ie in self._revision_to_objects(rev, tree,
 
429
            roundtrip=True):
 
430
            if isinstance(obj, Commit):
 
431
                testament3 = StrictTestament3(rev, tree.inventory)
 
432
                ie = { "testament3-sha1": testament3.as_sha1() }
 
433
            updater.add_object(obj, ie, path)
336
434
        commit_obj = updater.finish()
337
435
        return commit_obj.id
338
436
 
385
483
                        [(entry.file_id, entry.revision, None)]).next().id
386
484
            else:
387
485
                raise AssertionError("unknown entry kind '%s'" % entry.kind)
388
 
        tree = directory_to_tree(inv[fileid], get_ie_sha1, unusual_modes)
 
486
        tree = directory_to_tree(inv[fileid], get_ie_sha1, unusual_modes,
 
487
            self.mapping.BZR_DUMMY_FILE)
 
488
        if (inv.root.file_id == fileid and
 
489
            self.mapping.BZR_FILE_IDS_FILE is not None):
 
490
            b = self._create_fileid_map_blob(inv)
 
491
            # If this is the root tree, add the file ids
 
492
            tree[self.mapping.BZR_FILE_IDS_FILE] = ((stat.S_IFREG | 0644), b.id)
389
493
        _check_expected_sha(expected_sha, tree)
390
494
        return tree
391
495
 
408
512
            try:
409
513
                return mapping_registry.parse_revision_id(revid)[0]
410
514
            except errors.InvalidRevisionId:
411
 
                self._update_sha_map(revid)
 
515
                self.repository.lock_read()
 
516
                try:
 
517
                    self._update_sha_map(revid)
 
518
                finally:
 
519
                    self.repository.unlock()
412
520
                return self._cache.idmap.lookup_commit(revid)
413
521
 
414
522
    def get_raw(self, sha):
422
530
    def __contains__(self, sha):
423
531
        # See if sha is in map
424
532
        try:
425
 
            (type, type_data) = self._lookup_git_sha(sha)
 
533
            (type, type_data) = self.lookup_git_sha(sha)
426
534
            if type == "commit":
427
535
                return self.repository.has_revision(type_data[0])
428
536
            elif type == "blob":
429
 
                return self.repository.texts.has_version(type_data)
 
537
                return self.repository.texts.has_key(type_data)
430
538
            elif type == "tree":
431
539
                return self.repository.has_revision(type_data[1])
432
540
            else:
434
542
        except KeyError:
435
543
            return False
436
544
 
437
 
    def _lookup_git_sha(self, sha):
438
 
        # See if sha is in map
439
 
        try:
440
 
            return self._cache.idmap.lookup_git_sha(sha)
441
 
        except KeyError:
442
 
            # if not, see if there are any unconverted revisions and add them
443
 
            # to the map, search for sha in map again
444
 
            self._update_sha_map()
445
 
            return self._cache.idmap.lookup_git_sha(sha)
 
545
    def lookup_git_shas(self, shas, update_map=True):
 
546
        from dulwich.protocol import ZERO_SHA
 
547
        ret = {}
 
548
        for sha in shas:
 
549
            if sha == ZERO_SHA:
 
550
                ret[sha] = ("commit", (NULL_REVISION, None, {}))
 
551
                continue
 
552
            try:
 
553
                ret[sha] = self._cache.idmap.lookup_git_sha(sha)
 
554
            except KeyError:
 
555
                if update_map:
 
556
                    # if not, see if there are any unconverted revisions and add
 
557
                    # them to the map, search for sha in map again
 
558
                    self._update_sha_map()
 
559
                    update_map = False
 
560
                    try:
 
561
                        ret[sha] = self._cache.idmap.lookup_git_sha(sha)
 
562
                    except KeyError:
 
563
                        pass
 
564
        return ret
 
565
 
 
566
    def lookup_git_sha(self, sha, update_map=True):
 
567
        return self.lookup_git_shas([sha], update_map=update_map)[sha]
446
568
 
447
569
    def __getitem__(self, sha):
448
570
        if self._cache.content_cache is not None:
450
572
                return self._cache.content_cache[sha]
451
573
            except KeyError:
452
574
                pass
453
 
        (type, type_data) = self._lookup_git_sha(sha)
 
575
        (type, type_data) = self.lookup_git_sha(sha)
454
576
        # convert object to git object
455
577
        if type == "commit":
456
 
            (revid, tree_sha) = type_data
 
578
            (revid, tree_sha, verifiers) = type_data
457
579
            try:
458
580
                rev = self.repository.get_revision(revid)
459
581
            except errors.NoSuchRevision:
460
582
                trace.mutter('entry for %s %s in shamap: %r, but not found in '
461
583
                             'repository', type, sha, type_data)
462
584
                raise KeyError(sha)
463
 
            commit = self._reconstruct_commit(rev, tree_sha)
 
585
            commit = self._reconstruct_commit(rev, tree_sha, roundtrip=True,
 
586
                verifiers=verifiers)
464
587
            _check_expected_sha(sha, commit)
465
588
            return commit
466
589
        elif type == "blob":
483
606
        else:
484
607
            raise AssertionError("Unknown object type '%s'" % type)
485
608
 
486
 
    def generate_pack_contents(self, have, want, progress=None, get_tagged=None):
 
609
    def generate_lossy_pack_contents(self, have, want, progress=None,
 
610
            get_tagged=None):
 
611
        return self.generate_pack_contents(have, want, progress, get_tagged,
 
612
            lossy=True)
 
613
 
 
614
    def generate_pack_contents(self, have, want, progress=None,
 
615
            get_tagged=None, lossy=False):
487
616
        """Iterate over the contents of a pack file.
488
617
 
489
618
        :param have: List of SHA1s of objects that should not be sent
490
619
        :param want: List of SHA1s of objects that should be sent
491
620
        """
492
621
        processed = set()
 
622
        ret = self.lookup_git_shas(have + want)
493
623
        for commit_sha in have:
494
624
            try:
495
 
                (type, (revid, tree_sha)) = self._lookup_git_sha(commit_sha)
 
625
                (type, (revid, tree_sha)) = ret[commit_sha]
496
626
            except KeyError:
497
627
                pass
498
628
            else:
502
632
        for commit_sha in want:
503
633
            if commit_sha in have:
504
634
                continue
505
 
            (type, (revid, tree_sha)) = self._lookup_git_sha(commit_sha)
506
 
            assert type == "commit"
507
 
            pending.add(revid)
508
 
        todo = set()
509
 
        while pending:
510
 
            processed.update(pending)
511
 
            next_map = self.repository.get_parent_map(pending)
512
 
            next_pending = set()
513
 
            for item in next_map.iteritems():
514
 
                todo.add(item[0])
515
 
                next_pending.update(p for p in item[1] if p not in processed)
516
 
            pending = next_pending
517
 
        if NULL_REVISION in todo:
518
 
            todo.remove(NULL_REVISION)
 
635
            try:
 
636
                (type, (revid, tree_sha)) = ret[commit_sha]
 
637
            except KeyError:
 
638
                pass
 
639
            else:
 
640
                assert type == "commit"
 
641
                pending.add(revid)
 
642
 
 
643
        todo = _find_missing_bzr_revids(self.repository.get_parent_map, 
 
644
                                        pending, processed)
519
645
        trace.mutter('sending revisions %r', todo)
520
646
        ret = []
521
647
        pb = ui.ui_factory.nested_progress_bar()
524
650
                pb.update("generating git objects", i, len(todo))
525
651
                rev = self.repository.get_revision(revid)
526
652
                tree = self.tree_cache.revision_tree(revid)
527
 
                for path, obj, ie in self._revision_to_objects(rev, tree):
 
653
                for path, obj, ie in self._revision_to_objects(rev, tree,
 
654
                    roundtrip=not lossy):
528
655
                    ret.append((obj, path))
529
656
        finally:
530
657
            pb.finished()