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 (
32
from dulwich.walk import Walker
43
from ..errors import (
46
from ..bzr.inventory import (
52
from ..repository import (
55
from ..revision import (
58
from ..bzr.inventorytree import InventoryRevisionTree
59
from ..sixish import text_type
60
from ..testament import (
66
from ..bzr.versionedfile import (
67
ChunkedContentFactory,
70
from .mapping import (
76
from .object_store import (
86
from .repository import (
93
def import_git_blob(texts, mapping, path, name, hexshas,
94
base_bzr_tree, parent_id, revision_id,
95
parent_bzr_trees, lookup_object, modes, store_updater,
97
"""Import a git blob object into a bzr repository.
99
:param texts: VersionedFiles to add to
100
:param path: Path in the tree
101
:param blob: A git blob
102
:return: Inventory delta for this file
104
if not isinstance(path, bytes):
105
raise TypeError(path)
106
decoded_path = path.decode('utf-8')
107
(base_mode, mode) = modes
108
(base_hexsha, hexsha) = hexshas
109
if mapping.is_special_file(path):
111
if base_hexsha == hexsha and base_mode == mode:
112
# If nothing has changed since the base revision, we're done
114
file_id = lookup_file_id(decoded_path)
115
if stat.S_ISLNK(mode):
119
ie = cls(file_id, name.decode("utf-8"), parent_id)
120
if ie.kind == "file":
121
ie.executable = mode_is_executable(mode)
122
if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
123
base_exec = base_bzr_tree.is_executable(decoded_path)
124
if ie.kind == "symlink":
125
ie.symlink_target = base_bzr_tree.get_symlink_target(decoded_path)
127
ie.text_size = base_bzr_tree.get_file_size(decoded_path)
128
ie.text_sha1 = base_bzr_tree.get_file_sha1(decoded_path)
129
if ie.kind == "symlink" or ie.executable == base_exec:
130
ie.revision = base_bzr_tree.get_file_revision(decoded_path)
132
blob = lookup_object(hexsha)
134
blob = lookup_object(hexsha)
135
if ie.kind == "symlink":
137
ie.symlink_target = blob.data.decode("utf-8")
139
ie.text_size = sum(map(len, blob.chunked))
140
ie.text_sha1 = osutils.sha_strings(blob.chunked)
141
# Check what revision we should store
143
for ptree in parent_bzr_trees:
145
ppaths = base_bzr_tree.find_related_paths_across_trees([decoded_path], trees=[ptree])
146
except errors.PathsNotVersionedError:
149
pkind = ptree.kind(ppath, file_id)
150
if (pkind == ie.kind and
151
((pkind == "symlink" and ptree.get_symlink_target(ppath, file_id) == ie.symlink_target) or
152
(pkind == "file" and ptree.get_file_sha1(ppath, file_id) == ie.text_sha1 and
153
ptree.is_executable(ppath, file_id) == ie.executable))):
154
# found a revision in one of the parents to use
155
ie.revision = ptree.get_file_revision(ppath, file_id)
157
parent_key = (file_id, ptree.get_file_revision(ppath, file_id))
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
if ie.revision is None:
164
raise ValueError("no file revision set")
165
if ie.kind == 'symlink':
168
chunks = blob.chunked
169
texts.insert_record_stream([
170
ChunkedContentFactory((file_id, ie.revision),
171
tuple(parent_keys), ie.text_sha1, chunks)])
173
if base_hexsha is not None:
174
old_path = decoded_path # 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))
180
invdelta.append((old_path, decoded_path, file_id, ie))
181
if base_hexsha != hexsha:
182
store_updater.add_object(blob, (ie.file_id, ie.revision), path)
186
class SubmodulesRequireSubtrees(BzrError):
187
_fmt = ("The repository you are fetching from contains submodules, "
188
"which require a Bazaar format that supports tree references.")
192
def import_git_submodule(texts, mapping, path, name, hexshas,
193
base_bzr_tree, parent_id, revision_id, parent_bzr_trees, lookup_object,
194
modes, store_updater, lookup_file_id):
195
"""Import a git submodule."""
196
(base_hexsha, hexsha) = hexshas
197
(base_mode, mode) = modes
198
if base_hexsha == hexsha and base_mode == mode:
200
file_id = lookup_file_id(path)
202
ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
203
ie.revision = revision_id
204
if base_hexsha is not None:
205
old_path = path.decode("utf-8") # Renames are not supported yet
206
if stat.S_ISDIR(base_mode):
207
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
208
lookup_object(base_hexsha), [], lookup_object))
211
ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
212
texts.insert_record_stream([
213
ChunkedContentFactory((file_id, ie.revision), (), None, [])])
214
invdelta.append((old_path, path, file_id, ie))
218
def remove_disappeared_children(base_bzr_tree, path, base_tree, existing_children,
220
"""Generate an inventory delta for removed children.
222
:param base_bzr_tree: Base bzr tree against which to generate the
224
:param path: Path to process (unicode)
225
:param base_tree: Git Tree base object
226
:param existing_children: Children that still exist
227
:param lookup_object: Lookup a git object by its SHA1
228
:return: Inventory delta, as list
230
if not isinstance(path, text_type):
231
raise TypeError(path)
233
for name, mode, hexsha in base_tree.iteritems():
234
if name in existing_children:
236
c_path = posixpath.join(path, name.decode("utf-8"))
237
file_id = base_bzr_tree.path2id(c_path)
239
raise TypeError(file_id)
240
ret.append((c_path, None, file_id, None))
241
if stat.S_ISDIR(mode):
242
ret.extend(remove_disappeared_children(
243
base_bzr_tree, c_path, lookup_object(hexsha), [], lookup_object))
247
def import_git_tree(texts, mapping, path, name, hexshas,
248
base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
249
lookup_object, modes, store_updater,
250
lookup_file_id, allow_submodules=False):
251
"""Import a git tree object into a bzr repository.
253
:param texts: VersionedFiles object to add to
254
:param path: Path in the tree (str)
255
:param name: Name of the tree (str)
256
:param tree: A git tree object
257
:param base_bzr_tree: Base inventory against which to return inventory delta
258
:return: Inventory delta for this subtree
260
(base_hexsha, hexsha) = hexshas
261
(base_mode, mode) = modes
262
if not isinstance(path, bytes):
263
raise TypeError(path)
264
if not isinstance(name, bytes):
265
raise TypeError(name)
266
if base_hexsha == hexsha and base_mode == mode:
267
# If nothing has changed since the base revision, we're done
270
file_id = lookup_file_id(osutils.safe_unicode(path))
271
# We just have to hope this is indeed utf-8:
272
ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
273
tree = lookup_object(hexsha)
274
if base_hexsha is None:
276
old_path = None # Newly appeared here
278
base_tree = lookup_object(base_hexsha)
279
old_path = path.decode("utf-8") # Renames aren't supported yet
280
new_path = path.decode("utf-8")
281
if base_tree is None or type(base_tree) is not Tree:
282
ie.revision = revision_id
283
invdelta.append((old_path, new_path, ie.file_id, ie))
284
texts.insert_record_stream([
285
ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
286
# Remember for next time
287
existing_children = set()
289
for name, child_mode, child_hexsha in tree.iteritems():
290
existing_children.add(name)
291
child_path = posixpath.join(path, name)
292
if type(base_tree) is Tree:
294
child_base_mode, child_base_hexsha = base_tree[name]
296
child_base_hexsha = None
299
child_base_hexsha = None
301
if stat.S_ISDIR(child_mode):
302
subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
303
child_path, name, (child_base_hexsha, child_hexsha),
304
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
305
lookup_object, (child_base_mode, child_mode), store_updater,
306
lookup_file_id, allow_submodules=allow_submodules)
307
elif S_ISGITLINK(child_mode): # submodule
308
if not allow_submodules:
309
raise SubmodulesRequireSubtrees()
310
subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
311
child_path, name, (child_base_hexsha, child_hexsha),
312
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
313
lookup_object, (child_base_mode, child_mode), store_updater,
316
if not mapping.is_special_file(name):
317
subinvdelta = import_git_blob(texts, mapping, child_path, name,
318
(child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
319
revision_id, parent_bzr_trees, lookup_object,
320
(child_base_mode, child_mode), store_updater, lookup_file_id)
324
child_modes.update(grandchildmodes)
325
invdelta.extend(subinvdelta)
326
if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
327
stat.S_IFLNK, DEFAULT_FILE_MODE|0o111,
329
child_modes[child_path] = child_mode
330
# Remove any children that have disappeared
331
if base_tree is not None and type(base_tree) is Tree:
332
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
333
base_tree, existing_children, lookup_object))
334
store_updater.add_object(tree, (file_id, revision_id), path)
335
return invdelta, child_modes
338
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
339
o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
340
new_unusual_modes = mapping.export_unusual_file_modes(rev)
341
if new_unusual_modes != unusual_modes:
342
raise AssertionError("unusual modes don't match: %r != %r" % (
343
unusual_modes, new_unusual_modes))
344
# Verify that we can reconstruct the commit properly
345
rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
348
raise AssertionError("Reconstructed commit differs: %r != %r" % (
352
for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
353
target_git_object_retriever._cache.idmap, unusual_modes,
354
mapping.BZR_DUMMY_FILE):
355
old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
357
if obj.id != old_obj_id:
358
diff.append((path, lookup_object(old_obj_id), obj))
359
for (path, old_obj, new_obj) in diff:
360
while (old_obj.type_name == "tree" and
361
new_obj.type_name == "tree" and
362
sorted(old_obj) == sorted(new_obj)):
364
if old_obj[name][0] != new_obj[name][0]:
365
raise AssertionError("Modes for %s differ: %o != %o" %
366
(path, old_obj[name][0], new_obj[name][0]))
367
if old_obj[name][1] != new_obj[name][1]:
368
# Found a differing child, delve deeper
369
path = posixpath.join(path, name)
370
old_obj = lookup_object(old_obj[name][1])
371
new_obj = new_objs[path]
373
raise AssertionError("objects differ for %s: %r != %r" % (path,
377
def ensure_inventories_in_repo(repo, trees):
378
real_inv_vf = repo.inventories.without_fallbacks()
380
revid = t.get_revision_id()
381
if not real_inv_vf.get_parent_map([(revid, )]):
382
repo.add_inventory(revid, t.root_inventory, t.get_parent_ids())
385
def import_git_commit(repo, mapping, head, lookup_object,
386
target_git_object_retriever, trees_cache):
387
o = lookup_object(head)
388
# Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
389
# were bzr roundtripped revisions they would be specified in the
391
rev, roundtrip_revid, verifiers = mapping.import_commit(
392
o, mapping.revision_id_foreign_to_bzr)
393
if roundtrip_revid is not None:
394
original_revid = rev.revision_id
395
rev.revision_id = roundtrip_revid
396
# We have to do this here, since we have to walk the tree and
397
# we need to make sure to import the blobs / trees with the right
398
# path; this may involve adding them more than once.
399
parent_trees = trees_cache.revision_trees(rev.parent_ids)
400
ensure_inventories_in_repo(repo, parent_trees)
401
if parent_trees == []:
402
base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
406
base_bzr_tree = parent_trees[0]
407
base_tree = lookup_object(o.parents[0]).tree
408
base_mode = stat.S_IFDIR
409
store_updater = target_git_object_retriever._get_updater(rev)
410
tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
411
inv_delta, unusual_modes = import_git_tree(repo.texts,
412
mapping, b"", b"", (base_tree, o.tree), base_bzr_tree,
413
None, rev.revision_id, parent_trees,
414
lookup_object, (base_mode, stat.S_IFDIR), store_updater,
415
tree_supplement.lookup_file_id,
416
allow_submodules=repo._format.supports_tree_reference)
417
if unusual_modes != {}:
418
for path, mode in unusual_modes.iteritems():
419
warn_unusual_mode(rev.foreign_revid, path, mode)
420
mapping.import_unusual_file_modes(rev, unusual_modes)
422
basis_id = rev.parent_ids[0]
424
basis_id = NULL_REVISION
425
base_bzr_inventory = None
427
base_bzr_inventory = base_bzr_tree.root_inventory
428
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
429
inv_delta, rev.revision_id, rev.parent_ids,
431
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
433
if verifiers and roundtrip_revid is not None:
434
testament = StrictTestament3(rev, ret_tree)
435
calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
436
if calculated_verifiers != verifiers:
437
trace.mutter("Testament SHA1 %r for %r did not match %r.",
438
calculated_verifiers["testament3-sha1"],
439
rev.revision_id, verifiers["testament3-sha1"])
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)
445
calculated_verifiers = {}
446
store_updater.add_object(o, calculated_verifiers, None)
447
store_updater.finish()
448
trees_cache.add(ret_tree)
449
repo.add_revision(rev.revision_id, rev)
450
if "verify" in debug.debug_flags:
451
verify_commit_reconstruction(target_git_object_retriever,
452
lookup_object, o, rev, ret_tree, parent_trees, mapping,
453
unusual_modes, verifiers)
456
def import_git_objects(repo, mapping, object_iter,
457
target_git_object_retriever, heads, pb=None, limit=None):
458
"""Import a set of git objects into a bzr repository.
460
:param repo: Target Bazaar repository
461
:param mapping: Mapping to use
462
:param object_iter: Iterator over Git objects.
463
:return: Tuple with pack hints and last imported revision id
465
def lookup_object(sha):
467
return object_iter[sha]
469
return target_git_object_retriever[sha]
472
heads = list(set(heads))
473
trees_cache = LRUTreeCache(repo)
474
# Find and convert commit objects
477
pb.update("finding revisions to fetch", len(graph), None)
481
if not isinstance(head, bytes):
482
raise TypeError(head)
484
o = lookup_object(head)
487
if isinstance(o, Commit):
488
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
489
mapping.revision_id_foreign_to_bzr)
490
if (repo.has_revision(rev.revision_id) or
491
(roundtrip_revid and repo.has_revision(roundtrip_revid))):
493
graph.append((o.id, o.parents))
494
heads.extend([p for p in o.parents if p not in checked])
495
elif isinstance(o, Tag):
496
if o.object[1] not in checked:
497
heads.append(o.object[1])
499
trace.warning("Unable to import head object %r" % o)
502
# Order the revisions
503
# Create the inventory objects
505
revision_ids = topo_sort(graph)
507
if limit is not None:
508
revision_ids = revision_ids[:limit]
510
for offset in range(0, len(revision_ids), batch_size):
511
target_git_object_retriever.start_write_group()
513
repo.start_write_group()
515
for i, head in enumerate(
516
revision_ids[offset:offset+batch_size]):
518
pb.update("fetching revisions", offset+i,
520
import_git_commit(repo, mapping, head, lookup_object,
521
target_git_object_retriever, trees_cache)
524
repo.abort_write_group()
527
hint = repo.commit_write_group()
529
pack_hints.extend(hint)
531
target_git_object_retriever.abort_write_group()
534
target_git_object_retriever.commit_write_group()
535
return pack_hints, last_imported
538
class DetermineWantsRecorder(object):
540
def __init__(self, actual):
543
self.remote_refs = {}
545
def __call__(self, refs):
546
if type(refs) is not dict:
547
raise TypeError(refs)
548
self.remote_refs = refs
549
self.wants = self.actual(refs)