/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: 2019-02-03 01:42:11 UTC
  • mto: This revision was merged to the branch mainline in revision 7267.
  • Revision ID: jelmer@jelmer.uk-20190203014211-poj1fv922sejfsb4
Don't require that short git shas have an even number of characters.

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