140
150
def import_unusual_file_modes(self, rev, unusual_file_modes):
141
151
if unusual_file_modes:
142
ret = [(name, unusual_file_modes[name]) for name in sorted(unusual_file_modes.keys())]
152
ret = [(path, unusual_file_modes[path])
153
for path in sorted(unusual_file_modes.keys())]
143
154
rev.properties['file-modes'] = bencode.bencode(ret)
145
156
def export_unusual_file_modes(self, rev):
147
return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(rev.properties['file-modes'])])
158
return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(rev.properties['file-modes'].encode("utf-8"))])
162
def _generate_git_svn_metadata(self, rev, encoding):
164
return "\ngit-svn-id: %s\n" % rev.properties["git-svn-id"].encode(
169
def _generate_hg_message_tail(self, rev):
173
for name in rev.properties:
174
if name == 'hg:extra:branch':
175
branch = rev.properties['hg:extra:branch']
176
elif name.startswith('hg:extra'):
177
extra[name[len('hg:extra:'):]] = base64.b64decode(
178
rev.properties[name])
179
elif name == 'hg:renames':
180
renames = bencode.bdecode(base64.b64decode(
181
rev.properties['hg:renames']))
182
# TODO: Export other properties as 'bzr:' extras?
183
ret = format_hg_metadata(renames, branch, extra)
184
assert isinstance(ret, str)
187
def _extract_git_svn_metadata(self, rev, message):
188
lines = message.split("\n")
189
if not (lines[-1] == "" and lines[-2].startswith("git-svn-id:")):
191
git_svn_id = lines[-2].split(": ", 1)[1]
192
rev.properties['git-svn-id'] = git_svn_id
193
(url, rev, uuid) = parse_git_svn_id(git_svn_id)
194
# FIXME: Convert this to converted-from property somehow..
195
ret = "\n".join(lines[:-2])
196
assert isinstance(ret, str)
199
def _extract_hg_metadata(self, rev, message):
200
(message, renames, branch, extra) = extract_hg_metadata(message)
201
if branch is not None:
202
rev.properties['hg:extra:branch'] = branch
203
for name, value in extra.iteritems():
204
rev.properties['hg:extra:' + name] = base64.b64encode(value)
206
rev.properties['hg:renames'] = base64.b64encode(bencode.bencode(
207
[(new, old) for (old, new) in renames.iteritems()]))
210
def _decode_commit_message(self, rev, message, encoding):
211
return message.decode(encoding)
213
def _encode_commit_message(self, rev, message, encoding):
214
return message.encode(encoding)
216
def export_commit(self, rev, tree_sha, parent_lookup):
217
"""Turn a Bazaar revision in to a Git commit
219
:param tree_sha: Tree sha for the commit
220
:param parent_lookup: Function for looking up the GIT sha equiv of a
222
:return dulwich.objects.Commit represent the revision:
224
from dulwich.objects import Commit
226
commit.tree = tree_sha
227
for p in rev.parent_ids:
229
git_p = parent_lookup(p)
232
if git_p is not None:
233
assert len(git_p) == 40, "unexpected length for %r" % git_p
234
commit.parents.append(git_p)
236
encoding = rev.properties['git-explicit-encoding']
238
encoding = rev.properties.get('git-implicit-encoding', 'utf-8')
239
commit.encoding = rev.properties.get('git-explicit-encoding')
240
commit.committer = fix_person_identifier(rev.committer.encode(
242
commit.author = fix_person_identifier(
243
rev.get_apparent_authors()[0].encode(encoding))
244
commit.commit_time = long(rev.timestamp)
245
if 'author-timestamp' in rev.properties:
246
commit.author_time = long(rev.properties['author-timestamp'])
248
commit.author_time = commit.commit_time
249
commit._commit_timezone_neg_utc = "commit-timezone-neg-utc" in rev.properties
250
commit.commit_timezone = rev.timezone
251
commit._author_timezone_neg_utc = "author-timezone-neg-utc" in rev.properties
252
if 'author-timezone' in rev.properties:
253
commit.author_timezone = int(rev.properties['author-timezone'])
255
commit.author_timezone = commit.commit_timezone
256
commit.message = self._encode_commit_message(rev, rev.message,
151
260
def import_commit(self, commit):
152
261
"""Convert a git commit to a bzr revision.
156
265
if commit is None:
157
266
raise AssertionError("Commit object can't be None")
158
rev = ForeignRevision(commit.id, self, self.revision_id_foreign_to_bzr(commit.id))
267
rev = ForeignRevision(commit.id, self,
268
self.revision_id_foreign_to_bzr(commit.id))
159
269
rev.parent_ids = tuple([self.revision_id_foreign_to_bzr(p) for p in commit.parents])
160
rev.message = commit.message.decode("utf-8", "replace")
161
rev.committer = str(commit.committer).decode("utf-8", "replace")
162
if commit.committer != commit.author:
163
rev.properties['author'] = str(commit.author).decode("utf-8", "replace")
270
def decode_using_encoding(rev, commit, encoding):
271
rev.committer = str(commit.committer).decode(encoding)
272
if commit.committer != commit.author:
273
rev.properties['author'] = str(commit.author).decode(encoding)
274
rev.message = self._decode_commit_message(rev, commit.message,
276
if commit.encoding is not None:
277
rev.properties['git-explicit-encoding'] = commit.encoding
278
decode_using_encoding(rev, commit, commit.encoding)
280
for encoding in ('utf-8', 'latin1'):
282
decode_using_encoding(rev, commit, encoding)
283
except UnicodeDecodeError:
286
if encoding != 'utf-8':
287
rev.properties['git-implicit-encoding'] = encoding
165
289
if commit.commit_time != commit.author_time:
166
290
rev.properties['author-timestamp'] = str(commit.author_time)
167
291
if commit.commit_timezone != commit.author_timezone:
168
rev.properties['author-timezone'] = "%d" % (commit.author_timezone, )
292
rev.properties['author-timezone'] = "%d" % commit.author_timezone
293
if commit._author_timezone_neg_utc:
294
rev.properties['author-timezone-neg-utc'] = ""
295
if commit._commit_timezone_neg_utc:
296
rev.properties['commit-timezone-neg-utc'] = ""
169
297
rev.timestamp = commit.commit_time
170
298
rev.timezone = commit.commit_timezone
183
311
revid_prefix = 'git-experimental'
184
312
experimental = True
314
def _decode_commit_message(self, rev, message, encoding):
315
message = self._extract_hg_metadata(rev, message)
316
message = self._extract_git_svn_metadata(rev, message)
317
return message.decode(encoding)
319
def _encode_commit_message(self, rev, message, encoding):
320
ret = message.encode(encoding)
321
ret += self._generate_hg_message_tail(rev)
322
ret += self._generate_git_svn_metadata(rev, encoding)
325
def import_commit(self, commit):
326
rev = super(BzrGitMappingExperimental, self).import_commit(commit)
327
rev.properties['converted_revision'] = "git %s\n" % commit.id
187
331
class GitMappingRegistry(VcsMappingRegistry):
188
332
"""Registry with available git mappings."""
190
334
def revision_id_bzr_to_foreign(self, bzr_revid):
335
if bzr_revid == NULL_REVISION:
336
return "0" * 20, None
191
337
if not bzr_revid.startswith("git-"):
192
338
raise errors.InvalidRevisionId(bzr_revid, None)
193
339
(mapping_version, git_sha) = bzr_revid.split(":", 1)
200
346
mapping_registry = GitMappingRegistry()
201
347
mapping_registry.register_lazy('git-v1', "bzrlib.plugins.git.mapping",
203
mapping_registry.register_lazy('git-experimental', "bzrlib.plugins.git.mapping",
204
"BzrGitMappingExperimental")
349
mapping_registry.register_lazy('git-experimental',
350
"bzrlib.plugins.git.mapping", "BzrGitMappingExperimental")
351
mapping_registry.set_default('git-v1')
207
354
class ForeignGit(ForeignVcs):
208
355
"""The Git Stupid Content Tracker"""
358
def branch_format(self):
359
from bzrlib.plugins.git.branch import GitBranchFormat
360
return GitBranchFormat()
363
def repository_format(self):
364
from bzrlib.plugins.git.repository import GitRepositoryFormat
365
return GitRepositoryFormat()
210
367
def __init__(self):
211
368
super(ForeignGit, self).__init__(mapping_registry)
369
self.abbreviation = "git"
372
def serialize_foreign_revid(self, foreign_revid):
214
376
def show_foreign_revid(cls, foreign_revid):
260
417
"Unknown kind, perms=%r." % (mode,))
263
def entry_mode(entry):
264
"""Determine the git file mode for an inventory entry."""
265
if entry.kind == 'directory':
420
def object_mode(kind, executable):
421
if kind == 'directory':
266
422
return stat.S_IFDIR
267
elif entry.kind == 'symlink':
269
elif entry.kind == 'file':
423
elif kind == 'symlink':
270
429
mode = stat.S_IFREG | 0644
433
elif kind == 'tree-reference':
434
from dulwich.objects import S_IFGITLINK
275
437
raise AssertionError
440
def entry_mode(entry):
441
"""Determine the git file mode for an inventory entry."""
442
return object_mode(entry.kind, entry.executable)
278
445
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes):
279
446
from dulwich.objects import Tree
281
for name in sorted(entry.children.keys()):
448
for name, value in entry.children.iteritems():
282
449
ie = entry.children[name]
284
451
mode = unusual_modes[ie.file_id]
286
453
mode = entry_mode(ie)
287
tree.add(mode, name.encode("utf-8"), lookup_ie_sha1(ie))
454
hexsha = lookup_ie_sha1(ie)
455
if hexsha is not None:
456
tree.add(mode, name.encode("utf-8"), hexsha)
457
if entry.parent_id is not None and len(tree) == 0:
458
# Only the root can be an empty tree
292
463
def extract_unusual_modes(rev):
294
foreign_revid, mapping = mapping_registry.parse_revision_id(rev.revision_id)
465
foreign_revid, mapping = mapping_registry.parse_revision_id(
295
467
except errors.InvalidRevisionId:
298
470
return mapping.export_unusual_file_modes(rev)
301
def inventory_to_tree_and_blobs(inventory, texts, mapping, unusual_modes, cur=None):
302
"""Convert a Bazaar tree to a Git tree.
304
:return: Yields tuples with object sha1, object and path
306
from dulwich.objects import Tree
313
# stack contains the set of trees that we haven't
314
# finished constructing
315
for path, entry in inventory.iter_entries():
316
while stack and not path.startswith(osutils.pathjoin(cur, "")):
317
# We've hit a file that's not a child of the previous path
320
yield sha, tree, cur.encode("utf-8")
321
mode = unusual_modes.get(cur.encode("utf-8"), stat.S_IFDIR)
322
t = (mode, urlutils.basename(cur).encode('UTF-8'), sha)
323
cur, tree = stack.pop()
326
if entry.kind == "directory":
327
stack.append((cur, tree))
331
if entry.kind == "file":
332
blob = text_to_blob(texts, entry)
333
elif entry.kind == "symlink":
334
blob = symlink_to_blob(entry)
336
raise AssertionError("Unknown kind %s" % entry.kind)
338
yield sha, blob, path.encode("utf-8")
339
name = urlutils.basename(path).encode("utf-8")
340
mode = unusual_modes.get(path.encode("utf-8"), entry_mode(entry))
341
tree.add(mode, name, sha)
343
while len(stack) > 1:
346
yield sha, tree, cur.encode("utf-8")
347
mode = unusual_modes.get(cur.encode('utf-8'), stat.S_IFDIR)
348
t = (mode, urlutils.basename(cur).encode('UTF-8'), sha)
349
cur, tree = stack.pop()
353
yield tree.id, tree, cur.encode("utf-8")
356
def revision_to_commit(rev, tree_sha, parent_lookup):
357
"""Turn a Bazaar revision in to a Git commit
359
:param tree_sha: Tree sha for the commit
360
:param parent_lookup: Function for looking up the GIT sha equiv of a bzr revision
361
:return dulwich.objects.Commit represent the revision:
363
from dulwich.objects import Commit
365
commit.tree = tree_sha
366
for p in rev.parent_ids:
367
git_p = parent_lookup(p)
368
if git_p is not None:
369
assert len(git_p) == 40, "unexpected length for %r" % git_p
370
commit.parents.append(git_p)
371
commit.message = rev.message.encode("utf-8")
372
commit.committer = fix_person_identifier(rev.committer.encode("utf-8"))
373
commit.author = fix_person_identifier(rev.get_apparent_authors()[0].encode("utf-8"))
374
commit.commit_time = long(rev.timestamp)
375
if 'author-timestamp' in rev.properties:
376
commit.author_time = long(rev.properties['author-timestamp'])
378
commit.author_time = commit.commit_time
379
commit.commit_timezone = rev.timezone
380
if 'author-timezone' in rev.properties:
381
commit.author_timezone = int(rev.properties['author-timezone'])
383
commit.author_timezone = commit.commit_timezone
473
def parse_git_svn_id(text):
474
(head, uuid) = text.rsplit(" ", 1)
475
(full_url, rev) = head.rsplit("@", 1)
476
return (full_url, int(rev), uuid)