/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

be quieter.

Show diffs side-by-side

added added

removed removed

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