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
33
from itertools import (
47
from ...errors import (
50
from ...bzr.inventory import (
56
from ...repository import (
59
from ...revision import (
62
from ...bzr.inventorytree import InventoryRevisionTree
63
from ...testament import (
66
from ...tsort import (
69
from ...bzr.versionedfile import (
70
ChunkedContentFactory,
73
from .mapping import (
79
from .object_store import (
88
from .repository import (
95
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha),
96
base_bzr_tree, parent_id, revision_id,
97
parent_bzr_trees, lookup_object, (base_mode, mode), store_updater,
99
"""Import a git blob object into a bzr repository.
101
:param texts: VersionedFiles to add to
102
:param path: Path in the tree
103
:param blob: A git blob
104
:return: Inventory delta for this file
106
if mapping.is_special_file(path):
108
if base_hexsha == hexsha and base_mode == mode:
109
# If nothing has changed since the base revision, we're done
111
file_id = lookup_file_id(path)
112
if stat.S_ISLNK(mode):
116
ie = cls(file_id, name.decode("utf-8"), parent_id)
117
if ie.kind == "file":
118
ie.executable = mode_is_executable(mode)
119
if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
120
base_exec = base_bzr_tree.is_executable(path)
121
if ie.kind == "symlink":
122
ie.symlink_target = base_bzr_tree.get_symlink_target(path)
124
ie.text_size = base_bzr_tree.get_file_size(path)
125
ie.text_sha1 = base_bzr_tree.get_file_sha1(path)
126
if ie.kind == "symlink" or ie.executable == base_exec:
127
ie.revision = base_bzr_tree.get_file_revision(path)
129
blob = lookup_object(hexsha)
131
blob = lookup_object(hexsha)
132
if ie.kind == "symlink":
134
ie.symlink_target = blob.data.decode("utf-8")
136
ie.text_size = sum(imap(len, blob.chunked))
137
ie.text_sha1 = osutils.sha_strings(blob.chunked)
138
# Check what revision we should store
140
for ptree in parent_bzr_trees:
142
ppath = ptree.id2path(file_id)
143
except errors.NoSuchId:
145
pkind = ptree.kind(ppath, file_id)
146
if (pkind == ie.kind and
147
((pkind == "symlink" and ptree.get_symlink_target(ppath, file_id) == ie.symlink_target) or
148
(pkind == "file" and ptree.get_file_sha1(ppath, file_id) == ie.text_sha1 and
149
ptree.is_executable(ppath, file_id) == ie.executable))):
150
# found a revision in one of the parents to use
151
ie.revision = ptree.get_file_revision(ppath, file_id)
153
parent_key = (file_id, ptree.get_file_revision(ppath, file_id))
154
if not parent_key in parent_keys:
155
parent_keys.append(parent_key)
156
if ie.revision is None:
157
# Need to store a new revision
158
ie.revision = revision_id
159
if ie.revision is None:
160
raise ValueError("no file revision set")
161
if ie.kind == 'symlink':
164
chunks = blob.chunked
165
texts.insert_record_stream([
166
ChunkedContentFactory((file_id, ie.revision),
167
tuple(parent_keys), ie.text_sha1, chunks)])
169
if base_hexsha is not None:
170
old_path = path.decode("utf-8") # Renames are not supported yet
171
if stat.S_ISDIR(base_mode):
172
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
173
lookup_object(base_hexsha), [], lookup_object))
176
new_path = path.decode("utf-8")
177
invdelta.append((old_path, new_path, file_id, ie))
178
if base_hexsha != hexsha:
179
store_updater.add_object(blob, (ie.file_id, ie.revision), path)
183
class SubmodulesRequireSubtrees(BzrError):
184
_fmt = ("The repository you are fetching from contains submodules, "
185
"which are not yet supported.")
189
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
190
base_bzr_tree, parent_id, revision_id, parent_bzr_trees, lookup_object,
191
(base_mode, mode), store_updater, lookup_file_id):
192
"""Import a git submodule."""
193
if base_hexsha == hexsha and base_mode == mode:
195
file_id = lookup_file_id(path)
197
ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
198
ie.revision = revision_id
199
if base_hexsha is not None:
200
old_path = path.decode("utf-8") # Renames are not supported yet
201
if stat.S_ISDIR(base_mode):
202
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
203
lookup_object(base_hexsha), [], lookup_object))
206
ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
207
texts.insert_record_stream([
208
ChunkedContentFactory((file_id, ie.revision), (), None, [])])
209
invdelta.append((old_path, path, file_id, ie))
213
def remove_disappeared_children(base_bzr_tree, path, base_tree, existing_children,
215
"""Generate an inventory delta for removed children.
217
:param base_bzr_tree: Base bzr tree against which to generate the
219
:param path: Path to process (unicode)
220
:param base_tree: Git Tree base object
221
:param existing_children: Children that still exist
222
:param lookup_object: Lookup a git object by its SHA1
223
:return: Inventory delta, as list
225
if type(path) is not unicode:
226
raise TypeError(path)
228
for name, mode, hexsha in base_tree.iteritems():
229
if name in existing_children:
231
c_path = posixpath.join(path, name.decode("utf-8"))
232
file_id = base_bzr_tree.path2id(c_path)
234
raise TypeError(file_id)
235
ret.append((c_path, None, file_id, None))
236
if stat.S_ISDIR(mode):
237
ret.extend(remove_disappeared_children(
238
base_bzr_tree, c_path, lookup_object(hexsha), [], lookup_object))
242
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
243
base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
244
lookup_object, (base_mode, mode), store_updater,
245
lookup_file_id, allow_submodules=False):
246
"""Import a git tree object into a bzr repository.
248
:param texts: VersionedFiles object to add to
249
:param path: Path in the tree (str)
250
:param name: Name of the tree (str)
251
:param tree: A git tree object
252
:param base_bzr_tree: Base inventory against which to return inventory delta
253
:return: Inventory delta for this subtree
255
if type(path) is not str:
256
raise TypeError(path)
257
if type(name) is not str:
258
raise TypeError(name)
259
if base_hexsha == hexsha and base_mode == mode:
260
# If nothing has changed since the base revision, we're done
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:
269
old_path = None # Newly appeared here
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()
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:
287
child_base_mode, child_base_hexsha = base_tree[name]
289
child_base_hexsha = None
292
child_base_hexsha = None
294
if stat.S_ISDIR(child_mode):
295
subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
296
child_path, name, (child_base_hexsha, child_hexsha),
297
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
298
lookup_object, (child_base_mode, child_mode), store_updater,
299
lookup_file_id, allow_submodules=allow_submodules)
300
elif S_ISGITLINK(child_mode): # submodule
301
if not allow_submodules:
302
raise SubmodulesRequireSubtrees()
303
subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
304
child_path, name, (child_base_hexsha, child_hexsha),
305
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
306
lookup_object, (child_base_mode, child_mode), store_updater,
309
if not mapping.is_special_file(name):
310
subinvdelta = import_git_blob(texts, mapping, child_path, name,
311
(child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
312
revision_id, parent_bzr_trees, lookup_object,
313
(child_base_mode, child_mode), store_updater, lookup_file_id)
317
child_modes.update(grandchildmodes)
318
invdelta.extend(subinvdelta)
319
if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
320
stat.S_IFLNK, DEFAULT_FILE_MODE|0111,
322
child_modes[child_path] = child_mode
323
# Remove any children that have disappeared
324
if base_tree is not None and type(base_tree) is Tree:
325
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
326
base_tree, existing_children, lookup_object))
327
store_updater.add_object(tree, (file_id, ), path)
328
return invdelta, child_modes
331
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
332
o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
333
new_unusual_modes = mapping.export_unusual_file_modes(rev)
334
if new_unusual_modes != unusual_modes:
335
raise AssertionError("unusual modes don't match: %r != %r" % (
336
unusual_modes, new_unusual_modes))
337
# Verify that we can reconstruct the commit properly
338
rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
341
raise AssertionError("Reconstructed commit differs: %r != %r" % (
345
for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
346
target_git_object_retriever._cache.idmap, unusual_modes,
347
mapping.BZR_DUMMY_FILE):
348
old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
350
if obj.id != old_obj_id:
351
diff.append((path, lookup_object(old_obj_id), obj))
352
for (path, old_obj, new_obj) in diff:
353
while (old_obj.type_name == "tree" and
354
new_obj.type_name == "tree" and
355
sorted(old_obj) == sorted(new_obj)):
357
if old_obj[name][0] != new_obj[name][0]:
358
raise AssertionError("Modes for %s differ: %o != %o" %
359
(path, old_obj[name][0], new_obj[name][0]))
360
if old_obj[name][1] != new_obj[name][1]:
361
# Found a differing child, delve deeper
362
path = posixpath.join(path, name)
363
old_obj = lookup_object(old_obj[name][1])
364
new_obj = new_objs[path]
366
raise AssertionError("objects differ for %s: %r != %r" % (path,
370
def ensure_inventories_in_repo(repo, trees):
371
real_inv_vf = repo.inventories.without_fallbacks()
373
revid = t.get_revision_id()
374
if not real_inv_vf.get_parent_map([(revid, )]):
375
repo.add_inventory(revid, t.inventory, t.get_parent_ids())
378
def import_git_commit(repo, mapping, head, lookup_object,
379
target_git_object_retriever, trees_cache):
380
o = lookup_object(head)
381
# Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
382
# were bzr roundtripped revisions they would be specified in the
384
rev, roundtrip_revid, verifiers = mapping.import_commit(
385
o, mapping.revision_id_foreign_to_bzr)
386
if roundtrip_revid is not None:
387
original_revid = rev.revision_id
388
rev.revision_id = roundtrip_revid
389
# We have to do this here, since we have to walk the tree and
390
# we need to make sure to import the blobs / trees with the right
391
# path; this may involve adding them more than once.
392
parent_trees = trees_cache.revision_trees(rev.parent_ids)
393
ensure_inventories_in_repo(repo, parent_trees)
394
if parent_trees == []:
395
base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
399
base_bzr_tree = parent_trees[0]
400
base_tree = lookup_object(o.parents[0]).tree
401
base_mode = stat.S_IFDIR
402
store_updater = target_git_object_retriever._get_updater(rev)
403
tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
404
inv_delta, unusual_modes = import_git_tree(repo.texts,
405
mapping, "", "", (base_tree, o.tree), base_bzr_tree,
406
None, rev.revision_id, parent_trees,
407
lookup_object, (base_mode, stat.S_IFDIR), store_updater,
408
tree_supplement.lookup_file_id,
409
allow_submodules=getattr(repo._format, "supports_tree_reference",
411
if unusual_modes != {}:
412
for path, mode in unusual_modes.iteritems():
413
warn_unusual_mode(rev.foreign_revid, path, mode)
414
mapping.import_unusual_file_modes(rev, unusual_modes)
416
basis_id = rev.parent_ids[0]
418
basis_id = NULL_REVISION
419
base_bzr_inventory = None
422
base_bzr_inventory = base_bzr_tree.root_inventory
423
except AttributeError: # bzr < 2.6
424
base_bzr_inventory = base_bzr_tree.inventory
425
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
426
inv_delta, rev.revision_id, rev.parent_ids,
428
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
430
if verifiers and roundtrip_revid is not None:
431
testament = StrictTestament3(rev, ret_tree)
432
calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
433
if calculated_verifiers != verifiers:
434
trace.mutter("Testament SHA1 %r for %r did not match %r.",
435
calculated_verifiers["testament3-sha1"],
436
rev.revision_id, verifiers["testament3-sha1"])
437
rev.revision_id = original_revid
438
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
439
inv_delta, rev.revision_id, rev.parent_ids, base_bzr_tree)
440
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
442
calculated_verifiers = {}
443
store_updater.add_object(o, calculated_verifiers, None)
444
store_updater.finish()
445
trees_cache.add(ret_tree)
446
repo.add_revision(rev.revision_id, rev)
447
if "verify" in debug.debug_flags:
448
verify_commit_reconstruction(target_git_object_retriever,
449
lookup_object, o, rev, ret_tree, parent_trees, mapping,
450
unusual_modes, verifiers)
453
def import_git_objects(repo, mapping, object_iter,
454
target_git_object_retriever, heads, pb=None, limit=None):
455
"""Import a set of git objects into a bzr repository.
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 type(head) is not str:
479
raise TypeError(head)
481
o = lookup_object(head)
484
if isinstance(o, Commit):
485
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
486
mapping.revision_id_foreign_to_bzr)
487
if (repo.has_revision(rev.revision_id) or
488
(roundtrip_revid and repo.has_revision(roundtrip_revid))):
490
graph.append((o.id, o.parents))
491
heads.extend([p for p in o.parents if p not in checked])
492
elif isinstance(o, Tag):
493
if o.object[1] not in checked:
494
heads.append(o.object[1])
496
trace.warning("Unable to import head object %r" % o)
499
# Order the revisions
500
# Create the inventory objects
502
revision_ids = topo_sort(graph)
504
if limit is not None:
505
revision_ids = revision_ids[:limit]
507
for offset in range(0, len(revision_ids), batch_size):
508
target_git_object_retriever.start_write_group()
510
repo.start_write_group()
512
for i, head in enumerate(
513
revision_ids[offset:offset+batch_size]):
515
pb.update("fetching revisions", offset+i,
517
import_git_commit(repo, mapping, head, lookup_object,
518
target_git_object_retriever, trees_cache)
521
repo.abort_write_group()
524
hint = repo.commit_write_group()
526
pack_hints.extend(hint)
528
target_git_object_retriever.abort_write_group()
531
target_git_object_retriever.commit_write_group()
532
return pack_hints, last_imported
535
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
536
def report_git_progress(pb, text):
537
text = text.rstrip("\r\n")
538
trace.mutter('git: %s', text)
539
g = _GIT_PROGRESS_RE.match(text)
541
(text, pct, current, total) = g.groups()
542
pb.update(text, int(current), int(total))
544
pb.update(text, 0, 0)
547
class DetermineWantsRecorder(object):
549
def __init__(self, actual):
552
self.remote_refs = {}
554
def __call__(self, refs):
555
if type(refs) is not dict:
556
raise TypeError(refs)
557
self.remote_refs = refs
558
self.wants = self.actual(refs)