/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/git/fetch.py

  • Committer: Jelmer Vernooij
  • Date: 2018-11-10 17:18:27 UTC
  • mto: (7143.11.2 unused-imports)
  • mto: This revision was merged to the branch mainline in revision 7144.
  • Revision ID: jelmer@jelmer.uk-20181110171827-46xer5sa9fzgab1q
Add flake8 configuration to monkey patch for lazy imports.

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