1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Fetching from git into bzr."""
19
from __future__ import absolute_import
21
from dulwich.objects import (
29
from dulwich.object_store import (
41
from ..errors import (
44
from ..bzr.inventory import (
50
from ..revision import (
53
from ..bzr.inventorytree import InventoryRevisionTree
54
from ..sixish import text_type
55
from ..bzr.testament import (
58
from ..tree import find_previous_path
62
from ..bzr.versionedfile import (
63
ChunkedContentFactory,
66
from .mapping import (
72
from .object_store import (
78
def import_git_blob(texts, mapping, path, name, hexshas,
79
base_bzr_tree, parent_id, revision_id,
80
parent_bzr_trees, lookup_object, modes, store_updater,
82
"""Import a git blob object into a bzr repository.
84
:param texts: VersionedFiles to add to
85
:param path: Path in the tree
86
:param blob: A git blob
87
:return: Inventory delta for this file
89
if not isinstance(path, bytes):
91
decoded_path = path.decode('utf-8')
92
(base_mode, mode) = modes
93
(base_hexsha, hexsha) = hexshas
94
if mapping.is_special_file(path):
96
if base_hexsha == hexsha and base_mode == mode:
97
# If nothing has changed since the base revision, we're done
99
file_id = lookup_file_id(decoded_path)
100
if stat.S_ISLNK(mode):
104
ie = cls(file_id, name.decode("utf-8"), parent_id)
105
if ie.kind == "file":
106
ie.executable = mode_is_executable(mode)
107
if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
108
base_exec = base_bzr_tree.is_executable(decoded_path)
109
if ie.kind == "symlink":
110
ie.symlink_target = base_bzr_tree.get_symlink_target(decoded_path)
112
ie.text_size = base_bzr_tree.get_file_size(decoded_path)
113
ie.text_sha1 = base_bzr_tree.get_file_sha1(decoded_path)
114
if ie.kind == "symlink" or ie.executable == base_exec:
115
ie.revision = base_bzr_tree.get_file_revision(decoded_path)
117
blob = lookup_object(hexsha)
119
blob = lookup_object(hexsha)
120
if ie.kind == "symlink":
122
ie.symlink_target = blob.data.decode("utf-8")
124
ie.text_size = sum(map(len, blob.chunked))
125
ie.text_sha1 = osutils.sha_strings(blob.chunked)
126
# Check what revision we should store
128
for ptree in parent_bzr_trees:
129
ppath = find_previous_path(base_bzr_tree, ptree, decoded_path, file_id, recurse='none')
132
pkind = ptree.kind(ppath)
133
if (pkind == ie.kind and
134
((pkind == "symlink" and ptree.get_symlink_target(ppath) == ie.symlink_target) or
135
(pkind == "file" and ptree.get_file_sha1(ppath) == ie.text_sha1 and
136
ptree.is_executable(ppath) == ie.executable))):
137
# found a revision in one of the parents to use
138
ie.revision = ptree.get_file_revision(ppath)
140
parent_key = (file_id, ptree.get_file_revision(ppath))
141
if parent_key not in parent_keys:
142
parent_keys.append(parent_key)
143
if ie.revision is None:
144
# Need to store a new revision
145
ie.revision = revision_id
146
if ie.revision is None:
147
raise ValueError("no file revision set")
148
if ie.kind == 'symlink':
151
chunks = blob.chunked
152
texts.insert_record_stream([
153
ChunkedContentFactory((file_id, ie.revision),
154
tuple(parent_keys), ie.text_sha1, chunks)])
156
if base_hexsha is not None:
157
old_path = decoded_path # Renames are not supported yet
158
if stat.S_ISDIR(base_mode):
159
invdelta.extend(remove_disappeared_children(
160
base_bzr_tree, old_path, lookup_object(base_hexsha), [],
164
invdelta.append((old_path, decoded_path, file_id, ie))
165
if base_hexsha != hexsha:
166
store_updater.add_object(blob, (ie.file_id, ie.revision), path)
170
class SubmodulesRequireSubtrees(BzrError):
171
_fmt = ("The repository you are fetching from contains submodules, "
172
"which require a Bazaar format that supports tree references.")
176
def import_git_submodule(texts, mapping, path, name, hexshas,
177
base_bzr_tree, parent_id, revision_id,
178
parent_bzr_trees, lookup_object,
179
modes, store_updater, lookup_file_id):
180
"""Import a git submodule."""
181
(base_hexsha, hexsha) = hexshas
182
(base_mode, mode) = modes
183
if base_hexsha == hexsha and base_mode == mode:
185
path = path.decode('utf-8')
186
file_id = lookup_file_id(path)
188
ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
189
ie.revision = revision_id
190
if base_hexsha is not None:
191
old_path = path # Renames are not supported yet
192
if stat.S_ISDIR(base_mode):
193
invdelta.extend(remove_disappeared_children(
194
base_bzr_tree, old_path, lookup_object(base_hexsha), [],
198
ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
199
texts.insert_record_stream([
200
ChunkedContentFactory((file_id, ie.revision), (), None, [])])
201
invdelta.append((old_path, path, file_id, ie))
205
def remove_disappeared_children(base_bzr_tree, path, base_tree,
206
existing_children, lookup_object):
207
"""Generate an inventory delta for removed children.
209
:param base_bzr_tree: Base bzr tree against which to generate the
211
:param path: Path to process (unicode)
212
:param base_tree: Git Tree base object
213
:param existing_children: Children that still exist
214
:param lookup_object: Lookup a git object by its SHA1
215
:return: Inventory delta, as list
217
if not isinstance(path, text_type):
218
raise TypeError(path)
220
for name, mode, hexsha in base_tree.iteritems():
221
if name in existing_children:
223
c_path = posixpath.join(path, name.decode("utf-8"))
224
file_id = base_bzr_tree.path2id(c_path)
226
raise TypeError(file_id)
227
ret.append((c_path, None, file_id, None))
228
if stat.S_ISDIR(mode):
229
ret.extend(remove_disappeared_children(
230
base_bzr_tree, c_path, lookup_object(hexsha), [],
235
def import_git_tree(texts, mapping, path, name, hexshas,
236
base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
237
lookup_object, modes, store_updater,
238
lookup_file_id, allow_submodules=False):
239
"""Import a git tree object into a bzr repository.
241
:param texts: VersionedFiles object to add to
242
:param path: Path in the tree (str)
243
:param name: Name of the tree (str)
244
:param tree: A git tree object
245
:param base_bzr_tree: Base inventory against which to return inventory
247
:return: Inventory delta for this subtree
249
(base_hexsha, hexsha) = hexshas
250
(base_mode, mode) = modes
251
if not isinstance(path, bytes):
252
raise TypeError(path)
253
if not isinstance(name, bytes):
254
raise TypeError(name)
255
if base_hexsha == hexsha and base_mode == mode:
256
# If nothing has changed since the base revision, we're done
259
file_id = lookup_file_id(osutils.safe_unicode(path))
260
# We just have to hope this is indeed utf-8:
261
ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
262
tree = lookup_object(hexsha)
263
if base_hexsha is None:
265
old_path = None # Newly appeared here
267
base_tree = lookup_object(base_hexsha)
268
old_path = path.decode("utf-8") # Renames aren't supported yet
269
new_path = path.decode("utf-8")
270
if base_tree is None or type(base_tree) is not Tree:
271
ie.revision = revision_id
272
invdelta.append((old_path, new_path, ie.file_id, ie))
273
texts.insert_record_stream([
274
ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
275
# Remember for next time
276
existing_children = set()
278
for name, child_mode, child_hexsha in tree.iteritems():
279
existing_children.add(name)
280
child_path = posixpath.join(path, name)
281
if type(base_tree) is Tree:
283
child_base_mode, child_base_hexsha = base_tree[name]
285
child_base_hexsha = None
288
child_base_hexsha = None
290
if stat.S_ISDIR(child_mode):
291
subinvdelta, grandchildmodes = import_git_tree(
292
texts, mapping, child_path, name,
293
(child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
294
revision_id, parent_bzr_trees, lookup_object,
295
(child_base_mode, child_mode), store_updater, lookup_file_id,
296
allow_submodules=allow_submodules)
297
elif S_ISGITLINK(child_mode): # submodule
298
if not allow_submodules:
299
raise SubmodulesRequireSubtrees()
300
subinvdelta, grandchildmodes = import_git_submodule(
301
texts, mapping, child_path, name,
302
(child_base_hexsha, child_hexsha),
303
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
304
lookup_object, (child_base_mode, child_mode), store_updater,
307
if not mapping.is_special_file(name):
308
subinvdelta = import_git_blob(
309
texts, mapping, child_path, name,
310
(child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
311
revision_id, parent_bzr_trees, lookup_object,
312
(child_base_mode, child_mode), store_updater,
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 | 0o111,
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(
326
base_bzr_tree, old_path, base_tree, existing_children,
328
store_updater.add_object(tree, (file_id, revision_id), path)
329
return invdelta, child_modes
332
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
333
o, rev, ret_tree, parent_trees, mapping,
334
unusual_modes, verifiers):
335
new_unusual_modes = mapping.export_unusual_file_modes(rev)
336
if new_unusual_modes != unusual_modes:
337
raise AssertionError("unusual modes don't match: %r != %r" % (
338
unusual_modes, new_unusual_modes))
339
# Verify that we can reconstruct the commit properly
340
rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
343
raise AssertionError("Reconstructed commit differs: %r != %r" % (
347
for path, obj, ie in _tree_to_objects(
348
ret_tree, parent_trees, target_git_object_retriever._cache.idmap,
349
unusual_modes, mapping.BZR_DUMMY_FILE):
350
old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
352
if obj.id != old_obj_id:
353
diff.append((path, lookup_object(old_obj_id), obj))
354
for (path, old_obj, new_obj) in diff:
355
while (old_obj.type_name == "tree"
356
and new_obj.type_name == "tree"
357
and sorted(old_obj) == sorted(new_obj)):
359
if old_obj[name][0] != new_obj[name][0]:
360
raise AssertionError(
361
"Modes for %s differ: %o != %o" %
362
(path, old_obj[name][0], new_obj[name][0]))
363
if old_obj[name][1] != new_obj[name][1]:
364
# Found a differing child, delve deeper
365
path = posixpath.join(path, name)
366
old_obj = lookup_object(old_obj[name][1])
367
new_obj = new_objs[path]
369
raise AssertionError(
370
"objects differ for %s: %r != %r" % (path, old_obj, new_obj))
373
def ensure_inventories_in_repo(repo, trees):
374
real_inv_vf = repo.inventories.without_fallbacks()
376
revid = t.get_revision_id()
377
if not real_inv_vf.get_parent_map([(revid, )]):
378
repo.add_inventory(revid, t.root_inventory, t.get_parent_ids())
381
def import_git_commit(repo, mapping, head, lookup_object,
382
target_git_object_retriever, trees_cache, strict):
383
o = lookup_object(head)
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
387
rev, roundtrip_revid, verifiers = mapping.import_commit(
388
o, mapping.revision_id_foreign_to_bzr, strict)
389
if roundtrip_revid is not None:
390
original_revid = rev.revision_id
391
rev.revision_id = roundtrip_revid
392
# We have to do this here, since we have to walk the tree and
393
# we need to make sure to import the blobs / trees with the right
394
# path; this may involve adding them more than once.
395
parent_trees = trees_cache.revision_trees(rev.parent_ids)
396
ensure_inventories_in_repo(repo, parent_trees)
397
if parent_trees == []:
398
base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
402
base_bzr_tree = parent_trees[0]
403
base_tree = lookup_object(o.parents[0]).tree
404
base_mode = stat.S_IFDIR
405
store_updater = target_git_object_retriever._get_updater(rev)
406
inv_delta, unusual_modes = import_git_tree(
407
repo.texts, mapping, b"", b"", (base_tree, o.tree), base_bzr_tree,
408
None, rev.revision_id, parent_trees, lookup_object,
409
(base_mode, stat.S_IFDIR), store_updater,
410
mapping.generate_file_id,
411
allow_submodules=repo._format.supports_tree_reference)
412
if unusual_modes != {}:
413
for path, mode in unusual_modes.iteritems():
414
warn_unusual_mode(rev.foreign_revid, path, mode)
415
mapping.import_unusual_file_modes(rev, unusual_modes)
417
basis_id = rev.parent_ids[0]
419
basis_id = NULL_REVISION
420
base_bzr_inventory = None
422
base_bzr_inventory = base_bzr_tree.root_inventory
423
rev.inventory_sha1, inv = repo.add_inventory_by_delta(
424
basis_id, inv_delta, rev.revision_id, rev.parent_ids,
426
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
428
if verifiers and roundtrip_revid is not None:
429
testament = StrictTestament3(rev, ret_tree)
430
calculated_verifiers = {"testament3-sha1": testament.as_sha1()}
431
if calculated_verifiers != verifiers:
432
trace.mutter("Testament SHA1 %r for %r did not match %r.",
433
calculated_verifiers["testament3-sha1"],
434
rev.revision_id, verifiers["testament3-sha1"])
435
rev.revision_id = original_revid
436
rev.inventory_sha1, inv = repo.add_inventory_by_delta(
437
basis_id, inv_delta, rev.revision_id, rev.parent_ids,
439
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
441
calculated_verifiers = {}
442
store_updater.add_object(o, calculated_verifiers, None)
443
store_updater.finish()
444
trees_cache.add(ret_tree)
445
repo.add_revision(rev.revision_id, rev)
446
if "verify" in debug.debug_flags:
447
verify_commit_reconstruction(
448
target_git_object_retriever, lookup_object, o, rev, ret_tree,
449
parent_trees, mapping, unusual_modes, verifiers)
452
def import_git_objects(repo, mapping, object_iter,
453
target_git_object_retriever, heads, pb=None,
455
"""Import a set of git objects into a bzr repository.
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
462
def lookup_object(sha):
464
return object_iter[sha]
466
return target_git_object_retriever[sha]
469
heads = list(set(heads))
470
trees_cache = LRUTreeCache(repo)
471
# Find and convert commit objects
474
pb.update("finding revisions to fetch", len(graph), None)
478
if not isinstance(head, bytes):
479
raise TypeError(head)
481
o = lookup_object(head)
484
if isinstance(o, Commit):
485
rev, roundtrip_revid, verifiers = mapping.import_commit(
486
o, mapping.revision_id_foreign_to_bzr, strict=True)
487
if (repo.has_revision(rev.revision_id)
488
or (roundtrip_revid and
489
repo.has_revision(roundtrip_revid))):
491
graph.append((o.id, o.parents))
492
heads.extend([p for p in o.parents if p not in checked])
493
elif isinstance(o, Tag):
494
if o.object[1] not in checked:
495
heads.append(o.object[1])
497
trace.warning("Unable to import head object %r" % o)
500
# Order the revisions
501
# Create the inventory objects
503
revision_ids = topo_sort(graph)
505
if limit is not None:
506
revision_ids = revision_ids[:limit]
508
for offset in range(0, len(revision_ids), batch_size):
509
target_git_object_retriever.start_write_group()
511
repo.start_write_group()
513
for i, head in enumerate(
514
revision_ids[offset:offset + batch_size]):
516
pb.update("fetching revisions", offset + i,
518
import_git_commit(repo, mapping, head, lookup_object,
519
target_git_object_retriever, trees_cache,
522
except BaseException:
523
repo.abort_write_group()
526
hint = repo.commit_write_group()
528
pack_hints.extend(hint)
529
except BaseException:
530
target_git_object_retriever.abort_write_group()
533
target_git_object_retriever.commit_write_group()
534
return pack_hints, last_imported
537
class DetermineWantsRecorder(object):
539
def __init__(self, actual):
542
self.remote_refs = {}
544
def __call__(self, refs):
545
if type(refs) is not dict:
546
raise TypeError(refs)
547
self.remote_refs = refs
548
self.wants = self.actual(refs)