/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 fetch.py

Fix thin packs.

Merged from https://code.launchpad.net/~jelmer/brz-git/fix-thin-packs/+merge/342292

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
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.errors import (
 
22
    NotCommitError,
 
23
    )
 
24
from dulwich.objects import (
 
25
    Commit,
 
26
    Tag,
 
27
    Tree,
 
28
    S_IFGITLINK,
 
29
    S_ISGITLINK,
 
30
    ZERO_SHA,
 
31
    )
 
32
from dulwich.object_store import (
 
33
    ObjectStoreGraphWalker,
 
34
    tree_lookup_path,
 
35
    )
 
36
from dulwich.protocol import CAPABILITY_THIN_PACK
 
37
from dulwich.walk import Walker
 
38
from itertools import (
 
39
    imap,
 
40
    )
 
41
from io import BytesIO
 
42
import posixpath
 
43
import re
 
44
import stat
 
45
 
 
46
from ... import (
 
47
    debug,
 
48
    errors,
 
49
    osutils,
 
50
    trace,
 
51
    ui,
 
52
    )
 
53
from ...errors import (
 
54
    BzrError,
 
55
    )
 
56
from ...bzr.inventory import (
 
57
    InventoryDirectory,
 
58
    InventoryFile,
 
59
    InventoryLink,
 
60
    TreeReference,
 
61
    )
 
62
from ...repository import (
 
63
    InterRepository,
 
64
    )
 
65
from ...revision import (
 
66
    NULL_REVISION,
 
67
    )
 
68
from ...bzr.inventorytree import InventoryRevisionTree
 
69
from ...testament import (
 
70
    StrictTestament3,
 
71
    )
 
72
from ...tsort import (
 
73
    topo_sort,
 
74
    )
 
75
from ...bzr.versionedfile import (
 
76
    ChunkedContentFactory,
 
77
    )
 
78
 
 
79
from .mapping import (
 
80
    DEFAULT_FILE_MODE,
 
81
    mode_is_executable,
 
82
    mode_kind,
 
83
    warn_unusual_mode,
 
84
    )
 
85
from .object_store import (
 
86
    BazaarObjectStore,
 
87
    LRUTreeCache,
 
88
    _tree_to_objects,
 
89
    )
 
90
from .refs import (
 
91
    is_tag,
 
92
    )
 
93
from .remote import (
 
94
    RemoteGitRepository,
 
95
    )
 
96
from .repository import (
 
97
    GitRepository,
 
98
    GitRepositoryFormat,
 
99
    LocalGitRepository,
 
100
    )
 
101
 
 
102
 
 
103
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha),
 
104
        base_bzr_tree, parent_id, revision_id,
 
105
        parent_bzr_trees, lookup_object, (base_mode, mode), store_updater,
 
106
        lookup_file_id):
 
107
    """Import a git blob object into a bzr repository.
 
108
 
 
109
    :param texts: VersionedFiles to add to
 
110
    :param path: Path in the tree
 
111
    :param blob: A git blob
 
112
    :return: Inventory delta for this file
 
113
    """
 
114
    if mapping.is_special_file(path):
 
115
        return []
 
116
    if base_hexsha == hexsha and base_mode == mode:
 
117
        # If nothing has changed since the base revision, we're done
 
118
        return []
 
119
    file_id = lookup_file_id(path)
 
120
    if stat.S_ISLNK(mode):
 
121
        cls = InventoryLink
 
122
    else:
 
123
        cls = InventoryFile
 
124
    ie = cls(file_id, name.decode("utf-8"), parent_id)
 
125
    if ie.kind == "file":
 
126
        ie.executable = mode_is_executable(mode)
 
127
    if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
 
128
        base_exec = base_bzr_tree.is_executable(path)
 
129
        if ie.kind == "symlink":
 
130
            ie.symlink_target = base_bzr_tree.get_symlink_target(path)
 
131
        else:
 
132
            ie.text_size = base_bzr_tree.get_file_size(path)
 
133
            ie.text_sha1 = base_bzr_tree.get_file_sha1(path)
 
134
        if ie.kind == "symlink" or ie.executable == base_exec:
 
135
            ie.revision = base_bzr_tree.get_file_revision(path)
 
136
        else:
 
137
            blob = lookup_object(hexsha)
 
138
    else:
 
139
        blob = lookup_object(hexsha)
 
140
        if ie.kind == "symlink":
 
141
            ie.revision = None
 
142
            ie.symlink_target = blob.data.decode("utf-8")
 
143
        else:
 
144
            ie.text_size = sum(imap(len, blob.chunked))
 
145
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
 
146
    # Check what revision we should store
 
147
    parent_keys = []
 
148
    for ptree in parent_bzr_trees:
 
149
        try:
 
150
            ppath = ptree.id2path(file_id)
 
151
        except errors.NoSuchId:
 
152
            continue
 
153
        pkind = ptree.kind(ppath, file_id)
 
154
        if (pkind == ie.kind and
 
155
            ((pkind == "symlink" and ptree.get_symlink_target(ppath, file_id) == ie.symlink_target) or
 
156
             (pkind == "file" and ptree.get_file_sha1(ppath, file_id) == ie.text_sha1 and
 
157
                ptree.is_executable(ppath, file_id) == ie.executable))):
 
158
            # found a revision in one of the parents to use
 
159
            ie.revision = ptree.get_file_revision(ppath, file_id)
 
160
            break
 
161
        parent_key = (file_id, ptree.get_file_revision(ppath, file_id))
 
162
        if not parent_key in parent_keys:
 
163
            parent_keys.append(parent_key)
 
164
    if ie.revision is None:
 
165
        # Need to store a new revision
 
166
        ie.revision = revision_id
 
167
        if ie.revision is None:
 
168
            raise ValueError("no file revision set")
 
169
        if ie.kind == 'symlink':
 
170
            chunks = []
 
171
        else:
 
172
            chunks = blob.chunked
 
173
        texts.insert_record_stream([
 
174
            ChunkedContentFactory((file_id, ie.revision),
 
175
                tuple(parent_keys), ie.text_sha1, chunks)])
 
176
    invdelta = []
 
177
    if base_hexsha is not None:
 
178
        old_path = path.decode("utf-8") # Renames are not supported yet
 
179
        if stat.S_ISDIR(base_mode):
 
180
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
 
181
                lookup_object(base_hexsha), [], lookup_object))
 
182
    else:
 
183
        old_path = None
 
184
    new_path = path.decode("utf-8")
 
185
    invdelta.append((old_path, new_path, file_id, ie))
 
186
    if base_hexsha != hexsha:
 
187
        store_updater.add_object(blob, (ie.file_id, ie.revision), path)
 
188
    return invdelta
 
189
 
 
190
 
 
191
class SubmodulesRequireSubtrees(BzrError):
 
192
    _fmt = ("The repository you are fetching from contains submodules, "
 
193
            "which are not yet supported.")
 
194
    internal = False
 
195
 
 
196
 
 
197
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
 
198
    base_bzr_tree, parent_id, revision_id, parent_bzr_trees, lookup_object,
 
199
    (base_mode, mode), store_updater, lookup_file_id):
 
200
    """Import a git submodule."""
 
201
    if base_hexsha == hexsha and base_mode == mode:
 
202
        return [], {}
 
203
    file_id = lookup_file_id(path)
 
204
    invdelta = []
 
205
    ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
 
206
    ie.revision = revision_id
 
207
    if base_hexsha is not None:
 
208
        old_path = path.decode("utf-8") # Renames are not supported yet
 
209
        if stat.S_ISDIR(base_mode):
 
210
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
 
211
                lookup_object(base_hexsha), [], lookup_object))
 
212
    else:
 
213
        old_path = None
 
214
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
 
215
    texts.insert_record_stream([
 
216
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
 
217
    invdelta.append((old_path, path, file_id, ie))
 
218
    return invdelta, {}
 
219
 
 
220
 
 
221
def remove_disappeared_children(base_bzr_tree, path, base_tree, existing_children,
 
222
        lookup_object):
 
223
    """Generate an inventory delta for removed children.
 
224
 
 
225
    :param base_bzr_tree: Base bzr tree against which to generate the
 
226
        inventory delta.
 
227
    :param path: Path to process (unicode)
 
228
    :param base_tree: Git Tree base object
 
229
    :param existing_children: Children that still exist
 
230
    :param lookup_object: Lookup a git object by its SHA1
 
231
    :return: Inventory delta, as list
 
232
    """
 
233
    if type(path) is not unicode:
 
234
        raise TypeError(path)
 
235
    ret = []
 
236
    for name, mode, hexsha in base_tree.iteritems():
 
237
        if name in existing_children:
 
238
            continue
 
239
        c_path = posixpath.join(path, name.decode("utf-8"))
 
240
        file_id = base_bzr_tree.path2id(c_path)
 
241
        if file_id is None:
 
242
            raise TypeError(file_id)
 
243
        ret.append((c_path, None, file_id, None))
 
244
        if stat.S_ISDIR(mode):
 
245
            ret.extend(remove_disappeared_children(
 
246
                base_bzr_tree, c_path, lookup_object(hexsha), [], lookup_object))
 
247
    return ret
 
248
 
 
249
 
 
250
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
 
251
        base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
 
252
        lookup_object, (base_mode, mode), store_updater,
 
253
        lookup_file_id, allow_submodules=False):
 
254
    """Import a git tree object into a bzr repository.
 
255
 
 
256
    :param texts: VersionedFiles object to add to
 
257
    :param path: Path in the tree (str)
 
258
    :param name: Name of the tree (str)
 
259
    :param tree: A git tree object
 
260
    :param base_bzr_tree: Base inventory against which to return inventory delta
 
261
    :return: Inventory delta for this subtree
 
262
    """
 
263
    if type(path) is not str:
 
264
        raise TypeError(path)
 
265
    if type(name) is not str:
 
266
        raise TypeError(name)
 
267
    if base_hexsha == hexsha and base_mode == mode:
 
268
        # If nothing has changed since the base revision, we're done
 
269
        return [], {}
 
270
    invdelta = []
 
271
    file_id = lookup_file_id(path)
 
272
    # We just have to hope this is indeed utf-8:
 
273
    ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
 
274
    tree = lookup_object(hexsha)
 
275
    if base_hexsha is None:
 
276
        base_tree = None
 
277
        old_path = None # Newly appeared here
 
278
    else:
 
279
        base_tree = lookup_object(base_hexsha)
 
280
        old_path = path.decode("utf-8") # Renames aren't supported yet
 
281
    new_path = path.decode("utf-8")
 
282
    if base_tree is None or type(base_tree) is not Tree:
 
283
        ie.revision = revision_id
 
284
        invdelta.append((old_path, new_path, ie.file_id, ie))
 
285
        texts.insert_record_stream([
 
286
            ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
 
287
    # Remember for next time
 
288
    existing_children = set()
 
289
    child_modes = {}
 
290
    for name, child_mode, child_hexsha in tree.iteritems():
 
291
        existing_children.add(name)
 
292
        child_path = posixpath.join(path, name)
 
293
        if type(base_tree) is Tree:
 
294
            try:
 
295
                child_base_mode, child_base_hexsha = base_tree[name]
 
296
            except KeyError:
 
297
                child_base_hexsha = None
 
298
                child_base_mode = 0
 
299
        else:
 
300
            child_base_hexsha = None
 
301
            child_base_mode = 0
 
302
        if stat.S_ISDIR(child_mode):
 
303
            subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
 
304
                child_path, name, (child_base_hexsha, child_hexsha),
 
305
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
 
306
                lookup_object, (child_base_mode, child_mode), store_updater,
 
307
                lookup_file_id, allow_submodules=allow_submodules)
 
308
        elif S_ISGITLINK(child_mode): # submodule
 
309
            if not allow_submodules:
 
310
                raise SubmodulesRequireSubtrees()
 
311
            subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
 
312
                child_path, name, (child_base_hexsha, child_hexsha),
 
313
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
 
314
                lookup_object, (child_base_mode, child_mode), store_updater,
 
315
                lookup_file_id)
 
316
        else:
 
317
            if not mapping.is_special_file(name):
 
318
                subinvdelta = import_git_blob(texts, mapping, child_path, name,
 
319
                    (child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
 
320
                    revision_id, parent_bzr_trees, lookup_object,
 
321
                    (child_base_mode, child_mode), store_updater, lookup_file_id)
 
322
            else:
 
323
                subinvdelta = []
 
324
            grandchildmodes = {}
 
325
        child_modes.update(grandchildmodes)
 
326
        invdelta.extend(subinvdelta)
 
327
        if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
 
328
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111,
 
329
                        S_IFGITLINK):
 
330
            child_modes[child_path] = child_mode
 
331
    # Remove any children that have disappeared
 
332
    if base_tree is not None and type(base_tree) is Tree:
 
333
        invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
 
334
            base_tree, existing_children, lookup_object))
 
335
    store_updater.add_object(tree, (file_id, ), path)
 
336
    return invdelta, child_modes
 
337
 
 
338
 
 
339
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
 
340
    o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
 
341
    new_unusual_modes = mapping.export_unusual_file_modes(rev)
 
342
    if new_unusual_modes != unusual_modes:
 
343
        raise AssertionError("unusual modes don't match: %r != %r" % (
 
344
            unusual_modes, new_unusual_modes))
 
345
    # Verify that we can reconstruct the commit properly
 
346
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
 
347
        verifiers)
 
348
    if rec_o != o:
 
349
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
 
350
            rec_o, o))
 
351
    diff = []
 
352
    new_objs = {}
 
353
    for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
 
354
        target_git_object_retriever._cache.idmap, unusual_modes,
 
355
        mapping.BZR_DUMMY_FILE):
 
356
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
 
357
        new_objs[path] = obj
 
358
        if obj.id != old_obj_id:
 
359
            diff.append((path, lookup_object(old_obj_id), obj))
 
360
    for (path, old_obj, new_obj) in diff:
 
361
        while (old_obj.type_name == "tree" and
 
362
               new_obj.type_name == "tree" and
 
363
               sorted(old_obj) == sorted(new_obj)):
 
364
            for name in old_obj:
 
365
                if old_obj[name][0] != new_obj[name][0]:
 
366
                    raise AssertionError("Modes for %s differ: %o != %o" %
 
367
                        (path, old_obj[name][0], new_obj[name][0]))
 
368
                if old_obj[name][1] != new_obj[name][1]:
 
369
                    # Found a differing child, delve deeper
 
370
                    path = posixpath.join(path, name)
 
371
                    old_obj = lookup_object(old_obj[name][1])
 
372
                    new_obj = new_objs[path]
 
373
                    break
 
374
        raise AssertionError("objects differ for %s: %r != %r" % (path,
 
375
            old_obj, new_obj))
 
376
 
 
377
 
 
378
def ensure_inventories_in_repo(repo, trees):
 
379
    real_inv_vf = repo.inventories.without_fallbacks()
 
380
    for t in trees:
 
381
        revid = t.get_revision_id()
 
382
        if not real_inv_vf.get_parent_map([(revid, )]):
 
383
            repo.add_inventory(revid, t.inventory, t.get_parent_ids())
 
384
 
 
385
 
 
386
def import_git_commit(repo, mapping, head, lookup_object,
 
387
                      target_git_object_retriever, trees_cache):
 
388
    o = lookup_object(head)
 
389
    # Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
 
390
    # were bzr roundtripped revisions they would be specified in the
 
391
    # roundtrip data.
 
392
    rev, roundtrip_revid, verifiers = mapping.import_commit(
 
393
        o, mapping.revision_id_foreign_to_bzr)
 
394
    if roundtrip_revid is not None:
 
395
        original_revid = rev.revision_id
 
396
        rev.revision_id = roundtrip_revid
 
397
    # We have to do this here, since we have to walk the tree and
 
398
    # we need to make sure to import the blobs / trees with the right
 
399
    # path; this may involve adding them more than once.
 
400
    parent_trees = trees_cache.revision_trees(rev.parent_ids)
 
401
    ensure_inventories_in_repo(repo, parent_trees)
 
402
    if parent_trees == []:
 
403
        base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
 
404
        base_tree = None
 
405
        base_mode = None
 
406
    else:
 
407
        base_bzr_tree = parent_trees[0]
 
408
        base_tree = lookup_object(o.parents[0]).tree
 
409
        base_mode = stat.S_IFDIR
 
410
    store_updater = target_git_object_retriever._get_updater(rev)
 
411
    tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
 
412
    inv_delta, unusual_modes = import_git_tree(repo.texts,
 
413
            mapping, "", "", (base_tree, o.tree), base_bzr_tree,
 
414
            None, rev.revision_id, parent_trees,
 
415
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
 
416
            tree_supplement.lookup_file_id,
 
417
            allow_submodules=getattr(repo._format, "supports_tree_reference",
 
418
                False))
 
419
    if unusual_modes != {}:
 
420
        for path, mode in unusual_modes.iteritems():
 
421
            warn_unusual_mode(rev.foreign_revid, path, mode)
 
422
        mapping.import_unusual_file_modes(rev, unusual_modes)
 
423
    try:
 
424
        basis_id = rev.parent_ids[0]
 
425
    except IndexError:
 
426
        basis_id = NULL_REVISION
 
427
        base_bzr_inventory = None
 
428
    else:
 
429
        try:
 
430
            base_bzr_inventory = base_bzr_tree.root_inventory
 
431
        except AttributeError: # bzr < 2.6
 
432
            base_bzr_inventory = base_bzr_tree.inventory
 
433
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
434
              inv_delta, rev.revision_id, rev.parent_ids,
 
435
              base_bzr_inventory)
 
436
    ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
437
    # Check verifiers
 
438
    if verifiers and roundtrip_revid is not None:
 
439
        testament = StrictTestament3(rev, ret_tree)
 
440
        calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
 
441
        if calculated_verifiers != verifiers:
 
442
            trace.mutter("Testament SHA1 %r for %r did not match %r.",
 
443
                         calculated_verifiers["testament3-sha1"],
 
444
                         rev.revision_id, verifiers["testament3-sha1"])
 
445
            rev.revision_id = original_revid
 
446
            rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
447
              inv_delta, rev.revision_id, rev.parent_ids, base_bzr_tree)
 
448
            ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
449
    else:
 
450
        calculated_verifiers = {}
 
451
    store_updater.add_object(o, calculated_verifiers, None)
 
452
    store_updater.finish()
 
453
    trees_cache.add(ret_tree)
 
454
    repo.add_revision(rev.revision_id, rev)
 
455
    if "verify" in debug.debug_flags:
 
456
        verify_commit_reconstruction(target_git_object_retriever,
 
457
            lookup_object, o, rev, ret_tree, parent_trees, mapping,
 
458
            unusual_modes, verifiers)
 
459
 
 
460
 
 
461
def import_git_objects(repo, mapping, object_iter,
 
462
    target_git_object_retriever, heads, pb=None, limit=None):
 
463
    """Import a set of git objects into a bzr repository.
 
464
 
 
465
    :param repo: Target Bazaar repository
 
466
    :param mapping: Mapping to use
 
467
    :param object_iter: Iterator over Git objects.
 
468
    :return: Tuple with pack hints and last imported revision id
 
469
    """
 
470
    def lookup_object(sha):
 
471
        try:
 
472
            return object_iter[sha]
 
473
        except KeyError:
 
474
            return target_git_object_retriever[sha]
 
475
    graph = []
 
476
    checked = set()
 
477
    heads = list(set(heads))
 
478
    trees_cache = LRUTreeCache(repo)
 
479
    # Find and convert commit objects
 
480
    while heads:
 
481
        if pb is not None:
 
482
            pb.update("finding revisions to fetch", len(graph), None)
 
483
        head = heads.pop()
 
484
        if head == ZERO_SHA:
 
485
            continue
 
486
        if type(head) is not str:
 
487
            raise TypeError(head)
 
488
        try:
 
489
            o = lookup_object(head)
 
490
        except KeyError:
 
491
            continue
 
492
        if isinstance(o, Commit):
 
493
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
 
494
                mapping.revision_id_foreign_to_bzr)
 
495
            if (repo.has_revision(rev.revision_id) or
 
496
                (roundtrip_revid and repo.has_revision(roundtrip_revid))):
 
497
                continue
 
498
            graph.append((o.id, o.parents))
 
499
            heads.extend([p for p in o.parents if p not in checked])
 
500
        elif isinstance(o, Tag):
 
501
            if o.object[1] not in checked:
 
502
                heads.append(o.object[1])
 
503
        else:
 
504
            trace.warning("Unable to import head object %r" % o)
 
505
        checked.add(o.id)
 
506
    del checked
 
507
    # Order the revisions
 
508
    # Create the inventory objects
 
509
    batch_size = 1000
 
510
    revision_ids = topo_sort(graph)
 
511
    pack_hints = []
 
512
    if limit is not None:
 
513
        revision_ids = revision_ids[:limit]
 
514
    last_imported = None
 
515
    for offset in range(0, len(revision_ids), batch_size):
 
516
        target_git_object_retriever.start_write_group()
 
517
        try:
 
518
            repo.start_write_group()
 
519
            try:
 
520
                for i, head in enumerate(
 
521
                    revision_ids[offset:offset+batch_size]):
 
522
                    if pb is not None:
 
523
                        pb.update("fetching revisions", offset+i,
 
524
                                  len(revision_ids))
 
525
                    import_git_commit(repo, mapping, head, lookup_object,
 
526
                        target_git_object_retriever, trees_cache)
 
527
                    last_imported = head
 
528
            except:
 
529
                repo.abort_write_group()
 
530
                raise
 
531
            else:
 
532
                hint = repo.commit_write_group()
 
533
                if hint is not None:
 
534
                    pack_hints.extend(hint)
 
535
        except:
 
536
            target_git_object_retriever.abort_write_group()
 
537
            raise
 
538
        else:
 
539
            target_git_object_retriever.commit_write_group()
 
540
    return pack_hints, last_imported
 
541
 
 
542
 
 
543
class InterFromGitRepository(InterRepository):
 
544
 
 
545
    _matching_repo_format = GitRepositoryFormat()
 
546
 
 
547
    def _target_has_shas(self, shas):
 
548
        raise NotImplementedError(self._target_has_shas)
 
549
 
 
550
    def get_determine_wants_heads(self, wants, include_tags=False):
 
551
        wants = set(wants)
 
552
        def determine_wants(refs):
 
553
            potential = set(wants)
 
554
            if include_tags:
 
555
                for k, unpeeled in refs.iteritems():
 
556
                    if k.endswith("^{}"):
 
557
                        continue
 
558
                    if not is_tag(k):
 
559
                        continue
 
560
                    if unpeeled == ZERO_SHA:
 
561
                        continue
 
562
                    potential.add(unpeeled)
 
563
            return list(potential - self._target_has_shas(potential))
 
564
        return determine_wants
 
565
 
 
566
    def determine_wants_all(self, refs):
 
567
        raise NotImplementedError(self.determine_wants_all)
 
568
 
 
569
    @staticmethod
 
570
    def _get_repo_format_to_test():
 
571
        return None
 
572
 
 
573
    def copy_content(self, revision_id=None):
 
574
        """See InterRepository.copy_content."""
 
575
        self.fetch(revision_id, find_ghosts=False)
 
576
 
 
577
    def search_missing_revision_ids(self,
 
578
            find_ghosts=True, revision_ids=None, if_present_ids=None,
 
579
            limit=None):
 
580
        if limit is not None:
 
581
            raise errors.FetchLimitUnsupported(self)
 
582
        git_shas = []
 
583
        todo = []
 
584
        if revision_ids:
 
585
            todo.extend(revision_ids)
 
586
        if if_present_ids:
 
587
            todo.extend(revision_ids)
 
588
        for revid in revision_ids:
 
589
            if revid == NULL_REVISION:
 
590
                continue
 
591
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
592
            git_shas.append(git_sha)
 
593
        walker = Walker(self.source._git.object_store,
 
594
            include=git_shas, exclude=[
 
595
                sha for sha in self.target.controldir.get_refs_container().as_dict().values()
 
596
                if sha != ZERO_SHA])
 
597
        missing_revids = set()
 
598
        for entry in walker:
 
599
            missing_revids.add(self.source.lookup_foreign_revision_id(entry.commit.id))
 
600
        return self.source.revision_ids_to_search_result(missing_revids)
 
601
 
 
602
 
 
603
class InterGitNonGitRepository(InterFromGitRepository):
 
604
    """Base InterRepository that copies revisions from a Git into a non-Git
 
605
    repository."""
 
606
 
 
607
    def _target_has_shas(self, shas):
 
608
        revids = {}
 
609
        for sha in shas:
 
610
            try:
 
611
                revid = self.source.lookup_foreign_revision_id(sha)
 
612
            except NotCommitError:
 
613
                # Commit is definitely not present
 
614
                continue
 
615
            else:
 
616
                revids[revid] = sha
 
617
        return set([revids[r] for r in self.target.has_revisions(revids)])
 
618
 
 
619
    def determine_wants_all(self, refs):
 
620
        potential = set()
 
621
        for k, v in refs.iteritems():
 
622
            # For non-git target repositories, only worry about peeled
 
623
            if v == ZERO_SHA:
 
624
                continue
 
625
            potential.add(self.source.controldir.get_peeled(k) or v)
 
626
        return list(potential - self._target_has_shas(potential))
 
627
 
 
628
    def get_determine_wants_heads(self, wants, include_tags=False):
 
629
        wants = set(wants)
 
630
        def determine_wants(refs):
 
631
            potential = set(wants)
 
632
            if include_tags:
 
633
                for k, unpeeled in refs.iteritems():
 
634
                    if not is_tag(k):
 
635
                        continue
 
636
                    if unpeeled == ZERO_SHA:
 
637
                        continue
 
638
                    potential.add(self.source.controldir.get_peeled(k) or unpeeled)
 
639
            return list(potential - self._target_has_shas(potential))
 
640
        return determine_wants
 
641
 
 
642
    def _warn_slow(self):
 
643
        trace.warning(
 
644
            'Fetching from Git to Bazaar repository. '
 
645
            'For better performance, fetch into a Git repository.')
 
646
 
 
647
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
 
648
        """Fetch objects from a remote server.
 
649
 
 
650
        :param determine_wants: determine_wants callback
 
651
        :param mapping: BzrGitMapping to use
 
652
        :param limit: Maximum number of commits to import.
 
653
        :return: Tuple with pack hint, last imported revision id and remote refs
 
654
        """
 
655
        raise NotImplementedError(self.fetch_objects)
 
656
 
 
657
    def get_determine_wants_revids(self, revids, include_tags=False):
 
658
        wants = set()
 
659
        for revid in set(revids):
 
660
            if self.target.has_revision(revid):
 
661
                continue
 
662
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
663
            wants.add(git_sha)
 
664
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
 
665
 
 
666
    def fetch(self, revision_id=None, find_ghosts=False,
 
667
              mapping=None, fetch_spec=None, include_tags=False):
 
668
        if mapping is None:
 
669
            mapping = self.source.get_mapping()
 
670
        if revision_id is not None:
 
671
            interesting_heads = [revision_id]
 
672
        elif fetch_spec is not None:
 
673
            recipe = fetch_spec.get_recipe()
 
674
            if recipe[0] in ("search", "proxy-search"):
 
675
                interesting_heads = recipe[1]
 
676
            else:
 
677
                raise AssertionError("Unsupported search result type %s" %
 
678
                        recipe[0])
 
679
        else:
 
680
            interesting_heads = None
 
681
 
 
682
        if interesting_heads is not None:
 
683
            determine_wants = self.get_determine_wants_revids(
 
684
                interesting_heads, include_tags=include_tags)
 
685
        else:
 
686
            determine_wants = self.determine_wants_all
 
687
 
 
688
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
 
689
            mapping)
 
690
        if pack_hint is not None and self.target._format.pack_compresses:
 
691
            self.target.pack(hint=pack_hint)
 
692
        return remote_refs
 
693
 
 
694
 
 
695
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
 
696
def report_git_progress(pb, text):
 
697
    text = text.rstrip("\r\n")
 
698
    trace.mutter('git: %s', text)
 
699
    g = _GIT_PROGRESS_RE.match(text)
 
700
    if g is not None:
 
701
        (text, pct, current, total) = g.groups()
 
702
        pb.update(text, int(current), int(total))
 
703
    else:
 
704
        pb.update(text, 0, 0)
 
705
 
 
706
 
 
707
class DetermineWantsRecorder(object):
 
708
 
 
709
    def __init__(self, actual):
 
710
        self.actual = actual
 
711
        self.wants = []
 
712
        self.remote_refs = {}
 
713
 
 
714
    def __call__(self, refs):
 
715
        if type(refs) is not dict:
 
716
            raise TypeError(refs)
 
717
        self.remote_refs = refs
 
718
        self.wants = self.actual(refs)
 
719
        return self.wants
 
720
 
 
721
 
 
722
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
 
723
    """InterRepository that copies revisions from a remote Git into a non-Git
 
724
    repository."""
 
725
 
 
726
    def get_target_heads(self):
 
727
        # FIXME: This should be more efficient
 
728
        all_revs = self.target.all_revision_ids()
 
729
        parent_map = self.target.get_parent_map(all_revs)
 
730
        all_parents = set()
 
731
        map(all_parents.update, parent_map.itervalues())
 
732
        return set(all_revs) - all_parents
 
733
 
 
734
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
 
735
        """See `InterGitNonGitRepository`."""
 
736
        self._warn_slow()
 
737
        store = BazaarObjectStore(self.target, mapping)
 
738
        with store.lock_write():
 
739
            heads = self.get_target_heads()
 
740
            graph_walker = ObjectStoreGraphWalker(
 
741
                [store._lookup_revision_sha1(head) for head in heads],
 
742
                lambda sha: store[sha].parents)
 
743
            wants_recorder = DetermineWantsRecorder(determine_wants)
 
744
 
 
745
            pb = ui.ui_factory.nested_progress_bar()
 
746
            try:
 
747
                objects_iter = self.source.fetch_objects(
 
748
                    wants_recorder, graph_walker, store.get_raw,
 
749
                    progress=lambda text: report_git_progress(pb, text),)
 
750
                trace.mutter("Importing %d new revisions",
 
751
                             len(wants_recorder.wants))
 
752
                (pack_hint, last_rev) = import_git_objects(self.target,
 
753
                    mapping, objects_iter, store, wants_recorder.wants, pb,
 
754
                    limit)
 
755
                return (pack_hint, last_rev, wants_recorder.remote_refs)
 
756
            finally:
 
757
                pb.finished()
 
758
 
 
759
    @staticmethod
 
760
    def is_compatible(source, target):
 
761
        """Be compatible with GitRepository."""
 
762
        if not isinstance(source, RemoteGitRepository):
 
763
            return False
 
764
        if not target.supports_rich_root():
 
765
            return False
 
766
        if isinstance(target, GitRepository):
 
767
            return False
 
768
        if not getattr(target._format, "supports_full_versioned_files", True):
 
769
            return False
 
770
        return True
 
771
 
 
772
 
 
773
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
 
774
    """InterRepository that copies revisions from a local Git into a non-Git
 
775
    repository."""
 
776
 
 
777
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
 
778
        """See `InterGitNonGitRepository`."""
 
779
        self._warn_slow()
 
780
        remote_refs = self.source.controldir.get_refs_container().as_dict()
 
781
        wants = determine_wants(remote_refs)
 
782
        create_pb = None
 
783
        pb = ui.ui_factory.nested_progress_bar()
 
784
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
 
785
        try:
 
786
            target_git_object_retriever.lock_write()
 
787
            try:
 
788
                (pack_hint, last_rev) = import_git_objects(self.target,
 
789
                    mapping, self.source._git.object_store,
 
790
                    target_git_object_retriever, wants, pb, limit)
 
791
                return (pack_hint, last_rev, remote_refs)
 
792
            finally:
 
793
                target_git_object_retriever.unlock()
 
794
        finally:
 
795
            pb.finished()
 
796
 
 
797
    @staticmethod
 
798
    def is_compatible(source, target):
 
799
        """Be compatible with GitRepository."""
 
800
        if not isinstance(source, LocalGitRepository):
 
801
            return False
 
802
        if not target.supports_rich_root():
 
803
            return False
 
804
        if isinstance(target, GitRepository):
 
805
            return False
 
806
        if not getattr(target._format, "supports_full_versioned_files", True):
 
807
            return False
 
808
        return True
 
809
 
 
810
 
 
811
class InterGitGitRepository(InterFromGitRepository):
 
812
    """InterRepository that copies between Git repositories."""
 
813
 
 
814
    def fetch_refs(self, update_refs, lossy=False):
 
815
        if lossy:
 
816
            raise errors.LossyPushToSameVCS(self.source, self.target)
 
817
        old_refs = self.target.controldir.get_refs_container()
 
818
        ref_changes = {}
 
819
        def determine_wants(heads):
 
820
            old_refs = dict([(k, (v, None)) for (k, v) in heads.as_dict().iteritems()])
 
821
            new_refs = update_refs(old_refs)
 
822
            ref_changes.update(new_refs)
 
823
            return [sha1 for (sha1, bzr_revid) in new_refs.itervalues()]
 
824
        self.fetch_objects(determine_wants, lossy=lossy)
 
825
        for k, (git_sha, bzr_revid) in ref_changes.iteritems():
 
826
            self.target._git.refs[k] = git_sha
 
827
        new_refs = self.target.controldir.get_refs_container()
 
828
        return None, old_refs, new_refs
 
829
 
 
830
    def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
 
831
        if lossy:
 
832
            raise errors.LossyPushToSameVCS(self.source, self.target)
 
833
        if limit is not None:
 
834
            raise errors.FetchLimitUnsupported(self)
 
835
        graphwalker = self.target._git.get_graph_walker()
 
836
        if (isinstance(self.source, LocalGitRepository) and
 
837
            isinstance(self.target, LocalGitRepository)):
 
838
            pb = ui.ui_factory.nested_progress_bar()
 
839
            try:
 
840
                refs = self.source._git.fetch(self.target._git, determine_wants,
 
841
                    lambda text: report_git_progress(pb, text))
 
842
            finally:
 
843
                pb.finished()
 
844
            return (None, None, refs)
 
845
        elif (isinstance(self.source, LocalGitRepository) and
 
846
              isinstance(self.target, RemoteGitRepository)):
 
847
            raise NotImplementedError
 
848
        elif (isinstance(self.source, RemoteGitRepository) and
 
849
              isinstance(self.target, LocalGitRepository)):
 
850
            pb = ui.ui_factory.nested_progress_bar()
 
851
            try:
 
852
                if CAPABILITY_THIN_PACK in self.source.controldir._client._fetch_capabilities:
 
853
                    # TODO(jelmer): Avoid reading entire file into memory and
 
854
                    # only processing it after the whole file has been fetched.
 
855
                    f = BytesIO()
 
856
 
 
857
                    def commit():
 
858
                        if f.tell():
 
859
                            f.seek(0)
 
860
                            self.target._git.object_store.move_in_thin_pack(f)
 
861
 
 
862
                    def abort():
 
863
                        pass
 
864
                else:
 
865
                    f, commit, abort = self.target._git.object_store.add_pack()
 
866
                try:
 
867
                    refs = self.source.controldir.fetch_pack(
 
868
                        determine_wants, graphwalker, f.write,
 
869
                        lambda text: report_git_progress(pb, text))
 
870
                    commit()
 
871
                    return (None, None, refs)
 
872
                except BaseException:
 
873
                    abort()
 
874
                    raise
 
875
            finally:
 
876
                pb.finished()
 
877
        else:
 
878
            raise AssertionError("fetching between %r and %r not supported" %
 
879
                    (self.source, self.target))
 
880
 
 
881
    def _target_has_shas(self, shas):
 
882
        return set([sha for sha in shas if sha in self.target._git.object_store])
 
883
 
 
884
    def fetch(self, revision_id=None, find_ghosts=False,
 
885
              mapping=None, fetch_spec=None, branches=None, limit=None, include_tags=False):
 
886
        if mapping is None:
 
887
            mapping = self.source.get_mapping()
 
888
        r = self.target._git
 
889
        if revision_id is not None:
 
890
            args = [revision_id]
 
891
        elif fetch_spec is not None:
 
892
            recipe = fetch_spec.get_recipe()
 
893
            if recipe[0] in ("search", "proxy-search"):
 
894
                heads = recipe[1]
 
895
            else:
 
896
                raise AssertionError(
 
897
                    "Unsupported search result type %s" % recipe[0])
 
898
            args = heads
 
899
        if branches is not None:
 
900
            def determine_wants(refs):
 
901
                ret = []
 
902
                for name, value in refs.iteritems():
 
903
                    if value == ZERO_SHA:
 
904
                        continue
 
905
 
 
906
                    if name in branches or (include_tags and is_tag(name)):
 
907
                        ret.append(value)
 
908
                return ret
 
909
        elif fetch_spec is None and revision_id is None:
 
910
            determine_wants = self.determine_wants_all
 
911
        else:
 
912
            determine_wants = self.get_determine_wants_revids(args, include_tags=include_tags)
 
913
        wants_recorder = DetermineWantsRecorder(determine_wants)
 
914
        self.fetch_objects(wants_recorder, mapping, limit=limit)
 
915
        return wants_recorder.remote_refs
 
916
 
 
917
    @staticmethod
 
918
    def is_compatible(source, target):
 
919
        """Be compatible with GitRepository."""
 
920
        return (isinstance(source, GitRepository) and
 
921
                isinstance(target, GitRepository))
 
922
 
 
923
    def get_determine_wants_revids(self, revids, include_tags=False):
 
924
        wants = set()
 
925
        for revid in set(revids):
 
926
            if self.target.has_revision(revid):
 
927
                continue
 
928
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
 
929
            wants.add(git_sha)
 
930
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
 
931
 
 
932
    def determine_wants_all(self, refs):
 
933
        potential = set([v for v in refs.values() if not v == ZERO_SHA])
 
934
        return list(potential - self._target_has_shas(potential))