55
54
extract_bzr_metadata,
56
55
inject_bzr_metadata,
57
deserialize_fileid_map,
62
from urllib.parse import quote
64
from urllib import quote
61
66
DEFAULT_FILE_MODE = stat.S_IFREG | 0o644
62
HG_RENAME_SOURCE = b"HG:rename-source"
63
HG_EXTRA = b"HG:extra"
67
HG_RENAME_SOURCE = "HG:rename-source"
65
70
# This HG extra is used to indicate the commit that this commit was based on.
66
HG_EXTRA_AMEND_SOURCE = b"amend_source"
71
HG_EXTRA_AMEND_SOURCE = "amend_source"
68
73
FILE_ID_PREFIX = b'git:'
71
ROOT_ID = b"TREE_ROOT"
74
class UnknownCommitExtra(errors.BzrError):
75
_fmt = "Unknown extra fields in %(object)r: %(fields)r."
77
def __init__(self, object, fields):
78
errors.BzrError.__init__(self)
80
self.fields = ",".join(fields)
83
class UnknownMercurialCommitExtra(errors.BzrError):
84
_fmt = "Unknown mercurial extra fields in %(object)r: %(fields)r."
86
def __init__(self, object, fields):
87
errors.BzrError.__init__(self)
89
self.fields = b",".join(fields)
92
76
def escape_file_id(file_id):
93
file_id = file_id.replace(b'_', b'__')
94
file_id = file_id.replace(b' ', b'_s')
95
file_id = file_id.replace(b'\x0c', b'_c')
77
return file_id.replace('_', '__').replace(' ', '_s').replace('\x0c', '_c')
99
80
def unescape_file_id(file_id):
102
83
while i < len(file_id):
103
if file_id[i:i + 1] != b'_':
104
85
ret.append(file_id[i])
106
if file_id[i + 1:i + 2] == b'_':
108
elif file_id[i + 1:i + 2] == b's':
110
elif file_id[i + 1:i + 2] == b'c':
111
ret.append(b"\x0c"[0])
87
if file_id[i+1] == '_':
89
elif file_id[i+1] == 's':
91
elif file_id[i+1] == 'c':
113
94
raise ValueError("unknown escape character %s" %
114
file_id[i + 1:i + 2])
120
101
def fix_person_identifier(text):
121
if b"<" not in text and b">" not in text:
102
if not "<" in text and not ">" in text:
125
if text.rindex(b">") < text.rindex(b"<"):
106
if text.rindex(">") < text.rindex("<"):
126
107
raise ValueError(text)
127
username, email = text.split(b"<", 2)[-2:]
128
email = email.split(b">", 1)[0]
129
if username.endswith(b" "):
108
username, email = text.split("<", 2)[-2:]
109
email = email.split(">", 1)[0]
110
if username.endswith(" "):
130
111
username = username[:-1]
131
return b"%s <%s>" % (username, email)
112
return "%s <%s>" % (username, email)
134
115
def warn_escaped(commit, num_escaped):
145
126
"""Class that maps between Git and Bazaar semantics."""
146
127
experimental = False
129
BZR_FILE_IDS_FILE = None
148
131
BZR_DUMMY_FILE = None
150
133
def is_special_file(self, filename):
151
return (filename in (self.BZR_DUMMY_FILE, ))
134
return (filename in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE))
153
136
def __init__(self):
154
137
super(BzrGitMapping, self).__init__(foreign_vcs_git)
156
139
def __eq__(self, other):
157
return (type(self) == type(other)
158
and self.revid_prefix == other.revid_prefix)
140
return (type(self) == type(other) and
141
self.revid_prefix == other.revid_prefix)
161
144
def revision_id_foreign_to_bzr(cls, git_rev_id):
163
146
from dulwich.protocol import ZERO_SHA
164
147
if git_rev_id == ZERO_SHA:
165
148
return NULL_REVISION
166
return b"%s:%s" % (cls.revid_prefix, git_rev_id)
149
return "%s:%s" % (cls.revid_prefix, git_rev_id)
169
152
def revision_id_bzr_to_foreign(cls, bzr_rev_id):
170
153
"""Convert a Bazaar revision id to a git revision id handle."""
171
if not bzr_rev_id.startswith(b"%s:" % cls.revid_prefix):
154
if not bzr_rev_id.startswith("%s:" % cls.revid_prefix):
172
155
raise errors.InvalidRevisionId(bzr_rev_id, cls)
173
return bzr_rev_id[len(cls.revid_prefix) + 1:], cls()
156
return bzr_rev_id[len(cls.revid_prefix)+1:], cls()
175
158
def generate_file_id(self, path):
176
159
# Git paths are just bytestrings
177
160
# We must just hope they are valid UTF-8..
178
163
if isinstance(path, text_type):
179
164
path = path.encode("utf-8")
182
165
return FILE_ID_PREFIX + escape_file_id(path)
184
167
def parse_file_id(self, file_id):
185
168
if file_id == ROOT_ID:
187
170
if not file_id.startswith(FILE_ID_PREFIX):
189
return unescape_file_id(file_id[len(FILE_ID_PREFIX):]).decode('utf-8')
172
return unescape_file_id(file_id[len(FILE_ID_PREFIX):])
191
174
def revid_as_refname(self, revid):
192
if not isinstance(revid, bytes):
193
raise TypeError(revid)
195
revid = revid.decode('utf-8')
196
quoted_revid = urlutils.quote(revid)
197
return b"refs/bzr/" + quoted_revid.encode('utf-8')
175
return "refs/bzr/%s" % quote(revid)
199
177
def import_unusual_file_modes(self, rev, unusual_file_modes):
200
178
if unusual_file_modes:
201
179
ret = [(path, unusual_file_modes[path])
202
180
for path in sorted(unusual_file_modes.keys())]
203
rev.properties[u'file-modes'] = bencode.bencode(ret)
181
rev.properties['file-modes'] = bencode.bencode(ret)
205
183
def export_unusual_file_modes(self, rev):
207
file_modes = rev.properties[u'file-modes']
185
file_modes = rev.properties['file-modes']
224
202
branch = 'default'
225
203
for name in rev.properties:
226
if name == u'hg:extra:branch':
227
branch = rev.properties[u'hg:extra:branch']
228
elif name.startswith(u'hg:extra'):
229
extra[name[len(u'hg:extra:'):]] = base64.b64decode(
204
if name == 'hg:extra:branch':
205
branch = rev.properties['hg:extra:branch']
206
elif name.startswith('hg:extra'):
207
extra[name[len('hg:extra:'):]] = base64.b64decode(
230
208
rev.properties[name])
231
elif name == u'hg:renames':
209
elif name == 'hg:renames':
232
210
renames = bencode.bdecode(base64.b64decode(
233
rev.properties[u'hg:renames']))
211
rev.properties['hg:renames']))
234
212
# TODO: Export other properties as 'bzr:' extras?
235
213
ret = format_hg_metadata(renames, branch, extra)
236
if not isinstance(ret, bytes):
214
if type(ret) is not str:
237
215
raise TypeError(ret)
240
218
def _extract_git_svn_metadata(self, rev, message):
241
219
lines = message.split("\n")
242
if not (lines[-1] == "" and len(lines) >= 2 and
243
lines[-2].startswith("git-svn-id:")):
220
if not (lines[-1] == "" and len(lines) >= 2 and lines[-2].startswith("git-svn-id:")):
245
222
git_svn_id = lines[-2].split(": ", 1)[1]
246
rev.properties[u'git-svn-id'] = git_svn_id
223
rev.properties['git-svn-id'] = git_svn_id
247
224
(url, rev, uuid) = parse_git_svn_id(git_svn_id)
248
225
# FIXME: Convert this to converted-from property somehow..
249
226
return "\n".join(lines[:-2])
251
228
def _extract_hg_metadata(self, rev, message):
252
229
(message, renames, branch, extra) = extract_hg_metadata(message)
253
230
if branch is not None:
254
rev.properties[u'hg:extra:branch'] = branch
255
for name, value in viewitems(extra):
256
rev.properties[u'hg:extra:' + name] = base64.b64encode(value)
231
rev.properties['hg:extra:branch'] = branch
232
for name, value in extra.iteritems():
233
rev.properties['hg:extra:' + name] = base64.b64encode(value)
258
rev.properties[u'hg:renames'] = base64.b64encode(bencode.bencode(
259
[(new, old) for (old, new) in viewitems(renames)]))
235
rev.properties['hg:renames'] = base64.b64encode(bencode.bencode(
236
[(new, old) for (old, new) in renames.iteritems()]))
262
239
def _extract_bzr_metadata(self, rev, message):
269
246
def _encode_commit_message(self, rev, message, encoding):
270
247
return message.encode(encoding)
249
def export_fileid_map(self, fileid_map):
250
"""Export a file id map to a fileid map.
252
:param fileid_map: File id map, mapping paths to file ids
253
:return: A Git blob object (or None if there are no entries)
255
from dulwich.objects import Blob
257
b.set_raw_chunks(serialize_fileid_map(fileid_map))
272
260
def export_commit(self, rev, tree_sha, parent_lookup, lossy,
274
262
"""Turn a Bazaar revision in to a Git commit
302
290
parents.append(git_p)
303
291
commit.parents = parents
305
encoding = rev.properties[u'git-explicit-encoding']
293
encoding = rev.properties['git-explicit-encoding']
307
encoding = rev.properties.get(u'git-implicit-encoding', 'utf-8')
295
encoding = rev.properties.get('git-implicit-encoding', 'utf-8')
309
commit.encoding = rev.properties[u'git-explicit-encoding'].encode(
297
commit.encoding = rev.properties['git-explicit-encoding'].encode('ascii')
313
300
commit.committer = fix_person_identifier(rev.committer.encode(
315
302
commit.author = fix_person_identifier(
316
303
rev.get_apparent_authors()[0].encode(encoding))
317
# TODO(jelmer): Don't use this hack.
318
long = getattr(__builtins__, 'long', int)
319
304
commit.commit_time = long(rev.timestamp)
320
if u'author-timestamp' in rev.properties:
321
commit.author_time = long(rev.properties[u'author-timestamp'])
305
if 'author-timestamp' in rev.properties:
306
commit.author_time = long(rev.properties['author-timestamp'])
323
308
commit.author_time = commit.commit_time
324
commit._commit_timezone_neg_utc = (
325
u"commit-timezone-neg-utc" in rev.properties)
309
commit._commit_timezone_neg_utc = "commit-timezone-neg-utc" in rev.properties
326
310
commit.commit_timezone = rev.timezone
327
commit._author_timezone_neg_utc = (
328
u"author-timezone-neg-utc" in rev.properties)
329
if u'author-timezone' in rev.properties:
330
commit.author_timezone = int(rev.properties[u'author-timezone'])
311
commit._author_timezone_neg_utc = "author-timezone-neg-utc" in rev.properties
312
if 'author-timezone' in rev.properties:
313
commit.author_timezone = int(rev.properties['author-timezone'])
332
315
commit.author_timezone = commit.commit_timezone
333
if u'git-gpg-signature' in rev.properties:
334
commit.gpgsig = rev.properties[u'git-gpg-signature'].encode(
336
if u'git-gpg-signature-b64' in rev.properties:
337
commit.gpgsig = base64.b64decode(rev.properties[u'git-gpg-signature-b64'])
316
if 'git-gpg-signature' in rev.properties:
317
commit.gpgsig = rev.properties['git-gpg-signature'].encode('ascii')
338
318
commit.message = self._encode_commit_message(rev, rev.message,
340
if not isinstance(commit.message, bytes):
320
if type(commit.message) is not str:
341
321
raise TypeError(commit.message)
342
322
if metadata is not None:
345
325
except errors.InvalidRevisionId:
346
326
metadata.revision_id = rev.revision_id
347
327
mapping_properties = set(
348
[u'author', u'author-timezone', u'author-timezone-neg-utc',
349
u'commit-timezone-neg-utc', u'git-implicit-encoding',
350
u'git-gpg-signature', u'git-gpg-signature-b64',
351
u'git-explicit-encoding',
352
u'author-timestamp', u'file-modes'])
353
for k, v in viewitems(rev.properties):
354
if k not in mapping_properties:
328
['author', 'author-timezone', 'author-timezone-neg-utc',
329
'commit-timezone-neg-utc', 'git-implicit-encoding',
330
'git-gpg-signature', 'git-explicit-encoding',
331
'author-timestamp', 'file-modes'])
332
for k, v in rev.properties.iteritems():
333
if not k in mapping_properties:
355
334
metadata.properties[k] = v
356
335
if not lossy and metadata:
357
336
if self.roundtripping:
358
337
commit.message = inject_bzr_metadata(commit.message, metadata,
362
None, None, self, revision_id=rev.revision_id)
363
if not isinstance(commit.message, bytes):
340
raise NoPushSupport()
341
if type(commit.message) is not str:
364
342
raise TypeError(commit.message)
366
propname = u'git-mergetag-0'
344
propname = 'git-mergetag-0'
367
345
while propname in rev.properties:
368
commit.mergetag.append(Tag.from_string(rev.properties[propname]))
346
commit.mergetag.append(Tag.from_string(rev.properties[propname].encode(encoding)))
370
propname = u'git-mergetag-%d' % i
371
if u'git-extra' in rev.properties:
374
for l in rev.properties[u'git-extra'].splitlines()])
348
propname = 'git-mergetag-%d' % i
349
if 'git-extra' in rev.properties:
350
commit.extra.extend([l.split(' ', 1) for l in rev.properties['git-extra'].splitlines()])
377
def get_revision_id(self, commit):
379
encoding = commit.encoding.decode('ascii')
383
message, metadata = self._decode_commit_message(
384
None, commit.message, encoding)
385
except UnicodeDecodeError:
388
if metadata.revision_id:
389
return metadata.revision_id
390
return self.revision_id_foreign_to_bzr(commit.id)
392
def import_commit(self, commit, lookup_parent_revid, strict=True):
353
def import_fileid_map(self, blob):
354
"""Convert a git file id map blob.
356
:param blob: Git blob object with fileid map
357
:return: Dictionary mapping paths to file ids
359
return deserialize_fileid_map(blob.data)
361
def import_commit(self, commit, lookup_parent_revid):
393
362
"""Convert a git commit to a bzr revision.
395
364
:return: a `breezy.revision.Revision` object, foreign revid and a
398
367
if commit is None:
399
368
raise AssertionError("Commit object can't be None")
400
369
rev = ForeignRevision(commit.id, self,
401
self.revision_id_foreign_to_bzr(commit.id))
370
self.revision_id_foreign_to_bzr(commit.id))
402
371
rev.git_metadata = None
404
372
def decode_using_encoding(rev, commit, encoding):
405
rev.committer = commit.committer.decode(encoding)
373
rev.committer = str(commit.committer).decode(encoding)
406
374
if commit.committer != commit.author:
407
rev.properties[u'author'] = commit.author.decode(encoding)
375
rev.properties['author'] = str(commit.author).decode(encoding)
408
376
rev.message, rev.git_metadata = self._decode_commit_message(
409
377
rev, commit.message, encoding)
410
378
if commit.encoding is not None:
411
rev.properties[u'git-explicit-encoding'] = commit.encoding.decode(
413
decode_using_encoding(rev, commit, commit.encoding.decode('ascii'))
379
rev.properties['git-explicit-encoding'] = commit.encoding
380
decode_using_encoding(rev, commit, commit.encoding)
415
382
for encoding in ('utf-8', 'latin1'):
421
388
if encoding != 'utf-8':
422
rev.properties[u'git-implicit-encoding'] = encoding
389
rev.properties['git-implicit-encoding'] = encoding
424
391
if commit.commit_time != commit.author_time:
425
rev.properties[u'author-timestamp'] = str(commit.author_time)
392
rev.properties['author-timestamp'] = str(commit.author_time)
426
393
if commit.commit_timezone != commit.author_timezone:
427
rev.properties[u'author-timezone'] = "%d" % commit.author_timezone
394
rev.properties['author-timezone'] = "%d" % commit.author_timezone
428
395
if commit._author_timezone_neg_utc:
429
rev.properties[u'author-timezone-neg-utc'] = ""
396
rev.properties['author-timezone-neg-utc'] = ""
430
397
if commit._commit_timezone_neg_utc:
431
rev.properties[u'commit-timezone-neg-utc'] = ""
398
rev.properties['commit-timezone-neg-utc'] = ""
432
399
if commit.gpgsig:
434
rev.properties[u'git-gpg-signature'] = commit.gpgsig.decode(
436
except UnicodeDecodeError:
437
rev.properties[u'git-gpg-signature-b64'] = base64.b64encode(
400
rev.properties['git-gpg-signature'] = commit.gpgsig.decode('ascii')
439
401
if commit.mergetag:
440
402
for i, tag in enumerate(commit.mergetag):
441
rev.properties[u'git-mergetag-%d' % i] = tag.as_raw_string()
403
rev.properties['git-mergetag-%d' % i] = tag.as_raw_string()
442
404
rev.timestamp = commit.commit_time
443
405
rev.timezone = commit.commit_timezone
444
406
rev.parent_ids = None
459
421
parents.append(lookup_parent_revid(p))
461
423
parents.append(self.revision_id_foreign_to_bzr(p))
462
rev.parent_ids = list(parents)
424
rev.parent_ids = tuple(parents)
463
425
unknown_extra_fields = []
465
427
for k, v in commit.extra:
466
428
if k == HG_RENAME_SOURCE:
467
extra_lines.append(k + b' ' + v + b'\n')
429
extra_lines.append(k + ' ' + v + '\n')
468
430
elif k == HG_EXTRA:
469
hgk, hgv = v.split(b':', 1)
470
if hgk not in (HG_EXTRA_AMEND_SOURCE, ) and strict:
471
raise UnknownMercurialCommitExtra(commit, [hgk])
472
extra_lines.append(k + b' ' + v + b'\n')
431
hgk, hgv = v.split(':', 1)
432
if hgk not in (HG_EXTRA_AMEND_SOURCE, ):
433
raise UnknownMercurialCommitExtra(commit, hgk)
434
extra_lines.append(k + ' ' + v + '\n')
474
436
unknown_extra_fields.append(k)
475
if unknown_extra_fields and strict:
476
raise UnknownCommitExtra(
478
[f.decode('ascii', 'replace') for f in unknown_extra_fields])
437
if unknown_extra_fields:
438
raise UnknownCommitExtra(commit, unknown_extra_fields)
480
rev.properties[u'git-extra'] = b''.join(extra_lines)
440
rev.properties['git-extra'] = ''.join(extra_lines)
481
441
return rev, roundtrip_revid, verifiers
443
def get_fileid_map(self, lookup_object, tree_sha):
444
"""Obtain a fileid map for a particular tree.
446
:param lookup_object: Function for looking up an object
447
:param tree_sha: SHA of the root tree
448
:return: GitFileIdMap instance
451
file_id_map_sha = lookup_object(tree_sha)[self.BZR_FILE_IDS_FILE][1]
455
file_ids = self.import_fileid_map(lookup_object(file_id_map_sha))
456
return GitFileIdMap(file_ids, self)
484
459
class BzrGitMappingv1(BzrGitMapping):
485
revid_prefix = b'git-v1'
460
revid_prefix = 'git-v1'
486
461
experimental = False
488
463
def __str__(self):
492
467
class BzrGitMappingExperimental(BzrGitMappingv1):
493
revid_prefix = b'git-experimental'
468
revid_prefix = 'git-experimental'
494
469
experimental = True
495
roundtripping = False
472
BZR_FILE_IDS_FILE = '.bzrfileids'
497
474
BZR_DUMMY_FILE = '.bzrdummy'
499
476
def _decode_commit_message(self, rev, message, encoding):
502
477
message = self._extract_hg_metadata(rev, message)
503
478
message = self._extract_git_svn_metadata(rev, message)
504
479
message, metadata = self._extract_bzr_metadata(rev, message)
510
485
ret += self._generate_git_svn_metadata(rev, encoding)
513
def import_commit(self, commit, lookup_parent_revid, strict=True):
514
rev, roundtrip_revid, verifiers = super(
515
BzrGitMappingExperimental, self).import_commit(
516
commit, lookup_parent_revid, strict)
517
rev.properties[u'converted_revision'] = "git %s\n" % commit.id
488
def import_commit(self, commit, lookup_parent_revid):
489
rev, roundtrip_revid, verifiers = super(BzrGitMappingExperimental, self).import_commit(commit, lookup_parent_revid)
490
rev.properties['converted_revision'] = "git %s\n" % commit.id
518
491
return rev, roundtrip_revid, verifiers
525
498
if bzr_revid == NULL_REVISION:
526
499
from dulwich.protocol import ZERO_SHA
527
500
return ZERO_SHA, None
528
if not bzr_revid.startswith(b"git-"):
501
if not bzr_revid.startswith("git-"):
529
502
raise errors.InvalidRevisionId(bzr_revid, None)
530
(mapping_version, git_sha) = bzr_revid.split(b":", 1)
503
(mapping_version, git_sha) = bzr_revid.split(":", 1)
531
504
mapping = self.get(mapping_version)
532
505
return mapping.revision_id_bzr_to_foreign(bzr_revid)
537
510
mapping_registry = GitMappingRegistry()
538
mapping_registry.register_lazy(b'git-v1', __name__,
540
mapping_registry.register_lazy(b'git-experimental',
541
__name__, "BzrGitMappingExperimental")
511
mapping_registry.register_lazy('git-v1', "breezy.plugins.git.mapping",
513
mapping_registry.register_lazy('git-experimental',
514
"breezy.plugins.git.mapping", "BzrGitMappingExperimental")
542
515
# Uncomment the next line to enable the experimental bzr-git mappings.
543
516
# This will make sure all bzr metadata is pushed into git, allowing for
544
517
# full roundtripping later.
545
518
# NOTE: THIS IS EXPERIMENTAL. IT MAY EAT YOUR DATA OR CORRUPT
546
519
# YOUR BZR OR GIT REPOSITORIES. USE WITH CARE.
547
# mapping_registry.set_default('git-experimental')
548
mapping_registry.set_default(b'git-v1')
520
#mapping_registry.set_default('git-experimental')
521
mapping_registry.set_default('git-v1')
551
524
class ForeignGit(ForeignVcs):
656
629
return (full_url, int(rev), uuid)
632
class GitFileIdMap(object):
634
def __init__(self, file_ids, mapping):
635
self.file_ids = file_ids
637
self.mapping = mapping
639
def all_file_ids(self):
640
return self.file_ids.values()
642
def set_file_id(self, path, file_id):
643
if type(path) is not str:
644
raise TypeError(path)
645
if type(file_id) is not str:
646
raise TypeError(file_id)
647
self.file_ids[path] = file_id
649
def lookup_file_id(self, path):
650
if type(path) is not str:
651
raise TypeError(path)
653
file_id = self.file_ids[path]
655
file_id = self.mapping.generate_file_id(path)
656
if type(file_id) is not str:
657
raise TypeError(file_id)
660
def lookup_path(self, file_id):
661
if self.paths is None:
663
for k, v in self.file_ids.iteritems():
666
path = self.paths[file_id]
668
return self.mapping.parse_file_id(file_id)
670
if type(path) is not str:
671
raise TypeError(path)
675
return self.__class__(dict(self.file_ids), self.mapping)
659
678
def needs_roundtripping(repo, revid):
661
680
mapping_registry.parse_revision_id(revid)