14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from cStringIO import (
21
from dulwich.objects import (
26
from dulwich.object_store import (
38
from bzrlib.errors import (
43
from bzrlib.inventory import (
49
from bzrlib.lru_cache import (
52
from bzrlib.repository import (
55
from bzrlib.revision import (
58
from bzrlib.tsort import (
61
from bzrlib.versionedfile import (
62
FulltextContentFactory,
65
from bzrlib.plugins.git.mapping import (
67
inventory_to_tree_and_blobs,
72
from bzrlib.plugins.git.object_store import (
75
from bzrlib.plugins.git.remote import (
17
from bzrlib import osutils, ui, urlutils
18
from bzrlib.errors import InvalidRevisionId
19
from bzrlib.inventory import Inventory
20
from bzrlib.repository import InterRepository
21
from bzrlib.trace import info
22
from bzrlib.tsort import topo_sort
24
from bzrlib.plugins.git import git
78
25
from bzrlib.plugins.git.repository import (
85
def import_git_blob(texts, mapping, path, hexsha, base_inv, parent_id,
86
revision_id, parent_invs, shagitmap, lookup_object, executable, symlink):
30
from bzrlib.plugins.git.remote import RemoteGitRepository
32
from dulwich.objects import Commit
34
from cStringIO import StringIO
37
class BzrFetchGraphWalker(object):
39
def __init__(self, repository, mapping):
40
self.repository = repository
41
self.mapping = mapping
43
self.heads = set(repository.all_revision_ids())
47
revid = self.mapping.revision_id_foreign_to_bzr(sha)
50
def remove(self, revid):
53
self.heads.remove(revid)
54
if revid in self.parents:
55
for p in self.parents[revid]:
60
ret = self.heads.pop()
61
ps = self.repository.get_parent_map([ret])[ret]
62
self.parents[ret] = ps
63
self.heads.update([p for p in ps if not p in self.done])
66
return self.mapping.revision_id_bzr_to_foreign(ret)
67
except InvalidRevisionId:
72
def import_git_blob(repo, mapping, path, blob, inv, parent_invs, executable):
87
73
"""Import a git blob object into a bzr repository.
89
:param texts: VersionedFiles to add to
75
:param repo: bzr repository
90
76
:param path: Path in the tree
91
77
:param blob: A git blob
92
:return: Inventory delta for this file
94
79
file_id = mapping.generate_file_id(path)
99
# We just have to hope this is indeed utf-8:
100
ie = cls(file_id, urlutils.basename(path).decode("utf-8"), parent_id)
80
text_revision = inv.revision_id
81
repo.texts.add_lines((file_id, text_revision),
82
[(file_id, p[file_id].revision) for p in parent_invs if file_id in p],
83
osutils.split_lines(blob.data))
84
ie = inv.add_path(path, "file", file_id)
85
ie.revision = text_revision
86
ie.text_size = len(blob.data)
87
ie.text_sha1 = osutils.sha_string(blob.data)
101
88
ie.executable = executable
103
# See if this has changed at all
105
base_ie = base_inv[file_id]
110
base_sha = base_ie.text_id
113
base_sha = shagitmap.lookup_blob(file_id, base_ie.revision)
117
if (base_sha == hexsha and base_ie.executable == ie.executable
118
and base_ie.kind == ie.kind):
119
# If nothing has changed since the base revision, we're done
121
if base_sha == hexsha and base_ie.kind == ie.kind:
122
ie.text_size = base_ie.text_size
123
ie.text_sha1 = base_ie.text_sha1
124
ie.symlink_target = base_ie.symlink_target
125
if ie.executable == base_ie.executable:
126
ie.revision = base_ie.revision
128
blob = lookup_object(hexsha)
130
blob = lookup_object(hexsha)
131
if ie.kind == "symlink":
132
ie.symlink_target = blob.data
136
ie.text_size = len(blob.data)
137
ie.text_sha1 = osutils.sha_string(blob.data)
138
# Check what revision we should store
140
for pinv in parent_invs:
141
if pinv.revision_id == base_inv.revision_id:
150
if pie.text_sha1 == ie.text_sha1 and pie.executable == ie.executable:
151
# found a revision in one of the parents to use
152
ie.revision = pie.revision
154
parent_keys.append((file_id, pie.revision))
155
if ie.revision is None:
156
# Need to store a new revision
157
ie.revision = revision_id
158
assert file_id is not None
159
assert ie.revision is not None
160
texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, blob.data)])
161
shamap = [(hexsha, "blob", (ie.file_id, ie.revision))]
164
if file_id in base_inv:
165
old_path = base_inv.id2path(file_id)
168
return ([(old_path, path, file_id, ie)], shamap)
171
def import_git_submodule(texts, mapping, path, hexsha, base_inv, parent_id,
172
revision_id, parent_invs, shagitmap, lookup_object):
173
raise NotImplementedError(import_git_submodule)
176
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id,
177
revision_id, parent_invs, shagitmap, lookup_object):
91
def import_git_tree(repo, mapping, path, tree, inv, parent_invs, lookup_object):
178
92
"""Import a git tree object into a bzr repository.
180
:param texts: VersionedFiles object to add to
94
:param repo: A Bzr repository object
181
95
:param path: Path in the tree
182
96
:param tree: A git tree object
183
:param base_inv: Base inventory against which to return inventory delta
184
:return: Inventory delta for this subtree
97
:param inv: Inventory object
187
99
file_id = mapping.generate_file_id(path)
188
# We just have to hope this is indeed utf-8:
189
ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")),
193
base_ie = base_inv[file_id]
195
# Newly appeared here
197
ie.revision = revision_id
198
texts.add_lines((file_id, ie.revision), (), [])
199
invdelta.append((None, path, file_id, ie))
201
base_sha = base_ie.text_id
202
# See if this has changed at all
205
base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
209
if base_sha == hexsha:
210
# If nothing has changed since the base revision, we're done
212
# Remember for next time
213
existing_children = set()
216
tree = lookup_object(hexsha)
217
for mode, name, child_hexsha in tree.entries():
100
text_revision = inv.revision_id
101
repo.texts.add_lines((file_id, text_revision),
102
[(file_id, p[file_id].revision) for p in parent_invs if file_id in p],
104
ie = inv.add_path(path, "directory", file_id)
105
ie.revision = text_revision
106
for mode, name, hexsha in tree.entries():
107
entry_kind = (mode & 0700000) / 0100000
218
108
basename = name.decode("utf-8")
219
existing_children.add(basename)
220
child_path = osutils.pathjoin(path, name)
221
if stat.S_ISDIR(mode):
222
subinvdelta, grandchildmodes, subshamap = import_git_tree(texts,
223
mapping, child_path, child_hexsha, base_inv, file_id,
224
revision_id, parent_invs, shagitmap, lookup_object)
225
invdelta.extend(subinvdelta)
226
child_modes.update(grandchildmodes)
227
shamap.extend(subshamap)
228
elif S_ISGITLINK(mode): # submodule
229
subinvdelta, grandchildmodes, subshamap = import_git_submodule(
230
texts, mapping, child_path, child_hexsha, base_inv,
231
file_id, revision_id, parent_invs, shagitmap, lookup_object)
232
invdelta.extend(subinvdelta)
233
child_modes.update(grandchildmodes)
234
shamap.extend(subshamap)
236
subinvdelta, subshamap = import_git_blob(texts, mapping,
237
child_path, child_hexsha, base_inv, file_id, revision_id,
238
parent_invs, shagitmap, lookup_object,
239
mode_is_executable(mode), stat.S_ISLNK(mode))
240
invdelta.extend(subinvdelta)
241
shamap.extend(subshamap)
242
if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
243
stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
244
child_modes[child_path] = mode
245
# Remove any children that have disappeared
246
if base_ie is not None and base_ie.kind == 'directory':
247
deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
250
invdelta.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
251
if ie.kind == "directory":
252
deletable.extend(ie.children.values())
253
shamap.append((hexsha, "tree", (file_id, revision_id)))
254
return invdelta, child_modes, shamap
257
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever,
112
child_path = urlutils.join(path, name)
114
tree = lookup_object(hexsha)
115
import_git_tree(repo, mapping, child_path, tree, inv, parent_invs, lookup_object)
116
elif entry_kind == 1:
117
blob = lookup_object(hexsha)
118
fs_mode = mode & 0777
119
import_git_blob(repo, mapping, child_path, blob, inv, parent_invs, bool(fs_mode & 0111))
121
raise AssertionError("Unknown blob kind, perms=%r." % (mode,))
124
def import_git_objects(repo, mapping, object_iter, pb=None):
259
125
"""Import a set of git objects into a bzr repository.
261
:param repo: Target Bazaar repository
127
:param repo: Bazaar repository
262
128
:param mapping: Mapping to use
263
129
:param object_iter: Iterator over Git objects.
265
def lookup_object(sha):
267
return object_iter[sha]
269
return target_git_object_retriever[sha]
270
131
# TODO: a more (memory-)efficient implementation of this
133
for i, o in enumerate(object_iter):
135
pb.update("fetching objects", i)
276
parent_invs_cache = LRUCache(50)
277
140
# Find and convert commit objects
280
pb.update("finding revisions to fetch", len(graph), None)
282
assert isinstance(head, str)
284
o = lookup_object(head)
141
for o in objects.itervalues():
287
142
if isinstance(o, Commit):
288
143
rev = mapping.import_commit(o)
289
if repo.has_revision(rev.revision_id):
291
root_trees[rev.revision_id] = o.tree
144
root_trees[rev.revision_id] = objects[o.tree]
292
145
revisions[rev.revision_id] = rev
293
146
graph.append((rev.revision_id, rev.parent_ids))
294
target_git_object_retriever._idmap.add_entry(o.id, "commit",
295
(rev.revision_id, o.tree))
296
heads.extend([p for p in o.parents if p not in checked])
297
elif isinstance(o, Tag):
298
heads.append(o.object[1])
300
trace.warning("Unable to import head object %r" % o)
302
147
# Order the revisions
303
148
# Create the inventory objects
304
149
for i, revid in enumerate(topo_sort(graph)):
305
150
if pb is not None:
306
151
pb.update("fetching revisions", i, len(graph))
152
root_tree = root_trees[revid]
307
153
rev = revisions[revid]
308
154
# We have to do this here, since we have to walk the tree and
309
# we need to make sure to import the blobs / trees with the right
155
# we need to make sure to import the blobs / trees with the riht
310
156
# path; this may involve adding them more than once.
312
for parent_id in rev.parent_ids:
314
parent_invs.append(parent_invs_cache[parent_id])
316
parent_inv = repo.get_inventory(parent_id)
317
parent_invs.append(parent_inv)
318
parent_invs_cache[parent_id] = parent_inv
319
if parent_invs == []:
320
base_inv = Inventory(root_id=None)
322
base_inv = parent_invs[0]
323
inv_delta, unusual_modes, shamap = import_git_tree(repo.texts,
324
mapping, "", root_trees[revid], base_inv, None, revid,
325
parent_invs, target_git_object_retriever._idmap, lookup_object)
326
target_git_object_retriever._idmap.add_entries(shamap)
327
if unusual_modes != {}:
328
for path, mode in unusual_modes.iteritems():
329
warn_unusual_mode(rev.foreign_revid, path, mode)
331
basis_id = rev.parent_ids[0]
333
basis_id = NULL_REVISION
334
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
335
inv_delta, rev.revision_id, rev.parent_ids)
336
parent_invs_cache[rev.revision_id] = inv
337
repo.add_revision(rev.revision_id, rev)
338
if "verify" in debug.debug_flags:
339
objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping)
340
for sha1, newobj, path in objs:
341
assert path is not None
342
oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
343
assert oldobj == newobj, "%r != %r in %s" % (oldobj, newobj, path)
345
target_git_object_retriever._idmap.commit()
158
inv.revision_id = rev.revision_id
159
def lookup_object(sha):
162
return reconstruct_git_object(repo, mapping, sha)
163
parent_invs = [repo.get_inventory(r) for r in rev.parent_ids]
164
import_git_tree(repo, mapping, "", root_tree, inv, parent_invs,
166
repo.add_revision(rev.revision_id, rev, inv)
169
def reconstruct_git_commit(repo, rev):
170
raise NotImplementedError(self.reconstruct_git_commit)
173
def reconstruct_git_object(repo, mapping, sha):
175
revid = mapping.revision_id_foreign_to_bzr(sha)
177
rev = repo.get_revision(revid)
178
except NoSuchRevision:
181
return reconstruct_git_commit(rev)
185
raise KeyError("No such object %s" % sha)
348
188
class InterGitRepository(InterRepository):
350
_matching_repo_format = GitRepositoryFormat()
190
_matching_repo_format = GitFormat()
353
193
def _get_repo_format_to_test():
357
197
"""See InterRepository.copy_content."""
358
198
self.fetch(revision_id, pb, find_ghosts=False)
360
def fetch(self, revision_id=None, pb=None, find_ghosts=False, mapping=None,
362
self.fetch_refs(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts,
363
mapping=mapping, fetch_spec=fetch_spec)
366
class InterGitNonGitRepository(InterGitRepository):
367
"""Base InterRepository that copies revisions from a Git into a non-Git
370
def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False,
371
mapping=None, fetch_spec=None):
200
def fetch(self, revision_id=None, pb=None, find_ghosts=False,
372
202
if mapping is None:
373
203
mapping = self.source.get_mapping()
374
if revision_id is not None:
375
interesting_heads = [revision_id]
376
elif fetch_spec is not None:
377
interesting_heads = fetch_spec.heads
379
interesting_heads = None
381
def determine_wants(refs):
383
if interesting_heads is None:
384
ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
205
pb.note("git: %s", text)
206
def determine_wants(heads):
207
if revision_id is None:
386
ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
210
ret = [mapping.revision_id_bzr_to_foreign(revision_id)]
387
211
return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
388
self.fetch_objects(determine_wants, mapping, pb)
392
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
393
"""InterRepository that copies revisions from a remote Git into a non-Git
396
def fetch_objects(self, determine_wants, mapping, pb=None):
398
pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
399
store = BazaarObjectStore(self.target, mapping)
400
self.target.lock_write()
402
heads = self.target.get_graph().heads(self.target.all_revision_ids())
403
graph_walker = store.get_graph_walker(
404
[store._lookup_revision_sha1(head) for head in heads])
407
def record_determine_wants(heads):
408
wants = determine_wants(heads)
409
recorded_wants.extend(wants)
414
create_pb = pb = ui.ui_factory.nested_progress_bar()
416
self.target.start_write_group()
418
objects_iter = self.source.fetch_objects(
419
record_determine_wants, graph_walker,
420
store.get_raw, progress)
421
import_git_objects(self.target, mapping, objects_iter,
422
store, recorded_wants, pb)
424
self.target.commit_write_group()
432
def is_compatible(source, target):
433
"""Be compatible with GitRepository."""
434
# FIXME: Also check target uses VersionedFile
435
return (isinstance(source, RemoteGitRepository) and
436
target.supports_rich_root() and
437
not isinstance(target, GitRepository))
440
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
441
"""InterRepository that copies revisions from a local Git into a non-Git
444
def fetch_objects(self, determine_wants, mapping, pb=None):
445
wants = determine_wants(self.source._git.get_refs())
212
graph_walker = BzrFetchGraphWalker(self.target, mapping)
448
215
create_pb = pb = ui.ui_factory.nested_progress_bar()
449
target_git_object_retriever = BazaarObjectStore(self.target, mapping)
451
217
self.target.lock_write()
453
219
self.target.start_write_group()
455
import_git_objects(self.target, mapping,
456
self.source._git.object_store,
457
target_git_object_retriever, wants, pb)
221
import_git_objects(self.target, mapping,
222
iter(self.source.fetch_objects(determine_wants, graph_walker,
459
225
self.target.commit_write_group()