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

  • Committer: Jelmer Vernooij
  • Date: 2020-03-22 01:35:14 UTC
  • mfrom: (7490.7.6 work)
  • mto: This revision was merged to the branch mainline in revision 7499.
  • Revision ID: jelmer@jelmer.uk-20200322013514-7vw1ntwho04rcuj3
merge lp:brz/3.1.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
 
2
# Copyright (C) 2012 Canonical Ltd
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
 
 
18
"""Map from Git sha's to Bazaar objects."""
 
19
 
 
20
from dulwich.objects import (
 
21
    Blob,
 
22
    Commit,
 
23
    Tree,
 
24
    sha_to_hex,
 
25
    ZERO_SHA,
 
26
    )
 
27
from dulwich.object_store import (
 
28
    BaseObjectStore,
 
29
    )
 
30
from dulwich.pack import (
 
31
    pack_objects_to_data,
 
32
    PackData,
 
33
    Pack,
 
34
    )
 
35
 
 
36
from .. import (
 
37
    errors,
 
38
    lru_cache,
 
39
    trace,
 
40
    osutils,
 
41
    ui,
 
42
    )
 
43
from ..lock import LogicalLockResult
 
44
from ..revision import (
 
45
    NULL_REVISION,
 
46
    )
 
47
from ..tree import InterTree
 
48
from ..bzr.testament import (
 
49
    StrictTestament3,
 
50
    )
 
51
 
 
52
from .cache import (
 
53
    from_repository as cache_from_repository,
 
54
    )
 
55
from .mapping import (
 
56
    default_mapping,
 
57
    entry_mode,
 
58
    extract_unusual_modes,
 
59
    mapping_registry,
 
60
    symlink_to_blob,
 
61
    )
 
62
from .unpeel_map import (
 
63
    UnpeelMap,
 
64
    )
 
65
 
 
66
import posixpath
 
67
import stat
 
68
 
 
69
 
 
70
BANNED_FILENAMES = ['.git']
 
71
 
 
72
 
 
73
def get_object_store(repo, mapping=None):
 
74
    git = getattr(repo, "_git", None)
 
75
    if git is not None:
 
76
        git.object_store.unlock = lambda: None
 
77
        git.object_store.lock_read = lambda: LogicalLockResult(lambda: None)
 
78
        git.object_store.lock_write = lambda: LogicalLockResult(lambda: None)
 
79
        return git.object_store
 
80
    return BazaarObjectStore(repo, mapping)
 
81
 
 
82
 
 
83
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
 
84
 
 
85
 
 
86
class LRUTreeCache(object):
 
87
 
 
88
    def __init__(self, repository):
 
89
        def approx_tree_size(tree):
 
90
            # Very rough estimate, 250 per inventory entry
 
91
            try:
 
92
                inv = tree.root_inventory
 
93
            except AttributeError:
 
94
                inv = tree.inventory
 
95
            return len(inv) * 250
 
96
        self.repository = repository
 
97
        self._cache = lru_cache.LRUSizeCache(
 
98
            max_size=MAX_TREE_CACHE_SIZE, after_cleanup_size=None,
 
99
            compute_size=approx_tree_size)
 
100
 
 
101
    def revision_tree(self, revid):
 
102
        try:
 
103
            tree = self._cache[revid]
 
104
        except KeyError:
 
105
            tree = self.repository.revision_tree(revid)
 
106
            self.add(tree)
 
107
        return tree
 
108
 
 
109
    def iter_revision_trees(self, revids):
 
110
        trees = {}
 
111
        todo = []
 
112
        for revid in revids:
 
113
            try:
 
114
                tree = self._cache[revid]
 
115
            except KeyError:
 
116
                todo.append(revid)
 
117
            else:
 
118
                if tree.get_revision_id() != revid:
 
119
                    raise AssertionError(
 
120
                        "revision id did not match: %s != %s" % (
 
121
                            tree.get_revision_id(), revid))
 
122
                trees[revid] = tree
 
123
        for tree in self.repository.revision_trees(todo):
 
124
            trees[tree.get_revision_id()] = tree
 
125
            self.add(tree)
 
126
        return (trees[r] for r in revids)
 
127
 
 
128
    def revision_trees(self, revids):
 
129
        return list(self.iter_revision_trees(revids))
 
130
 
 
131
    def add(self, tree):
 
132
        self._cache[tree.get_revision_id()] = tree
 
133
 
 
134
 
 
135
def _find_missing_bzr_revids(graph, want, have):
 
136
    """Find the revisions that have to be pushed.
 
137
 
 
138
    :param get_parent_map: Function that returns the parents for a sequence
 
139
        of revisions.
 
140
    :param want: Revisions the target wants
 
141
    :param have: Revisions the target already has
 
142
    :return: Set of revisions to fetch
 
143
    """
 
144
    handled = set(have)
 
145
    todo = set()
 
146
    for rev in want:
 
147
        extra_todo = graph.find_unique_ancestors(rev, handled)
 
148
        todo.update(extra_todo)
 
149
        handled.update(extra_todo)
 
150
    if NULL_REVISION in todo:
 
151
        todo.remove(NULL_REVISION)
 
152
    return todo
 
153
 
 
154
 
 
155
def _check_expected_sha(expected_sha, object):
 
156
    """Check whether an object matches an expected SHA.
 
157
 
 
158
    :param expected_sha: None or expected SHA as either binary or as hex digest
 
159
    :param object: Object to verify
 
160
    """
 
161
    if expected_sha is None:
 
162
        return
 
163
    if len(expected_sha) == 40:
 
164
        if expected_sha != object.sha().hexdigest().encode('ascii'):
 
165
            raise AssertionError("Invalid sha for %r: %s" % (object,
 
166
                                                             expected_sha))
 
167
    elif len(expected_sha) == 20:
 
168
        if expected_sha != object.sha().digest():
 
169
            raise AssertionError("Invalid sha for %r: %s" % (
 
170
                object, sha_to_hex(expected_sha)))
 
171
    else:
 
172
        raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
 
173
                                                           expected_sha))
 
174
 
 
175
 
 
176
def directory_to_tree(path, children, lookup_ie_sha1, unusual_modes,
 
177
                      empty_file_name, allow_empty=False):
 
178
    """Create a Git Tree object from a Bazaar directory.
 
179
 
 
180
    :param path: directory path
 
181
    :param children: Children inventory entries
 
182
    :param lookup_ie_sha1: Lookup the Git SHA1 for a inventory entry
 
183
    :param unusual_modes: Dictionary with unusual file modes by file ids
 
184
    :param empty_file_name: Name to use for dummy files in empty directories,
 
185
        None to ignore empty directories.
 
186
    """
 
187
    tree = Tree()
 
188
    for value in children:
 
189
        if value.name in BANNED_FILENAMES:
 
190
            continue
 
191
        child_path = osutils.pathjoin(path, value.name)
 
192
        try:
 
193
            mode = unusual_modes[child_path]
 
194
        except KeyError:
 
195
            mode = entry_mode(value)
 
196
        hexsha = lookup_ie_sha1(child_path, value)
 
197
        if hexsha is not None:
 
198
            tree.add(value.name.encode("utf-8"), mode, hexsha)
 
199
    if not allow_empty and len(tree) == 0:
 
200
        # Only the root can be an empty tree
 
201
        if empty_file_name is not None:
 
202
            tree.add(empty_file_name, stat.S_IFREG | 0o644, Blob().id)
 
203
        else:
 
204
            return None
 
205
    return tree
 
206
 
 
207
 
 
208
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
 
209
                     dummy_file_name=None, add_cache_entry=None):
 
210
    """Iterate over the objects that were introduced in a revision.
 
211
 
 
212
    :param idmap: id map
 
213
    :param parent_trees: Parent revision trees
 
214
    :param unusual_modes: Unusual file modes dictionary
 
215
    :param dummy_file_name: File name to use for dummy files
 
216
        in empty directories. None to skip empty directories
 
217
    :return: Yields (path, object, ie) entries
 
218
    """
 
219
    dirty_dirs = set()
 
220
    new_blobs = []
 
221
    shamap = {}
 
222
    try:
 
223
        base_tree = parent_trees[0]
 
224
        other_parent_trees = parent_trees[1:]
 
225
    except IndexError:
 
226
        base_tree = tree._repository.revision_tree(NULL_REVISION)
 
227
        other_parent_trees = []
 
228
 
 
229
    def find_unchanged_parent_ie(path, kind, other, parent_trees):
 
230
        for ptree in parent_trees:
 
231
            intertree = InterTree.get(ptree, tree)
 
232
            ppath = intertree.find_source_path(path)
 
233
            if ppath is not None:
 
234
                pkind = ptree.kind(ppath)
 
235
                if kind == "file":
 
236
                    if (pkind == "file" and
 
237
                            ptree.get_file_sha1(ppath) == other):
 
238
                        return (
 
239
                            ptree.path2id(ppath), ptree.get_file_revision(ppath))
 
240
                if kind == "symlink":
 
241
                    if (pkind == "symlink" and
 
242
                            ptree.get_symlink_target(ppath) == other):
 
243
                        return (
 
244
                            ptree.path2id(ppath), ptree.get_file_revision(ppath))
 
245
        raise KeyError
 
246
 
 
247
    # Find all the changed blobs
 
248
    for change in tree.iter_changes(base_tree):
 
249
        if change.name[1] in BANNED_FILENAMES:
 
250
            continue
 
251
        if change.kind[1] == "file":
 
252
            sha1 = tree.get_file_sha1(change.path[1])
 
253
            blob_id = None
 
254
            try:
 
255
                (pfile_id, prevision) = find_unchanged_parent_ie(
 
256
                    change.path[1], change.kind[1], sha1, other_parent_trees)
 
257
            except KeyError:
 
258
                pass
 
259
            else:
 
260
                # It existed in one of the parents, with the same contents.
 
261
                # So no need to yield any new git objects.
 
262
                try:
 
263
                    blob_id = idmap.lookup_blob_id(
 
264
                        pfile_id, prevision)
 
265
                except KeyError:
 
266
                    if not change.changed_content:
 
267
                        # no-change merge ?
 
268
                        blob = Blob()
 
269
                        blob.data = tree.get_file_text(change.path[1])
 
270
                        blob_id = blob.id
 
271
            if blob_id is None:
 
272
                new_blobs.append((change.path[1], change.file_id))
 
273
            else:
 
274
                # TODO(jelmer): This code path does not have any test coverage.
 
275
                shamap[change.path[1]] = blob_id
 
276
                if add_cache_entry is not None:
 
277
                    add_cache_entry(
 
278
                        ("blob", blob_id),
 
279
                        (change.file_id, tree.get_file_revision(change.path[1])), change.path[1])
 
280
        elif change.kind[1] == "symlink":
 
281
            target = tree.get_symlink_target(change.path[1])
 
282
            blob = symlink_to_blob(target)
 
283
            shamap[change.path[1]] = blob.id
 
284
            if add_cache_entry is not None:
 
285
                add_cache_entry(
 
286
                    blob, (change.file_id, tree.get_file_revision(change.path[1])), change.path[1])
 
287
            try:
 
288
                find_unchanged_parent_ie(
 
289
                    change.path[1], change.kind[1], target, other_parent_trees)
 
290
            except KeyError:
 
291
                if change.changed_content:
 
292
                    yield (change.path[1], blob,
 
293
                           (change.file_id, tree.get_file_revision(change.path[1])))
 
294
        elif change.kind[1] is None:
 
295
            shamap[change.path[1]] = None
 
296
        elif change.kind[1] != 'directory':
 
297
            raise AssertionError(change.kind[1])
 
298
        for p in change.path:
 
299
            if p is None:
 
300
                continue
 
301
            dirty_dirs.add(osutils.dirname(p))
 
302
 
 
303
    # Fetch contents of the blobs that were changed
 
304
    for (path, file_id), chunks in tree.iter_files_bytes(
 
305
            [(path, (path, file_id)) for (path, file_id) in new_blobs]):
 
306
        obj = Blob()
 
307
        obj.chunked = chunks
 
308
        if add_cache_entry is not None:
 
309
            add_cache_entry(obj, (file_id, tree.get_file_revision(path)), path)
 
310
        yield path, obj, (file_id, tree.get_file_revision(path))
 
311
        shamap[path] = obj.id
 
312
 
 
313
    for path in unusual_modes:
 
314
        dirty_dirs.add(posixpath.dirname(path))
 
315
 
 
316
    for dir in list(dirty_dirs):
 
317
        for parent in osutils.parent_directories(dir):
 
318
            if parent in dirty_dirs:
 
319
                break
 
320
            dirty_dirs.add(parent)
 
321
 
 
322
    if dirty_dirs:
 
323
        dirty_dirs.add('')
 
324
 
 
325
    def ie_to_hexsha(path, ie):
 
326
        try:
 
327
            return shamap[path]
 
328
        except KeyError:
 
329
            pass
 
330
        # FIXME: Should be the same as in parent
 
331
        if ie.kind == "file":
 
332
            try:
 
333
                return idmap.lookup_blob_id(ie.file_id, ie.revision)
 
334
            except KeyError:
 
335
                # no-change merge ?
 
336
                blob = Blob()
 
337
                blob.data = tree.get_file_text(path)
 
338
                if add_cache_entry is not None:
 
339
                    add_cache_entry(blob, (ie.file_id, ie.revision), path)
 
340
                return blob.id
 
341
        elif ie.kind == "symlink":
 
342
            try:
 
343
                return idmap.lookup_blob_id(ie.file_id, ie.revision)
 
344
            except KeyError:
 
345
                # no-change merge ?
 
346
                target = tree.get_symlink_target(path)
 
347
                blob = symlink_to_blob(target)
 
348
                if add_cache_entry is not None:
 
349
                    add_cache_entry(blob, (ie.file_id, ie.revision), path)
 
350
                return blob.id
 
351
        elif ie.kind == "directory":
 
352
            # Not all cache backends store the tree information,
 
353
            # calculate again from scratch
 
354
            ret = directory_to_tree(
 
355
                path, ie.children.values(), ie_to_hexsha, unusual_modes,
 
356
                dummy_file_name, ie.parent_id is None)
 
357
            if ret is None:
 
358
                return ret
 
359
            return ret.id
 
360
        else:
 
361
            raise AssertionError
 
362
 
 
363
    for path in sorted(dirty_dirs, reverse=True):
 
364
        if not tree.has_filename(path):
 
365
            continue
 
366
 
 
367
        if tree.kind(path) != 'directory':
 
368
            continue
 
369
 
 
370
        obj = directory_to_tree(
 
371
            path, tree.iter_child_entries(path), ie_to_hexsha, unusual_modes,
 
372
            dummy_file_name, path == '')
 
373
 
 
374
        if obj is not None:
 
375
            file_id = tree.path2id(path)
 
376
            if add_cache_entry is not None:
 
377
                add_cache_entry(obj, (file_id, tree.get_revision_id()), path)
 
378
            yield path, obj, (file_id, tree.get_revision_id())
 
379
            shamap[path] = obj.id
 
380
 
 
381
 
 
382
class PackTupleIterable(object):
 
383
 
 
384
    def __init__(self, store):
 
385
        self.store = store
 
386
        self.store.lock_read()
 
387
        self.objects = {}
 
388
 
 
389
    def __del__(self):
 
390
        self.store.unlock()
 
391
 
 
392
    def add(self, sha, path):
 
393
        self.objects[sha] = path
 
394
 
 
395
    def __len__(self):
 
396
        return len(self.objects)
 
397
 
 
398
    def __iter__(self):
 
399
        return ((self.store[object_id], path) for (object_id, path) in
 
400
                self.objects.items())
 
401
 
 
402
 
 
403
class BazaarObjectStore(BaseObjectStore):
 
404
    """A Git-style object store backed onto a Bazaar repository."""
 
405
 
 
406
    def __init__(self, repository, mapping=None):
 
407
        self.repository = repository
 
408
        self._map_updated = False
 
409
        self._locked = None
 
410
        if mapping is None:
 
411
            self.mapping = default_mapping
 
412
        else:
 
413
            self.mapping = mapping
 
414
        self._cache = cache_from_repository(repository)
 
415
        self._content_cache_types = ("tree",)
 
416
        self.start_write_group = self._cache.idmap.start_write_group
 
417
        self.abort_write_group = self._cache.idmap.abort_write_group
 
418
        self.commit_write_group = self._cache.idmap.commit_write_group
 
419
        self.tree_cache = LRUTreeCache(self.repository)
 
420
        self.unpeel_map = UnpeelMap.from_repository(self.repository)
 
421
 
 
422
    def _missing_revisions(self, revisions):
 
423
        return self._cache.idmap.missing_revisions(revisions)
 
424
 
 
425
    def _update_sha_map(self, stop_revision=None):
 
426
        if not self.is_locked():
 
427
            raise errors.LockNotHeld(self)
 
428
        if self._map_updated:
 
429
            return
 
430
        if (stop_revision is not None and
 
431
                not self._missing_revisions([stop_revision])):
 
432
            return
 
433
        graph = self.repository.get_graph()
 
434
        if stop_revision is None:
 
435
            all_revids = self.repository.all_revision_ids()
 
436
            missing_revids = self._missing_revisions(all_revids)
 
437
        else:
 
438
            heads = set([stop_revision])
 
439
            missing_revids = self._missing_revisions(heads)
 
440
            while heads:
 
441
                parents = graph.get_parent_map(heads)
 
442
                todo = set()
 
443
                for p in parents.values():
 
444
                    todo.update([x for x in p if x not in missing_revids])
 
445
                heads = self._missing_revisions(todo)
 
446
                missing_revids.update(heads)
 
447
        if NULL_REVISION in missing_revids:
 
448
            missing_revids.remove(NULL_REVISION)
 
449
        missing_revids = self.repository.has_revisions(missing_revids)
 
450
        if not missing_revids:
 
451
            if stop_revision is None:
 
452
                self._map_updated = True
 
453
            return
 
454
        self.start_write_group()
 
455
        try:
 
456
            with ui.ui_factory.nested_progress_bar() as pb:
 
457
                for i, revid in enumerate(graph.iter_topo_order(
 
458
                        missing_revids)):
 
459
                    trace.mutter('processing %r', revid)
 
460
                    pb.update("updating git map", i, len(missing_revids))
 
461
                    self._update_sha_map_revision(revid)
 
462
            if stop_revision is None:
 
463
                self._map_updated = True
 
464
        except BaseException:
 
465
            self.abort_write_group()
 
466
            raise
 
467
        else:
 
468
            self.commit_write_group()
 
469
 
 
470
    def __iter__(self):
 
471
        self._update_sha_map()
 
472
        return iter(self._cache.idmap.sha1s())
 
473
 
 
474
    def _reconstruct_commit(self, rev, tree_sha, lossy, verifiers):
 
475
        """Reconstruct a Commit object.
 
476
 
 
477
        :param rev: Revision object
 
478
        :param tree_sha: SHA1 of the root tree object
 
479
        :param lossy: Whether or not to roundtrip bzr metadata
 
480
        :param verifiers: Verifiers for the commits
 
481
        :return: Commit object
 
482
        """
 
483
        def parent_lookup(revid):
 
484
            try:
 
485
                return self._lookup_revision_sha1(revid)
 
486
            except errors.NoSuchRevision:
 
487
                return None
 
488
        return self.mapping.export_commit(rev, tree_sha, parent_lookup,
 
489
                                          lossy, verifiers)
 
490
 
 
491
    def _revision_to_objects(self, rev, tree, lossy, add_cache_entry=None):
 
492
        """Convert a revision to a set of git objects.
 
493
 
 
494
        :param rev: Bazaar revision object
 
495
        :param tree: Bazaar revision tree
 
496
        :param lossy: Whether to not roundtrip all Bazaar revision data
 
497
        """
 
498
        unusual_modes = extract_unusual_modes(rev)
 
499
        present_parents = self.repository.has_revisions(rev.parent_ids)
 
500
        parent_trees = self.tree_cache.revision_trees(
 
501
            [p for p in rev.parent_ids if p in present_parents])
 
502
        root_tree = None
 
503
        for path, obj, bzr_key_data in _tree_to_objects(
 
504
                tree, parent_trees, self._cache.idmap, unusual_modes,
 
505
                self.mapping.BZR_DUMMY_FILE, add_cache_entry):
 
506
            if path == "":
 
507
                root_tree = obj
 
508
                root_key_data = bzr_key_data
 
509
                # Don't yield just yet
 
510
            else:
 
511
                yield path, obj
 
512
        if root_tree is None:
 
513
            # Pointless commit - get the tree sha elsewhere
 
514
            if not rev.parent_ids:
 
515
                root_tree = Tree()
 
516
            else:
 
517
                base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
 
518
                root_tree = self[self[base_sha1].tree]
 
519
            root_key_data = (tree.path2id(''), tree.get_revision_id())
 
520
        if add_cache_entry is not None:
 
521
            add_cache_entry(root_tree, root_key_data, "")
 
522
        yield "", root_tree
 
523
        if not lossy:
 
524
            testament3 = StrictTestament3(rev, tree)
 
525
            verifiers = {"testament3-sha1": testament3.as_sha1()}
 
526
        else:
 
527
            verifiers = {}
 
528
        commit_obj = self._reconstruct_commit(rev, root_tree.id,
 
529
                                              lossy=lossy, verifiers=verifiers)
 
530
        try:
 
531
            foreign_revid, mapping = mapping_registry.parse_revision_id(
 
532
                rev.revision_id)
 
533
        except errors.InvalidRevisionId:
 
534
            pass
 
535
        else:
 
536
            _check_expected_sha(foreign_revid, commit_obj)
 
537
        if add_cache_entry is not None:
 
538
            add_cache_entry(commit_obj, verifiers, None)
 
539
 
 
540
        yield None, commit_obj
 
541
 
 
542
    def _get_updater(self, rev):
 
543
        return self._cache.get_updater(rev)
 
544
 
 
545
    def _update_sha_map_revision(self, revid):
 
546
        rev = self.repository.get_revision(revid)
 
547
        tree = self.tree_cache.revision_tree(rev.revision_id)
 
548
        updater = self._get_updater(rev)
 
549
        # FIXME JRV 2011-12-15: Shouldn't we try both values for lossy ?
 
550
        for path, obj in self._revision_to_objects(
 
551
                rev, tree, lossy=(not self.mapping.roundtripping),
 
552
                add_cache_entry=updater.add_object):
 
553
            if isinstance(obj, Commit):
 
554
                commit_obj = obj
 
555
        commit_obj = updater.finish()
 
556
        return commit_obj.id
 
557
 
 
558
    def _reconstruct_blobs(self, keys):
 
559
        """Return a Git Blob object from a fileid and revision stored in bzr.
 
560
 
 
561
        :param fileid: File id of the text
 
562
        :param revision: Revision of the text
 
563
        """
 
564
        stream = self.repository.iter_files_bytes(
 
565
            ((key[0], key[1], key) for key in keys))
 
566
        for (file_id, revision, expected_sha), chunks in stream:
 
567
            blob = Blob()
 
568
            blob.chunked = chunks
 
569
            if blob.id != expected_sha and blob.data == b"":
 
570
                # Perhaps it's a symlink ?
 
571
                tree = self.tree_cache.revision_tree(revision)
 
572
                path = tree.id2path(file_id)
 
573
                if tree.kind(path) == 'symlink':
 
574
                    blob = symlink_to_blob(tree.get_symlink_target(path))
 
575
            _check_expected_sha(expected_sha, blob)
 
576
            yield blob
 
577
 
 
578
    def _reconstruct_tree(self, fileid, revid, bzr_tree, unusual_modes,
 
579
                          expected_sha=None):
 
580
        """Return a Git Tree object from a file id and a revision stored in bzr.
 
581
 
 
582
        :param fileid: fileid in the tree.
 
583
        :param revision: Revision of the tree.
 
584
        """
 
585
        def get_ie_sha1(path, entry):
 
586
            if entry.kind == "directory":
 
587
                try:
 
588
                    return self._cache.idmap.lookup_tree_id(entry.file_id,
 
589
                                                            revid)
 
590
                except (NotImplementedError, KeyError):
 
591
                    obj = self._reconstruct_tree(
 
592
                        entry.file_id, revid, bzr_tree, unusual_modes)
 
593
                    if obj is None:
 
594
                        return None
 
595
                    else:
 
596
                        return obj.id
 
597
            elif entry.kind in ("file", "symlink"):
 
598
                try:
 
599
                    return self._cache.idmap.lookup_blob_id(entry.file_id,
 
600
                                                            entry.revision)
 
601
                except KeyError:
 
602
                    # no-change merge?
 
603
                    return next(self._reconstruct_blobs(
 
604
                        [(entry.file_id, entry.revision, None)])).id
 
605
            elif entry.kind == 'tree-reference':
 
606
                # FIXME: Make sure the file id is the root id
 
607
                return self._lookup_revision_sha1(entry.reference_revision)
 
608
            else:
 
609
                raise AssertionError("unknown entry kind '%s'" % entry.kind)
 
610
        path = bzr_tree.id2path(fileid)
 
611
        tree = directory_to_tree(
 
612
            path,
 
613
            bzr_tree.iter_child_entries(path),
 
614
            get_ie_sha1, unusual_modes, self.mapping.BZR_DUMMY_FILE,
 
615
            bzr_tree.path2id('') == fileid)
 
616
        if tree is not None:
 
617
            _check_expected_sha(expected_sha, tree)
 
618
        return tree
 
619
 
 
620
    def get_parents(self, sha):
 
621
        """Retrieve the parents of a Git commit by SHA1.
 
622
 
 
623
        :param sha: SHA1 of the commit
 
624
        :raises: KeyError, NotCommitError
 
625
        """
 
626
        return self[sha].parents
 
627
 
 
628
    def _lookup_revision_sha1(self, revid):
 
629
        """Return the SHA1 matching a Bazaar revision."""
 
630
        if revid == NULL_REVISION:
 
631
            return ZERO_SHA
 
632
        try:
 
633
            return self._cache.idmap.lookup_commit(revid)
 
634
        except KeyError:
 
635
            try:
 
636
                return mapping_registry.parse_revision_id(revid)[0]
 
637
            except errors.InvalidRevisionId:
 
638
                self._update_sha_map(revid)
 
639
                return self._cache.idmap.lookup_commit(revid)
 
640
 
 
641
    def get_raw(self, sha):
 
642
        """Get the raw representation of a Git object by SHA1.
 
643
 
 
644
        :param sha: SHA1 of the git object
 
645
        """
 
646
        if len(sha) == 20:
 
647
            sha = sha_to_hex(sha)
 
648
        obj = self[sha]
 
649
        return (obj.type, obj.as_raw_string())
 
650
 
 
651
    def __contains__(self, sha):
 
652
        # See if sha is in map
 
653
        try:
 
654
            for (type, type_data) in self.lookup_git_sha(sha):
 
655
                if type == "commit":
 
656
                    if self.repository.has_revision(type_data[0]):
 
657
                        return True
 
658
                elif type == "blob":
 
659
                    if type_data in self.repository.texts:
 
660
                        return True
 
661
                elif type == "tree":
 
662
                    if self.repository.has_revision(type_data[1]):
 
663
                        return True
 
664
                else:
 
665
                    raise AssertionError("Unknown object type '%s'" % type)
 
666
            else:
 
667
                return False
 
668
        except KeyError:
 
669
            return False
 
670
 
 
671
    def lock_read(self):
 
672
        self._locked = 'r'
 
673
        self._map_updated = False
 
674
        self.repository.lock_read()
 
675
        return LogicalLockResult(self.unlock)
 
676
 
 
677
    def lock_write(self):
 
678
        self._locked = 'r'
 
679
        self._map_updated = False
 
680
        self.repository.lock_write()
 
681
        return LogicalLockResult(self.unlock)
 
682
 
 
683
    def is_locked(self):
 
684
        return (self._locked is not None)
 
685
 
 
686
    def unlock(self):
 
687
        self._locked = None
 
688
        self._map_updated = False
 
689
        self.repository.unlock()
 
690
 
 
691
    def lookup_git_shas(self, shas):
 
692
        ret = {}
 
693
        for sha in shas:
 
694
            if sha == ZERO_SHA:
 
695
                ret[sha] = [("commit", (NULL_REVISION, None, {}))]
 
696
                continue
 
697
            try:
 
698
                ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
 
699
            except KeyError:
 
700
                # if not, see if there are any unconverted revisions and
 
701
                # add them to the map, search for sha in map again
 
702
                self._update_sha_map()
 
703
                try:
 
704
                    ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
 
705
                except KeyError:
 
706
                    pass
 
707
        return ret
 
708
 
 
709
    def lookup_git_sha(self, sha):
 
710
        return self.lookup_git_shas([sha])[sha]
 
711
 
 
712
    def __getitem__(self, sha):
 
713
        for (kind, type_data) in self.lookup_git_sha(sha):
 
714
            # convert object to git object
 
715
            if kind == "commit":
 
716
                (revid, tree_sha, verifiers) = type_data
 
717
                try:
 
718
                    rev = self.repository.get_revision(revid)
 
719
                except errors.NoSuchRevision:
 
720
                    if revid == NULL_REVISION:
 
721
                        raise AssertionError(
 
722
                            "should not try to look up NULL_REVISION")
 
723
                    trace.mutter('entry for %s %s in shamap: %r, but not '
 
724
                                 'found in repository', kind, sha, type_data)
 
725
                    raise KeyError(sha)
 
726
                # FIXME: the type data should say whether conversion was
 
727
                # lossless
 
728
                commit = self._reconstruct_commit(
 
729
                    rev, tree_sha, lossy=(not self.mapping.roundtripping),
 
730
                    verifiers=verifiers)
 
731
                _check_expected_sha(sha, commit)
 
732
                return commit
 
733
            elif kind == "blob":
 
734
                (fileid, revision) = type_data
 
735
                blobs = self._reconstruct_blobs([(fileid, revision, sha)])
 
736
                return next(blobs)
 
737
            elif kind == "tree":
 
738
                (fileid, revid) = type_data
 
739
                try:
 
740
                    tree = self.tree_cache.revision_tree(revid)
 
741
                    rev = self.repository.get_revision(revid)
 
742
                except errors.NoSuchRevision:
 
743
                    trace.mutter(
 
744
                        'entry for %s %s in shamap: %r, but not found in '
 
745
                        'repository', kind, sha, type_data)
 
746
                    raise KeyError(sha)
 
747
                unusual_modes = extract_unusual_modes(rev)
 
748
                try:
 
749
                    return self._reconstruct_tree(
 
750
                        fileid, revid, tree, unusual_modes, expected_sha=sha)
 
751
                except errors.NoSuchRevision:
 
752
                    raise KeyError(sha)
 
753
            else:
 
754
                raise AssertionError("Unknown object type '%s'" % kind)
 
755
        else:
 
756
            raise KeyError(sha)
 
757
 
 
758
    def generate_lossy_pack_data(self, have, want, progress=None,
 
759
                                 get_tagged=None, ofs_delta=False):
 
760
        return pack_objects_to_data(
 
761
            self.generate_pack_contents(have, want, progress, get_tagged,
 
762
                                        lossy=True))
 
763
 
 
764
    def generate_pack_contents(self, have, want, progress=None,
 
765
                               ofs_delta=False, get_tagged=None, lossy=False):
 
766
        """Iterate over the contents of a pack file.
 
767
 
 
768
        :param have: List of SHA1s of objects that should not be sent
 
769
        :param want: List of SHA1s of objects that should be sent
 
770
        """
 
771
        processed = set()
 
772
        ret = self.lookup_git_shas(have + want)
 
773
        for commit_sha in have:
 
774
            commit_sha = self.unpeel_map.peel_tag(commit_sha, commit_sha)
 
775
            try:
 
776
                for (type, type_data) in ret[commit_sha]:
 
777
                    if type != "commit":
 
778
                        raise AssertionError("Type was %s, not commit" % type)
 
779
                    processed.add(type_data[0])
 
780
            except KeyError:
 
781
                trace.mutter("unable to find remote ref %s", commit_sha)
 
782
        pending = set()
 
783
        for commit_sha in want:
 
784
            if commit_sha in have:
 
785
                continue
 
786
            try:
 
787
                for (type, type_data) in ret[commit_sha]:
 
788
                    if type != "commit":
 
789
                        raise AssertionError("Type was %s, not commit" % type)
 
790
                    pending.add(type_data[0])
 
791
            except KeyError:
 
792
                pass
 
793
 
 
794
        graph = self.repository.get_graph()
 
795
        todo = _find_missing_bzr_revids(graph, pending, processed)
 
796
        ret = PackTupleIterable(self)
 
797
        with ui.ui_factory.nested_progress_bar() as pb:
 
798
            for i, revid in enumerate(graph.iter_topo_order(todo)):
 
799
                pb.update("generating git objects", i, len(todo))
 
800
                try:
 
801
                    rev = self.repository.get_revision(revid)
 
802
                except errors.NoSuchRevision:
 
803
                    continue
 
804
                tree = self.tree_cache.revision_tree(revid)
 
805
                for path, obj in self._revision_to_objects(
 
806
                        rev, tree, lossy=lossy):
 
807
                    ret.add(obj.id, path)
 
808
            return ret
 
809
 
 
810
    def add_thin_pack(self):
 
811
        import tempfile
 
812
        import os
 
813
        fd, path = tempfile.mkstemp(suffix=".pack")
 
814
        f = os.fdopen(fd, 'wb')
 
815
 
 
816
        def commit():
 
817
            from .fetch import import_git_objects
 
818
            os.fsync(fd)
 
819
            f.close()
 
820
            if os.path.getsize(path) == 0:
 
821
                return
 
822
            pd = PackData(path)
 
823
            pd.create_index_v2(path[:-5] + ".idx", self.object_store.get_raw)
 
824
 
 
825
            p = Pack(path[:-5])
 
826
            with self.repository.lock_write():
 
827
                self.repository.start_write_group()
 
828
                try:
 
829
                    import_git_objects(self.repository, self.mapping,
 
830
                                       p.iterobjects(get_raw=self.get_raw),
 
831
                                       self.object_store)
 
832
                except BaseException:
 
833
                    self.repository.abort_write_group()
 
834
                    raise
 
835
                else:
 
836
                    self.repository.commit_write_group()
 
837
        return f, commit
 
838
 
 
839
    # The pack isn't kept around anyway, so no point
 
840
    # in treating full packs different from thin packs
 
841
    add_pack = add_thin_pack