/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
0.200.1613 by Jelmer Vernooij
Handle encoding better in working tree iter changes.
2
# Copyright (C) 2012 Canonical Ltd
0.200.228 by Jelmer Vernooij
Split out map.
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
0.358.1 by Jelmer Vernooij
Fix FSF address.
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.228 by Jelmer Vernooij
Split out map.
17
18
"""Map from Git sha's to Bazaar objects."""
19
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
20
from __future__ import absolute_import
21
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
22
from dulwich.objects import (
23
    Blob,
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
24
    Commit,
0.200.864 by Jelmer Vernooij
Cope with the first commit being pointless.
25
    Tree,
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
26
    sha_to_hex,
0.200.1153 by Jelmer Vernooij
Import ZERO_SHA from dulwich.objects.
27
    ZERO_SHA,
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
28
    )
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
29
from dulwich.object_store import (
0.200.457 by Jelmer Vernooij
Use BaseObjectStore.
30
    BaseObjectStore,
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
31
    )
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
32
from dulwich.pack import (
33
    pack_objects_to_data,
34
    )
0.200.249 by Jelmer Vernooij
Implement Tree.
35
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
36
from ... import (
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
37
    errors,
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
38
    lru_cache,
0.200.478 by Jelmer Vernooij
Cope with disappeared revisions.
39
    trace,
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
40
    ui,
0.200.773 by Jelmer Vernooij
Implement inventory_to_objects
41
    urlutils,
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
42
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
43
from ...lock import LogicalLockResult
44
from ...revision import (
0.200.541 by Jelmer Vernooij
Cope with NULL_REVISION.
45
    NULL_REVISION,
46
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
47
from ...testament import(
0.200.1023 by Jelmer Vernooij
Set and verify testament.
48
    StrictTestament3,
49
    )
0.200.228 by Jelmer Vernooij
Split out map.
50
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
51
from .cache import (
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
52
    from_repository as cache_from_repository,
53
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
54
from .mapping import (
0.200.463 by Jelmer Vernooij
Support remote dpush (except for references).
55
    default_mapping,
0.200.359 by Jelmer Vernooij
Simplify file mode handling, avoid inventory_to_tree_and_blobs as it is expensive if trees/blobs have already been converted.
56
    directory_to_tree,
0.200.548 by Jelmer Vernooij
Extract unusual file modes from revision when reconstructing Trees.
57
    extract_unusual_modes,
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
58
    mapping_registry,
0.200.795 by Jelmer Vernooij
simplify sha extraction for blobs, process multiple blobs at once.
59
    symlink_to_blob,
0.200.229 by Jelmer Vernooij
More work on converter.
60
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
61
from .unpeel_map import (
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
62
    UnpeelMap,
0.200.231 by Jelmer Vernooij
Partially fix pull.
63
    )
64
0.200.878 by Jelmer Vernooij
Fix determining of unusual file modes.
65
import posixpath
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
66
import stat
0.200.878 by Jelmer Vernooij
Fix determining of unusual file modes.
67
0.200.228 by Jelmer Vernooij
Split out map.
68
0.200.452 by Jelmer Vernooij
Rename converter -> object_store, provide utility function for getting ObjectStore's.
69
def get_object_store(repo, mapping=None):
70
    git = getattr(repo, "_git", None)
71
    if git is not None:
0.200.1303 by Jelmer Vernooij
Fix locking.
72
        git.object_store.unlock = lambda: None
73
        git.object_store.lock_read = lambda: LogicalLockResult(lambda: None)
74
        git.object_store.lock_write = lambda: LogicalLockResult(lambda: None)
0.200.452 by Jelmer Vernooij
Rename converter -> object_store, provide utility function for getting ObjectStore's.
75
        return git.object_store
76
    return BazaarObjectStore(repo, mapping)
77
78
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
79
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
80
81
82
class LRUTreeCache(object):
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
83
84
    def __init__(self, repository):
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
85
        def approx_tree_size(tree):
0.275.1 by Jelmer Vernooij
Use root_inventory.
86
            # Very rough estimate, 250 per inventory entry
0.275.5 by Jelmer Vernooij
Cope with root_inventory and inventory.
87
            try:
88
                inv = tree.root_inventory
89
            except AttributeError:
90
                inv = tree.inventory
91
            return len(inv) * 250
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
92
        self.repository = repository
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
93
        self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
94
            after_cleanup_size=None, compute_size=approx_tree_size)
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
95
0.200.963 by Jelmer Vernooij
Add some tests for LRUTreeCache.
96
    def revision_tree(self, revid):
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
97
        try:
0.200.989 by Jelmer Vernooij
Add asserts.
98
            tree = self._cache[revid]
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
99
        except KeyError:
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
100
            tree = self.repository.revision_tree(revid)
101
            self.add(tree)
0.200.989 by Jelmer Vernooij
Add asserts.
102
        return tree
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
103
104
    def iter_revision_trees(self, revids):
0.200.989 by Jelmer Vernooij
Add asserts.
105
        trees = {}
106
        todo = []
107
        for revid in revids:
108
            try:
109
                tree = self._cache[revid]
110
            except KeyError:
111
                todo.append(revid)
112
            else:
0.361.1 by Jelmer Vernooij
Don't use assert.
113
                if tree.get_revision_id() != revid:
114
                    raise AssertionError(
115
                            "revision id did not match: %s != %s" % (
116
                                tree.get_revision_id(), revid))
0.200.989 by Jelmer Vernooij
Add asserts.
117
                trees[revid] = tree
118
        for tree in self.repository.revision_trees(todo):
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
119
            trees[tree.get_revision_id()] = tree
120
            self.add(tree)
121
        return (trees[r] for r in revids)
122
123
    def revision_trees(self, revids):
124
        return list(self.iter_revision_trees(revids))
125
126
    def add(self, tree):
0.270.1 by Martin
Avoid the deprecated LRUSizeCache.add method
127
        self._cache[tree.get_revision_id()] = tree
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
128
129
0.200.1053 by Jelmer Vernooij
Fix find_missing_bzr_revids.
130
def _find_missing_bzr_revids(graph, want, have):
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
131
    """Find the revisions that have to be pushed.
132
133
    :param get_parent_map: Function that returns the parents for a sequence
134
        of revisions.
135
    :param want: Revisions the target wants
136
    :param have: Revisions the target already has
137
    :return: Set of revisions to fetch
138
    """
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
139
    handled = set(have)
0.200.899 by Jelmer Vernooij
Add tests for find_missing_bzr_revids.
140
    todo = set()
0.200.1053 by Jelmer Vernooij
Fix find_missing_bzr_revids.
141
    for rev in want:
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
142
        extra_todo = graph.find_unique_ancestors(rev, handled)
143
        todo.update(extra_todo)
144
        handled.update(extra_todo)
0.200.899 by Jelmer Vernooij
Add tests for find_missing_bzr_revids.
145
    if NULL_REVISION in todo:
146
        todo.remove(NULL_REVISION)
147
    return todo
148
149
0.200.793 by Jelmer Vernooij
Make _check_expected_sha a global fn.
150
def _check_expected_sha(expected_sha, object):
0.200.797 by Jelmer Vernooij
Add docstring, fix formatting.
151
    """Check whether an object matches an expected SHA.
152
153
    :param expected_sha: None or expected SHA as either binary or as hex digest
154
    :param object: Object to verify
155
    """
0.200.793 by Jelmer Vernooij
Make _check_expected_sha a global fn.
156
    if expected_sha is None:
157
        return
158
    if len(expected_sha) == 40:
159
        if expected_sha != object.sha().hexdigest():
0.200.797 by Jelmer Vernooij
Add docstring, fix formatting.
160
            raise AssertionError("Invalid sha for %r: %s" % (object,
161
                expected_sha))
0.200.793 by Jelmer Vernooij
Make _check_expected_sha a global fn.
162
    elif len(expected_sha) == 20:
163
        if expected_sha != object.sha().digest():
0.200.797 by Jelmer Vernooij
Add docstring, fix formatting.
164
            raise AssertionError("Invalid sha for %r: %s" % (object,
165
                sha_to_hex(expected_sha)))
0.200.793 by Jelmer Vernooij
Make _check_expected_sha a global fn.
166
    else:
0.200.797 by Jelmer Vernooij
Add docstring, fix formatting.
167
        raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
168
            expected_sha))
0.200.793 by Jelmer Vernooij
Make _check_expected_sha a global fn.
169
170
0.200.931 by Jelmer Vernooij
Update docstring, deal with kind changes appropriately in _tree_to_objects
171
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
172
                     dummy_file_name=None):
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
173
    """Iterate over the objects that were introduced in a revision.
174
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
175
    :param idmap: id map
0.200.931 by Jelmer Vernooij
Update docstring, deal with kind changes appropriately in _tree_to_objects
176
    :param parent_trees: Parent revision trees
177
    :param unusual_modes: Unusual file modes dictionary
0.252.30 by Jelmer Vernooij
Support creating dummy files for empty directories.
178
    :param dummy_file_name: File name to use for dummy files
179
        in empty directories. None to skip empty directories
0.200.837 by Jelmer Vernooij
Return inventory entries when creating git objects for a revision.
180
    :return: Yields (path, object, ie) entries
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
181
    """
0.282.1 by William Grant
Rework _tree_to_objects to work out parents by ID, not path. Fixes weirdness with various directory renames.
182
    dirty_dirs = set()
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
183
    new_blobs = []
184
    shamap = {}
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
185
    try:
186
        base_tree = parent_trees[0]
187
        other_parent_trees = parent_trees[1:]
188
    except IndexError:
189
        base_tree = tree._repository.revision_tree(NULL_REVISION)
190
        other_parent_trees = []
0.275.1 by Jelmer Vernooij
Use root_inventory.
191
    def find_unchanged_parent_ie(file_id, kind, other, parent_trees):
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
192
        for ptree in parent_trees:
193
            try:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
194
                ppath = ptree.id2path(file_id)
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
195
            except errors.NoSuchId:
196
                pass
197
            else:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
198
                pkind = ptree.kind(ppath, file_id)
0.275.1 by Jelmer Vernooij
Use root_inventory.
199
                if kind == "file":
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
200
                    if (pkind == "file" and
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
201
                        ptree.get_file_sha1(ppath, file_id) == other):
202
                        return (file_id, ptree.get_file_revision(ppath, file_id))
0.275.1 by Jelmer Vernooij
Use root_inventory.
203
                if kind == "symlink":
204
                    if (pkind == "symlink" and
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
205
                        ptree.get_symlink_target(ppath, file_id) == other):
206
                        return (file_id, ptree.get_file_revision(ppath, file_id))
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
207
        raise KeyError
0.200.965 by Jelmer Vernooij
Formatting fixes.
208
0.200.931 by Jelmer Vernooij
Update docstring, deal with kind changes appropriately in _tree_to_objects
209
    # Find all the changed blobs
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
210
    for (file_id, path, changed_content, versioned, parent, name, kind,
211
         executable) in tree.iter_changes(base_tree):
212
        if kind[1] == "file":
213
            if changed_content:
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
214
                try:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
215
                    (pfile_id, prevision) = find_unchanged_parent_ie(file_id, kind[1], tree.get_file_sha1(path[1], file_id), other_parent_trees)
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
216
                except KeyError:
217
                    pass
218
                else:
0.252.40 by Jelmer Vernooij
Checks for roundtripping.
219
                    try:
0.275.1 by Jelmer Vernooij
Use root_inventory.
220
                        shamap[file_id] = idmap.lookup_blob_id(
0.200.1575 by Jelmer Vernooij
Fix name error.
221
                            pfile_id, prevision)
0.252.40 by Jelmer Vernooij
Checks for roundtripping.
222
                    except KeyError:
223
                        # no-change merge ?
224
                        blob = Blob()
0.326.1 by Jelmer Vernooij
Update objectstore to new API.
225
                        blob.data = tree.get_file_text(path[1], file_id)
0.275.1 by Jelmer Vernooij
Use root_inventory.
226
                        shamap[file_id] = blob.id
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
227
            if not file_id in shamap:
0.275.1 by Jelmer Vernooij
Use root_inventory.
228
                new_blobs.append((path[1], file_id))
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
229
        elif kind[1] == "symlink":
230
            if changed_content:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
231
                target = tree.get_symlink_target(path[1], file_id)
0.275.1 by Jelmer Vernooij
Use root_inventory.
232
                blob = symlink_to_blob(target)
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
233
                shamap[file_id] = blob.id
234
                try:
0.275.1 by Jelmer Vernooij
Use root_inventory.
235
                    find_unchanged_parent_ie(file_id, kind[1], target, other_parent_trees)
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
236
                except KeyError:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
237
                    yield path[1], blob, (file_id, tree.get_file_revision(path[1], file_id))
0.250.3 by Jelmer Vernooij
Simplify..
238
        elif kind[1] not in (None, "directory"):
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
239
            raise AssertionError(kind[1])
0.282.2 by William Grant
Always dirty both parents, fixing weird directory rename cases.
240
        for p in parent:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
241
            if p and tree.has_id(p) and tree.kind(tree.id2path(p)) == "directory":
0.282.2 by William Grant
Always dirty both parents, fixing weird directory rename cases.
242
                dirty_dirs.add(p)
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
243
0.200.931 by Jelmer Vernooij
Update docstring, deal with kind changes appropriately in _tree_to_objects
244
    # Fetch contents of the blobs that were changed
0.275.1 by Jelmer Vernooij
Use root_inventory.
245
    for (path, file_id), chunks in tree.iter_files_bytes(
0.387.1 by Jelmer Vernooij
Fix iter_files_bytes implementation.
246
        [(path, (path, file_id)) for (path, file_id) in new_blobs]):
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
247
        obj = Blob()
0.200.851 by Jelmer Vernooij
Use blob.chunked.
248
        obj.chunked = chunks
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
249
        yield path, obj, (file_id, tree.get_file_revision(path, file_id))
0.275.1 by Jelmer Vernooij
Use root_inventory.
250
        shamap[file_id] = obj.id
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
251
0.200.879 by Jelmer Vernooij
Fix unusual modes.
252
    for path in unusual_modes:
253
        parent_path = posixpath.dirname(path)
0.200.1577 by Jelmer Vernooij
Add assertion.
254
        file_id = tree.path2id(parent_path)
0.361.1 by Jelmer Vernooij
Don't use assert.
255
        if file_id is None:
256
            raise AssertionError("Unable to find file id for %r" % parent_path)
0.282.1 by William Grant
Rework _tree_to_objects to work out parents by ID, not path. Fixes weirdness with various directory renames.
257
        dirty_dirs.add(file_id)
258
259
    try:
260
        inv = tree.root_inventory
261
    except AttributeError:
262
        inv = tree.inventory
0.200.989 by Jelmer Vernooij
Add asserts.
263
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
264
    trees = {}
0.282.1 by William Grant
Rework _tree_to_objects to work out parents by ID, not path. Fixes weirdness with various directory renames.
265
    while dirty_dirs:
266
        new_dirs = set()
267
        for file_id in dirty_dirs:
268
            if file_id is None or not inv.has_id(file_id):
269
                continue
270
            trees[inv.id2path(file_id)] = file_id
0.390.4 by Jelmer Vernooij
Update for new Inventory API.
271
            ie = inv.get_entry(file_id)
0.282.1 by William Grant
Rework _tree_to_objects to work out parents by ID, not path. Fixes weirdness with various directory renames.
272
            if ie.parent_id is not None:
273
                new_dirs.add(ie.parent_id)
274
        dirty_dirs = new_dirs
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
275
0.200.808 by Jelmer Vernooij
Avoid recalculating tree shas we already have.
276
    def ie_to_hexsha(ie):
277
        try:
278
            return shamap[ie.file_id]
279
        except KeyError:
0.200.884 by Jelmer Vernooij
Cope with -0000 as timezone in Git commits.
280
            # FIXME: Should be the same as in parent
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
281
            if ie.kind in ("file", "symlink"):
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
282
                try:
283
                    return idmap.lookup_blob_id(ie.file_id, ie.revision)
284
                except KeyError:
285
                    # no-change merge ?
286
                    blob = Blob()
0.200.1725 by Jelmer Vernooij
Use path in argument to get_file_text.
287
                    path = tree.id2path(ie.file_id)
288
                    blob.data = tree.get_file_text(path, ie.file_id)
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
289
                    return blob.id
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
290
            elif ie.kind == "directory":
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
291
                # Not all cache backends store the tree information,
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
292
                # calculate again from scratch
0.275.4 by Jelmer Vernooij
Pass children list to directory_to_tree .
293
                ret = directory_to_tree(ie.children, ie_to_hexsha,
0.200.1573 by Jelmer Vernooij
Fix regression in allowing empty directory check.
294
                    unusual_modes, dummy_file_name, ie.parent_id is None)
0.250.1 by Jelmer Vernooij
Use iter_changes() rather than iterating over all contents of an inventory.
295
                if ret is None:
296
                    return ret
297
                return ret.id
298
            else:
299
                raise AssertionError
0.200.808 by Jelmer Vernooij
Avoid recalculating tree shas we already have.
300
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
301
    for path in sorted(trees.keys(), reverse=True):
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
302
        file_id = trees[path]
0.361.1 by Jelmer Vernooij
Don't use assert.
303
        if tree.kind(path, file_id) != 'directory':
304
            raise AssertionError
0.390.4 by Jelmer Vernooij
Update for new Inventory API.
305
        ie = inv.get_entry(file_id)
0.275.4 by Jelmer Vernooij
Pass children list to directory_to_tree .
306
        obj = directory_to_tree(ie.children, ie_to_hexsha, unusual_modes,
307
            dummy_file_name, path == "")
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
308
        if obj is not None:
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
309
            yield path, obj, (file_id, )
310
            shamap[file_id] = obj.id
0.200.798 by Jelmer Vernooij
Split out _inventory_to_objects into a function.
311
312
0.200.1290 by Jelmer Vernooij
Avoid storing all objects to push in memory.
313
class PackTupleIterable(object):
314
315
    def __init__(self, store):
316
        self.store = store
0.200.1432 by Jelmer Vernooij
Make sure object store is locked/unlocked.
317
        self.store.lock_read()
0.200.1290 by Jelmer Vernooij
Avoid storing all objects to push in memory.
318
        self.objects = {}
319
0.200.1432 by Jelmer Vernooij
Make sure object store is locked/unlocked.
320
    def __del__(self):
321
        self.store.unlock()
322
0.200.1290 by Jelmer Vernooij
Avoid storing all objects to push in memory.
323
    def add(self, sha, path):
324
        self.objects[sha] = path
325
326
    def __len__(self):
327
        return len(self.objects)
328
329
    def __iter__(self):
330
        return ((self.store[object_id], path) for (object_id, path) in
331
                self.objects.iteritems())
332
333
0.200.457 by Jelmer Vernooij
Use BaseObjectStore.
334
class BazaarObjectStore(BaseObjectStore):
0.200.320 by Jelmer Vernooij
Handle lightweight checkouts.
335
    """A Git-style object store backed onto a Bazaar repository."""
0.200.228 by Jelmer Vernooij
Split out map.
336
337
    def __init__(self, repository, mapping=None):
338
        self.repository = repository
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
339
        self._map_updated = False
340
        self._locked = None
0.200.228 by Jelmer Vernooij
Split out map.
341
        if mapping is None:
0.200.463 by Jelmer Vernooij
Support remote dpush (except for references).
342
            self.mapping = default_mapping
0.200.228 by Jelmer Vernooij
Split out map.
343
        else:
344
            self.mapping = mapping
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
345
        self._cache = cache_from_repository(repository)
0.200.1291 by Jelmer Vernooij
add hook for updating to local git cache.
346
        self._content_cache_types = ("tree",)
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
347
        self.start_write_group = self._cache.idmap.start_write_group
348
        self.abort_write_group = self._cache.idmap.abort_write_group
349
        self.commit_write_group = self._cache.idmap.commit_write_group
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
350
        self.tree_cache = LRUTreeCache(self.repository)
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
351
        self.unpeel_map = UnpeelMap.from_repository(self.repository)
0.200.228 by Jelmer Vernooij
Split out map.
352
0.200.1319 by Jelmer Vernooij
Only update git cache during post-commit if parents are already in the cache.
353
    def _missing_revisions(self, revisions):
354
        return self._cache.idmap.missing_revisions(revisions)
355
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
356
    def _update_sha_map(self, stop_revision=None):
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
357
        if not self.is_locked():
358
            raise AssertionError()
359
        if self._map_updated:
360
            return
0.200.1264 by Jelmer Vernooij
Fix updating cache for single revision - don't consider it an update of the full cache.
361
        if (stop_revision is not None and
0.200.1319 by Jelmer Vernooij
Only update git cache during post-commit if parents are already in the cache.
362
            not self._missing_revisions([stop_revision])):
0.200.1264 by Jelmer Vernooij
Fix updating cache for single revision - don't consider it an update of the full cache.
363
            return
0.200.683 by Jelmer Vernooij
Lazier checking of which revisions need to be fetched.
364
        graph = self.repository.get_graph()
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
365
        if stop_revision is None:
0.200.1301 by Jelmer Vernooij
Avoid expensive get_parent_map call.
366
            all_revids = self.repository.all_revision_ids()
0.200.1319 by Jelmer Vernooij
Only update git cache during post-commit if parents are already in the cache.
367
            missing_revids = self._missing_revisions(all_revids)
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
368
        else:
0.200.683 by Jelmer Vernooij
Lazier checking of which revisions need to be fetched.
369
            heads = set([stop_revision])
0.200.1319 by Jelmer Vernooij
Only update git cache during post-commit if parents are already in the cache.
370
            missing_revids = self._missing_revisions(heads)
0.200.1301 by Jelmer Vernooij
Avoid expensive get_parent_map call.
371
            while heads:
372
                parents = graph.get_parent_map(heads)
373
                todo = set()
374
                for p in parents.values():
375
                    todo.update([x for x in p if x not in missing_revids])
0.200.1319 by Jelmer Vernooij
Only update git cache during post-commit if parents are already in the cache.
376
                heads = self._missing_revisions(todo)
0.200.1301 by Jelmer Vernooij
Avoid expensive get_parent_map call.
377
                missing_revids.update(heads)
0.200.694 by Jelmer Vernooij
Avoid processing NULL_REVISION.
378
        if NULL_REVISION in missing_revids:
379
            missing_revids.remove(NULL_REVISION)
0.254.16 by Jelmer Vernooij
Add optimization preventing recursive index updating.
380
        missing_revids = self.repository.has_revisions(missing_revids)
381
        if not missing_revids:
0.200.1264 by Jelmer Vernooij
Fix updating cache for single revision - don't consider it an update of the full cache.
382
            if stop_revision is None:
383
                self._map_updated = True
0.254.16 by Jelmer Vernooij
Add optimization preventing recursive index updating.
384
            return
0.200.735 by Jelmer Vernooij
Use convenience functions for start/stop write groups.
385
        self.start_write_group()
0.200.231 by Jelmer Vernooij
Partially fix pull.
386
        try:
0.254.4 by Jelmer Vernooij
Merge trunk.
387
            pb = ui.ui_factory.nested_progress_bar()
388
            try:
389
                for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
0.254.16 by Jelmer Vernooij
Add optimization preventing recursive index updating.
390
                    trace.mutter('processing %r', revid)
0.254.4 by Jelmer Vernooij
Merge trunk.
391
                    pb.update("updating git map", i, len(missing_revids))
392
                    self._update_sha_map_revision(revid)
393
            finally:
394
                pb.finished()
0.200.1264 by Jelmer Vernooij
Fix updating cache for single revision - don't consider it an update of the full cache.
395
            if stop_revision is None:
396
                self._map_updated = True
0.200.735 by Jelmer Vernooij
Use convenience functions for start/stop write groups.
397
        except:
398
            self.abort_write_group()
399
            raise
400
        else:
401
            self.commit_write_group()
0.200.229 by Jelmer Vernooij
More work on converter.
402
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
403
    def __iter__(self):
404
        self._update_sha_map()
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
405
        return iter(self._cache.idmap.sha1s())
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
406
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
407
    def _reconstruct_commit(self, rev, tree_sha, lossy, verifiers):
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
408
        """Reconstruct a Commit object.
409
410
        :param rev: Revision object
411
        :param tree_sha: SHA1 of the root tree object
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
412
        :param lossy: Whether or not to roundtrip bzr metadata
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
413
        :param verifiers: Verifiers for the commits
414
        :return: Commit object
415
        """
0.238.7 by Jelmer Vernooij
Cope with ghosts a bit better.
416
        def parent_lookup(revid):
417
            try:
418
                return self._lookup_revision_sha1(revid)
419
            except errors.NoSuchRevision:
420
                return None
0.252.4 by Jelmer Vernooij
More work on roundtripping.
421
        return self.mapping.export_commit(rev, tree_sha, parent_lookup,
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
422
            lossy, verifiers)
0.238.7 by Jelmer Vernooij
Cope with ghosts a bit better.
423
0.273.2 by Jelmer Vernooij
use tree objects rather than inventories
424
    def _create_fileid_map_blob(self, tree):
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
425
        # FIXME: This can probably be a lot more efficient,
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
426
        # not all files necessarily have to be processed.
427
        file_ids = {}
0.334.1 by Jelmer Vernooij
Improve transaction and write group handling.
428
        for (path, ie) in tree.iter_entries_by_dir():
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
429
            if self.mapping.generate_file_id(path) != ie.file_id:
430
                file_ids[path] = ie.file_id
431
        return self.mapping.export_fileid_map(file_ids)
432
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
433
    def _revision_to_objects(self, rev, tree, lossy):
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
434
        """Convert a revision to a set of git objects.
435
436
        :param rev: Bazaar revision object
437
        :param tree: Bazaar revision tree
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
438
        :param lossy: Whether to not roundtrip all Bazaar revision data
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
439
        """
0.200.548 by Jelmer Vernooij
Extract unusual file modes from revision when reconstructing Trees.
440
        unusual_modes = extract_unusual_modes(rev)
0.200.789 by Jelmer Vernooij
Cope with ghosts, cache inventories.
441
        present_parents = self.repository.has_revisions(rev.parent_ids)
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
442
        parent_trees = self.tree_cache.revision_trees(
0.200.797 by Jelmer Vernooij
Add docstring, fix formatting.
443
            [p for p in rev.parent_ids if p in present_parents])
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
444
        root_tree = None
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
445
        for path, obj, bzr_key_data in _tree_to_objects(tree, parent_trees,
0.252.30 by Jelmer Vernooij
Support creating dummy files for empty directories.
446
                self._cache.idmap, unusual_modes, self.mapping.BZR_DUMMY_FILE):
0.200.773 by Jelmer Vernooij
Implement inventory_to_objects
447
            if path == "":
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
448
                root_tree = obj
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
449
                root_key_data = bzr_key_data
0.252.34 by Jelmer Vernooij
Yield the proper object for the tree root.
450
                # Don't yield just yet
451
            else:
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
452
                yield path, obj, bzr_key_data
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
453
        if root_tree is None:
0.250.2 by Jelmer Vernooij
Make it work for evolution.
454
            # Pointless commit - get the tree sha elsewhere
0.200.864 by Jelmer Vernooij
Cope with the first commit being pointless.
455
            if not rev.parent_ids:
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
456
                root_tree = Tree()
0.200.864 by Jelmer Vernooij
Cope with the first commit being pointless.
457
            else:
458
                base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
459
                root_tree = self[self[base_sha1].tree]
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
460
            root_key_data = (tree.get_root_id(), )
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
461
        if not lossy and self.mapping.BZR_FILE_IDS_FILE is not None:
0.273.2 by Jelmer Vernooij
use tree objects rather than inventories
462
            b = self._create_fileid_map_blob(tree)
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
463
            if b is not None:
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
464
                root_tree[self.mapping.BZR_FILE_IDS_FILE] = (
465
                    (stat.S_IFREG | 0644), b.id)
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
466
                yield self.mapping.BZR_FILE_IDS_FILE, b, None
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
467
        yield "", root_tree, root_key_data
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
468
        if not lossy:
0.200.1559 by Jelmer Vernooij
Fix compatibility with bzr 2.5.
469
            testament3 = StrictTestament3(rev, tree)
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
470
            verifiers = { "testament3-sha1": testament3.as_sha1() }
0.200.1023 by Jelmer Vernooij
Set and verify testament.
471
        else:
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
472
            verifiers = {}
0.252.43 by Jelmer Vernooij
Some refactoring, support proper file ids in revision deltas.
473
        commit_obj = self._reconstruct_commit(rev, root_tree.id,
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
474
            lossy=lossy, verifiers=verifiers)
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
475
        try:
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
476
            foreign_revid, mapping = mapping_registry.parse_revision_id(
477
                rev.revision_id)
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
478
        except errors.InvalidRevisionId:
479
            pass
480
        else:
0.200.794 by Jelmer Vernooij
Use _check_expected_sha rather than custom checks.
481
            _check_expected_sha(foreign_revid, commit_obj)
0.200.837 by Jelmer Vernooij
Return inventory entries when creating git objects for a revision.
482
        yield None, commit_obj, None
0.200.783 by Jelmer Vernooij
Move object generation into a separate function.
483
0.200.838 by Jelmer Vernooij
Add convenience object for updating the object store.
484
    def _get_updater(self, rev):
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
485
        return self._cache.get_updater(rev)
0.200.838 by Jelmer Vernooij
Add convenience object for updating the object store.
486
0.200.783 by Jelmer Vernooij
Move object generation into a separate function.
487
    def _update_sha_map_revision(self, revid):
488
        rev = self.repository.get_revision(revid)
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
489
        tree = self.tree_cache.revision_tree(rev.revision_id)
0.200.838 by Jelmer Vernooij
Add convenience object for updating the object store.
490
        updater = self._get_updater(rev)
0.200.1510 by Jelmer Vernooij
Fix tests.
491
        # FIXME JRV 2011-12-15: Shouldn't we try both values for lossy ?
492
        for path, obj, ie in self._revision_to_objects(rev, tree, lossy=(not self.mapping.roundtripping)):
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
493
            if isinstance(obj, Commit):
0.200.1559 by Jelmer Vernooij
Fix compatibility with bzr 2.5.
494
                testament3 = StrictTestament3(rev, tree)
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
495
                ie = { "testament3-sha1": testament3.as_sha1() }
0.200.952 by Jelmer Vernooij
Write git pack files rather than loose objects.
496
            updater.add_object(obj, ie, path)
0.200.838 by Jelmer Vernooij
Add convenience object for updating the object store.
497
        commit_obj = updater.finish()
0.200.781 by Jelmer Vernooij
Return commit id after converting a revision.
498
        return commit_obj.id
0.200.229 by Jelmer Vernooij
More work on converter.
499
0.200.855 by Jelmer Vernooij
_get_ -> _reconstruct_.
500
    def _reconstruct_blobs(self, keys):
0.200.698 by Jelmer Vernooij
Merge fixes for SHA1s of symlinks.
501
        """Return a Git Blob object from a fileid and revision stored in bzr.
502
503
        :param fileid: File id of the text
504
        :param revision: Revision of the text
505
        """
0.250.2 by Jelmer Vernooij
Make it work for evolution.
506
        stream = self.repository.iter_files_bytes(
507
            ((key[0], key[1], key) for key in keys))
0.326.1 by Jelmer Vernooij
Update objectstore to new API.
508
        for (file_id, revision, expected_sha), chunks in stream:
0.200.854 by Jelmer Vernooij
_get_blob -> _get_blobs.
509
            blob = Blob()
510
            blob.chunked = chunks
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
511
            if blob.id != expected_sha and blob.data == "":
0.200.854 by Jelmer Vernooij
_get_blob -> _get_blobs.
512
                # Perhaps it's a symlink ?
513
                tree = self.tree_cache.revision_tree(revision)
0.326.1 by Jelmer Vernooij
Update objectstore to new API.
514
                path = tree.id2path(file_id)
515
                if tree.kind(path, file_id) == 'symlink':
516
                    blob = symlink_to_blob(tree.get_symlink_target(path, file_id))
0.200.854 by Jelmer Vernooij
_get_blob -> _get_blobs.
517
            _check_expected_sha(expected_sha, blob)
518
            yield blob
0.200.229 by Jelmer Vernooij
More work on converter.
519
0.273.2 by Jelmer Vernooij
use tree objects rather than inventories
520
    def _reconstruct_tree(self, fileid, revid, bzr_tree, unusual_modes,
0.200.855 by Jelmer Vernooij
_get_ -> _reconstruct_.
521
        expected_sha=None):
0.200.343 by Jelmer Vernooij
Use file ids consistently in map.
522
        """Return a Git Tree object from a file id and a revision stored in bzr.
0.200.249 by Jelmer Vernooij
Implement Tree.
523
0.200.343 by Jelmer Vernooij
Use file ids consistently in map.
524
        :param fileid: fileid in the tree.
0.200.249 by Jelmer Vernooij
Implement Tree.
525
        :param revision: Revision of the tree.
526
        """
0.200.776 by Jelmer Vernooij
Remove unnecessary lookups.
527
        def get_ie_sha1(entry):
528
            if entry.kind == "directory":
0.200.808 by Jelmer Vernooij
Avoid recalculating tree shas we already have.
529
                try:
0.200.859 by Jelmer Vernooij
Trivial cleanups.
530
                    return self._cache.idmap.lookup_tree_id(entry.file_id,
531
                        revid)
0.200.812 by Jelmer Vernooij
Catch KeyError from lookup_tree as well - some caches (such as sqlite) don't store all trees, only some.
532
                except (NotImplementedError, KeyError):
0.273.2 by Jelmer Vernooij
use tree objects rather than inventories
533
                    obj = self._reconstruct_tree(entry.file_id, revid, bzr_tree,
0.200.808 by Jelmer Vernooij
Avoid recalculating tree shas we already have.
534
                        unusual_modes)
535
                    if obj is None:
536
                        return None
537
                    else:
538
                        return obj.id
0.200.776 by Jelmer Vernooij
Remove unnecessary lookups.
539
            elif entry.kind in ("file", "symlink"):
0.200.868 by Jelmer Vernooij
Cope with no-change merges.
540
                try:
541
                    return self._cache.idmap.lookup_blob_id(entry.file_id,
542
                        entry.revision)
543
                except KeyError:
544
                    # no-change merge?
545
                    return self._reconstruct_blobs(
546
                        [(entry.file_id, entry.revision, None)]).next().id
0.200.1551 by Jelmer Vernooij
Support nested trees in reconstruction code.
547
            elif entry.kind == 'tree-reference':
548
                # FIXME: Make sure the file id is the root id
549
                return self._lookup_revision_sha1(entry.reference_revision)
0.200.776 by Jelmer Vernooij
Remove unnecessary lookups.
550
            else:
551
                raise AssertionError("unknown entry kind '%s'" % entry.kind)
0.275.5 by Jelmer Vernooij
Cope with root_inventory and inventory.
552
        try:
553
            inv = bzr_tree.root_inventory
554
        except AttributeError:
555
            inv = bzr_tree.inventory
0.390.4 by Jelmer Vernooij
Update for new Inventory API.
556
        tree = directory_to_tree(inv.get_entry(fileid).children,
0.275.4 by Jelmer Vernooij
Pass children list to directory_to_tree .
557
                get_ie_sha1, unusual_modes, self.mapping.BZR_DUMMY_FILE,
558
                bzr_tree.get_root_id() == fileid)
0.273.2 by Jelmer Vernooij
use tree objects rather than inventories
559
        if (bzr_tree.get_root_id() == fileid and
0.200.915 by Jelmer Vernooij
Cope with the fact that the old format didn't export file ids.
560
            self.mapping.BZR_FILE_IDS_FILE is not None):
0.200.1223 by Jelmer Vernooij
Cope with empty directories.
561
            if tree is None:
562
                tree = Tree()
0.273.2 by Jelmer Vernooij
use tree objects rather than inventories
563
            b = self._create_fileid_map_blob(bzr_tree)
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
564
            # If this is the root tree, add the file ids
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
565
            tree[self.mapping.BZR_FILE_IDS_FILE] = (
566
                (stat.S_IFREG | 0644), b.id)
0.200.1223 by Jelmer Vernooij
Cope with empty directories.
567
        if tree is not None:
568
            _check_expected_sha(expected_sha, tree)
0.200.249 by Jelmer Vernooij
Implement Tree.
569
        return tree
0.200.229 by Jelmer Vernooij
More work on converter.
570
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
571
    def get_parents(self, sha):
0.200.454 by Jelmer Vernooij
Use ObjectStore.find_missing_objects in server.
572
        """Retrieve the parents of a Git commit by SHA1.
573
574
        :param sha: SHA1 of the commit
575
        :raises: KeyError, NotCommitError
576
        """
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
577
        return self[sha].parents
578
0.200.364 by Jelmer Vernooij
Reimplement dpush, but more efficient and only writing a single pack file rather than one per revision.
579
    def _lookup_revision_sha1(self, revid):
0.200.449 by Jelmer Vernooij
Use BazaarObjectStore to find matching SHA1s for bzr revisions.
580
        """Return the SHA1 matching a Bazaar revision."""
0.200.541 by Jelmer Vernooij
Cope with NULL_REVISION.
581
        if revid == NULL_REVISION:
0.200.891 by Jelmer Vernooij
Use ZERO_SHA constant where possible.
582
            return ZERO_SHA
0.200.364 by Jelmer Vernooij
Reimplement dpush, but more efficient and only writing a single pack file rather than one per revision.
583
        try:
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
584
            return self._cache.idmap.lookup_commit(revid)
0.200.364 by Jelmer Vernooij
Reimplement dpush, but more efficient and only writing a single pack file rather than one per revision.
585
        except KeyError:
0.200.682 by Jelmer Vernooij
Avoid doing a full sha map update if we already know the SHA1.
586
            try:
587
                return mapping_registry.parse_revision_id(revid)[0]
588
            except errors.InvalidRevisionId:
0.200.1264 by Jelmer Vernooij
Fix updating cache for single revision - don't consider it an update of the full cache.
589
                self._update_sha_map(revid)
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
590
                return self._cache.idmap.lookup_commit(revid)
0.200.364 by Jelmer Vernooij
Reimplement dpush, but more efficient and only writing a single pack file rather than one per revision.
591
0.200.310 by Jelmer Vernooij
Fix pull from remote branches.
592
    def get_raw(self, sha):
0.200.454 by Jelmer Vernooij
Use ObjectStore.find_missing_objects in server.
593
        """Get the raw representation of a Git object by SHA1.
594
595
        :param sha: SHA1 of the git object
596
        """
0.200.1622 by William Grant
BazaarObjectStore.get_raw now copes with non-hex-encoded SHA-1s, as some ref delta resolution in dulwich apparently requires.
597
        if len(sha) == 20:
598
            sha = sha_to_hex(sha)
0.200.566 by Jelmer Vernooij
Fix ObjectStore.get_raw() .
599
        obj = self[sha]
600
        return (obj.type, obj.as_raw_string())
0.200.310 by Jelmer Vernooij
Fix pull from remote branches.
601
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
602
    def __contains__(self, sha):
603
        # See if sha is in map
604
        try:
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
605
            for (type, type_data) in self.lookup_git_sha(sha):
606
                if type == "commit":
607
                    if self.repository.has_revision(type_data[0]):
608
                        return True
609
                elif type == "blob":
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
610
                    if type_data in self.repository.texts:
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
611
                        return True
612
                elif type == "tree":
613
                    if self.repository.has_revision(type_data[1]):
614
                        return True
615
                else:
616
                    raise AssertionError("Unknown object type '%s'" % type)
0.200.568 by Jelmer Vernooij
Properly check that matching bzr objects exist.
617
            else:
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
618
                return False
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
619
        except KeyError:
620
            return False
621
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
622
    def lock_read(self):
623
        self._locked = 'r'
624
        self._map_updated = False
625
        self.repository.lock_read()
626
        return LogicalLockResult(self.unlock)
627
628
    def lock_write(self):
629
        self._locked = 'r'
630
        self._map_updated = False
631
        self.repository.lock_write()
632
        return LogicalLockResult(self.unlock)
633
634
    def is_locked(self):
635
        return (self._locked is not None)
636
637
    def unlock(self):
638
        self._locked = None
639
        self._map_updated = False
640
        self.repository.unlock()
641
642
    def lookup_git_shas(self, shas):
0.200.898 by Jelmer Vernooij
Optimize finding of git shas.
643
        ret = {}
644
        for sha in shas:
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
645
            if sha == ZERO_SHA:
0.200.1169 by Jelmer Vernooij
Fix some sha lookups.
646
                ret[sha] = [("commit", (NULL_REVISION, None, {}))]
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
647
                continue
0.200.898 by Jelmer Vernooij
Optimize finding of git shas.
648
            try:
0.261.3 by Jelmer Vernooij
Fix more tests.
649
                ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
0.200.898 by Jelmer Vernooij
Optimize finding of git shas.
650
            except KeyError:
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
651
                # if not, see if there are any unconverted revisions and
652
                # add them to the map, search for sha in map again
653
                self._update_sha_map()
654
                try:
655
                    ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
656
                except KeyError:
657
                    pass
0.200.898 by Jelmer Vernooij
Optimize finding of git shas.
658
        return ret
659
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
660
    def lookup_git_sha(self, sha):
661
        return self.lookup_git_shas([sha])[sha]
0.200.437 by Jelmer Vernooij
Implement BazaarObjectStore.__contains__, BazaarObjectStore.iter_shas, BazaarObjectStore.get_parents.
662
663
    def __getitem__(self, sha):
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
664
        if self._cache.content_cache is not None:
0.200.840 by Jelmer Vernooij
Support using content cache.
665
            try:
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
666
                return self._cache.content_cache[sha]
0.200.840 by Jelmer Vernooij
Support using content cache.
667
            except KeyError:
668
                pass
0.200.1169 by Jelmer Vernooij
Fix some sha lookups.
669
        for (kind, type_data) in self.lookup_git_sha(sha):
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
670
            # convert object to git object
0.200.1169 by Jelmer Vernooij
Fix some sha lookups.
671
            if kind == "commit":
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
672
                (revid, tree_sha, verifiers) = type_data
673
                try:
674
                    rev = self.repository.get_revision(revid)
675
                except errors.NoSuchRevision:
0.200.1341 by Jelmer Vernooij
Add check that callers don't try to look up NULL_REVISION.
676
                    if revid == NULL_REVISION:
677
                        raise AssertionError(
678
                            "should not try to look up NULL_REVISION")
0.200.1169 by Jelmer Vernooij
Fix some sha lookups.
679
                    trace.mutter('entry for %s %s in shamap: %r, but not '
680
                                 'found in repository', kind, sha, type_data)
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
681
                    raise KeyError(sha)
0.200.1510 by Jelmer Vernooij
Fix tests.
682
                # FIXME: the type data should say whether conversion was lossless
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
683
                commit = self._reconstruct_commit(rev, tree_sha,
0.200.1510 by Jelmer Vernooij
Fix tests.
684
                    lossy=(not self.mapping.roundtripping), verifiers=verifiers)
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
685
                _check_expected_sha(sha, commit)
686
                return commit
0.200.1169 by Jelmer Vernooij
Fix some sha lookups.
687
            elif kind == "blob":
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
688
                (fileid, revision) = type_data
0.200.1212 by Jelmer Vernooij
Support read locking object stores.
689
                blobs = self._reconstruct_blobs([(fileid, revision, sha)])
690
                return blobs.next()
0.200.1169 by Jelmer Vernooij
Fix some sha lookups.
691
            elif kind == "tree":
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
692
                (fileid, revid) = type_data
693
                try:
694
                    tree = self.tree_cache.revision_tree(revid)
695
                    rev = self.repository.get_revision(revid)
696
                except errors.NoSuchRevision:
0.200.1319 by Jelmer Vernooij
Only update git cache during post-commit if parents are already in the cache.
697
                    trace.mutter('entry for %s %s in shamap: %r, but not found in '
698
                        'repository', kind, sha, type_data)
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
699
                    raise KeyError(sha)
700
                unusual_modes = extract_unusual_modes(rev)
701
                try:
702
                    return self._reconstruct_tree(fileid, revid,
0.273.2 by Jelmer Vernooij
use tree objects rather than inventories
703
                        tree, unusual_modes, expected_sha=sha)
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
704
                except errors.NoSuchRevision:
705
                    raise KeyError(sha)
706
            else:
0.200.1169 by Jelmer Vernooij
Fix some sha lookups.
707
                raise AssertionError("Unknown object type '%s'" % kind)
0.200.228 by Jelmer Vernooij
Split out map.
708
        else:
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
709
            raise KeyError(sha)
0.200.782 by Jelmer Vernooij
Add custom generate_pack_contents implementation.
710
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
711
    def generate_lossy_pack_data(self, have, want, progress=None,
712
            get_tagged=None, ofs_delta=False):
713
        return pack_objects_to_data(
714
                self.generate_pack_contents(have, want, progress, get_tagged,
715
            lossy=True))
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
716
0.200.899 by Jelmer Vernooij
Add tests for find_missing_bzr_revids.
717
    def generate_pack_contents(self, have, want, progress=None,
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
718
            ofs_delta=False, get_tagged=None, lossy=False):
0.200.782 by Jelmer Vernooij
Add custom generate_pack_contents implementation.
719
        """Iterate over the contents of a pack file.
720
721
        :param have: List of SHA1s of objects that should not be sent
722
        :param want: List of SHA1s of objects that should be sent
723
        """
0.200.787 by Jelmer Vernooij
Implement custom ObjectWalker.generate_pack_contents.
724
        processed = set()
0.200.898 by Jelmer Vernooij
Optimize finding of git shas.
725
        ret = self.lookup_git_shas(have + want)
0.200.787 by Jelmer Vernooij
Implement custom ObjectWalker.generate_pack_contents.
726
        for commit_sha in have:
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
727
            commit_sha = self.unpeel_map.peel_tag(commit_sha, commit_sha)
0.200.787 by Jelmer Vernooij
Implement custom ObjectWalker.generate_pack_contents.
728
            try:
0.200.1180 by Jelmer Vernooij
Some dpush fixes.
729
                for (type, type_data) in ret[commit_sha]:
0.361.1 by Jelmer Vernooij
Don't use assert.
730
                    if type != "commit":
731
                        raise AssertionError("Type was %s, not commit" % type)
0.200.1180 by Jelmer Vernooij
Some dpush fixes.
732
                    processed.add(type_data[0])
0.200.787 by Jelmer Vernooij
Implement custom ObjectWalker.generate_pack_contents.
733
            except KeyError:
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
734
                trace.mutter("unable to find remote ref %s", commit_sha)
0.200.787 by Jelmer Vernooij
Implement custom ObjectWalker.generate_pack_contents.
735
        pending = set()
736
        for commit_sha in want:
737
            if commit_sha in have:
738
                continue
0.200.898 by Jelmer Vernooij
Optimize finding of git shas.
739
            try:
0.200.1180 by Jelmer Vernooij
Some dpush fixes.
740
                for (type, type_data) in ret[commit_sha]:
0.361.1 by Jelmer Vernooij
Don't use assert.
741
                    if type != "commit":
742
                        raise AssertionError("Type was %s, not commit" % type)
0.200.1180 by Jelmer Vernooij
Some dpush fixes.
743
                    pending.add(type_data[0])
0.200.898 by Jelmer Vernooij
Optimize finding of git shas.
744
            except KeyError:
745
                pass
0.200.899 by Jelmer Vernooij
Add tests for find_missing_bzr_revids.
746
0.200.1053 by Jelmer Vernooij
Fix find_missing_bzr_revids.
747
        graph = self.repository.get_graph()
748
        todo = _find_missing_bzr_revids(graph, pending, processed)
0.200.1290 by Jelmer Vernooij
Avoid storing all objects to push in memory.
749
        ret = PackTupleIterable(self)
0.200.787 by Jelmer Vernooij
Implement custom ObjectWalker.generate_pack_contents.
750
        pb = ui.ui_factory.nested_progress_bar()
751
        try:
752
            for i, revid in enumerate(todo):
753
                pb.update("generating git objects", i, len(todo))
0.200.1059 by Jelmer Vernooij
Fix graph tests.
754
                try:
755
                    rev = self.repository.get_revision(revid)
756
                except errors.NoSuchRevision:
757
                    continue
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
758
                tree = self.tree_cache.revision_tree(revid)
0.200.1509 by Jelmer Vernooij
Properly raise exception when pulling from git into bzr without experimental mappings.
759
                for path, obj, ie in self._revision_to_objects(rev, tree, lossy=lossy):
0.200.1290 by Jelmer Vernooij
Avoid storing all objects to push in memory.
760
                    ret.add(obj.id, path)
0.200.1298 by Jelmer Vernooij
Fix compatibility with newer versions of dulwich.
761
            return ret
0.200.787 by Jelmer Vernooij
Implement custom ObjectWalker.generate_pack_contents.
762
        finally:
763
            pb.finished()
0.251.1 by Jelmer Vernooij
Implement ObjectStore.add_{thin_,}pack.
764
765
    def add_thin_pack(self):
766
        import tempfile
767
        import os
768
        fd, path = tempfile.mkstemp(suffix=".pack")
769
        f = os.fdopen(fd, 'wb')
770
        def commit():
771
            from dulwich.pack import PackData, Pack
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
772
            from .fetch import import_git_objects
0.251.1 by Jelmer Vernooij
Implement ObjectStore.add_{thin_,}pack.
773
            os.fsync(fd)
774
            f.close()
775
            if os.path.getsize(path) == 0:
776
                return
777
            pd = PackData(path)
778
            pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
779
780
            p = Pack(path[:-5])
0.200.1788 by Jelmer Vernooij
Use context managers.
781
            with self.repository.lock_write():
0.251.1 by Jelmer Vernooij
Implement ObjectStore.add_{thin_,}pack.
782
                self.repository.start_write_group()
783
                try:
0.200.1289 by Jelmer Vernooij
Switch to dulwich 0.8.0.
784
                    import_git_objects(self.repository, self.mapping,
0.251.1 by Jelmer Vernooij
Implement ObjectStore.add_{thin_,}pack.
785
                        p.iterobjects(get_raw=self.get_raw),
786
                        self.object_store)
787
                except:
788
                    self.repository.abort_write_group()
789
                    raise
790
                else:
791
                    self.repository.commit_write_group()
792
        return f, commit
793
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
794
    # The pack isn't kept around anyway, so no point
0.251.1 by Jelmer Vernooij
Implement ObjectStore.add_{thin_,}pack.
795
    # in treating full packs different from thin packs
796
    add_pack = add_thin_pack