/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/plugins/git/fetch.py

  • Committer: Martin
  • Date: 2018-07-03 17:23:08 UTC
  • mto: (7027.4.10 python3-blackbox)
  • mto: This revision was merged to the branch mainline in revision 7028.
  • Revision ID: gzlist@googlemail.com-20180703172308-lre82d15bfkdv48e
Fixup low level knit tests for Python 3

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008 Canonical Ltd
 
1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
from bzrlib import osutils
18
 
from bzrlib.errors import InvalidRevisionId
19
 
from bzrlib.inventory import Inventory
20
 
from bzrlib.repository import InterRepository
21
 
from bzrlib.trace import info
22
 
 
23
 
from bzrlib.plugins.git import git
24
 
from bzrlib.plugins.git.repository import LocalGitRepository, GitRepository, GitFormat
25
 
from bzrlib.plugins.git.remote import RemoteGitRepository
26
 
 
27
 
from dulwich.objects import Commit
28
 
 
29
 
from cStringIO import StringIO
30
 
 
31
 
 
32
 
class BzrFetchGraphWalker(object):
33
 
 
34
 
    def __init__(self, repository, mapping):
35
 
        self.repository = repository
36
 
        self.mapping = mapping
37
 
        self.done = set()
38
 
        self.heads = set(repository.all_revision_ids())
39
 
        self.parents = {}
40
 
 
41
 
    def ack(self, sha):
42
 
        revid = self.mapping.revision_id_foreign_to_bzr(sha)
43
 
        self.remove(revid)
44
 
 
45
 
    def remove(self, revid):
46
 
        self.done.add(revid)
47
 
        if ref in self.heads:
48
 
            self.heads.remove(revid)
49
 
        if revid in self.parents:
50
 
            for p in self.parents[revid]:
51
 
                self.remove(p)
52
 
 
53
 
    def next(self):
54
 
        while self.heads:
55
 
            ret = self.heads.pop()
56
 
            ps = self.repository.get_parent_map([ret])[ret]
57
 
            self.parents[ret] = ps
58
 
            self.heads.update([p for p in ps if not p in self.done])
59
 
            try:
60
 
                self.done.add(ret)
61
 
                return self.mapping.revision_id_bzr_to_foreign(ret)
62
 
            except InvalidRevisionId:
63
 
                pass
64
 
        return None
65
 
 
66
 
 
67
 
def import_git_blob(repo, mapping, path, blob):
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Fetching from git into bzr."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
from dulwich.objects import (
 
22
    Commit,
 
23
    Tag,
 
24
    Tree,
 
25
    S_IFGITLINK,
 
26
    S_ISGITLINK,
 
27
    ZERO_SHA,
 
28
    )
 
29
from dulwich.object_store import (
 
30
    tree_lookup_path,
 
31
    )
 
32
from dulwich.walk import Walker
 
33
import posixpath
 
34
import stat
 
35
 
 
36
from ... import (
 
37
    debug,
 
38
    errors,
 
39
    osutils,
 
40
    trace,
 
41
    ui,
 
42
    )
 
43
from ...errors import (
 
44
    BzrError,
 
45
    )
 
46
from ...bzr.inventory import (
 
47
    InventoryDirectory,
 
48
    InventoryFile,
 
49
    InventoryLink,
 
50
    TreeReference,
 
51
    )
 
52
from ...repository import (
 
53
    InterRepository,
 
54
    )
 
55
from ...revision import (
 
56
    NULL_REVISION,
 
57
    )
 
58
from ...sixish import text_type
 
59
from ...bzr.inventorytree import InventoryRevisionTree
 
60
from ...testament import (
 
61
    StrictTestament3,
 
62
    )
 
63
from ...tsort import (
 
64
    topo_sort,
 
65
    )
 
66
from ...bzr.versionedfile import (
 
67
    ChunkedContentFactory,
 
68
    )
 
69
 
 
70
from .mapping import (
 
71
    DEFAULT_FILE_MODE,
 
72
    mode_is_executable,
 
73
    mode_kind,
 
74
    warn_unusual_mode,
 
75
    )
 
76
from .object_store import (
 
77
    LRUTreeCache,
 
78
    _tree_to_objects,
 
79
    )
 
80
from .refs import (
 
81
    is_tag,
 
82
    )
 
83
from .remote import (
 
84
    RemoteGitRepository,
 
85
    )
 
86
from .repository import (
 
87
    GitRepository,
 
88
    GitRepositoryFormat,
 
89
    LocalGitRepository,
 
90
    )
 
91
 
 
92
 
 
93
def import_git_blob(texts, mapping, path, name, hexshas,
 
94
        base_bzr_tree, parent_id, revision_id,
 
95
        parent_bzr_trees, lookup_object, modes, store_updater,
 
96
        lookup_file_id):
68
97
    """Import a git blob object into a bzr repository.
69
98
 
70
 
    :param repo: bzr repository
 
99
    :param texts: VersionedFiles to add to
71
100
    :param path: Path in the tree
72
101
    :param blob: A git blob
73
 
    """
74
 
    file_id = mapping.generate_file_id(path)
75
 
    repo.texts.add_lines((file_id, blob.id),
76
 
        [], #FIXME 
77
 
        osutils.split_lines(blob.data))
78
 
    inv.add_path(path, "file", file_id)
79
 
 
80
 
 
81
 
def import_git_tree(repo, mapping, path, tree, inv, lookup_object):
 
102
    :return: Inventory delta for this file
 
103
    """
 
104
    (base_mode, mode) = modes
 
105
    (base_hexsha, hexsha) = hexshas
 
106
    if mapping.is_special_file(path):
 
107
        return []
 
108
    if base_hexsha == hexsha and base_mode == mode:
 
109
        # If nothing has changed since the base revision, we're done
 
110
        return []
 
111
    file_id = lookup_file_id(osutils.safe_unicode(path))
 
112
    if stat.S_ISLNK(mode):
 
113
        cls = InventoryLink
 
114
    else:
 
115
        cls = InventoryFile
 
116
    ie = cls(file_id, name.decode("utf-8"), parent_id)
 
117
    if ie.kind == "file":
 
118
        ie.executable = mode_is_executable(mode)
 
119
    if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
 
120
        base_exec = base_bzr_tree.is_executable(path)
 
121
        if ie.kind == "symlink":
 
122
            ie.symlink_target = base_bzr_tree.get_symlink_target(path)
 
123
        else:
 
124
            ie.text_size = base_bzr_tree.get_file_size(path)
 
125
            ie.text_sha1 = base_bzr_tree.get_file_sha1(path)
 
126
        if ie.kind == "symlink" or ie.executable == base_exec:
 
127
            ie.revision = base_bzr_tree.get_file_revision(path)
 
128
        else:
 
129
            blob = lookup_object(hexsha)
 
130
    else:
 
131
        blob = lookup_object(hexsha)
 
132
        if ie.kind == "symlink":
 
133
            ie.revision = None
 
134
            ie.symlink_target = blob.data.decode("utf-8")
 
135
        else:
 
136
            ie.text_size = sum(map(len, blob.chunked))
 
137
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
 
138
    # Check what revision we should store
 
139
    parent_keys = []
 
140
    for ptree in parent_bzr_trees:
 
141
        try:
 
142
            ppath = ptree.id2path(file_id)
 
143
        except errors.NoSuchId:
 
144
            continue
 
145
        pkind = ptree.kind(ppath, file_id)
 
146
        if (pkind == ie.kind and
 
147
            ((pkind == "symlink" and ptree.get_symlink_target(ppath, file_id) == ie.symlink_target) or
 
148
             (pkind == "file" and ptree.get_file_sha1(ppath, file_id) == ie.text_sha1 and
 
149
                ptree.is_executable(ppath, file_id) == ie.executable))):
 
150
            # found a revision in one of the parents to use
 
151
            ie.revision = ptree.get_file_revision(ppath, file_id)
 
152
            break
 
153
        parent_key = (file_id, ptree.get_file_revision(ppath, file_id))
 
154
        if not parent_key in parent_keys:
 
155
            parent_keys.append(parent_key)
 
156
    if ie.revision is None:
 
157
        # Need to store a new revision
 
158
        ie.revision = revision_id
 
159
        if ie.revision is None:
 
160
            raise ValueError("no file revision set")
 
161
        if ie.kind == 'symlink':
 
162
            chunks = []
 
163
        else:
 
164
            chunks = blob.chunked
 
165
        texts.insert_record_stream([
 
166
            ChunkedContentFactory((file_id, ie.revision),
 
167
                tuple(parent_keys), ie.text_sha1, chunks)])
 
168
    invdelta = []
 
169
    if base_hexsha is not None:
 
170
        old_path = path.decode("utf-8") # Renames are not supported yet
 
171
        if stat.S_ISDIR(base_mode):
 
172
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
 
173
                lookup_object(base_hexsha), [], lookup_object))
 
174
    else:
 
175
        old_path = None
 
176
    new_path = path.decode("utf-8")
 
177
    invdelta.append((old_path, new_path, file_id, ie))
 
178
    if base_hexsha != hexsha:
 
179
        store_updater.add_object(blob, (ie.file_id, ie.revision), path)
 
180
    return invdelta
 
181
 
 
182
 
 
183
class SubmodulesRequireSubtrees(BzrError):
 
184
    _fmt = ("The repository you are fetching from contains submodules, "
 
185
            "which require a Bazaar format that supports tree references.")
 
186
    internal = False
 
187
 
 
188
 
 
189
def import_git_submodule(texts, mapping, path, name, hexshas,
 
190
    base_bzr_tree, parent_id, revision_id, parent_bzr_trees, lookup_object,
 
191
    modes, store_updater, lookup_file_id):
 
192
    """Import a git submodule."""
 
193
    (base_hexsha, hexsha) = hexshas
 
194
    (base_mode, mode) = modes
 
195
    if base_hexsha == hexsha and base_mode == mode:
 
196
        return [], {}
 
197
    file_id = lookup_file_id(path)
 
198
    invdelta = []
 
199
    ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
 
200
    ie.revision = revision_id
 
201
    if base_hexsha is not None:
 
202
        old_path = path.decode("utf-8") # Renames are not supported yet
 
203
        if stat.S_ISDIR(base_mode):
 
204
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
 
205
                lookup_object(base_hexsha), [], lookup_object))
 
206
    else:
 
207
        old_path = None
 
208
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
 
209
    texts.insert_record_stream([
 
210
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
 
211
    invdelta.append((old_path, path, file_id, ie))
 
212
    return invdelta, {}
 
213
 
 
214
 
 
215
def remove_disappeared_children(base_bzr_tree, path, base_tree, existing_children,
 
216
        lookup_object):
 
217
    """Generate an inventory delta for removed children.
 
218
 
 
219
    :param base_bzr_tree: Base bzr tree against which to generate the
 
220
        inventory delta.
 
221
    :param path: Path to process (unicode)
 
222
    :param base_tree: Git Tree base object
 
223
    :param existing_children: Children that still exist
 
224
    :param lookup_object: Lookup a git object by its SHA1
 
225
    :return: Inventory delta, as list
 
226
    """
 
227
    if not isinstance(path, text_type):
 
228
        raise TypeError(path)
 
229
    ret = []
 
230
    for name, mode, hexsha in base_tree.iteritems():
 
231
        if name in existing_children:
 
232
            continue
 
233
        c_path = posixpath.join(path, name.decode("utf-8"))
 
234
        file_id = base_bzr_tree.path2id(c_path)
 
235
        if file_id is None:
 
236
            raise TypeError(file_id)
 
237
        ret.append((c_path, None, file_id, None))
 
238
        if stat.S_ISDIR(mode):
 
239
            ret.extend(remove_disappeared_children(
 
240
                base_bzr_tree, c_path, lookup_object(hexsha), [], lookup_object))
 
241
    return ret
 
242
 
 
243
 
 
244
def import_git_tree(texts, mapping, path, name, hexshas,
 
245
        base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
 
246
        lookup_object, modes, store_updater,
 
247
        lookup_file_id, allow_submodules=False):
82
248
    """Import a git tree object into a bzr repository.
83
249
 
84
 
    :param repo: A Bzr repository object
85
 
    :param path: Path in the tree
 
250
    :param texts: VersionedFiles object to add to
 
251
    :param path: Path in the tree (str)
 
252
    :param name: Name of the tree (str)
86
253
    :param tree: A git tree object
87
 
    :param inv: Inventory object
 
254
    :param base_bzr_tree: Base inventory against which to return inventory delta
 
255
    :return: Inventory delta for this subtree
88
256
    """
89
 
    file_id = mapping.generate_file_id(path)
90
 
    repo.texts.add_lines((file_id, tree.id),
91
 
        [], #FIXME 
92
 
        [])
93
 
    inv.add_path(path, "directory", file_id)
94
 
    for mode, name, hexsha in tree.entries():
95
 
        entry_kind = (mode & 0700000) / 0100000
96
 
        basename = name.decode("utf-8")
97
 
        if path == "":
98
 
            child_path = name
99
 
        else:
100
 
            child_path = urlutils.join(path, name)
101
 
        if entry_kind == 0:
102
 
            import_git_tree(repo, mapping, child_path, lookup_object, inv)
103
 
        elif entry_kind == 1:
104
 
            import_git_blob(repo, mapping, child_path, lookup_object, inv)
105
 
        else:
106
 
            raise AssertionError("Unknown blob kind, perms=%r." % (mode,))
107
 
 
108
 
 
109
 
def import_git_objects(repo, mapping, object_iter):
 
257
    (base_hexsha, hexsha) = hexshas
 
258
    (base_mode, mode) = modes
 
259
    if not isinstance(path, bytes):
 
260
        raise TypeError(path)
 
261
    if not isinstance(name, bytes):
 
262
        raise TypeError(name)
 
263
    if base_hexsha == hexsha and base_mode == mode:
 
264
        # If nothing has changed since the base revision, we're done
 
265
        return [], {}
 
266
    invdelta = []
 
267
    file_id = lookup_file_id(osutils.safe_unicode(path))
 
268
    # We just have to hope this is indeed utf-8:
 
269
    ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
 
270
    tree = lookup_object(hexsha)
 
271
    if base_hexsha is None:
 
272
        base_tree = None
 
273
        old_path = None # Newly appeared here
 
274
    else:
 
275
        base_tree = lookup_object(base_hexsha)
 
276
        old_path = path.decode("utf-8") # Renames aren't supported yet
 
277
    new_path = path.decode("utf-8")
 
278
    if base_tree is None or type(base_tree) is not Tree:
 
279
        ie.revision = revision_id
 
280
        invdelta.append((old_path, new_path, ie.file_id, ie))
 
281
        texts.insert_record_stream([
 
282
            ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
 
283
    # Remember for next time
 
284
    existing_children = set()
 
285
    child_modes = {}
 
286
    for name, child_mode, child_hexsha in tree.iteritems():
 
287
        existing_children.add(name)
 
288
        child_path = posixpath.join(path, name)
 
289
        if type(base_tree) is Tree:
 
290
            try:
 
291
                child_base_mode, child_base_hexsha = base_tree[name]
 
292
            except KeyError:
 
293
                child_base_hexsha = None
 
294
                child_base_mode = 0
 
295
        else:
 
296
            child_base_hexsha = None
 
297
            child_base_mode = 0
 
298
        if stat.S_ISDIR(child_mode):
 
299
            subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
 
300
                child_path, name, (child_base_hexsha, child_hexsha),
 
301
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
 
302
                lookup_object, (child_base_mode, child_mode), store_updater,
 
303
                lookup_file_id, allow_submodules=allow_submodules)
 
304
        elif S_ISGITLINK(child_mode): # submodule
 
305
            if not allow_submodules:
 
306
                raise SubmodulesRequireSubtrees()
 
307
            subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
 
308
                child_path, name, (child_base_hexsha, child_hexsha),
 
309
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
 
310
                lookup_object, (child_base_mode, child_mode), store_updater,
 
311
                lookup_file_id)
 
312
        else:
 
313
            if not mapping.is_special_file(name):
 
314
                subinvdelta = import_git_blob(texts, mapping, child_path, name,
 
315
                    (child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
 
316
                    revision_id, parent_bzr_trees, lookup_object,
 
317
                    (child_base_mode, child_mode), store_updater, lookup_file_id)
 
318
            else:
 
319
                subinvdelta = []
 
320
            grandchildmodes = {}
 
321
        child_modes.update(grandchildmodes)
 
322
        invdelta.extend(subinvdelta)
 
323
        if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
 
324
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0o111,
 
325
                        S_IFGITLINK):
 
326
            child_modes[child_path] = child_mode
 
327
    # Remove any children that have disappeared
 
328
    if base_tree is not None and type(base_tree) is Tree:
 
329
        invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
 
330
            base_tree, existing_children, lookup_object))
 
331
    store_updater.add_object(tree, (file_id, revision_id), path)
 
332
    return invdelta, child_modes
 
333
 
 
334
 
 
335
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
 
336
    o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
 
337
    new_unusual_modes = mapping.export_unusual_file_modes(rev)
 
338
    if new_unusual_modes != unusual_modes:
 
339
        raise AssertionError("unusual modes don't match: %r != %r" % (
 
340
            unusual_modes, new_unusual_modes))
 
341
    # Verify that we can reconstruct the commit properly
 
342
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
 
343
        verifiers)
 
344
    if rec_o != o:
 
345
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
 
346
            rec_o, o))
 
347
    diff = []
 
348
    new_objs = {}
 
349
    for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
 
350
        target_git_object_retriever._cache.idmap, unusual_modes,
 
351
        mapping.BZR_DUMMY_FILE):
 
352
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
 
353
        new_objs[path] = obj
 
354
        if obj.id != old_obj_id:
 
355
            diff.append((path, lookup_object(old_obj_id), obj))
 
356
    for (path, old_obj, new_obj) in diff:
 
357
        while (old_obj.type_name == "tree" and
 
358
               new_obj.type_name == "tree" and
 
359
               sorted(old_obj) == sorted(new_obj)):
 
360
            for name in old_obj:
 
361
                if old_obj[name][0] != new_obj[name][0]:
 
362
                    raise AssertionError("Modes for %s differ: %o != %o" %
 
363
                        (path, old_obj[name][0], new_obj[name][0]))
 
364
                if old_obj[name][1] != new_obj[name][1]:
 
365
                    # Found a differing child, delve deeper
 
366
                    path = posixpath.join(path, name)
 
367
                    old_obj = lookup_object(old_obj[name][1])
 
368
                    new_obj = new_objs[path]
 
369
                    break
 
370
        raise AssertionError("objects differ for %s: %r != %r" % (path,
 
371
            old_obj, new_obj))
 
372
 
 
373
 
 
374
def ensure_inventories_in_repo(repo, trees):
 
375
    real_inv_vf = repo.inventories.without_fallbacks()
 
376
    for t in trees:
 
377
        revid = t.get_revision_id()
 
378
        if not real_inv_vf.get_parent_map([(revid, )]):
 
379
            repo.add_inventory(revid, t.root_inventory, t.get_parent_ids())
 
380
 
 
381
 
 
382
def import_git_commit(repo, mapping, head, lookup_object,
 
383
                      target_git_object_retriever, trees_cache):
 
384
    o = lookup_object(head)
 
385
    # Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
 
386
    # were bzr roundtripped revisions they would be specified in the
 
387
    # roundtrip data.
 
388
    rev, roundtrip_revid, verifiers = mapping.import_commit(
 
389
        o, mapping.revision_id_foreign_to_bzr)
 
390
    if roundtrip_revid is not None:
 
391
        original_revid = rev.revision_id
 
392
        rev.revision_id = roundtrip_revid
 
393
    # We have to do this here, since we have to walk the tree and
 
394
    # we need to make sure to import the blobs / trees with the right
 
395
    # path; this may involve adding them more than once.
 
396
    parent_trees = trees_cache.revision_trees(rev.parent_ids)
 
397
    ensure_inventories_in_repo(repo, parent_trees)
 
398
    if parent_trees == []:
 
399
        base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
 
400
        base_tree = None
 
401
        base_mode = None
 
402
    else:
 
403
        base_bzr_tree = parent_trees[0]
 
404
        base_tree = lookup_object(o.parents[0]).tree
 
405
        base_mode = stat.S_IFDIR
 
406
    store_updater = target_git_object_retriever._get_updater(rev)
 
407
    tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
 
408
    inv_delta, unusual_modes = import_git_tree(repo.texts,
 
409
            mapping, b"", b"", (base_tree, o.tree), base_bzr_tree,
 
410
            None, rev.revision_id, parent_trees,
 
411
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
 
412
            tree_supplement.lookup_file_id,
 
413
            allow_submodules=repo._format.supports_tree_reference)
 
414
    if unusual_modes != {}:
 
415
        for path, mode in unusual_modes.iteritems():
 
416
            warn_unusual_mode(rev.foreign_revid, path, mode)
 
417
        mapping.import_unusual_file_modes(rev, unusual_modes)
 
418
    try:
 
419
        basis_id = rev.parent_ids[0]
 
420
    except IndexError:
 
421
        basis_id = NULL_REVISION
 
422
        base_bzr_inventory = None
 
423
    else:
 
424
        base_bzr_inventory = base_bzr_tree.root_inventory
 
425
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
426
              inv_delta, rev.revision_id, rev.parent_ids,
 
427
              base_bzr_inventory)
 
428
    ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
429
    # Check verifiers
 
430
    if verifiers and roundtrip_revid is not None:
 
431
        testament = StrictTestament3(rev, ret_tree)
 
432
        calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
 
433
        if calculated_verifiers != verifiers:
 
434
            trace.mutter("Testament SHA1 %r for %r did not match %r.",
 
435
                         calculated_verifiers["testament3-sha1"],
 
436
                         rev.revision_id, verifiers["testament3-sha1"])
 
437
            rev.revision_id = original_revid
 
438
            rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
439
              inv_delta, rev.revision_id, rev.parent_ids, base_bzr_tree)
 
440
            ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
441
    else:
 
442
        calculated_verifiers = {}
 
443
    store_updater.add_object(o, calculated_verifiers, None)
 
444
    store_updater.finish()
 
445
    trees_cache.add(ret_tree)
 
446
    repo.add_revision(rev.revision_id, rev)
 
447
    if "verify" in debug.debug_flags:
 
448
        verify_commit_reconstruction(target_git_object_retriever,
 
449
            lookup_object, o, rev, ret_tree, parent_trees, mapping,
 
450
            unusual_modes, verifiers)
 
451
 
 
452
 
 
453
def import_git_objects(repo, mapping, object_iter,
 
454
    target_git_object_retriever, heads, pb=None, limit=None):
110
455
    """Import a set of git objects into a bzr repository.
111
456
 
112
 
    :param repo: Bazaar repository
 
457
    :param repo: Target Bazaar repository
113
458
    :param mapping: Mapping to use
114
459
    :param object_iter: Iterator over Git objects.
 
460
    :return: Tuple with pack hints and last imported revision id
115
461
    """
116
 
    # TODO: a more (memory-)efficient implementation of this
117
 
    objects = {}
118
 
    for o in object_iter:
119
 
        objects[o.id] = o
120
 
    root_trees = {}
 
462
    def lookup_object(sha):
 
463
        try:
 
464
            return object_iter[sha]
 
465
        except KeyError:
 
466
            return target_git_object_retriever[sha]
 
467
    graph = []
 
468
    checked = set()
 
469
    heads = list(set(heads))
 
470
    trees_cache = LRUTreeCache(repo)
121
471
    # Find and convert commit objects
122
 
    for o in objects.iterkeys():
 
472
    while heads:
 
473
        if pb is not None:
 
474
            pb.update("finding revisions to fetch", len(graph), None)
 
475
        head = heads.pop()
 
476
        if head == ZERO_SHA:
 
477
            continue
 
478
        if not isinstance(head, bytes):
 
479
            raise TypeError(head)
 
480
        try:
 
481
            o = lookup_object(head)
 
482
        except KeyError:
 
483
            continue
123
484
        if isinstance(o, Commit):
124
 
            rev = mapping.import_commit(o)
125
 
            root_trees[rev] = objects[o.tree_sha]
 
485
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
 
486
                mapping.revision_id_foreign_to_bzr)
 
487
            if (repo.has_revision(rev.revision_id) or
 
488
                (roundtrip_revid and repo.has_revision(roundtrip_revid))):
 
489
                continue
 
490
            graph.append((o.id, o.parents))
 
491
            heads.extend([p for p in o.parents if p not in checked])
 
492
        elif isinstance(o, Tag):
 
493
            if o.object[1] not in checked:
 
494
                heads.append(o.object[1])
 
495
        else:
 
496
            trace.warning("Unable to import head object %r" % o)
 
497
        checked.add(o.id)
 
498
    del checked
 
499
    # Order the revisions
126
500
    # Create the inventory objects
127
 
    for rev, root_tree in root_trees.iteritems():
128
 
        # We have to do this here, since we have to walk the tree and 
129
 
        # we need to make sure to import the blobs / trees with the riht 
130
 
        # path; this may involve adding them more than once.
131
 
        inv = Inventory()
132
 
        def lookup_object(sha):
133
 
            if sha in objects:
134
 
                return objects[sha]
135
 
            return reconstruct_git_object(repo, mapping, sha)
136
 
        import_git_tree(repo, mapping, "", tree, inv, lookup_object)
137
 
        repo.add_revision(rev.revision_id, rev, inv)
138
 
 
139
 
 
140
 
def reconstruct_git_commit(repo, rev):
141
 
    raise NotImplementedError(self.reconstruct_git_commit)
142
 
 
143
 
 
144
 
def reconstruct_git_object(repo, mapping, sha):
145
 
    # Commit
146
 
    revid = mapping.revision_id_foreign_to_bzr(sha)
147
 
    try:
148
 
        rev = repo.get_revision(revid)
149
 
    except NoSuchRevision:
150
 
        pass
151
 
    else:
152
 
        return reconstruct_git_commit(rev)
153
 
 
154
 
    # TODO: Tree
155
 
    # TODO: Blob
156
 
    raise KeyError("No such object %s" % sha)
157
 
 
158
 
 
159
 
class InterGitRepository(InterRepository):
160
 
 
161
 
    _matching_repo_format = GitFormat()
162
 
 
163
 
    @staticmethod
164
 
    def _get_repo_format_to_test():
165
 
        return None
166
 
 
167
 
    def copy_content(self, revision_id=None, pb=None):
168
 
        """See InterRepository.copy_content."""
169
 
        self.fetch(revision_id, pb, find_ghosts=False)
170
 
 
171
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, 
172
 
              mapping=None):
173
 
        if mapping is None:
174
 
            mapping = self.source.get_mapping()
175
 
        def progress(text):
176
 
            if pb is not None:
177
 
                pb.note("git: %s" % text)
178
 
            else:
179
 
                info("git: %s" % text)
180
 
        def determine_wants(heads):
181
 
            if revision_id is None:
182
 
                ret = heads.values()
183
 
            else:
184
 
                ret = [mapping.revision_id_bzr_to_foreign(revision_id)]
185
 
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
186
 
        graph_walker = BzrFetchGraphWalker(self.target, mapping)
187
 
        self.target.lock_write()
 
501
    batch_size = 1000
 
502
    revision_ids = topo_sort(graph)
 
503
    pack_hints = []
 
504
    if limit is not None:
 
505
        revision_ids = revision_ids[:limit]
 
506
    last_imported = None
 
507
    for offset in range(0, len(revision_ids), batch_size):
 
508
        target_git_object_retriever.start_write_group()
188
509
        try:
189
 
            import_git_objects(self.target, mapping,
190
 
                self.source.fetch_objects(determine_wants, graph_walker, 
191
 
                    progress))
192
 
        finally:
193
 
            self.target.unlock()
194
 
 
195
 
    @staticmethod
196
 
    def is_compatible(source, target):
197
 
        """Be compatible with GitRepository."""
198
 
        # FIXME: Also check target uses VersionedFile
199
 
        return (isinstance(source, LocalGitRepository) and 
200
 
                target.supports_rich_root())
 
510
            repo.start_write_group()
 
511
            try:
 
512
                for i, head in enumerate(
 
513
                    revision_ids[offset:offset+batch_size]):
 
514
                    if pb is not None:
 
515
                        pb.update("fetching revisions", offset+i,
 
516
                                  len(revision_ids))
 
517
                    import_git_commit(repo, mapping, head, lookup_object,
 
518
                        target_git_object_retriever, trees_cache)
 
519
                    last_imported = head
 
520
            except:
 
521
                repo.abort_write_group()
 
522
                raise
 
523
            else:
 
524
                hint = repo.commit_write_group()
 
525
                if hint is not None:
 
526
                    pack_hints.extend(hint)
 
527
        except:
 
528
            target_git_object_retriever.abort_write_group()
 
529
            raise
 
530
        else:
 
531
            target_git_object_retriever.commit_write_group()
 
532
    return pack_hints, last_imported
 
533
 
 
534
 
 
535
class DetermineWantsRecorder(object):
 
536
 
 
537
    def __init__(self, actual):
 
538
        self.actual = actual
 
539
        self.wants = []
 
540
        self.remote_refs = {}
 
541
 
 
542
    def __call__(self, refs):
 
543
        if type(refs) is not dict:
 
544
            raise TypeError(refs)
 
545
        self.remote_refs = refs
 
546
        self.wants = self.actual(refs)
 
547
        return self.wants
 
548
 
 
549
 
 
550