/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to fetch.py

Fix revision_history test when no DeprecationWarning is printed and bzr 2.5
is used.

Older prereleases of bzr 2.5 didn't deprecate Branch.revision_history.

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