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