79
93
def warn_unusual_mode(commit, path, mode):
80
trace.mutter("Unusual file mode %o for %s in %s. Storing as revision property. ",
84
def squash_revision(target_repo, rev):
85
"""Remove characters that can't be stored from a revision, if necessary.
87
:param target_repo: Repository in which the revision will be stored
88
:param rev: Revision object, will be modified in-place
90
if not getattr(target_repo._serializer, "squashes_xml_invalid_characters", True):
92
from bzrlib.xml_serializer import escape_invalid_chars
93
rev.message, num_escaped = escape_invalid_chars(rev.message)
95
warn_escaped(rev.foreign_revid, num_escaped)
96
if 'author' in rev.properties:
97
rev.properties['author'], num_escaped = escape_invalid_chars(
98
rev.properties['author'])
100
warn_escaped(rev.foreign_revid, num_escaped)
101
rev.committer, num_escaped = escape_invalid_chars(rev.committer)
103
warn_escaped(rev.foreign_revid, num_escaped)
94
trace.mutter("Unusual file mode %o for %s in %s. Storing as revision "
95
"property. ", mode, path, commit)
106
98
class BzrGitMapping(foreign.VcsMapping):
107
99
"""Class that maps between Git and Bazaar semantics."""
108
100
experimental = False
102
BZR_FILE_IDS_FILE = '.bzrfileids'
104
BZR_DUMMY_FILE = '.bzrdummy'
110
106
def __init__(self):
111
107
super(BzrGitMapping, self).__init__(foreign_git)
113
109
def __eq__(self, other):
114
return type(self) == type(other) and self.revid_prefix == other.revid_prefix
110
return (type(self) == type(other) and
111
self.revid_prefix == other.revid_prefix)
117
114
def revision_id_foreign_to_bzr(cls, git_rev_id):
118
115
"""Convert a git revision id handle to a Bazaar revision id."""
116
from dulwich.protocol import ZERO_SHA
117
if git_rev_id == ZERO_SHA:
119
119
return "%s:%s" % (cls.revid_prefix, git_rev_id)
133
133
return escape_file_id(path)
135
def is_control_file(self, path):
136
return path in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE)
135
138
def parse_file_id(self, file_id):
136
139
if file_id == ROOT_ID:
138
141
return unescape_file_id(file_id)
143
def revid_as_refname(self, revid):
145
return "refs/bzr/%s" % urllib.quote(revid)
140
147
def import_unusual_file_modes(self, rev, unusual_file_modes):
141
148
if unusual_file_modes:
142
ret = [(name, unusual_file_modes[name]) for name in sorted(unusual_file_modes.keys())]
149
ret = [(path, unusual_file_modes[path])
150
for path in sorted(unusual_file_modes.keys())]
143
151
rev.properties['file-modes'] = bencode.bencode(ret)
145
153
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'])])
155
file_modes = rev.properties['file-modes']
151
def import_commit(self, commit):
159
return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(file_modes.encode("utf-8"))])
161
def _generate_git_svn_metadata(self, rev, encoding):
163
git_svn_id = rev.properties["git-svn-id"]
167
return "\ngit-svn-id: %s\n" % git_svn_id.encode(encoding)
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 _extract_bzr_metadata(self, rev, message):
211
(message, metadata) = extract_bzr_metadata(message)
212
return message, metadata
214
def _decode_commit_message(self, rev, message, encoding):
215
message, metadata = self._extract_bzr_metadata(rev, message)
216
return message.decode(encoding), metadata
218
def _encode_commit_message(self, rev, message, encoding):
219
return message.encode(encoding)
221
def export_fileid_map(self, fileid_map):
222
"""Export a file id map to a fileid map.
224
:param fileid_map: File id map, mapping paths to file ids
225
:return: A Git blob object
227
from dulwich.objects import Blob
229
b.set_raw_chunks(serialize_fileid_map(fileid_map))
232
def export_commit(self, rev, tree_sha, parent_lookup, roundtrip):
233
"""Turn a Bazaar revision in to a Git commit
235
:param tree_sha: Tree sha for the commit
236
:param parent_lookup: Function for looking up the GIT sha equiv of a
238
:return dulwich.objects.Commit represent the revision:
240
from dulwich.objects import Commit
242
commit.tree = tree_sha
244
metadata = BzrGitRevisionMetadata()
248
for p in rev.parent_ids:
250
git_p = parent_lookup(p)
253
if metadata is not None:
254
metadata.explicit_parent_ids = rev.parent_ids
255
if git_p is not None:
256
assert len(git_p) == 40, "unexpected length for %r" % git_p
257
parents.append(git_p)
258
commit.parents = parents
260
encoding = rev.properties['git-explicit-encoding']
262
encoding = rev.properties.get('git-implicit-encoding', 'utf-8')
263
commit.encoding = rev.properties.get('git-explicit-encoding')
264
commit.committer = fix_person_identifier(rev.committer.encode(
266
commit.author = fix_person_identifier(
267
rev.get_apparent_authors()[0].encode(encoding))
268
commit.commit_time = long(rev.timestamp)
269
if 'author-timestamp' in rev.properties:
270
commit.author_time = long(rev.properties['author-timestamp'])
272
commit.author_time = commit.commit_time
273
commit._commit_timezone_neg_utc = "commit-timezone-neg-utc" in rev.properties
274
commit.commit_timezone = rev.timezone
275
commit._author_timezone_neg_utc = "author-timezone-neg-utc" in rev.properties
276
if 'author-timezone' in rev.properties:
277
commit.author_timezone = int(rev.properties['author-timezone'])
279
commit.author_timezone = commit.commit_timezone
280
commit.message = self._encode_commit_message(rev, rev.message,
282
assert type(commit.message) == str
283
if metadata is not None:
285
mapping_registry.parse_revision_id(rev.revision_id)
286
except errors.InvalidRevisionId:
287
metadata.revision_id = rev.revision_id
288
mapping_properties = set(
289
['author', 'author-timezone', 'author-timezone-neg-utc',
290
'commit-timezone-neg-utc', 'git-implicit-encoding',
291
'git-explicit-encoding', 'author-timestamp', 'file-modes'])
292
for k, v in rev.properties.iteritems():
293
if not k in mapping_properties:
294
metadata.properties[k] = v
295
commit.message = inject_bzr_metadata(commit.message, metadata,
297
assert type(commit.message) == str
300
def import_fileid_map(self, blob):
301
"""Convert a git file id map blob.
303
:param blob: Git blob object with fileid map
304
:return: Dictionary mapping paths to file ids
306
return deserialize_fileid_map(blob.data)
308
def import_commit(self, commit, lookup_parent_revid):
152
309
"""Convert a git commit to a bzr revision.
154
:return: a `bzrlib.revision.Revision` object.
311
:return: a `bzrlib.revision.Revision` object and a
312
dictionary of path -> file ids
156
314
if commit is None:
157
315
raise AssertionError("Commit object can't be None")
158
rev = ForeignRevision(commit.id, self, self.revision_id_foreign_to_bzr(commit.id))
159
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")
316
rev = ForeignRevision(commit.id, self,
317
self.revision_id_foreign_to_bzr(commit.id))
318
rev.parent_ids = tuple([lookup_parent_revid(p) for p in commit.parents])
319
rev.git_metadata = None
320
def decode_using_encoding(rev, commit, encoding):
321
rev.committer = str(commit.committer).decode(encoding)
322
if commit.committer != commit.author:
323
rev.properties['author'] = str(commit.author).decode(encoding)
324
rev.message, rev.git_metadata = self._decode_commit_message(
325
rev, commit.message, encoding)
326
if commit.encoding is not None:
327
rev.properties['git-explicit-encoding'] = commit.encoding
328
decode_using_encoding(rev, commit, commit.encoding)
330
for encoding in ('utf-8', 'latin1'):
332
decode_using_encoding(rev, commit, encoding)
333
except UnicodeDecodeError:
336
if encoding != 'utf-8':
337
rev.properties['git-implicit-encoding'] = encoding
165
339
if commit.commit_time != commit.author_time:
166
340
rev.properties['author-timestamp'] = str(commit.author_time)
167
341
if commit.commit_timezone != commit.author_timezone:
168
rev.properties['author-timezone'] = "%d" % (commit.author_timezone, )
342
rev.properties['author-timezone'] = "%d" % commit.author_timezone
343
if commit._author_timezone_neg_utc:
344
rev.properties['author-timezone-neg-utc'] = ""
345
if commit._commit_timezone_neg_utc:
346
rev.properties['commit-timezone-neg-utc'] = ""
169
347
rev.timestamp = commit.commit_time
170
348
rev.timezone = commit.commit_timezone
349
if rev.git_metadata is not None:
350
md = rev.git_metadata
352
rev.revision_id = md.revision_id
353
if md.explicit_parent_ids:
354
rev.parent_ids = md.explicit_parent_ids
355
rev.properties.update(md.properties)
358
def get_fileid_map(self, lookup_object, tree_sha):
359
"""Obtain a fileid map for a particular tree.
361
:param lookup_object: Function for looking up an object
362
:param tree_sha: SHA of the root tree
363
:return: GitFileIdMap instance
366
file_id_map_sha = lookup_object(tree_sha)[self.BZR_FILE_IDS_FILE][1]
370
file_ids = self.import_fileid_map(lookup_object(file_id_map_sha))
371
return GitFileIdMap(file_ids, self)
174
374
class BzrGitMappingv1(BzrGitMapping):
175
375
revid_prefix = 'git-v1'
260
491
"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':
494
def object_mode(kind, executable):
495
if kind == 'directory':
266
496
return stat.S_IFDIR
267
elif entry.kind == 'symlink':
269
elif entry.kind == 'file':
497
elif kind == 'symlink':
270
503
mode = stat.S_IFREG | 0644
507
elif kind == 'tree-reference':
508
from dulwich.objects import S_IFGITLINK
275
511
raise AssertionError
278
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes):
279
from dulwich.objects import Tree
514
def entry_mode(entry):
515
"""Determine the git file mode for an inventory entry."""
516
return object_mode(entry.kind, entry.executable)
519
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes, empty_file_name):
520
"""Create a Git Tree object from a Bazaar directory.
522
:param entry: Inventory entry
523
:param lookup_ie_sha1: Lookup the Git SHA1 for a inventory entry
524
:param unusual_modes: Dictionary with unusual file modes by file ids
525
:param empty_file_name: Name to use for dummy files in empty directories,
526
None to ignore empty directories.
528
from dulwich.objects import Blob, Tree
281
for name in sorted(entry.children.keys()):
530
for name, value in entry.children.iteritems():
282
531
ie = entry.children[name]
284
533
mode = unusual_modes[ie.file_id]
286
535
mode = entry_mode(ie)
287
tree.add(mode, name.encode("utf-8"), lookup_ie_sha1(ie))
536
hexsha = lookup_ie_sha1(ie)
537
if hexsha is not None:
538
tree.add(mode, name.encode("utf-8"), hexsha)
539
if entry.parent_id is not None and len(tree) == 0:
540
# Only the root can be an empty tree
541
if empty_file_name is not None:
542
tree.add(stat.S_IFREG | 0644, empty_file_name,
292
549
def extract_unusual_modes(rev):
294
foreign_revid, mapping = mapping_registry.parse_revision_id(rev.revision_id)
551
foreign_revid, mapping = mapping_registry.parse_revision_id(
295
553
except errors.InvalidRevisionId:
298
556
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
559
def parse_git_svn_id(text):
560
(head, uuid) = text.rsplit(" ", 1)
561
(full_url, rev) = head.rsplit("@", 1)
562
return (full_url, int(rev), uuid)
565
class GitFileIdMap(object):
567
def __init__(self, file_ids, mapping):
568
self.file_ids = file_ids
570
self.mapping = mapping
572
def lookup_file_id(self, path):
574
return self.file_ids[path]
576
return self.mapping.generate_file_id(path)
578
def lookup_path(self, file_id):
579
if self.paths is None:
581
for k, v in self.file_ids.iteritems():
584
return self.paths[file_id]
586
return self.mapping.parse_file_id(file_id)