/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

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

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