/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

Fix updating cache for single revision - don't consider it an update of the full cache.

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