156
148
ie.revision = revision_id
157
149
assert file_id is not None
158
150
assert ie.revision is not None
159
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, blob.data)])
160
shamap = [(hexsha, "blob", (ie.file_id, ie.revision))]
163
if file_id in base_inv:
151
if ie.kind == 'symlink':
155
chunks = blob.chunked
156
except AttributeError: # older version of dulwich
158
texts.insert_record_stream([ChunkedContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, chunks)])
159
shamap = { ie.file_id: hexsha }
161
if base_ie is not None:
164
162
old_path = base_inv.id2path(file_id)
163
if base_ie.kind == "directory":
164
invdelta.extend(remove_disappeared_children(old_path, base_ie.children, []))
167
invdelta = [(old_path, path, file_id, ie)]
168
invdelta.extend(remove_disappeared_children(base_inv, base_ie, []))
167
invdelta.append((old_path, path, file_id, ie))
169
168
return (invdelta, shamap)
172
def import_git_submodule(texts, mapping, path, hexsha, base_inv, parent_id,
173
revision_id, parent_invs, shagitmap, lookup_object):
174
raise NotImplementedError(import_git_submodule)
177
def remove_disappeared_children(base_inv, base_ie, existing_children):
178
if base_ie is None or base_ie.kind != 'directory':
171
class SubmodulesRequireSubtrees(BzrError):
172
_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'."""
176
def import_git_submodule(texts, mapping, path, hexsha, base_inv, base_ie,
177
parent_id, revision_id, parent_invs, lookup_object):
178
file_id = mapping.generate_file_id(path)
179
ie = TreeReference(file_id, urlutils.basename(path.decode("utf-8")),
181
ie.revision = revision_id
186
if (base_ie.kind == ie.kind and
187
base_ie.reference_revision == ie.reference_revision):
188
ie.revision = base_ie.revision
189
ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
190
texts.insert_record_stream([ChunkedContentFactory((file_id, ie.revision), (), None, [])])
191
invdelta = [(oldpath, path, file_id, ie)]
192
return invdelta, {}, {}
195
def remove_disappeared_children(path, base_children, existing_children):
181
deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
197
deletable = [(osutils.pathjoin(path, k), v) for k,v in base_children.iteritems() if k not in existing_children]
184
ret.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
199
(path, ie) = deletable.pop()
200
ret.append((path, None, ie.file_id, None))
185
201
if ie.kind == "directory":
186
deletable.extend(ie.children.values())
202
for name, child_ie in ie.children.iteritems():
203
deletable.append((osutils.pathjoin(path, name), child_ie))
190
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id,
191
revision_id, parent_invs, shagitmap, lookup_object):
207
def import_git_tree(texts, mapping, path, hexsha, base_inv, base_inv_shamap,
208
base_ie, parent_id, revision_id, parent_invs, lookup_object,
209
allow_submodules=False):
192
210
"""Import a git tree object into a bzr repository.
194
212
:param texts: VersionedFiles object to add to
235
254
child_path = osutils.pathjoin(path, name)
236
255
if stat.S_ISDIR(mode):
237
256
subinvdelta, grandchildmodes, subshamap = import_git_tree(
238
texts, mapping, child_path, child_hexsha, base_inv,
239
file_id, revision_id, parent_invs, shagitmap, lookup_object)
240
invdelta.extend(subinvdelta)
241
child_modes.update(grandchildmodes)
242
shamap.extend(subshamap)
257
texts, mapping, child_path, child_hexsha, base_inv,
258
base_inv_shamap, base_children.get(basename), file_id,
259
revision_id, parent_invs, lookup_object,
260
allow_submodules=allow_submodules)
243
261
elif S_ISGITLINK(mode): # submodule
262
if not allow_submodules:
263
raise SubmodulesRequireSubtrees()
244
264
subinvdelta, grandchildmodes, subshamap = import_git_submodule(
245
texts, mapping, child_path, child_hexsha, base_inv,
246
file_id, revision_id, parent_invs, shagitmap, lookup_object)
247
invdelta.extend(subinvdelta)
248
child_modes.update(grandchildmodes)
249
shamap.extend(subshamap)
265
texts, mapping, child_path, child_hexsha, base_inv, base_children.get(basename),
266
file_id, revision_id, parent_invs, lookup_object)
251
subinvdelta, subshamap = import_git_blob(texts, mapping,
252
child_path, child_hexsha, base_inv, file_id, revision_id,
253
parent_invs, shagitmap, lookup_object,
268
subinvdelta, subshamap = import_git_blob(texts, mapping,
269
child_path, child_hexsha, base_inv, base_inv_shamap,
270
base_children.get(basename), file_id,
271
revision_id, parent_invs, lookup_object,
254
272
mode_is_executable(mode), stat.S_ISLNK(mode))
255
invdelta.extend(subinvdelta)
256
shamap.extend(subshamap)
274
child_modes.update(grandchildmodes)
275
invdelta.extend(subinvdelta)
276
shamap.update(subshamap)
257
277
if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
258
278
stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
259
279
child_modes[child_path] = mode
260
280
# Remove any children that have disappeared
261
invdelta.extend(remove_disappeared_children(base_inv, base_ie, existing_children))
262
shamap.append((hexsha, "tree", (file_id, revision_id)))
281
if base_ie is not None and base_ie.kind == "directory":
282
invdelta.extend(remove_disappeared_children(base_inv.id2path(file_id),
283
base_children, existing_children))
284
shamap[file_id] = hexsha
263
285
return invdelta, child_modes, shamap
266
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever,
288
def import_git_commit(repo, mapping, head, lookup_object,
289
target_git_object_retriever, parent_invs_cache):
290
o = lookup_object(head)
291
rev = mapping.import_commit(o)
292
# We have to do this here, since we have to walk the tree and
293
# we need to make sure to import the blobs / trees with the right
294
# path; this may involve adding them more than once.
295
parent_invs = parent_invs_cache.get_inventories(rev.parent_ids)
296
if parent_invs == []:
297
base_inv = Inventory(root_id=None)
299
base_inv_shamap = None # Should never be accessed
301
base_inv = parent_invs[0]
302
base_ie = base_inv.root
303
base_inv_shamap = target_git_object_retriever._idmap.get_inventory_sha_map(base_inv.revision_id)
304
inv_delta, unusual_modes, shamap = import_git_tree(repo.texts,
305
mapping, "", o.tree, base_inv, base_inv_shamap, base_ie, None,
306
rev.revision_id, parent_invs, lookup_object,
307
allow_submodules=getattr(repo._format, "supports_tree_reference", False))
309
for (oldpath, newpath, fileid, new_ie) in inv_delta:
311
entries.append((fileid, None, None, None))
313
if new_ie.kind in ("file", "symlink"):
314
entries.append((fileid, "blob", shamap[fileid], new_ie.revision))
315
elif new_ie.kind == "directory":
316
entries.append((fileid, "tree", shamap[fileid], rev.revision_id))
319
target_git_object_retriever._idmap.add_entries(rev.revision_id,
320
rev.parent_ids, head, o.tree, entries)
321
if unusual_modes != {}:
322
for path, mode in unusual_modes.iteritems():
323
warn_unusual_mode(rev.foreign_revid, path, mode)
324
mapping.import_unusual_file_modes(rev, unusual_modes)
326
basis_id = rev.parent_ids[0]
328
basis_id = NULL_REVISION
330
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
331
inv_delta, rev.revision_id, rev.parent_ids,
333
parent_invs_cache.add(rev.revision_id, inv)
334
repo.add_revision(rev.revision_id, rev)
335
if "verify" in debug.debug_flags:
336
new_unusual_modes = mapping.export_unusual_file_modes(rev)
337
if new_unusual_modes != unusual_modes:
338
raise AssertionError("unusual modes don't match: %r != %r" % (unusual_modes, new_unusual_modes))
339
objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping, unusual_modes)
340
for newsha1, newobj, path in objs:
341
assert path is not None
345
(oldmode, oldsha1) = tree_lookup_path(lookup_object, o.tree, path)
346
if oldsha1 != newsha1:
347
raise AssertionError("%r != %r in %s" % (oldsha1, newsha1, path))
350
def import_git_objects(repo, mapping, object_iter,
351
target_git_object_retriever, heads, pb=None, limit=None):
268
352
"""Import a set of git objects into a bzr repository.
270
354
:param repo: Target Bazaar repository
271
355
:param mapping: Mapping to use
272
356
:param object_iter: Iterator over Git objects.
357
:return: Tuple with pack hints and last imported revision id
274
359
def lookup_object(sha):
298
382
if repo.has_revision(rev.revision_id):
300
384
squash_revision(repo, rev)
301
root_trees[rev.revision_id] = o.tree
302
revisions[rev.revision_id] = rev
303
graph.append((rev.revision_id, rev.parent_ids))
304
target_git_object_retriever._idmap.add_entry(o.id, "commit",
305
(rev.revision_id, o.tree))
385
graph.append((o.id, o.parents))
306
386
heads.extend([p for p in o.parents if p not in checked])
307
387
elif isinstance(o, Tag):
308
heads.append(o.object[1])
388
if o.object[1] not in checked:
389
heads.append(o.object[1])
310
391
trace.warning("Unable to import head object %r" % o)
312
394
# Order the revisions
313
395
# Create the inventory objects
314
for i, revid in enumerate(topo_sort(graph)):
316
pb.update("fetching revisions", i, len(graph))
317
rev = revisions[revid]
318
# We have to do this here, since we have to walk the tree and
319
# we need to make sure to import the blobs / trees with the right
320
# path; this may involve adding them more than once.
322
for parent_id in rev.parent_ids:
324
parent_invs.append(parent_invs_cache[parent_id])
326
parent_inv = repo.get_inventory(parent_id)
327
parent_invs.append(parent_inv)
328
parent_invs_cache[parent_id] = parent_inv
329
if parent_invs == []:
330
base_inv = Inventory(root_id=None)
397
revision_ids = topo_sort(graph)
399
if limit is not None:
400
revision_ids = revision_ids[:limit]
402
for offset in range(0, len(revision_ids), batch_size):
403
repo.start_write_group()
405
for i, head in enumerate(revision_ids[offset:offset+batch_size]):
407
pb.update("fetching revisions", offset+i, len(revision_ids))
408
import_git_commit(repo, mapping, head, lookup_object,
409
target_git_object_retriever,
413
repo.abort_write_group()
332
base_inv = parent_invs[0]
333
inv_delta, unusual_modes, shamap = import_git_tree(repo.texts,
334
mapping, "", root_trees[revid], base_inv, None, revid,
335
parent_invs, target_git_object_retriever._idmap, lookup_object)
336
target_git_object_retriever._idmap.add_entries(shamap)
337
if unusual_modes != {}:
338
for path, mode in unusual_modes.iteritems():
339
warn_unusual_mode(rev.foreign_revid, path, mode)
340
mapping.import_unusual_file_modes(rev, unusual_modes)
342
basis_id = rev.parent_ids[0]
344
basis_id = NULL_REVISION
345
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
346
inv_delta, rev.revision_id, rev.parent_ids)
347
parent_invs_cache[rev.revision_id] = inv
348
repo.add_revision(rev.revision_id, rev)
349
if "verify" in debug.debug_flags:
350
new_unusual_modes = mapping.export_unusual_file_modes(rev)
351
if new_unusual_modes != unusual_modes:
352
raise AssertionError("unusual modes don't match: %r != %r" % (unusual_modes, new_unusual_modes))
353
objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping, unusual_modes)
354
for sha1, newobj, path in objs:
355
assert path is not None
356
oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
358
raise AssertionError("%r != %r in %s" % (oldobj, newobj, path))
360
target_git_object_retriever._idmap.commit()
416
hint = repo.commit_write_group()
418
pack_hints.extend(hint)
419
target_git_object_retriever.commit_write_group()
420
return pack_hints, last_imported
363
423
class InterGitRepository(InterRepository):
372
432
"""See InterRepository.copy_content."""
373
433
self.fetch(revision_id, pb, find_ghosts=False)
375
def fetch(self, revision_id=None, pb=None, find_ghosts=False, mapping=None,
377
self.fetch_refs(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts,
378
mapping=mapping, fetch_spec=fetch_spec)
435
def fetch(self, revision_id=None, pb=None, find_ghosts=False,
436
mapping=None, fetch_spec=None):
437
self.fetch_refs(revision_id=revision_id, pb=pb,
438
find_ghosts=find_ghosts, mapping=mapping, fetch_spec=fetch_spec)
381
441
class InterGitNonGitRepository(InterGitRepository):
382
"""Base InterRepository that copies revisions from a Git into a non-Git
442
"""Base InterRepository that copies revisions from a Git into a non-Git
385
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
445
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
386
446
mapping=None, fetch_spec=None):
387
447
if mapping is None:
388
448
mapping = self.source.get_mapping()
401
461
ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
402
462
return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
403
self.fetch_objects(determine_wants, mapping, pb)
463
(pack_hint, _) = self.fetch_objects(determine_wants, mapping, pb)
464
if pack_hint is not None and self.target._format.pack_compresses:
465
self.target.pack(hint=pack_hint)
466
if interesting_heads is not None:
467
present_interesting_heads = self.target.has_revisions(interesting_heads)
468
missing_interesting_heads = set(interesting_heads) - present_interesting_heads
469
if missing_interesting_heads:
470
raise AssertionError("Missing interesting heads: %r" % missing_interesting_heads)
404
471
return self._refs
474
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
475
def report_git_progress(pb, text):
476
text = text.rstrip("\r\n")
477
g = _GIT_PROGRESS_RE.match(text)
479
(text, pct, current, total) = g.groups()
480
pb.update(text, int(current), int(total))
482
pb.update(text, 0, 0)
407
485
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
408
"""InterRepository that copies revisions from a remote Git into a non-Git
486
"""InterRepository that copies revisions from a remote Git into a non-Git
411
def fetch_objects(self, determine_wants, mapping, pb=None):
489
def get_target_heads(self):
490
# FIXME: This should be more efficient
491
all_revs = self.target.all_revision_ids()
492
parent_map = self.target.get_parent_map(all_revs)
494
map(all_parents.update, parent_map.itervalues())
495
return set(all_revs) - all_parents
497
def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
412
498
def progress(text):
413
pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
499
report_git_progress(pb, text)
414
500
store = BazaarObjectStore(self.target, mapping)
415
501
self.target.lock_write()
417
heads = self.target.get_graph().heads(self.target.all_revision_ids())
503
heads = self.get_target_heads()
418
504
graph_walker = store.get_graph_walker(
419
505
[store._lookup_revision_sha1(head) for head in heads])
420
506
recorded_wants = []
490
570
class InterGitGitRepository(InterGitRepository):
491
571
"""InterRepository that copies between Git repositories."""
493
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
573
def fetch_objects(self, determine_wants, mapping, pb=None):
575
trace.note("git: %s", text)
576
graphwalker = self.target._git.get_graph_walker()
577
if (isinstance(self.source, LocalGitRepository) and
578
isinstance(self.target, LocalGitRepository)):
579
return self.source._git.fetch(self.target._git, determine_wants,
581
elif (isinstance(self.source, LocalGitRepository) and
582
isinstance(self.target, RemoteGitRepository)):
583
raise NotImplementedError
584
elif (isinstance(self.source, RemoteGitRepository) and
585
isinstance(self.target, LocalGitRepository)):
586
f, commit = self.target._git.object_store.add_thin_pack()
588
refs = self.source._git.fetch_pack(determine_wants,
589
graphwalker, f.write, progress)
598
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
494
599
mapping=None, fetch_spec=None, branches=None):
495
600
if mapping is None:
496
601
mapping = self.source.get_mapping()
498
trace.info("git: %s", text)
499
602
r = self.target._git
500
603
if revision_id is not None:
501
604
args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]