/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

Avoid using verifiers for natively imported revisions, save a lot of time.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Map from Git sha's to Bazaar objects."""
 
18
 
 
19
from dulwich.objects import (
 
20
    Blob,
 
21
    Commit,
 
22
    Tree,
 
23
    sha_to_hex,
 
24
    ZERO_SHA,
 
25
    )
 
26
from dulwich.object_store import (
 
27
    BaseObjectStore,
 
28
    )
 
29
 
 
30
from bzrlib import (
 
31
    errors,
 
32
    lru_cache,
 
33
    trace,
 
34
    ui,
 
35
    urlutils,
 
36
    )
 
37
from bzrlib.revision import (
 
38
    NULL_REVISION,
 
39
    )
 
40
from bzrlib.testament import(
 
41
    StrictTestament3,
 
42
    )
 
43
 
 
44
from bzrlib.plugins.git.mapping import (
 
45
    default_mapping,
 
46
    directory_to_tree,
 
47
    extract_unusual_modes,
 
48
    mapping_registry,
 
49
    symlink_to_blob,
 
50
    )
 
51
from bzrlib.plugins.git.cache import (
 
52
    from_repository as cache_from_repository,
 
53
    )
 
54
 
 
55
import posixpath
 
56
import stat
 
57
 
 
58
 
 
59
def get_object_store(repo, mapping=None):
 
60
    git = getattr(repo, "_git", None)
 
61
    if git is not None:
 
62
        return git.object_store
 
63
    return BazaarObjectStore(repo, mapping)
 
64
 
 
65
 
 
66
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
 
67
 
 
68
 
 
69
class LRUTreeCache(object):
 
70
 
 
71
    def __init__(self, repository):
 
72
        def approx_tree_size(tree):
 
73
            # Very rough estimate, 1k per inventory entry
 
74
            return len(tree.inventory) * 1024
 
75
        self.repository = repository
 
76
        self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
 
77
            after_cleanup_size=None, compute_size=approx_tree_size)
 
78
 
 
79
    def revision_tree(self, revid):
 
80
        try:
 
81
            tree = self._cache[revid]
 
82
        except KeyError:
 
83
            tree = self.repository.revision_tree(revid)
 
84
            self.add(tree)
 
85
        assert tree.get_revision_id() == tree.inventory.revision_id
 
86
        return tree
 
87
 
 
88
    def iter_revision_trees(self, revids):
 
89
        trees = {}
 
90
        todo = []
 
91
        for revid in revids:
 
92
            try:
 
93
                tree = self._cache[revid]
 
94
            except KeyError:
 
95
                todo.append(revid)
 
96
            else:
 
97
                assert tree.get_revision_id() == revid
 
98
                assert tree.inventory.revision_id == revid
 
99
                trees[revid] = tree
 
100
        for tree in self.repository.revision_trees(todo):
 
101
            trees[tree.get_revision_id()] = tree
 
102
            self.add(tree)
 
103
        return (trees[r] for r in revids)
 
104
 
 
105
    def revision_trees(self, revids):
 
106
        return list(self.iter_revision_trees(revids))
 
107
 
 
108
    def add(self, tree):
 
109
        self._cache.add(tree.get_revision_id(), tree)
 
110
 
 
111
 
 
112
def _find_missing_bzr_revids(graph, want, have):
 
113
    """Find the revisions that have to be pushed.
 
114
 
 
115
    :param get_parent_map: Function that returns the parents for a sequence
 
116
        of revisions.
 
117
    :param want: Revisions the target wants
 
118
    :param have: Revisions the target already has
 
119
    :return: Set of revisions to fetch
 
120
    """
 
121
    todo = set()
 
122
    for rev in want:
 
123
        todo.update(graph.find_unique_ancestors(rev, have))
 
124
    if NULL_REVISION in todo:
 
125
        todo.remove(NULL_REVISION)
 
126
    return todo
 
127
 
 
128
 
 
129
def _check_expected_sha(expected_sha, object):
 
130
    """Check whether an object matches an expected SHA.
 
131
 
 
132
    :param expected_sha: None or expected SHA as either binary or as hex digest
 
133
    :param object: Object to verify
 
134
    """
 
135
    if expected_sha is None:
 
136
        return
 
137
    if len(expected_sha) == 40:
 
138
        if expected_sha != object.sha().hexdigest():
 
139
            raise AssertionError("Invalid sha for %r: %s" % (object,
 
140
                expected_sha))
 
141
    elif len(expected_sha) == 20:
 
142
        if expected_sha != object.sha().digest():
 
143
            raise AssertionError("Invalid sha for %r: %s" % (object,
 
144
                sha_to_hex(expected_sha)))
 
145
    else:
 
146
        raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
 
147
            expected_sha))
 
148
 
 
149
 
 
150
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
 
151
                     dummy_file_name=None):
 
152
    """Iterate over the objects that were introduced in a revision.
 
153
 
 
154
    :param idmap: id map
 
155
    :param parent_trees: Parent revision trees
 
156
    :param unusual_modes: Unusual file modes dictionary
 
157
    :param dummy_file_name: File name to use for dummy files
 
158
        in empty directories. None to skip empty directories
 
159
    :return: Yields (path, object, ie) entries
 
160
    """
 
161
    new_trees = {}
 
162
    new_blobs = []
 
163
    shamap = {}
 
164
    try:
 
165
        base_tree = parent_trees[0]
 
166
        other_parent_trees = parent_trees[1:]
 
167
    except IndexError:
 
168
        base_tree = tree._repository.revision_tree(NULL_REVISION)
 
169
        other_parent_trees = []
 
170
    def find_unchanged_parent_ie(ie, parent_trees):
 
171
        assert ie.kind in ("symlink", "file")
 
172
        for ptree in parent_trees:
 
173
            try:
 
174
                pie = ptree.inventory[ie.file_id]
 
175
            except errors.NoSuchId:
 
176
                pass
 
177
            else:
 
178
                if (pie.text_sha1 == ie.text_sha1 and 
 
179
                    pie.kind == ie.kind and
 
180
                    pie.symlink_target == ie.symlink_target):
 
181
                    return pie
 
182
        raise KeyError
 
183
 
 
184
    # Find all the changed blobs
 
185
    for (file_id, path, changed_content, versioned, parent, name, kind,
 
186
         executable) in tree.iter_changes(base_tree):
 
187
        if kind[1] == "file":
 
188
            ie = tree.inventory[file_id]
 
189
            if changed_content:
 
190
                try:
 
191
                    pie = find_unchanged_parent_ie(ie, other_parent_trees)
 
192
                except KeyError:
 
193
                    pass
 
194
                else:
 
195
                    try:
 
196
                        shamap[ie.file_id] = idmap.lookup_blob_id(
 
197
                            pie.file_id, pie.revision)
 
198
                    except KeyError:
 
199
                        # no-change merge ?
 
200
                        blob = Blob()
 
201
                        blob.data = tree.get_file_text(ie.file_id)
 
202
                        shamap[ie.file_id] = blob.id
 
203
            if not file_id in shamap:
 
204
                new_blobs.append((path[1], ie))
 
205
            new_trees[posixpath.dirname(path[1])] = parent[1]
 
206
        elif kind[1] == "symlink":
 
207
            ie = tree.inventory[file_id]
 
208
            if changed_content:
 
209
                blob = symlink_to_blob(ie)
 
210
                shamap[file_id] = blob.id
 
211
                try:
 
212
                    find_unchanged_parent_ie(ie, other_parent_trees)
 
213
                except KeyError:
 
214
                    yield path[1], blob, ie
 
215
            new_trees[posixpath.dirname(path[1])] = parent[1]
 
216
        elif kind[1] not in (None, "directory"):
 
217
            raise AssertionError(kind[1])
 
218
        if (path[0] not in (None, "") and
 
219
            parent[0] in tree.inventory and
 
220
            tree.inventory[parent[0]].kind == "directory"):
 
221
            # Removal
 
222
            new_trees[posixpath.dirname(path[0])] = parent[0]
 
223
    
 
224
    # Fetch contents of the blobs that were changed
 
225
    for (path, ie), chunks in tree.iter_files_bytes(
 
226
        [(ie.file_id, (path, ie)) for (path, ie) in new_blobs]):
 
227
        obj = Blob()
 
228
        obj.chunked = chunks
 
229
        yield path, obj, ie
 
230
        shamap[ie.file_id] = obj.id
 
231
 
 
232
    for path in unusual_modes:
 
233
        parent_path = posixpath.dirname(path)
 
234
        new_trees[parent_path] = tree.path2id(parent_path)
 
235
 
 
236
    trees = {}
 
237
    while new_trees:
 
238
        items = new_trees.items()
 
239
        new_trees = {}
 
240
        for path, file_id in items:
 
241
            parent_id = tree.inventory[file_id].parent_id
 
242
            if parent_id is not None:
 
243
                parent_path = urlutils.dirname(path)
 
244
                new_trees[parent_path] = parent_id
 
245
            trees[path] = file_id
 
246
 
 
247
    def ie_to_hexsha(ie):
 
248
        try:
 
249
            return shamap[ie.file_id]
 
250
        except KeyError:
 
251
            # FIXME: Should be the same as in parent
 
252
            if ie.kind in ("file", "symlink"):
 
253
                try:
 
254
                    return idmap.lookup_blob_id(ie.file_id, ie.revision)
 
255
                except KeyError:
 
256
                    # no-change merge ?
 
257
                    blob = Blob()
 
258
                    blob.data = tree.get_file_text(ie.file_id)
 
259
                    return blob.id
 
260
            elif ie.kind == "directory":
 
261
                # Not all cache backends store the tree information, 
 
262
                # calculate again from scratch
 
263
                ret = directory_to_tree(ie, ie_to_hexsha, unusual_modes,
 
264
                    dummy_file_name)
 
265
                if ret is None:
 
266
                    return ret
 
267
                return ret.id
 
268
            else:
 
269
                raise AssertionError
 
270
 
 
271
    for path in sorted(trees.keys(), reverse=True):
 
272
        ie = tree.inventory[trees[path]]
 
273
        assert ie.kind == "directory"
 
274
        obj = directory_to_tree(ie, ie_to_hexsha, unusual_modes,
 
275
            dummy_file_name)
 
276
        if obj is not None:
 
277
            yield path, obj, ie
 
278
            shamap[ie.file_id] = obj.id
 
279
 
 
280
 
 
281
class BazaarObjectStore(BaseObjectStore):
 
282
    """A Git-style object store backed onto a Bazaar repository."""
 
283
 
 
284
    def __init__(self, repository, mapping=None):
 
285
        self.repository = repository
 
286
        if mapping is None:
 
287
            self.mapping = default_mapping
 
288
        else:
 
289
            self.mapping = mapping
 
290
        self._cache = cache_from_repository(repository)
 
291
        self._content_cache_types = ("tree")
 
292
        self.start_write_group = self._cache.idmap.start_write_group
 
293
        self.abort_write_group = self._cache.idmap.abort_write_group
 
294
        self.commit_write_group = self._cache.idmap.commit_write_group
 
295
        self.tree_cache = LRUTreeCache(self.repository)
 
296
 
 
297
    def _update_sha_map(self, stop_revision=None):
 
298
        graph = self.repository.get_graph()
 
299
        if stop_revision is None:
 
300
            heads = graph.heads(self.repository.all_revision_ids())
 
301
        else:
 
302
            heads = set([stop_revision])
 
303
        missing_revids = self._cache.idmap.missing_revisions(heads)
 
304
        while heads:
 
305
            parents = graph.get_parent_map(heads)
 
306
            todo = set()
 
307
            for p in parents.values():
 
308
                todo.update([x for x in p if x not in missing_revids])
 
309
            heads = self._cache.idmap.missing_revisions(todo)
 
310
            missing_revids.update(heads)
 
311
        if NULL_REVISION in missing_revids:
 
312
            missing_revids.remove(NULL_REVISION)
 
313
        missing_revids = self.repository.has_revisions(missing_revids)
 
314
        if not missing_revids:
 
315
            return
 
316
        self.start_write_group()
 
317
        try:
 
318
            pb = ui.ui_factory.nested_progress_bar()
 
319
            try:
 
320
                for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
 
321
                    trace.mutter('processing %r', revid)
 
322
                    pb.update("updating git map", i, len(missing_revids))
 
323
                    self._update_sha_map_revision(revid)
 
324
            finally:
 
325
                pb.finished()
 
326
        except:
 
327
            self.abort_write_group()
 
328
            raise
 
329
        else:
 
330
            self.commit_write_group()
 
331
 
 
332
    def __iter__(self):
 
333
        self._update_sha_map()
 
334
        return iter(self._cache.idmap.sha1s())
 
335
 
 
336
    def _reconstruct_commit(self, rev, tree_sha, roundtrip, verifiers):
 
337
        """Reconstruct a Commit object.
 
338
 
 
339
        :param rev: Revision object
 
340
        :param tree_sha: SHA1 of the root tree object
 
341
        :param roundtrip: Whether or not to roundtrip bzr metadata
 
342
        :param verifiers: Verifiers for the commits
 
343
        :return: Commit object
 
344
        """
 
345
        def parent_lookup(revid):
 
346
            try:
 
347
                return self._lookup_revision_sha1(revid)
 
348
            except errors.NoSuchRevision:
 
349
                return None
 
350
        return self.mapping.export_commit(rev, tree_sha, parent_lookup,
 
351
            roundtrip, verifiers)
 
352
 
 
353
    def _create_fileid_map_blob(self, inv):
 
354
        # FIXME: This can probably be a lot more efficient, 
 
355
        # not all files necessarily have to be processed.
 
356
        file_ids = {}
 
357
        for (path, ie) in inv.iter_entries():
 
358
            if self.mapping.generate_file_id(path) != ie.file_id:
 
359
                file_ids[path] = ie.file_id
 
360
        return self.mapping.export_fileid_map(file_ids)
 
361
 
 
362
    def _revision_to_objects(self, rev, tree, roundtrip):
 
363
        """Convert a revision to a set of git objects.
 
364
 
 
365
        :param rev: Bazaar revision object
 
366
        :param tree: Bazaar revision tree
 
367
        :param roundtrip: Whether to roundtrip all Bazaar revision data
 
368
        """
 
369
        unusual_modes = extract_unusual_modes(rev)
 
370
        present_parents = self.repository.has_revisions(rev.parent_ids)
 
371
        parent_trees = self.tree_cache.revision_trees(
 
372
            [p for p in rev.parent_ids if p in present_parents])
 
373
        root_tree = None
 
374
        for path, obj, ie in _tree_to_objects(tree, parent_trees,
 
375
                self._cache.idmap, unusual_modes, self.mapping.BZR_DUMMY_FILE):
 
376
            if path == "":
 
377
                root_tree = obj
 
378
                root_ie = ie
 
379
                # Don't yield just yet
 
380
            else:
 
381
                yield path, obj, ie
 
382
        if root_tree is None:
 
383
            # Pointless commit - get the tree sha elsewhere
 
384
            if not rev.parent_ids:
 
385
                root_tree = Tree()
 
386
            else:
 
387
                base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
 
388
                root_tree = self[self[base_sha1].tree]
 
389
            root_ie = tree.inventory.root
 
390
        if roundtrip and self.mapping.BZR_FILE_IDS_FILE is not None:
 
391
            b = self._create_fileid_map_blob(tree.inventory)
 
392
            if b is not None:
 
393
                root_tree[self.mapping.BZR_FILE_IDS_FILE] = ((stat.S_IFREG | 0644), b.id)
 
394
                yield self.mapping.BZR_FILE_IDS_FILE, b, None
 
395
        yield "", root_tree, root_ie
 
396
        if roundtrip:
 
397
            testament3 = StrictTestament3(rev, tree.inventory)
 
398
            verifiers = { "testament3-sha1": testament3.as_sha1() }
 
399
        else:
 
400
            verifiers = {}
 
401
        commit_obj = self._reconstruct_commit(rev, root_tree.id,
 
402
            roundtrip=roundtrip, verifiers=verifiers)
 
403
        try:
 
404
            foreign_revid, mapping = mapping_registry.parse_revision_id(
 
405
                rev.revision_id)
 
406
        except errors.InvalidRevisionId:
 
407
            pass
 
408
        else:
 
409
            _check_expected_sha(foreign_revid, commit_obj)
 
410
        yield None, commit_obj, None
 
411
 
 
412
    def _get_updater(self, rev):
 
413
        return self._cache.get_updater(rev)
 
414
 
 
415
    def _update_sha_map_revision(self, revid):
 
416
        rev = self.repository.get_revision(revid)
 
417
        tree = self.tree_cache.revision_tree(rev.revision_id)
 
418
        updater = self._get_updater(rev)
 
419
        for path, obj, ie in self._revision_to_objects(rev, tree,
 
420
            roundtrip=True):
 
421
            if isinstance(obj, Commit):
 
422
                testament3 = StrictTestament3(rev, tree.inventory)
 
423
                ie = { "testament3-sha1": testament3.as_sha1() }
 
424
            updater.add_object(obj, ie, path)
 
425
        commit_obj = updater.finish()
 
426
        return commit_obj.id
 
427
 
 
428
    def _reconstruct_blobs(self, keys):
 
429
        """Return a Git Blob object from a fileid and revision stored in bzr.
 
430
 
 
431
        :param fileid: File id of the text
 
432
        :param revision: Revision of the text
 
433
        """
 
434
        stream = self.repository.iter_files_bytes(
 
435
            ((key[0], key[1], key) for key in keys))
 
436
        for (fileid, revision, expected_sha), chunks in stream:
 
437
            blob = Blob()
 
438
            blob.chunked = chunks
 
439
            if blob.id != expected_sha and blob.data == "":
 
440
                # Perhaps it's a symlink ?
 
441
                tree = self.tree_cache.revision_tree(revision)
 
442
                entry = tree.inventory[fileid]
 
443
                if entry.kind == 'symlink':
 
444
                    blob = symlink_to_blob(entry)
 
445
            _check_expected_sha(expected_sha, blob)
 
446
            yield blob
 
447
 
 
448
    def _reconstruct_tree(self, fileid, revid, inv, unusual_modes,
 
449
        expected_sha=None):
 
450
        """Return a Git Tree object from a file id and a revision stored in bzr.
 
451
 
 
452
        :param fileid: fileid in the tree.
 
453
        :param revision: Revision of the tree.
 
454
        """
 
455
        def get_ie_sha1(entry):
 
456
            if entry.kind == "directory":
 
457
                try:
 
458
                    return self._cache.idmap.lookup_tree_id(entry.file_id,
 
459
                        revid)
 
460
                except (NotImplementedError, KeyError):
 
461
                    obj = self._reconstruct_tree(entry.file_id, revid, inv,
 
462
                        unusual_modes)
 
463
                    if obj is None:
 
464
                        return None
 
465
                    else:
 
466
                        return obj.id
 
467
            elif entry.kind in ("file", "symlink"):
 
468
                try:
 
469
                    return self._cache.idmap.lookup_blob_id(entry.file_id,
 
470
                        entry.revision)
 
471
                except KeyError:
 
472
                    # no-change merge?
 
473
                    return self._reconstruct_blobs(
 
474
                        [(entry.file_id, entry.revision, None)]).next().id
 
475
            else:
 
476
                raise AssertionError("unknown entry kind '%s'" % entry.kind)
 
477
        tree = directory_to_tree(inv[fileid], get_ie_sha1, unusual_modes,
 
478
            self.mapping.BZR_DUMMY_FILE)
 
479
        if (inv.root.file_id == fileid and
 
480
            self.mapping.BZR_FILE_IDS_FILE is not None):
 
481
            b = self._create_fileid_map_blob(inv)
 
482
            # If this is the root tree, add the file ids
 
483
            tree[self.mapping.BZR_FILE_IDS_FILE] = ((stat.S_IFREG | 0644), b.id)
 
484
        _check_expected_sha(expected_sha, tree)
 
485
        return tree
 
486
 
 
487
    def get_parents(self, sha):
 
488
        """Retrieve the parents of a Git commit by SHA1.
 
489
 
 
490
        :param sha: SHA1 of the commit
 
491
        :raises: KeyError, NotCommitError
 
492
        """
 
493
        return self[sha].parents
 
494
 
 
495
    def _lookup_revision_sha1(self, revid):
 
496
        """Return the SHA1 matching a Bazaar revision."""
 
497
        if revid == NULL_REVISION:
 
498
            return ZERO_SHA
 
499
        try:
 
500
            return self._cache.idmap.lookup_commit(revid)
 
501
        except KeyError:
 
502
            try:
 
503
                return mapping_registry.parse_revision_id(revid)[0]
 
504
            except errors.InvalidRevisionId:
 
505
                self.repository.lock_read()
 
506
                try:
 
507
                    self._update_sha_map(revid)
 
508
                finally:
 
509
                    self.repository.unlock()
 
510
                return self._cache.idmap.lookup_commit(revid)
 
511
 
 
512
    def get_raw(self, sha):
 
513
        """Get the raw representation of a Git object by SHA1.
 
514
 
 
515
        :param sha: SHA1 of the git object
 
516
        """
 
517
        obj = self[sha]
 
518
        return (obj.type, obj.as_raw_string())
 
519
 
 
520
    def __contains__(self, sha):
 
521
        # See if sha is in map
 
522
        try:
 
523
            for (type, type_data) in self.lookup_git_sha(sha):
 
524
                if type == "commit":
 
525
                    if self.repository.has_revision(type_data[0]):
 
526
                        return True
 
527
                elif type == "blob":
 
528
                    if self.repository.texts.has_key(type_data):
 
529
                        return True
 
530
                elif type == "tree":
 
531
                    if self.repository.has_revision(type_data[1]):
 
532
                        return True
 
533
                else:
 
534
                    raise AssertionError("Unknown object type '%s'" % type)
 
535
            else:
 
536
                return False
 
537
        except KeyError:
 
538
            return False
 
539
 
 
540
    def lookup_git_shas(self, shas, update_map=True):
 
541
        ret = {}
 
542
        for sha in shas:
 
543
            if sha == ZERO_SHA:
 
544
                ret[sha] = [("commit", (NULL_REVISION, None, {}))]
 
545
                continue
 
546
            try:
 
547
                ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
 
548
            except KeyError:
 
549
                if update_map:
 
550
                    # if not, see if there are any unconverted revisions and add
 
551
                    # them to the map, search for sha in map again
 
552
                    self._update_sha_map()
 
553
                    update_map = False
 
554
                    try:
 
555
                        ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
 
556
                    except KeyError:
 
557
                        pass
 
558
        return ret
 
559
 
 
560
    def lookup_git_sha(self, sha, update_map=True):
 
561
        return self.lookup_git_shas([sha], update_map=update_map)[sha]
 
562
 
 
563
    def __getitem__(self, sha):
 
564
        if self._cache.content_cache is not None:
 
565
            try:
 
566
                return self._cache.content_cache[sha]
 
567
            except KeyError:
 
568
                pass
 
569
        for (kind, type_data) in self.lookup_git_sha(sha):
 
570
            # convert object to git object
 
571
            if kind == "commit":
 
572
                (revid, tree_sha, verifiers) = type_data
 
573
                try:
 
574
                    rev = self.repository.get_revision(revid)
 
575
                except errors.NoSuchRevision:
 
576
                    trace.mutter('entry for %s %s in shamap: %r, but not '
 
577
                                 'found in repository', kind, sha, type_data)
 
578
                    raise KeyError(sha)
 
579
                commit = self._reconstruct_commit(rev, tree_sha, roundtrip=True,
 
580
                    verifiers=verifiers)
 
581
                _check_expected_sha(sha, commit)
 
582
                return commit
 
583
            elif kind == "blob":
 
584
                (fileid, revision) = type_data
 
585
                return self._reconstruct_blobs([(fileid, revision, sha)]).next()
 
586
            elif kind == "tree":
 
587
                (fileid, revid) = type_data
 
588
                try:
 
589
                    tree = self.tree_cache.revision_tree(revid)
 
590
                    rev = self.repository.get_revision(revid)
 
591
                except errors.NoSuchRevision:
 
592
                    trace.mutter('entry for %s %s in shamap: %r, but not found in repository', kind, sha, type_data)
 
593
                    raise KeyError(sha)
 
594
                unusual_modes = extract_unusual_modes(rev)
 
595
                try:
 
596
                    return self._reconstruct_tree(fileid, revid,
 
597
                        tree.inventory, unusual_modes, expected_sha=sha)
 
598
                except errors.NoSuchRevision:
 
599
                    raise KeyError(sha)
 
600
            else:
 
601
                raise AssertionError("Unknown object type '%s'" % kind)
 
602
        else:
 
603
            raise KeyError(sha)
 
604
 
 
605
    def generate_lossy_pack_contents(self, have, want, progress=None,
 
606
            get_tagged=None):
 
607
        return self.generate_pack_contents(have, want, progress, get_tagged,
 
608
            lossy=True)
 
609
 
 
610
    def generate_pack_contents(self, have, want, progress=None,
 
611
            get_tagged=None, lossy=False):
 
612
        """Iterate over the contents of a pack file.
 
613
 
 
614
        :param have: List of SHA1s of objects that should not be sent
 
615
        :param want: List of SHA1s of objects that should be sent
 
616
        """
 
617
        processed = set()
 
618
        ret = self.lookup_git_shas(have + want)
 
619
        for commit_sha in have:
 
620
            try:
 
621
                (type, (revid, tree_sha, verifiers)) = ret[commit_sha]
 
622
            except KeyError:
 
623
                pass
 
624
            else:
 
625
                assert type == "commit"
 
626
                processed.add(revid)
 
627
        pending = set()
 
628
        for commit_sha in want:
 
629
            if commit_sha in have:
 
630
                continue
 
631
            try:
 
632
                (type, (revid, tree_sha, verifiers)) = ret[commit_sha]
 
633
            except KeyError:
 
634
                pass
 
635
            else:
 
636
                assert type == "commit"
 
637
                pending.add(revid)
 
638
 
 
639
        graph = self.repository.get_graph()
 
640
        todo = _find_missing_bzr_revids(graph, pending, processed)
 
641
        trace.mutter('sending revisions %r', todo)
 
642
        ret = []
 
643
        pb = ui.ui_factory.nested_progress_bar()
 
644
        try:
 
645
            for i, revid in enumerate(todo):
 
646
                pb.update("generating git objects", i, len(todo))
 
647
                try:
 
648
                    rev = self.repository.get_revision(revid)
 
649
                except errors.NoSuchRevision:
 
650
                    continue
 
651
                tree = self.tree_cache.revision_tree(revid)
 
652
                for path, obj, ie in self._revision_to_objects(rev, tree,
 
653
                    roundtrip=not lossy):
 
654
                    ret.append((obj, path))
 
655
        finally:
 
656
            pb.finished()
 
657
        return ret
 
658
 
 
659
    def add_thin_pack(self):
 
660
        import tempfile
 
661
        import os
 
662
        fd, path = tempfile.mkstemp(suffix=".pack")
 
663
        f = os.fdopen(fd, 'wb')
 
664
        def commit():
 
665
            from dulwich.pack import PackData, Pack
 
666
            from bzrlib.plugins.git.fetch import import_git_objects
 
667
            os.fsync(fd)
 
668
            f.close()
 
669
            if os.path.getsize(path) == 0:
 
670
                return
 
671
            pd = PackData(path)
 
672
            pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
 
673
 
 
674
            p = Pack(path[:-5])
 
675
            self.repository.lock_write()
 
676
            try:
 
677
                self.repository.start_write_group()
 
678
                try:
 
679
                    import_git_objects(self.repository, self.mapping, 
 
680
                        p.iterobjects(get_raw=self.get_raw),
 
681
                        self.object_store)
 
682
                except:
 
683
                    self.repository.abort_write_group()
 
684
                    raise
 
685
                else:
 
686
                    self.repository.commit_write_group()
 
687
            finally:
 
688
                self.repository.unlock()
 
689
        return f, commit
 
690
 
 
691
    # The pack isn't kept around anyway, so no point 
 
692
    # in treating full packs different from thin packs
 
693
    add_pack = add_thin_pack