/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: Canonical.com Patch Queue Manager
  • Date: 2006-04-13 23:16:57 UTC
  • mfrom: (1662.1.1 bzr.mbp.integration)
  • Revision ID: pqm@pqm.ubuntu.com-20060413231657-bce3d67d3e7a4f2b
(mbp/olaf) push/pull/merge --remember improvements

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