133
155
return escape_file_id(path)
157
def is_control_file(self, path):
158
return path in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE)
135
160
def parse_file_id(self, file_id):
136
161
if file_id == ROOT_ID:
138
163
return unescape_file_id(file_id)
165
def revid_as_refname(self, revid):
167
return "refs/bzr/%s" % urllib.quote(revid)
140
169
def import_unusual_file_modes(self, rev, unusual_file_modes):
141
170
if unusual_file_modes:
142
ret = [(name, unusual_file_modes[name]) for name in sorted(unusual_file_modes.keys())]
171
ret = [(path, unusual_file_modes[path])
172
for path in sorted(unusual_file_modes.keys())]
143
173
rev.properties['file-modes'] = bencode.bencode(ret)
145
175
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'])])
177
file_modes = rev.properties['file-modes']
181
return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(file_modes.encode("utf-8"))])
183
def _generate_git_svn_metadata(self, rev, encoding):
185
git_svn_id = rev.properties["git-svn-id"]
189
return "\ngit-svn-id: %s\n" % git_svn_id.encode(encoding)
191
def _generate_hg_message_tail(self, rev):
195
for name in rev.properties:
196
if name == 'hg:extra:branch':
197
branch = rev.properties['hg:extra:branch']
198
elif name.startswith('hg:extra'):
199
extra[name[len('hg:extra:'):]] = base64.b64decode(
200
rev.properties[name])
201
elif name == 'hg:renames':
202
renames = bencode.bdecode(base64.b64decode(
203
rev.properties['hg:renames']))
204
# TODO: Export other properties as 'bzr:' extras?
205
ret = format_hg_metadata(renames, branch, extra)
206
assert isinstance(ret, str)
209
def _extract_git_svn_metadata(self, rev, message):
210
lines = message.split("\n")
211
if not (lines[-1] == "" and lines[-2].startswith("git-svn-id:")):
213
git_svn_id = lines[-2].split(": ", 1)[1]
214
rev.properties['git-svn-id'] = git_svn_id
215
(url, rev, uuid) = parse_git_svn_id(git_svn_id)
216
# FIXME: Convert this to converted-from property somehow..
217
ret = "\n".join(lines[:-2])
218
assert isinstance(ret, str)
221
def _extract_hg_metadata(self, rev, message):
222
(message, renames, branch, extra) = extract_hg_metadata(message)
223
if branch is not None:
224
rev.properties['hg:extra:branch'] = branch
225
for name, value in extra.iteritems():
226
rev.properties['hg:extra:' + name] = base64.b64encode(value)
228
rev.properties['hg:renames'] = base64.b64encode(bencode.bencode(
229
[(new, old) for (old, new) in renames.iteritems()]))
232
def _extract_bzr_metadata(self, rev, message):
233
(message, metadata) = extract_bzr_metadata(message)
234
return message, metadata
236
def _decode_commit_message(self, rev, message, encoding):
237
message, metadata = self._extract_bzr_metadata(rev, message)
238
return message.decode(encoding), metadata
240
def _encode_commit_message(self, rev, message, encoding):
241
return message.encode(encoding)
243
def export_fileid_map(self, fileid_map):
244
"""Export a file id map to a fileid map.
246
:param fileid_map: File id map, mapping paths to file ids
247
:return: A Git blob object
249
from dulwich.objects import Blob
251
b.set_raw_chunks(serialize_fileid_map(fileid_map))
254
def export_commit(self, rev, tree_sha, parent_lookup, roundtrip):
255
"""Turn a Bazaar revision in to a Git commit
257
:param tree_sha: Tree sha for the commit
258
:param parent_lookup: Function for looking up the GIT sha equiv of a
260
:return dulwich.objects.Commit represent the revision:
262
from dulwich.objects import Commit
264
commit.tree = tree_sha
266
metadata = BzrGitRevisionMetadata()
270
for p in rev.parent_ids:
272
git_p = parent_lookup(p)
275
if metadata is not None:
276
metadata.explicit_parent_ids = rev.parent_ids
277
if git_p is not None:
278
assert len(git_p) == 40, "unexpected length for %r" % git_p
279
parents.append(git_p)
280
commit.parents = parents
282
encoding = rev.properties['git-explicit-encoding']
284
encoding = rev.properties.get('git-implicit-encoding', 'utf-8')
285
commit.encoding = rev.properties.get('git-explicit-encoding')
286
commit.committer = fix_person_identifier(rev.committer.encode(
288
commit.author = fix_person_identifier(
289
rev.get_apparent_authors()[0].encode(encoding))
290
commit.commit_time = long(rev.timestamp)
291
if 'author-timestamp' in rev.properties:
292
commit.author_time = long(rev.properties['author-timestamp'])
294
commit.author_time = commit.commit_time
295
commit._commit_timezone_neg_utc = "commit-timezone-neg-utc" in rev.properties
296
commit.commit_timezone = rev.timezone
297
commit._author_timezone_neg_utc = "author-timezone-neg-utc" in rev.properties
298
if 'author-timezone' in rev.properties:
299
commit.author_timezone = int(rev.properties['author-timezone'])
301
commit.author_timezone = commit.commit_timezone
302
commit.message = self._encode_commit_message(rev, rev.message,
304
assert type(commit.message) == str
305
if metadata is not None:
307
mapping_registry.parse_revision_id(rev.revision_id)
308
except errors.InvalidRevisionId:
309
metadata.revision_id = rev.revision_id
310
mapping_properties = set(
311
['author', 'author-timezone', 'author-timezone-neg-utc',
312
'commit-timezone-neg-utc', 'git-implicit-encoding',
313
'git-explicit-encoding', 'author-timestamp', 'file-modes'])
314
for k, v in rev.properties.iteritems():
315
if not k in mapping_properties:
316
metadata.properties[k] = v
317
commit.message = inject_bzr_metadata(commit.message, metadata,
319
assert type(commit.message) == str
322
def import_fileid_map(self, blob):
323
"""Convert a git file id map blob.
325
:param blob: Git blob object with fileid map
326
:return: Dictionary mapping paths to file ids
328
return deserialize_fileid_map(blob.data)
151
330
def import_commit(self, commit):
152
331
"""Convert a git commit to a bzr revision.
154
:return: a `bzrlib.revision.Revision` object.
333
:return: a `bzrlib.revision.Revision` object and a
334
dictionary of path -> file ids
156
336
if commit is None:
157
337
raise AssertionError("Commit object can't be None")
158
rev = ForeignRevision(commit.id, self, self.revision_id_foreign_to_bzr(commit.id))
338
rev = ForeignRevision(commit.id, self,
339
self.revision_id_foreign_to_bzr(commit.id))
159
340
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")
341
rev.git_metadata = None
342
def decode_using_encoding(rev, commit, encoding):
343
rev.committer = str(commit.committer).decode(encoding)
344
if commit.committer != commit.author:
345
rev.properties['author'] = str(commit.author).decode(encoding)
346
rev.message, rev.git_metadata = self._decode_commit_message(
347
rev, commit.message, encoding)
348
if commit.encoding is not None:
349
rev.properties['git-explicit-encoding'] = commit.encoding
350
decode_using_encoding(rev, commit, commit.encoding)
352
for encoding in ('utf-8', 'latin1'):
354
decode_using_encoding(rev, commit, encoding)
355
except UnicodeDecodeError:
358
if encoding != 'utf-8':
359
rev.properties['git-implicit-encoding'] = encoding
165
361
if commit.commit_time != commit.author_time:
166
362
rev.properties['author-timestamp'] = str(commit.author_time)
167
363
if commit.commit_timezone != commit.author_timezone:
168
rev.properties['author-timezone'] = "%d" % (commit.author_timezone, )
364
rev.properties['author-timezone'] = "%d" % commit.author_timezone
365
if commit._author_timezone_neg_utc:
366
rev.properties['author-timezone-neg-utc'] = ""
367
if commit._commit_timezone_neg_utc:
368
rev.properties['commit-timezone-neg-utc'] = ""
169
369
rev.timestamp = commit.commit_time
170
370
rev.timezone = commit.commit_timezone
371
if rev.git_metadata is not None:
372
md = rev.git_metadata
374
rev.revision_id = md.revision_id
375
if md.explicit_parent_ids:
376
rev.parent_ids = md.explicit_parent_ids
377
rev.properties.update(md.properties)
380
def get_fileid_map(self, lookup_object, tree_sha):
381
"""Obtain a fileid map for a particular tree.
383
:param lookup_object: Function for looking up an object
384
:param tree_sha: SHA of the root tree
385
:return: GitFileIdMap instance
388
file_id_map_sha = lookup_object(tree_sha)[self.BZR_FILE_IDS_FILE][1]
392
file_ids = self.import_fileid_map(lookup_object(file_id_map_sha))
393
return GitFileIdMap(file_ids, self)
174
396
class BzrGitMappingv1(BzrGitMapping):
175
397
revid_prefix = 'git-v1'
260
513
"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':
516
def object_mode(kind, executable):
517
if kind == 'directory':
266
518
return stat.S_IFDIR
267
elif entry.kind == 'symlink':
269
elif entry.kind == 'file':
519
elif kind == 'symlink':
270
525
mode = stat.S_IFREG | 0644
529
elif kind == 'tree-reference':
530
from dulwich.objects import S_IFGITLINK
275
533
raise AssertionError
278
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes):
279
from dulwich.objects import Tree
536
def entry_mode(entry):
537
"""Determine the git file mode for an inventory entry."""
538
return object_mode(entry.kind, entry.executable)
541
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes, empty_file_name):
542
"""Create a Git Tree object from a Bazaar directory.
544
:param entry: Inventory entry
545
:param lookup_ie_sha1: Lookup the Git SHA1 for a inventory entry
546
:param unusual_modes: Dictionary with unusual file modes by file ids
547
:param empty_file_name: Name to use for dummy files in empty directories,
548
None to ignore empty directories.
550
from dulwich.objects import Blob, Tree
281
for name in sorted(entry.children.keys()):
552
for name, value in entry.children.iteritems():
282
553
ie = entry.children[name]
284
555
mode = unusual_modes[ie.file_id]
286
557
mode = entry_mode(ie)
287
tree.add(mode, name.encode("utf-8"), lookup_ie_sha1(ie))
558
hexsha = lookup_ie_sha1(ie)
559
if hexsha is not None:
560
tree.add(mode, name.encode("utf-8"), hexsha)
561
if entry.parent_id is not None and len(tree) == 0:
562
# Only the root can be an empty tree
563
if empty_file_name is not None:
564
tree.add(stat.S_IFREG | 0644, empty_file_name,
292
571
def extract_unusual_modes(rev):
294
foreign_revid, mapping = mapping_registry.parse_revision_id(rev.revision_id)
573
foreign_revid, mapping = mapping_registry.parse_revision_id(
295
575
except errors.InvalidRevisionId:
298
578
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
581
def parse_git_svn_id(text):
582
(head, uuid) = text.rsplit(" ", 1)
583
(full_url, rev) = head.rsplit("@", 1)
584
return (full_url, int(rev), uuid)
587
class GitFileIdMap(object):
589
def __init__(self, file_ids, mapping):
590
self.file_ids = file_ids
592
self.mapping = mapping
594
def lookup_file_id(self, path):
596
return self.file_ids[path]
598
return self.mapping.generate_file_id(path)
600
def lookup_path(self, file_id):
601
if self.paths is None:
603
for k, v in self.file_ids.iteritems():
606
return self.paths[file_id]
608
return self.mapping.parse_file_id(file_id)