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

  • Committer: Jelmer Vernooij
  • Date: 2018-05-19 13:16:11 UTC
  • mto: (6968.4.3 git-archive)
  • mto: This revision was merged to the branch mainline in revision 6972.
  • Revision ID: jelmer@jelmer.uk-20180519131611-l9h9ud41j7qg1m03
Move tar/zip to breezy.archive.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008-2010 Jelmer Vernooij <jelmer@samba.org>
 
1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Fetching from git into bzr."""
 
18
 
 
19
from __future__ import absolute_import
16
20
 
17
21
from dulwich.objects import (
18
22
    Commit,
19
23
    Tag,
20
24
    Tree,
 
25
    S_IFGITLINK,
21
26
    S_ISGITLINK,
 
27
    ZERO_SHA,
22
28
    )
23
29
from dulwich.object_store import (
24
30
    tree_lookup_path,
25
31
    )
26
 
from itertools import (
27
 
    imap,
28
 
    )
 
32
from dulwich.walk import Walker
29
33
import posixpath
30
 
import re
31
34
import stat
32
35
 
33
 
from bzrlib import (
 
36
from ... import (
34
37
    debug,
 
38
    errors,
35
39
    osutils,
36
40
    trace,
37
41
    ui,
38
42
    )
39
 
from bzrlib.errors import (
 
43
from ...errors import (
40
44
    BzrError,
41
 
    NoSuchId,
42
45
    )
43
 
from bzrlib.inventory import (
44
 
    Inventory,
 
46
from ...bzr.inventory import (
45
47
    InventoryDirectory,
46
48
    InventoryFile,
47
49
    InventoryLink,
48
50
    TreeReference,
49
51
    )
50
 
from bzrlib.repository import (
 
52
from ...repository import (
51
53
    InterRepository,
52
54
    )
53
 
from bzrlib.revision import (
 
55
from ...revision import (
54
56
    NULL_REVISION,
55
57
    )
56
 
from bzrlib.revisiontree import (
57
 
    RevisionTree,
58
 
    )
59
 
from bzrlib.testament import (
 
58
from ...bzr.inventorytree import InventoryRevisionTree
 
59
from ...testament import (
60
60
    StrictTestament3,
61
61
    )
62
 
from bzrlib.tsort import (
 
62
from ...tsort import (
63
63
    topo_sort,
64
64
    )
65
 
from bzrlib.versionedfile import (
 
65
from ...bzr.versionedfile import (
66
66
    ChunkedContentFactory,
67
67
    )
68
68
 
69
 
from bzrlib.plugins.git.mapping import (
 
69
from .mapping import (
70
70
    DEFAULT_FILE_MODE,
71
71
    mode_is_executable,
72
72
    mode_kind,
73
73
    warn_unusual_mode,
74
74
    )
75
 
from bzrlib.plugins.git.object_store import (
76
 
    BazaarObjectStore,
 
75
from .object_store import (
77
76
    LRUTreeCache,
78
77
    _tree_to_objects,
79
78
    )
80
 
from bzrlib.plugins.git.remote import (
 
79
from .refs import (
 
80
    is_tag,
 
81
    )
 
82
from .remote import (
81
83
    RemoteGitRepository,
82
84
    )
83
 
from bzrlib.plugins.git.repository import (
 
85
from .repository import (
84
86
    GitRepository,
85
87
    GitRepositoryFormat,
86
88
    LocalGitRepository,
87
89
    )
88
90
 
89
91
 
90
 
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha), 
91
 
        base_inv, parent_id, revision_id,
92
 
        parent_invs, lookup_object, (base_mode, mode), store_updater,
 
92
def import_git_blob(texts, mapping, path, name, hexshas,
 
93
        base_bzr_tree, parent_id, revision_id,
 
94
        parent_bzr_trees, lookup_object, modes, store_updater,
93
95
        lookup_file_id):
94
96
    """Import a git blob object into a bzr repository.
95
97
 
98
100
    :param blob: A git blob
99
101
    :return: Inventory delta for this file
100
102
    """
101
 
    if mapping.is_control_file(path):
 
103
    (base_mode, mode) = modes
 
104
    (base_hexsha, hexsha) = hexshas
 
105
    if mapping.is_special_file(path):
102
106
        return []
103
107
    if base_hexsha == hexsha and base_mode == mode:
104
108
        # If nothing has changed since the base revision, we're done
112
116
    if ie.kind == "file":
113
117
        ie.executable = mode_is_executable(mode)
114
118
    if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
115
 
        base_ie = base_inv[base_inv.path2id(path)]
116
 
        ie.text_size = base_ie.text_size
117
 
        ie.text_sha1 = base_ie.text_sha1
 
119
        base_exec = base_bzr_tree.is_executable(path)
118
120
        if ie.kind == "symlink":
119
 
            ie.symlink_target = base_ie.symlink_target
120
 
        if ie.executable == base_ie.executable:
121
 
            ie.revision = base_ie.revision
 
121
            ie.symlink_target = base_bzr_tree.get_symlink_target(path)
 
122
        else:
 
123
            ie.text_size = base_bzr_tree.get_file_size(path)
 
124
            ie.text_sha1 = base_bzr_tree.get_file_sha1(path)
 
125
        if ie.kind == "symlink" or ie.executable == base_exec:
 
126
            ie.revision = base_bzr_tree.get_file_revision(path)
122
127
        else:
123
128
            blob = lookup_object(hexsha)
124
129
    else:
125
130
        blob = lookup_object(hexsha)
126
131
        if ie.kind == "symlink":
127
132
            ie.revision = None
128
 
            ie.symlink_target = blob.data
 
133
            ie.symlink_target = blob.data.decode("utf-8")
129
134
        else:
130
 
            ie.text_size = sum(imap(len, blob.chunked))
 
135
            ie.text_size = sum(map(len, blob.chunked))
131
136
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
132
137
    # Check what revision we should store
133
138
    parent_keys = []
134
 
    for pinv in parent_invs:
 
139
    for ptree in parent_bzr_trees:
135
140
        try:
136
 
            pie = pinv[file_id]
137
 
        except NoSuchId:
 
141
            ppath = ptree.id2path(file_id)
 
142
        except errors.NoSuchId:
138
143
            continue
139
 
        if (pie.text_sha1 == ie.text_sha1 and
140
 
            pie.executable == ie.executable and
141
 
            pie.symlink_target == ie.symlink_target):
 
144
        pkind = ptree.kind(ppath, file_id)
 
145
        if (pkind == ie.kind and
 
146
            ((pkind == "symlink" and ptree.get_symlink_target(ppath, file_id) == ie.symlink_target) or
 
147
             (pkind == "file" and ptree.get_file_sha1(ppath, file_id) == ie.text_sha1 and
 
148
                ptree.is_executable(ppath, file_id) == ie.executable))):
142
149
            # found a revision in one of the parents to use
143
 
            ie.revision = pie.revision
 
150
            ie.revision = ptree.get_file_revision(ppath, file_id)
144
151
            break
145
 
        parent_key = (file_id, pie.revision)
 
152
        parent_key = (file_id, ptree.get_file_revision(ppath, file_id))
146
153
        if not parent_key in parent_keys:
147
154
            parent_keys.append(parent_key)
148
155
    if ie.revision is None:
149
156
        # Need to store a new revision
150
157
        ie.revision = revision_id
151
 
        assert ie.revision is not None
 
158
        if ie.revision is None:
 
159
            raise ValueError("no file revision set")
152
160
        if ie.kind == 'symlink':
153
161
            chunks = []
154
 
        else: 
 
162
        else:
155
163
            chunks = blob.chunked
156
164
        texts.insert_record_stream([
157
165
            ChunkedContentFactory((file_id, ie.revision),
160
168
    if base_hexsha is not None:
161
169
        old_path = path.decode("utf-8") # Renames are not supported yet
162
170
        if stat.S_ISDIR(base_mode):
163
 
            invdelta.extend(remove_disappeared_children(base_inv, old_path,
 
171
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
164
172
                lookup_object(base_hexsha), [], lookup_object))
165
173
    else:
166
174
        old_path = None
167
175
    new_path = path.decode("utf-8")
168
176
    invdelta.append((old_path, new_path, file_id, ie))
169
177
    if base_hexsha != hexsha:
170
 
        store_updater.add_object(blob, ie, path)
 
178
        store_updater.add_object(blob, (ie.file_id, ie.revision), path)
171
179
    return invdelta
172
180
 
173
181
 
174
182
class SubmodulesRequireSubtrees(BzrError):
175
 
    _fmt = """The repository you are fetching from contains submodules. To continue, upgrade your Bazaar repository to a format that supports nested trees, such as 'development-subtree'."""
 
183
    _fmt = ("The repository you are fetching from contains submodules, "
 
184
            "which require a Bazaar format that supports tree references.")
176
185
    internal = False
177
186
 
178
187
 
179
 
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
180
 
    base_inv, parent_id, revision_id, parent_invs, lookup_object,
181
 
    (base_mode, mode), store_updater, lookup_file_id):
 
188
def import_git_submodule(texts, mapping, path, name, hexshas,
 
189
    base_bzr_tree, parent_id, revision_id, parent_bzr_trees, lookup_object,
 
190
    modes, store_updater, lookup_file_id):
 
191
    """Import a git submodule."""
 
192
    (base_hexsha, hexsha) = hexshas
 
193
    (base_mode, mode) = modes
182
194
    if base_hexsha == hexsha and base_mode == mode:
183
195
        return [], {}
184
196
    file_id = lookup_file_id(path)
 
197
    invdelta = []
185
198
    ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
186
199
    ie.revision = revision_id
187
 
    if base_hexsha is None:
188
 
        oldpath = None
 
200
    if base_hexsha is not None:
 
201
        old_path = path.decode("utf-8") # Renames are not supported yet
 
202
        if stat.S_ISDIR(base_mode):
 
203
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
 
204
                lookup_object(base_hexsha), [], lookup_object))
189
205
    else:
190
 
        oldpath = path
 
206
        old_path = None
191
207
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
192
208
    texts.insert_record_stream([
193
209
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
194
 
    invdelta = [(oldpath, path, file_id, ie)]
 
210
    invdelta.append((old_path, path, file_id, ie))
195
211
    return invdelta, {}
196
212
 
197
213
 
198
 
def remove_disappeared_children(base_inv, path, base_tree, existing_children,
 
214
def remove_disappeared_children(base_bzr_tree, path, base_tree, existing_children,
199
215
        lookup_object):
200
216
    """Generate an inventory delta for removed children.
201
217
 
202
 
    :param base_inv: Base inventory against which to generate the 
 
218
    :param base_bzr_tree: Base bzr tree against which to generate the
203
219
        inventory delta.
204
220
    :param path: Path to process (unicode)
205
221
    :param base_tree: Git Tree base object
207
223
    :param lookup_object: Lookup a git object by its SHA1
208
224
    :return: Inventory delta, as list
209
225
    """
210
 
    assert type(path) is unicode
 
226
    if type(path) is not unicode:
 
227
        raise TypeError(path)
211
228
    ret = []
212
229
    for name, mode, hexsha in base_tree.iteritems():
213
230
        if name in existing_children:
214
231
            continue
215
232
        c_path = posixpath.join(path, name.decode("utf-8"))
216
 
        file_id = base_inv.path2id(c_path)
217
 
        assert file_id is not None
 
233
        file_id = base_bzr_tree.path2id(c_path)
 
234
        if file_id is None:
 
235
            raise TypeError(file_id)
218
236
        ret.append((c_path, None, file_id, None))
219
237
        if stat.S_ISDIR(mode):
220
238
            ret.extend(remove_disappeared_children(
221
 
                base_inv, c_path, lookup_object(hexsha), [], lookup_object))
 
239
                base_bzr_tree, c_path, lookup_object(hexsha), [], lookup_object))
222
240
    return ret
223
241
 
224
242
 
225
 
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
226
 
        base_inv, parent_id, revision_id, parent_invs,
227
 
        lookup_object, (base_mode, mode), store_updater,
 
243
def import_git_tree(texts, mapping, path, name, hexshas,
 
244
        base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
 
245
        lookup_object, modes, store_updater,
228
246
        lookup_file_id, allow_submodules=False):
229
247
    """Import a git tree object into a bzr repository.
230
248
 
232
250
    :param path: Path in the tree (str)
233
251
    :param name: Name of the tree (str)
234
252
    :param tree: A git tree object
235
 
    :param base_inv: Base inventory against which to return inventory delta
 
253
    :param base_bzr_tree: Base inventory against which to return inventory delta
236
254
    :return: Inventory delta for this subtree
237
255
    """
238
 
    assert type(path) is str
239
 
    assert type(name) is str
 
256
    (base_hexsha, hexsha) = hexshas
 
257
    (base_mode, mode) = modes
 
258
    if type(path) is not str:
 
259
        raise TypeError(path)
 
260
    if type(name) is not str:
 
261
        raise TypeError(name)
240
262
    if base_hexsha == hexsha and base_mode == mode:
241
263
        # If nothing has changed since the base revision, we're done
242
264
        return [], {}
260
282
    # Remember for next time
261
283
    existing_children = set()
262
284
    child_modes = {}
263
 
    for child_mode, name, child_hexsha in tree.entries():
 
285
    for name, child_mode, child_hexsha in tree.iteritems():
264
286
        existing_children.add(name)
265
287
        child_path = posixpath.join(path, name)
266
288
        if type(base_tree) is Tree:
274
296
            child_base_mode = 0
275
297
        if stat.S_ISDIR(child_mode):
276
298
            subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
277
 
                child_path, name, (child_base_hexsha, child_hexsha), base_inv,
278
 
                file_id, revision_id, parent_invs, lookup_object, 
279
 
                (child_base_mode, child_mode), store_updater, lookup_file_id,
280
 
                allow_submodules=allow_submodules)
 
299
                child_path, name, (child_base_hexsha, child_hexsha),
 
300
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
 
301
                lookup_object, (child_base_mode, child_mode), store_updater,
 
302
                lookup_file_id, allow_submodules=allow_submodules)
281
303
        elif S_ISGITLINK(child_mode): # submodule
282
304
            if not allow_submodules:
283
305
                raise SubmodulesRequireSubtrees()
284
306
            subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
285
 
                child_path, name, (child_base_hexsha, child_hexsha), base_inv,
286
 
                file_id, revision_id, parent_invs, lookup_object,
287
 
                (child_base_mode, child_mode), store_updater, lookup_file_id)
 
307
                child_path, name, (child_base_hexsha, child_hexsha),
 
308
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
 
309
                lookup_object, (child_base_mode, child_mode), store_updater,
 
310
                lookup_file_id)
288
311
        else:
289
 
            subinvdelta = import_git_blob(texts, mapping, child_path, name,
290
 
                (child_base_hexsha, child_hexsha), base_inv, file_id,
291
 
                revision_id, parent_invs, lookup_object,
292
 
                (child_base_mode, child_mode), store_updater, lookup_file_id)
 
312
            if not mapping.is_special_file(name):
 
313
                subinvdelta = import_git_blob(texts, mapping, child_path, name,
 
314
                    (child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
 
315
                    revision_id, parent_bzr_trees, lookup_object,
 
316
                    (child_base_mode, child_mode), store_updater, lookup_file_id)
 
317
            else:
 
318
                subinvdelta = []
293
319
            grandchildmodes = {}
294
320
        child_modes.update(grandchildmodes)
295
321
        invdelta.extend(subinvdelta)
296
322
        if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
297
 
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
 
323
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0o111,
 
324
                        S_IFGITLINK):
298
325
            child_modes[child_path] = child_mode
299
326
    # Remove any children that have disappeared
300
327
    if base_tree is not None and type(base_tree) is Tree:
301
 
        invdelta.extend(remove_disappeared_children(base_inv, old_path,
 
328
        invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
302
329
            base_tree, existing_children, lookup_object))
303
 
    store_updater.add_object(tree, ie, path)
 
330
    store_updater.add_object(tree, (file_id, revision_id), path)
304
331
    return invdelta, child_modes
305
332
 
306
333
 
307
334
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
308
 
    o, rev, ret_tree, parent_trees, mapping, unusual_modes):
 
335
    o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
309
336
    new_unusual_modes = mapping.export_unusual_file_modes(rev)
310
337
    if new_unusual_modes != unusual_modes:
311
338
        raise AssertionError("unusual modes don't match: %r != %r" % (
312
339
            unusual_modes, new_unusual_modes))
313
340
    # Verify that we can reconstruct the commit properly
314
 
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True)
 
341
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
 
342
        verifiers)
315
343
    if rec_o != o:
316
344
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
317
345
            rec_o, o))
318
346
    diff = []
319
347
    new_objs = {}
320
348
    for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
321
 
        target_git_object_retriever._cache.idmap, unusual_modes, mapping.BZR_DUMMY_FILE):
 
349
        target_git_object_retriever._cache.idmap, unusual_modes,
 
350
        mapping.BZR_DUMMY_FILE):
322
351
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
323
352
        new_objs[path] = obj
324
353
        if obj.id != old_obj_id:
341
370
            old_obj, new_obj))
342
371
 
343
372
 
 
373
def ensure_inventories_in_repo(repo, trees):
 
374
    real_inv_vf = repo.inventories.without_fallbacks()
 
375
    for t in trees:
 
376
        revid = t.get_revision_id()
 
377
        if not real_inv_vf.get_parent_map([(revid, )]):
 
378
            repo.add_inventory(revid, t.inventory, t.get_parent_ids())
 
379
 
 
380
 
344
381
def import_git_commit(repo, mapping, head, lookup_object,
345
382
                      target_git_object_retriever, trees_cache):
346
383
    o = lookup_object(head)
347
 
    rev, roundtrip_revid, verifiers = mapping.import_commit(o,
348
 
            lambda x: target_git_object_retriever.lookup_git_sha(x)[1][0])
 
384
    # Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
 
385
    # were bzr roundtripped revisions they would be specified in the
 
386
    # roundtrip data.
 
387
    rev, roundtrip_revid, verifiers = mapping.import_commit(
 
388
        o, mapping.revision_id_foreign_to_bzr)
 
389
    if roundtrip_revid is not None:
 
390
        original_revid = rev.revision_id
 
391
        rev.revision_id = roundtrip_revid
349
392
    # We have to do this here, since we have to walk the tree and
350
393
    # we need to make sure to import the blobs / trees with the right
351
394
    # path; this may involve adding them more than once.
352
395
    parent_trees = trees_cache.revision_trees(rev.parent_ids)
 
396
    ensure_inventories_in_repo(repo, parent_trees)
353
397
    if parent_trees == []:
354
 
        base_inv = Inventory(root_id=None)
 
398
        base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
355
399
        base_tree = None
356
400
        base_mode = None
357
401
    else:
358
 
        base_inv = parent_trees[0].inventory
 
402
        base_bzr_tree = parent_trees[0]
359
403
        base_tree = lookup_object(o.parents[0]).tree
360
404
        base_mode = stat.S_IFDIR
361
405
    store_updater = target_git_object_retriever._get_updater(rev)
362
 
    fileid_map = mapping.get_fileid_map(lookup_object, o.tree)
 
406
    tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
363
407
    inv_delta, unusual_modes = import_git_tree(repo.texts,
364
 
            mapping, "", "", (base_tree, o.tree), base_inv,
365
 
            None, rev.revision_id, [p.inventory for p in parent_trees],
 
408
            mapping, "", "", (base_tree, o.tree), base_bzr_tree,
 
409
            None, rev.revision_id, parent_trees,
366
410
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
367
 
            fileid_map.lookup_file_id,
368
 
            allow_submodules=getattr(repo._format, "supports_tree_reference", False))
 
411
            tree_supplement.lookup_file_id,
 
412
            allow_submodules=getattr(repo._format, "supports_tree_reference",
 
413
                False))
369
414
    if unusual_modes != {}:
370
415
        for path, mode in unusual_modes.iteritems():
371
416
            warn_unusual_mode(rev.foreign_revid, path, mode)
374
419
        basis_id = rev.parent_ids[0]
375
420
    except IndexError:
376
421
        basis_id = NULL_REVISION
377
 
        base_inv = None
 
422
        base_bzr_inventory = None
 
423
    else:
 
424
        try:
 
425
            base_bzr_inventory = base_bzr_tree.root_inventory
 
426
        except AttributeError: # bzr < 2.6
 
427
            base_bzr_inventory = base_bzr_tree.inventory
378
428
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
379
 
              inv_delta, rev.revision_id, rev.parent_ids, base_inv)
380
 
    # FIXME: Check verifiers
381
 
    testament = StrictTestament3(rev, inv)
382
 
    calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
383
 
    if roundtrip_revid is not None:
384
 
        original_revid = rev.revision_id
385
 
        rev.revision_id = roundtrip_revid
 
429
              inv_delta, rev.revision_id, rev.parent_ids,
 
430
              base_bzr_inventory)
 
431
    ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
432
    # Check verifiers
 
433
    if verifiers and roundtrip_revid is not None:
 
434
        testament = StrictTestament3(rev, ret_tree)
 
435
        calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
386
436
        if calculated_verifiers != verifiers:
387
437
            trace.mutter("Testament SHA1 %r for %r did not match %r.",
388
438
                         calculated_verifiers["testament3-sha1"],
389
439
                         rev.revision_id, verifiers["testament3-sha1"])
390
440
            rev.revision_id = original_revid
 
441
            rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
442
              inv_delta, rev.revision_id, rev.parent_ids, base_bzr_tree)
 
443
            ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
 
444
    else:
 
445
        calculated_verifiers = {}
391
446
    store_updater.add_object(o, calculated_verifiers, None)
392
447
    store_updater.finish()
393
 
    ret_tree = RevisionTree(repo, inv, rev.revision_id)
394
448
    trees_cache.add(ret_tree)
395
449
    repo.add_revision(rev.revision_id, rev)
396
450
    if "verify" in debug.debug_flags:
397
 
        verify_commit_reconstruction(target_git_object_retriever, 
 
451
        verify_commit_reconstruction(target_git_object_retriever,
398
452
            lookup_object, o, rev, ret_tree, parent_trees, mapping,
399
 
            unusual_modes)
 
453
            unusual_modes, verifiers)
400
454
 
401
455
 
402
456
def import_git_objects(repo, mapping, object_iter,
422
476
        if pb is not None:
423
477
            pb.update("finding revisions to fetch", len(graph), None)
424
478
        head = heads.pop()
425
 
        assert isinstance(head, str)
 
479
        if head == ZERO_SHA:
 
480
            continue
 
481
        if type(head) is not str:
 
482
            raise TypeError(head)
426
483
        try:
427
484
            o = lookup_object(head)
428
485
        except KeyError:
429
486
            continue
430
487
        if isinstance(o, Commit):
431
488
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
432
 
                lambda x: None)
 
489
                mapping.revision_id_foreign_to_bzr)
433
490
            if (repo.has_revision(rev.revision_id) or
434
491
                (roundtrip_revid and repo.has_revision(roundtrip_revid))):
435
492
                continue
451
508
        revision_ids = revision_ids[:limit]
452
509
    last_imported = None
453
510
    for offset in range(0, len(revision_ids), batch_size):
454
 
        target_git_object_retriever.start_write_group() 
 
511
        target_git_object_retriever.start_write_group()
455
512
        try:
456
513
            repo.start_write_group()
457
514
            try:
478
535
    return pack_hints, last_imported
479
536
 
480
537
 
481
 
class InterGitRepository(InterRepository):
482
 
 
483
 
    _matching_repo_format = GitRepositoryFormat()
484
 
 
485
 
    @staticmethod
486
 
    def _get_repo_format_to_test():
487
 
        return None
488
 
 
489
 
    def copy_content(self, revision_id=None, pb=None):
490
 
        """See InterRepository.copy_content."""
491
 
        self.fetch(revision_id, pb, find_ghosts=False)
492
 
 
493
 
 
494
 
class InterGitNonGitRepository(InterGitRepository):
495
 
    """Base InterRepository that copies revisions from a Git into a non-Git
496
 
    repository."""
497
 
 
498
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
499
 
        """Fetch objects from a remote server.
500
 
 
501
 
        :param determine_wants: determine_wants callback
502
 
        :param mapping: BzrGitMapping to use
503
 
        :param pb: Optional progress bar
504
 
        :param limit: Maximum number of commits to import.
505
 
        :return: Tuple with pack hint, last imported revision id and remote refs
506
 
        """
507
 
        raise NotImplementedError(self.fetch_objects)
508
 
 
509
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
510
 
              mapping=None, fetch_spec=None):
511
 
        if mapping is None:
512
 
            mapping = self.source.get_mapping()
513
 
        if revision_id is not None:
514
 
            interesting_heads = [revision_id]
515
 
        elif fetch_spec is not None:
516
 
            interesting_heads = fetch_spec.heads
517
 
        else:
518
 
            interesting_heads = None
519
 
        def determine_wants(refs):
520
 
            if interesting_heads is None:
521
 
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
522
 
            else:
523
 
                ret = [self.source.lookup_bzr_revision_id(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
524
 
            return [rev for rev in ret if not self.target.has_revision(self.source.lookup_foreign_revision_id(rev))]
525
 
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants, mapping, pb)
526
 
        if pack_hint is not None and self.target._format.pack_compresses:
527
 
            self.target.pack(hint=pack_hint)
528
 
        return remote_refs
529
 
 
530
 
 
531
 
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
532
 
def report_git_progress(pb, text):
533
 
    text = text.rstrip("\r\n")
534
 
    g = _GIT_PROGRESS_RE.match(text)
535
 
    if g is not None:
536
 
        (text, pct, current, total) = g.groups()
537
 
        pb.update(text, int(current), int(total))
538
 
    else:
539
 
        pb.update(text, 0, 0)
540
 
 
541
 
 
542
538
class DetermineWantsRecorder(object):
543
539
 
544
540
    def __init__(self, actual):
547
543
        self.remote_refs = {}
548
544
 
549
545
    def __call__(self, refs):
 
546
        if type(refs) is not dict:
 
547
            raise TypeError(refs)
550
548
        self.remote_refs = refs
551
549
        self.wants = self.actual(refs)
552
550
        return self.wants
553
551
 
554
552
 
555
 
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
556
 
    """InterRepository that copies revisions from a remote Git into a non-Git
557
 
    repository."""
558
 
 
559
 
    def get_target_heads(self):
560
 
        # FIXME: This should be more efficient
561
 
        all_revs = self.target.all_revision_ids()
562
 
        parent_map = self.target.get_parent_map(all_revs)
563
 
        all_parents = set()
564
 
        map(all_parents.update, parent_map.itervalues())
565
 
        return set(all_revs) - all_parents
566
 
 
567
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
568
 
        """See `InterGitNonGitRepository`."""
569
 
        def progress(text):
570
 
            report_git_progress(pb, text)
571
 
        store = BazaarObjectStore(self.target, mapping)
572
 
        self.target.lock_write()
573
 
        try:
574
 
            heads = self.get_target_heads()
575
 
            graph_walker = store.get_graph_walker(
576
 
                    [store._lookup_revision_sha1(head) for head in heads])
577
 
            wants_recorder = DetermineWantsRecorder(determine_wants)
578
 
 
579
 
            create_pb = None
580
 
            if pb is None:
581
 
                create_pb = pb = ui.ui_factory.nested_progress_bar()
582
 
            try:
583
 
                objects_iter = self.source.fetch_objects(
584
 
                    wants_recorder, graph_walker, store.get_raw,
585
 
                    progress)
586
 
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
587
 
                    objects_iter, store, wants_recorder.wants, pb, limit)
588
 
                return (pack_hint, last_rev, wants_recorder.remote_refs)
589
 
            finally:
590
 
                if create_pb:
591
 
                    create_pb.finished()
592
 
        finally:
593
 
            self.target.unlock()
594
 
 
595
 
    @staticmethod
596
 
    def is_compatible(source, target):
597
 
        """Be compatible with GitRepository."""
598
 
        return (isinstance(source, RemoteGitRepository) and
599
 
                target.supports_rich_root() and
600
 
                not isinstance(target, GitRepository) and
601
 
                target.texts is not None)
602
 
 
603
 
 
604
 
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
605
 
    """InterRepository that copies revisions from a local Git into a non-Git
606
 
    repository."""
607
 
 
608
 
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
609
 
        """See `InterGitNonGitRepository`."""
610
 
        remote_refs = self.source._git.get_refs()
611
 
        wants = determine_wants(remote_refs)
612
 
        create_pb = None
613
 
        if pb is None:
614
 
            create_pb = pb = ui.ui_factory.nested_progress_bar()
615
 
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
616
 
        try:
617
 
            self.target.lock_write()
618
 
            try:
619
 
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
620
 
                    self.source._git.object_store,
621
 
                    target_git_object_retriever, wants, pb, limit)
622
 
                return (pack_hint, last_rev, remote_refs)
623
 
            finally:
624
 
                self.target.unlock()
625
 
        finally:
626
 
            if create_pb:
627
 
                create_pb.finished()
628
 
 
629
 
    @staticmethod
630
 
    def is_compatible(source, target):
631
 
        """Be compatible with GitRepository."""
632
 
        return (isinstance(source, LocalGitRepository) and
633
 
                target.supports_rich_root() and
634
 
                not isinstance(target, GitRepository) and
635
 
                target.texts is not None)
636
 
 
637
 
 
638
 
class InterGitGitRepository(InterGitRepository):
639
 
    """InterRepository that copies between Git repositories."""
640
 
 
641
 
    def fetch_objects(self, determine_wants, mapping, pb=None):
642
 
        def progress(text):
643
 
            trace.note("git: %s", text)
644
 
        graphwalker = self.target._git.get_graph_walker()
645
 
        if (isinstance(self.source, LocalGitRepository) and
646
 
            isinstance(self.target, LocalGitRepository)):
647
 
            refs = self.source._git.fetch(self.target._git, determine_wants,
648
 
                progress)
649
 
            return (None, None, refs)
650
 
        elif (isinstance(self.source, LocalGitRepository) and
651
 
              isinstance(self.target, RemoteGitRepository)):
652
 
            raise NotImplementedError
653
 
        elif (isinstance(self.source, RemoteGitRepository) and
654
 
              isinstance(self.target, LocalGitRepository)):
655
 
            f, commit = self.target._git.object_store.add_thin_pack()
656
 
            try:
657
 
                refs = self.source.bzrdir.root_transport.fetch_pack(
658
 
                    determine_wants, graphwalker, f.write, progress)
659
 
                commit()
660
 
                return (None, None, refs)
661
 
            except:
662
 
                f.close()
663
 
                raise
664
 
        else:
665
 
            raise AssertionError
666
 
 
667
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
668
 
              mapping=None, fetch_spec=None, branches=None):
669
 
        if mapping is None:
670
 
            mapping = self.source.get_mapping()
671
 
        r = self.target._git
672
 
        if revision_id is not None:
673
 
            args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]
674
 
        elif fetch_spec is not None:
675
 
            args = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in fetch_spec.heads]
676
 
        if branches is not None:
677
 
            determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store]
678
 
        elif fetch_spec is None and revision_id is None:
679
 
            determine_wants = r.object_store.determine_wants_all
680
 
        else:
681
 
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
682
 
        self.fetch_objects(determine_wants, mapping)
683
 
 
684
 
    @staticmethod
685
 
    def is_compatible(source, target):
686
 
        """Be compatible with GitRepository."""
687
 
        return (isinstance(source, GitRepository) and
688
 
                isinstance(target, GitRepository))
 
553