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