71
76
RemoteGitRepository,
73
78
from bzrlib.plugins.git.repository import (
75
80
GitRepositoryFormat,
76
81
LocalGitRepository,
80
MAX_INV_CACHE_SIZE = 50 * 1024 * 1024
83
def import_git_blob(texts, mapping, path, hexsha, base_inv, base_ie, parent_id,
85
class BzrFetchGraphWalker(object):
86
"""GraphWalker implementation that uses a Bazaar repository."""
88
def __init__(self, repository, mapping):
89
self.repository = repository
90
self.mapping = mapping
92
self.heads = set(repository.all_revision_ids())
96
return iter(self.next, None)
99
revid = self.mapping.revision_id_foreign_to_bzr(sha)
102
def remove(self, revid):
104
if revid in self.heads:
105
self.heads.remove(revid)
106
if revid in self.parents:
107
for p in self.parents[revid]:
112
ret = self.heads.pop()
113
ps = self.repository.get_parent_map([ret])[ret]
114
self.parents[ret] = ps
115
self.heads.update([p for p in ps if not p in self.done])
118
return self.mapping.revision_id_bzr_to_foreign(ret)[0]
119
except InvalidRevisionId:
124
def import_git_blob(texts, mapping, path, hexsha, base_inv, parent_id,
84
125
revision_id, parent_invs, shagitmap, lookup_object, executable, symlink):
85
126
"""Import a git blob object into a bzr repository.
150
193
ie.revision = revision_id
151
194
assert file_id is not None
152
195
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)])
196
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, blob.data)])
158
197
shamap = [(hexsha, "blob", (ie.file_id, ie.revision))]
162
if base_ie is not None:
200
if file_id in base_inv:
163
201
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):
204
return ([(old_path, path, file_id, ie)], shamap)
207
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id,
208
revision_id, parent_invs, shagitmap, lookup_object):
210
209
"""Import a git tree object into a bzr repository.
212
211
:param texts: VersionedFiles object to add to
219
218
file_id = mapping.generate_file_id(path)
220
219
# We just have to hope this is indeed utf-8:
221
ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")),
220
ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")),
224
base_ie = base_inv[file_id]
224
226
# Newly appeared here
225
228
ie.revision = revision_id
226
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), (), None, "")])
229
texts.add_lines((file_id, ie.revision), (), [])
227
230
invdelta.append((None, path, file_id, ie))
232
base_sha = base_ie.text_id
229
233
# See if this has changed at all
231
base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
236
base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
235
240
if base_sha == hexsha:
236
241
# If nothing has changed since the base revision, we're done
237
242
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
243
# Remember for next time
247
244
existing_children = set()
253
250
existing_children.add(basename)
254
251
child_path = osutils.pathjoin(path, name)
255
252
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)
253
subinvdelta, grandchildmodes, subshamap = import_git_tree(texts,
254
mapping, child_path, child_hexsha, base_inv, file_id,
255
revision_id, parent_invs, shagitmap, lookup_object)
270
256
invdelta.extend(subinvdelta)
271
257
child_modes.update(grandchildmodes)
272
258
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))
260
fs_mode = stat.S_IMODE(mode)
261
symlink = stat.S_ISLNK(mode)
262
subinvdelta, subshamap = import_git_blob(texts, mapping,
263
child_path, child_hexsha, base_inv, file_id, revision_id,
264
parent_invs, shagitmap, lookup_object,
265
bool(fs_mode & 0111), symlink)
278
266
invdelta.extend(subinvdelta)
279
267
shamap.extend(subshamap)
280
268
if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
281
269
stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
282
270
child_modes[child_path] = mode
283
271
# 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))
272
if base_ie is not None:
273
deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
276
invdelta.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
277
if ie.kind == "directory":
278
deletable.extend(ie.children.values())
287
279
shamap.append((hexsha, "tree", (file_id, revision_id)))
288
280
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,
283
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever,
350
285
"""Import a set of git objects into a bzr repository.
352
:param repo: Target Bazaar repository
287
:param repo: Bazaar repository
353
288
:param mapping: Mapping to use
354
289
:param object_iter: Iterator over Git objects.
356
target_git_object_retriever._idmap.start_write_group() # FIXME: try/finally
357
def lookup_object(sha):
359
return object_iter[sha]
361
return target_git_object_retriever[sha]
362
291
# TODO: a more (memory-)efficient implementation of this
365
296
heads = list(heads)
366
parent_invs_cache = lru_cache.LRUSizeCache(compute_size=approx_inv_size,
367
max_size=MAX_INV_CACHE_SIZE)
297
parent_invs_cache = LRUCache(50)
368
298
# Find and convert commit objects
370
300
if pb is not None:
372
302
head = heads.pop()
373
303
assert isinstance(head, str)
375
o = lookup_object(head)
305
o = object_iter[head]
377
trace.mutter('missing head %s', head)
379
308
if isinstance(o, Commit):
380
309
rev = mapping.import_commit(o)
381
310
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",
312
root_trees[rev.revision_id] = o.tree
313
revisions[rev.revision_id] = rev
314
graph.append((rev.revision_id, rev.parent_ids))
315
target_git_object_retriever._idmap.add_entry(o.id, "commit",
386
316
(rev.revision_id, o.tree))
387
317
heads.extend([p for p in o.parents if p not in checked])
388
318
elif isinstance(o, Tag):
389
319
heads.append(o.object[1])
391
321
trace.warning("Unable to import head object %r" % o)
394
323
# Order the revisions
395
324
# 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()
325
for i, revid in enumerate(topo_sort(graph)):
327
pb.update("fetching revisions", i, len(graph))
328
rev = revisions[revid]
329
# We have to do this here, since we have to walk the tree and
330
# we need to make sure to import the blobs / trees with the right
331
# path; this may involve adding them more than once.
332
def lookup_object(sha):
334
return object_iter[sha]
336
return target_git_object_retriever[sha]
338
for parent_id in rev.parent_ids:
340
parent_invs.append(parent_invs_cache[parent_id])
342
parent_inv = repo.get_inventory(parent_id)
343
parent_invs.append(parent_inv)
344
parent_invs_cache[parent_id] = parent_inv
345
if parent_invs == []:
346
base_inv = Inventory(root_id=None)
348
base_inv = parent_invs[0]
349
inv_delta, unusual_modes, shamap = import_git_tree(repo.texts,
350
mapping, "", root_trees[revid], base_inv, None, revid,
351
parent_invs, target_git_object_retriever._idmap, lookup_object)
352
target_git_object_retriever._idmap.add_entries(shamap)
353
if unusual_modes != {}:
354
ret = "unusual modes: \n"
355
for item in unusual_modes.iteritems():
356
ret += "\t%s: %o\n" % item
357
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()
359
basis_id = rev.parent_ids[0]
361
basis_id = NULL_REVISION
362
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
363
inv_delta, rev.revision_id, rev.parent_ids)
364
parent_invs_cache[rev.revision_id] = inv
365
repo.add_revision(rev.revision_id, rev)
366
if "verify" in debug.debug_flags:
367
objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping)
368
for sha1, newobj, path in objs:
369
assert path is not None
370
oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
371
assert oldobj == newobj, "%r != %r in %s" % (oldobj, newobj, path)
373
target_git_object_retriever._idmap.commit()
419
376
class InterGitRepository(InterRepository):
454
411
if interesting_heads is None:
455
412
ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
457
ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
414
ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid != NULL_REVISION]
458
415
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)
416
self.fetch_objects(determine_wants, mapping, pb)
467
417
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
421
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
482
"""InterRepository that copies revisions from a remote Git into a non-Git
422
"""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
425
def fetch_objects(self, determine_wants, mapping, pb=None):
494
426
def progress(text):
495
report_git_progress(pb, text)
496
store = BazaarObjectStore(self.target, mapping)
497
self.target.lock_write()
427
pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
428
graph_walker = BzrFetchGraphWalker(self.target, mapping)
431
create_pb = pb = ui.ui_factory.nested_progress_bar()
432
target_git_object_retriever = BazaarObjectStore(self.target, mapping)
435
def record_determine_wants(heads):
436
wants = determine_wants(heads)
437
recorded_wants.extend(wants)
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()
441
self.target.lock_write()
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)
443
self.target.start_write_group()
445
objects_iter = self.source.fetch_objects(
446
record_determine_wants,
448
target_git_object_retriever.get_raw,
450
import_git_objects(self.target, mapping, objects_iter,
451
target_git_object_retriever, recorded_wants, pb)
453
self.target.commit_write_group()
525
461
def is_compatible(source, target):
526
462
"""Be compatible with GitRepository."""
527
463
# FIXME: Also check target uses VersionedFile
528
return (isinstance(source, RemoteGitRepository) and
464
return (isinstance(source, RemoteGitRepository) and
529
465
target.supports_rich_root() and
530
466
not isinstance(target, GitRepository))
533
469
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
534
"""InterRepository that copies revisions from a local Git into a non-Git
470
"""InterRepository that copies revisions from a remote Git into a non-Git
537
473
def fetch_objects(self, determine_wants, mapping, pb=None):
564
504
class InterGitGitRepository(InterGitRepository):
565
505
"""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,
507
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
593
508
mapping=None, fetch_spec=None, branches=None):
594
509
if mapping is None:
595
510
mapping = self.source.get_mapping()
512
trace.info("git: %s", text)
596
513
r = self.target._git
597
514
if revision_id is not None:
598
515
args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]