150
151
ie.revision = revision_id
151
152
assert file_id is not None
152
153
assert ie.revision is not None
153
if ie.kind == 'symlink':
157
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, data)])
154
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, blob.data)])
158
155
shamap = [(hexsha, "blob", (ie.file_id, ie.revision))]
162
if base_ie is not None:
158
if file_id in base_inv:
163
159
old_path = base_inv.id2path(file_id)
164
if base_ie.kind == "directory":
165
invdelta.extend(remove_disappeared_children(old_path, base_ie.children, []))
168
invdelta.append((old_path, path, file_id, ie))
169
return (invdelta, shamap)
172
class SubmodulesRequireSubtrees(BzrError):
173
_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'."""
177
def import_git_submodule(texts, mapping, path, hexsha, base_inv, base_ie,
178
parent_id, revision_id, parent_invs, shagitmap, lookup_object):
179
file_id = mapping.generate_file_id(path)
180
ie = TreeReference(file_id, urlutils.basename(path.decode("utf-8")),
182
ie.revision = revision_id
187
if (base_ie.kind == ie.kind and
188
base_ie.reference_revision == ie.reference_revision):
189
ie.revision = base_ie.revision
190
ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
191
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), (), None, "")])
192
invdelta = [(oldpath, path, file_id, ie)]
193
return invdelta, {}, {}
196
def remove_disappeared_children(path, base_children, existing_children):
198
deletable = [(osutils.pathjoin(path, k), v) for k,v in base_children.iteritems() if k not in existing_children]
200
(path, ie) = deletable.pop()
201
ret.append((path, None, ie.file_id, None))
202
if ie.kind == "directory":
203
for name, child_ie in ie.children.iteritems():
204
deletable.append((osutils.pathjoin(path, name), child_ie))
208
def import_git_tree(texts, mapping, path, hexsha, base_inv, base_ie, parent_id,
209
revision_id, parent_invs, shagitmap, lookup_object, allow_submodules=False):
162
return ([(old_path, path, file_id, ie)], shamap)
165
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id,
166
revision_id, parent_invs, shagitmap, lookup_object):
210
167
"""Import a git tree object into a bzr repository.
212
169
:param texts: VersionedFiles object to add to
219
176
file_id = mapping.generate_file_id(path)
220
177
# We just have to hope this is indeed utf-8:
221
ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")),
178
ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")),
182
base_ie = base_inv[file_id]
224
184
# Newly appeared here
225
186
ie.revision = revision_id
226
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), (), None, "")])
187
texts.add_lines((file_id, ie.revision), (), [])
227
188
invdelta.append((None, path, file_id, ie))
190
base_sha = base_ie.text_id
229
191
# See if this has changed at all
231
base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
194
base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
235
198
if base_sha == hexsha:
236
199
# If nothing has changed since the base revision, we're done
237
200
return [], {}, []
238
if base_ie.kind != "directory":
239
ie.revision = revision_id
240
texts.insert_record_stream([FulltextContentFactory((ie.file_id, ie.revision), (), None, "")])
241
invdelta.append((base_inv.id2path(ie.file_id), path, ie.file_id, ie))
242
if base_ie is not None and base_ie.kind == "directory":
243
base_children = base_ie.children
246
201
# Remember for next time
247
202
existing_children = set()
253
208
existing_children.add(basename)
254
209
child_path = osutils.pathjoin(path, name)
255
210
if stat.S_ISDIR(mode):
256
subinvdelta, grandchildmodes, subshamap = import_git_tree(
257
texts, mapping, child_path, child_hexsha, base_inv,
258
base_children.get(basename), file_id, revision_id,
259
parent_invs, shagitmap, lookup_object,
260
allow_submodules=allow_submodules)
261
invdelta.extend(subinvdelta)
262
child_modes.update(grandchildmodes)
263
shamap.extend(subshamap)
264
elif S_ISGITLINK(mode): # submodule
265
if not allow_submodules:
266
raise SubmodulesRequireSubtrees()
267
subinvdelta, grandchildmodes, subshamap = import_git_submodule(
268
texts, mapping, child_path, child_hexsha, base_inv, base_children.get(basename),
269
file_id, revision_id, parent_invs, shagitmap, lookup_object)
211
subinvdelta, grandchildmodes, subshamap = import_git_tree(texts,
212
mapping, child_path, child_hexsha, base_inv, file_id,
213
revision_id, parent_invs, shagitmap, lookup_object)
270
214
invdelta.extend(subinvdelta)
271
215
child_modes.update(grandchildmodes)
272
216
shamap.extend(subshamap)
274
subinvdelta, subshamap = import_git_blob(texts, mapping,
275
child_path, child_hexsha, base_inv, base_children.get(basename), file_id,
276
revision_id, parent_invs, shagitmap, lookup_object,
277
mode_is_executable(mode), stat.S_ISLNK(mode))
218
fs_mode = stat.S_IMODE(mode)
219
symlink = stat.S_ISLNK(mode)
220
subinvdelta, subshamap = import_git_blob(texts, mapping,
221
child_path, child_hexsha, base_inv, file_id, revision_id,
222
parent_invs, shagitmap, lookup_object,
223
bool(fs_mode & 0111), symlink)
278
224
invdelta.extend(subinvdelta)
279
225
shamap.extend(subshamap)
280
226
if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
281
227
stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
282
228
child_modes[child_path] = mode
283
229
# Remove any children that have disappeared
284
if base_ie is not None and base_ie.kind == "directory":
285
invdelta.extend(remove_disappeared_children(base_inv.id2path(file_id),
286
base_children, existing_children))
230
if base_ie is not None:
231
deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
234
invdelta.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
235
if ie.kind == "directory":
236
deletable.extend(ie.children.values())
287
237
shamap.append((hexsha, "tree", (file_id, revision_id)))
288
238
return invdelta, child_modes, shamap
291
def approx_inv_size(inv):
292
# Very rough estimate, 1k per inventory entry
293
return len(inv) * 1024
296
def import_git_commit(repo, mapping, head, lookup_object,
297
target_git_object_retriever, parent_invs_cache):
298
o = lookup_object(head)
299
rev = mapping.import_commit(o)
300
# We have to do this here, since we have to walk the tree and
301
# we need to make sure to import the blobs / trees with the right
302
# path; this may involve adding them more than once.
304
for parent_id in rev.parent_ids:
306
parent_invs.append(parent_invs_cache[parent_id])
308
parent_inv = repo.get_inventory(parent_id)
309
parent_invs.append(parent_inv)
310
parent_invs_cache[parent_id] = parent_inv
311
if parent_invs == []:
312
base_inv = Inventory(root_id=None)
315
base_inv = parent_invs[0]
316
base_ie = base_inv.root
317
inv_delta, unusual_modes, shamap = import_git_tree(repo.texts,
318
mapping, "", o.tree, base_inv, base_ie, None, rev.revision_id,
319
parent_invs, target_git_object_retriever._idmap, lookup_object,
320
allow_submodules=getattr(repo._format, "supports_tree_reference", False))
321
target_git_object_retriever._idmap.add_entries(shamap)
322
if unusual_modes != {}:
323
for path, mode in unusual_modes.iteritems():
324
warn_unusual_mode(rev.foreign_revid, path, mode)
325
mapping.import_unusual_file_modes(rev, unusual_modes)
327
basis_id = rev.parent_ids[0]
329
basis_id = NULL_REVISION
331
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
332
inv_delta, rev.revision_id, rev.parent_ids,
334
parent_invs_cache[rev.revision_id] = inv
335
repo.add_revision(rev.revision_id, rev)
336
if "verify" in debug.debug_flags:
337
new_unusual_modes = mapping.export_unusual_file_modes(rev)
338
if new_unusual_modes != unusual_modes:
339
raise AssertionError("unusual modes don't match: %r != %r" % (unusual_modes, new_unusual_modes))
340
objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping, unusual_modes)
341
for sha1, newobj, path in objs:
342
assert path is not None
343
oldobj = tree_lookup_path(lookup_object, o.tree, path)
345
raise AssertionError("%r != %r in %s" % (oldobj, newobj, path))
348
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever,
241
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever,
350
243
"""Import a set of git objects into a bzr repository.
352
:param repo: Target Bazaar repository
245
:param repo: Bazaar repository
353
246
:param mapping: Mapping to use
354
247
:param object_iter: Iterator over Git objects.
356
target_git_object_retriever._idmap.start_write_group() # FIXME: try/finally
357
249
def lookup_object(sha):
359
251
return object_iter[sha]
375
268
o = lookup_object(head)
377
trace.mutter('missing head %s', head)
379
271
if isinstance(o, Commit):
380
272
rev = mapping.import_commit(o)
381
273
if repo.has_revision(rev.revision_id):
383
squash_revision(repo, rev)
384
graph.append((o.id, o.parents))
385
target_git_object_retriever._idmap.add_entry(o.id, "commit",
275
root_trees[rev.revision_id] = o.tree
276
revisions[rev.revision_id] = rev
277
graph.append((rev.revision_id, rev.parent_ids))
278
target_git_object_retriever._idmap.add_entry(o.id, "commit",
386
279
(rev.revision_id, o.tree))
387
280
heads.extend([p for p in o.parents if p not in checked])
388
281
elif isinstance(o, Tag):
389
282
heads.append(o.object[1])
391
284
trace.warning("Unable to import head object %r" % o)
394
286
# Order the revisions
395
287
# Create the inventory objects
397
revision_ids = topo_sort(graph)
399
for offset in range(0, len(revision_ids), batch_size):
400
repo.start_write_group()
288
for i, revid in enumerate(topo_sort(graph)):
290
pb.update("fetching revisions", i, len(graph))
291
rev = revisions[revid]
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.
296
for parent_id in rev.parent_ids:
298
parent_invs.append(parent_invs_cache[parent_id])
300
parent_inv = repo.get_inventory(parent_id)
301
parent_invs.append(parent_inv)
302
parent_invs_cache[parent_id] = parent_inv
303
if parent_invs == []:
304
base_inv = Inventory(root_id=None)
306
base_inv = parent_invs[0]
307
inv_delta, unusual_modes, shamap = import_git_tree(repo.texts,
308
mapping, "", root_trees[revid], base_inv, None, revid,
309
parent_invs, target_git_object_retriever._idmap, lookup_object)
310
target_git_object_retriever._idmap.add_entries(shamap)
311
if unusual_modes != {}:
312
ret = "unusual modes: \n"
313
for item in unusual_modes.iteritems():
314
ret += "\t%s: %o\n" % item
315
raise AssertionError(ret)
402
for i, head in enumerate(revision_ids[offset:offset+batch_size]):
404
pb.update("fetching revisions", offset+i, len(revision_ids))
405
import_git_commit(repo, mapping, head, lookup_object,
406
target_git_object_retriever,
409
repo.abort_write_group()
412
hint = repo.commit_write_group()
414
pack_hints.extend(hint)
415
target_git_object_retriever._idmap.commit_write_group()
317
basis_id = rev.parent_ids[0]
319
basis_id = NULL_REVISION
320
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
321
inv_delta, rev.revision_id, rev.parent_ids)
322
parent_invs_cache[rev.revision_id] = inv
323
repo.add_revision(rev.revision_id, rev)
324
if "verify" in debug.debug_flags:
325
objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping)
326
for sha1, newobj, path in objs:
327
assert path is not None
328
oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
329
assert oldobj == newobj, "%r != %r in %s" % (oldobj, newobj, path)
331
target_git_object_retriever._idmap.commit()
419
334
class InterGitRepository(InterRepository):
457
372
ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
458
373
return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
459
pack_hint = self.fetch_objects(determine_wants, mapping, pb)
460
if pack_hint is not None and self.target._format.pack_compresses:
461
self.target.pack(hint=pack_hint)
462
if interesting_heads is not None:
463
present_interesting_heads = self.target.has_revisions(interesting_heads)
464
missing_interesting_heads = set(interesting_heads) - present_interesting_heads
465
if missing_interesting_heads:
466
raise AssertionError("Missing interesting heads: %r" % missing_interesting_heads)
374
self.fetch_objects(determine_wants, mapping, pb)
467
375
return self._refs
470
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
471
def report_git_progress(pb, text):
472
text = text.rstrip("\r\n")
473
g = _GIT_PROGRESS_RE.match(text)
475
(text, pct, current, total) = g.groups()
476
pb.update(text, int(current), int(total))
478
pb.update(text, 0, 0)
481
378
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
482
"""InterRepository that copies revisions from a remote Git into a non-Git
379
"""InterRepository that copies revisions from a remote Git into a non-Git
485
def get_target_heads(self):
486
# FIXME: This should be more efficient
487
all_revs = self.target.all_revision_ids()
488
parent_map = self.target.get_parent_map(all_revs)
490
map(all_parents.update, parent_map.itervalues())
491
return set(all_revs) - all_parents
493
382
def fetch_objects(self, determine_wants, mapping, pb=None):
494
383
def progress(text):
495
report_git_progress(pb, text)
384
pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
496
385
store = BazaarObjectStore(self.target, mapping)
497
self.target.lock_write()
386
self.target.lock_read()
499
heads = self.get_target_heads()
500
graph_walker = store.get_graph_walker(
501
[store._lookup_revision_sha1(head) for head in heads])
504
def record_determine_wants(heads):
505
wants = determine_wants(heads)
506
recorded_wants.extend(wants)
511
create_pb = pb = ui.ui_factory.nested_progress_bar()
513
objects_iter = self.source.fetch_objects(
514
record_determine_wants, graph_walker,
515
store.get_raw, progress)
516
return import_git_objects(self.target, mapping,
517
objects_iter, store, recorded_wants, pb)
388
heads = self.target.get_graph().heads(self.target.all_revision_ids())
522
390
self.target.unlock()
391
graph_walker = store.get_graph_walker(
392
[store._lookup_revision_sha1(head) for head in heads])
395
create_pb = pb = ui.ui_factory.nested_progress_bar()
398
def record_determine_wants(heads):
399
wants = determine_wants(heads)
400
recorded_wants.extend(wants)
404
self.target.lock_write()
406
self.target.start_write_group()
408
objects_iter = self.source.fetch_objects(
409
record_determine_wants, graph_walker,
410
store.get_raw, progress)
411
import_git_objects(self.target, mapping, objects_iter,
412
store, recorded_wants, pb)
414
self.target.commit_write_group()
525
422
def is_compatible(source, target):
526
423
"""Be compatible with GitRepository."""
527
424
# FIXME: Also check target uses VersionedFile
528
return (isinstance(source, RemoteGitRepository) and
425
return (isinstance(source, RemoteGitRepository) and
529
426
target.supports_rich_root() and
530
427
not isinstance(target, GitRepository))
533
430
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
534
"""InterRepository that copies revisions from a local Git into a non-Git
431
"""InterRepository that copies revisions from a remote Git into a non-Git
537
434
def fetch_objects(self, determine_wants, mapping, pb=None):
564
465
class InterGitGitRepository(InterGitRepository):
565
466
"""InterRepository that copies between Git repositories."""
567
def fetch_objects(self, determine_wants, mapping, pb=None):
569
trace.note("git: %s", text)
570
graphwalker = self.target._git.get_graph_walker()
571
if (isinstance(self.source, LocalGitRepository) and
572
isinstance(self.target, LocalGitRepository)):
573
return self.source._git.fetch(self.target._git, determine_wants,
575
elif (isinstance(self.source, LocalGitRepository) and
576
isinstance(self.target, RemoteGitRepository)):
577
raise NotImplementedError
578
elif (isinstance(self.source, RemoteGitRepository) and
579
isinstance(self.target, LocalGitRepository)):
580
f, commit = self.target._git.object_store.add_thin_pack()
582
refs = self.source._git.fetch_pack(determine_wants,
583
graphwalker, f.write, progress)
592
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
468
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
593
469
mapping=None, fetch_spec=None, branches=None):
594
470
if mapping is None:
595
471
mapping = self.source.get_mapping()
473
trace.info("git: %s", text)
596
474
r = self.target._git
597
475
if revision_id is not None:
598
476
args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]