/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

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

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