/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: 2017-07-23 22:06:41 UTC
  • mfrom: (6738 trunk)
  • mto: This revision was merged to the branch mainline in revision 6739.
  • Revision ID: jelmer@jelmer.uk-20170723220641-69eczax9bmv8d6kk
Merge trunk, address review comments.

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