1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
# Copyright (C) 2007 Canonical Ltd
3
# Copyright (C) 2008 John Carr
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
"""Converters, etc for going between Bazaar and Git ids."""
21
from __future__ import absolute_import
32
from ...bzr.inventory import (
35
from ...foreign import (
40
from ...revision import (
43
from ...sixish import text_type
47
UnknownMercurialCommitExtra,
53
from .roundtrip import (
57
deserialize_fileid_map,
62
from urllib.parse import quote
64
from urllib import quote
66
DEFAULT_FILE_MODE = stat.S_IFREG | 0o644
67
HG_RENAME_SOURCE = "HG:rename-source"
70
# This HG extra is used to indicate the commit that this commit was based on.
71
HG_EXTRA_AMEND_SOURCE = "amend_source"
73
FILE_ID_PREFIX = b'git:'
76
def escape_file_id(file_id):
77
return file_id.replace('_', '__').replace(' ', '_s').replace('\x0c', '_c')
80
def unescape_file_id(file_id):
83
while i < len(file_id):
85
ret.append(file_id[i])
87
if file_id[i+1] == '_':
89
elif file_id[i+1] == 's':
91
elif file_id[i+1] == 'c':
94
raise ValueError("unknown escape character %s" %
101
def fix_person_identifier(text):
102
if not "<" in text and not ">" in text:
106
if text.rindex(">") < text.rindex("<"):
107
raise ValueError(text)
108
username, email = text.split("<", 2)[-2:]
109
email = email.split(">", 1)[0]
110
if username.endswith(" "):
111
username = username[:-1]
112
return "%s <%s>" % (username, email)
115
def warn_escaped(commit, num_escaped):
116
trace.warning("Escaped %d XML-invalid characters in %s. Will be unable "
117
"to regenerate the SHA map.", num_escaped, commit)
120
def warn_unusual_mode(commit, path, mode):
121
trace.mutter("Unusual file mode %o for %s in %s. Storing as revision "
122
"property. ", mode, path, commit)
125
class BzrGitMapping(foreign.VcsMapping):
126
"""Class that maps between Git and Bazaar semantics."""
129
BZR_FILE_IDS_FILE = None
131
BZR_DUMMY_FILE = None
133
def is_special_file(self, filename):
134
return (filename in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE))
137
super(BzrGitMapping, self).__init__(foreign_vcs_git)
139
def __eq__(self, other):
140
return (type(self) == type(other) and
141
self.revid_prefix == other.revid_prefix)
144
def revision_id_foreign_to_bzr(cls, git_rev_id):
145
"""Convert a git revision id handle to a Bazaar revision id."""
146
from dulwich.protocol import ZERO_SHA
147
if git_rev_id == ZERO_SHA:
149
return "%s:%s" % (cls.revid_prefix, git_rev_id)
152
def revision_id_bzr_to_foreign(cls, bzr_rev_id):
153
"""Convert a Bazaar revision id to a git revision id handle."""
154
if not bzr_rev_id.startswith("%s:" % cls.revid_prefix):
155
raise errors.InvalidRevisionId(bzr_rev_id, cls)
156
return bzr_rev_id[len(cls.revid_prefix)+1:], cls()
158
def generate_file_id(self, path):
159
# Git paths are just bytestrings
160
# We must just hope they are valid UTF-8..
163
if isinstance(path, text_type):
164
path = path.encode("utf-8")
165
return FILE_ID_PREFIX + escape_file_id(path)
167
def parse_file_id(self, file_id):
168
if file_id == ROOT_ID:
170
if not file_id.startswith(FILE_ID_PREFIX):
172
return unescape_file_id(file_id[len(FILE_ID_PREFIX):])
174
def revid_as_refname(self, revid):
175
return "refs/bzr/%s" % quote(revid)
177
def import_unusual_file_modes(self, rev, unusual_file_modes):
178
if unusual_file_modes:
179
ret = [(path, unusual_file_modes[path])
180
for path in sorted(unusual_file_modes.keys())]
181
rev.properties[u'file-modes'] = bencode.bencode(ret)
183
def export_unusual_file_modes(self, rev):
185
file_modes = rev.properties[u'file-modes']
189
return dict(bencode.bdecode(file_modes.encode("utf-8")))
191
def _generate_git_svn_metadata(self, rev, encoding):
193
git_svn_id = rev.properties[u"git-svn-id"]
197
return "\ngit-svn-id: %s\n" % git_svn_id.encode(encoding)
199
def _generate_hg_message_tail(self, rev):
203
for name in rev.properties:
204
if name == u'hg:extra:branch':
205
branch = rev.properties[u'hg:extra:branch']
206
elif name.startswith(u'hg:extra'):
207
extra[name[len(u'hg:extra:'):]] = base64.b64decode(
208
rev.properties[name])
209
elif name == u'hg:renames':
210
renames = bencode.bdecode(base64.b64decode(
211
rev.properties[u'hg:renames']))
212
# TODO: Export other properties as 'bzr:' extras?
213
ret = format_hg_metadata(renames, branch, extra)
214
if type(ret) is not str:
218
def _extract_git_svn_metadata(self, rev, message):
219
lines = message.split("\n")
220
if not (lines[-1] == "" and len(lines) >= 2 and lines[-2].startswith("git-svn-id:")):
222
git_svn_id = lines[-2].split(": ", 1)[1]
223
rev.properties[u'git-svn-id'] = git_svn_id
224
(url, rev, uuid) = parse_git_svn_id(git_svn_id)
225
# FIXME: Convert this to converted-from property somehow..
226
return "\n".join(lines[:-2])
228
def _extract_hg_metadata(self, rev, message):
229
(message, renames, branch, extra) = extract_hg_metadata(message)
230
if branch is not None:
231
rev.properties[u'hg:extra:branch'] = branch
232
for name, value in extra.iteritems():
233
rev.properties[u'hg:extra:' + name] = base64.b64encode(value)
235
rev.properties[u'hg:renames'] = base64.b64encode(bencode.bencode(
236
[(new, old) for (old, new) in renames.iteritems()]))
239
def _extract_bzr_metadata(self, rev, message):
240
(message, metadata) = extract_bzr_metadata(message)
241
return message, metadata
243
def _decode_commit_message(self, rev, message, encoding):
244
return message.decode(encoding), CommitSupplement()
246
def _encode_commit_message(self, rev, message, encoding):
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))
260
def export_commit(self, rev, tree_sha, parent_lookup, lossy,
262
"""Turn a Bazaar revision in to a Git commit
264
:param tree_sha: Tree sha for the commit
265
:param parent_lookup: Function for looking up the GIT sha equiv of a
267
:param lossy: Whether to store roundtripping information.
268
:param verifiers: Verifiers info
269
:return dulwich.objects.Commit represent the revision:
271
from dulwich.objects import Commit, Tag
273
commit.tree = tree_sha
275
metadata = CommitSupplement()
276
metadata.verifiers = verifiers
280
for p in rev.parent_ids:
282
git_p = parent_lookup(p)
285
if metadata is not None:
286
metadata.explicit_parent_ids = rev.parent_ids
287
if git_p is not None:
289
raise AssertionError("unexpected length for %r" % git_p)
290
parents.append(git_p)
291
commit.parents = parents
293
encoding = rev.properties[u'git-explicit-encoding']
295
encoding = rev.properties.get(u'git-implicit-encoding', 'utf-8')
297
commit.encoding = rev.properties[u'git-explicit-encoding'].encode('ascii')
300
commit.committer = fix_person_identifier(rev.committer.encode(
302
commit.author = fix_person_identifier(
303
rev.get_apparent_authors()[0].encode(encoding))
304
commit.commit_time = long(rev.timestamp)
305
if u'author-timestamp' in rev.properties:
306
commit.author_time = long(rev.properties[u'author-timestamp'])
308
commit.author_time = commit.commit_time
309
commit._commit_timezone_neg_utc = u"commit-timezone-neg-utc" in rev.properties
310
commit.commit_timezone = rev.timezone
311
commit._author_timezone_neg_utc = u"author-timezone-neg-utc" in rev.properties
312
if u'author-timezone' in rev.properties:
313
commit.author_timezone = int(rev.properties[u'author-timezone'])
315
commit.author_timezone = commit.commit_timezone
316
if u'git-gpg-signature' in rev.properties:
317
commit.gpgsig = rev.properties[u'git-gpg-signature'].encode('ascii')
318
commit.message = self._encode_commit_message(rev, rev.message,
320
if type(commit.message) is not str:
321
raise TypeError(commit.message)
322
if metadata is not None:
324
mapping_registry.parse_revision_id(rev.revision_id)
325
except errors.InvalidRevisionId:
326
metadata.revision_id = rev.revision_id
327
mapping_properties = set(
328
[u'author', u'author-timezone', u'author-timezone-neg-utc',
329
u'commit-timezone-neg-utc', u'git-implicit-encoding',
330
u'git-gpg-signature', u'git-explicit-encoding',
331
u'author-timestamp', u'file-modes'])
332
for k, v in rev.properties.iteritems():
333
if not k in mapping_properties:
334
metadata.properties[k] = v
335
if not lossy and metadata:
336
if self.roundtripping:
337
commit.message = inject_bzr_metadata(commit.message, metadata,
340
raise NoPushSupport(None, None, self, revision_id=rev.revision_id)
341
if type(commit.message) is not str:
342
raise TypeError(commit.message)
344
propname = u'git-mergetag-0'
345
while propname in rev.properties:
346
commit.mergetag.append(Tag.from_string(rev.properties[propname].encode(encoding)))
348
propname = u'git-mergetag-%d' % i
349
if u'git-extra' in rev.properties:
350
commit.extra.extend([l.split(' ', 1) for l in rev.properties[u'git-extra'].splitlines()])
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):
362
"""Convert a git commit to a bzr revision.
364
:return: a `breezy.revision.Revision` object, foreign revid and a
368
raise AssertionError("Commit object can't be None")
369
rev = ForeignRevision(commit.id, self,
370
self.revision_id_foreign_to_bzr(commit.id))
371
rev.git_metadata = None
372
def decode_using_encoding(rev, commit, encoding):
373
rev.committer = str(commit.committer).decode(encoding)
374
if commit.committer != commit.author:
375
rev.properties[u'author'] = str(commit.author).decode(encoding)
376
rev.message, rev.git_metadata = self._decode_commit_message(
377
rev, commit.message, encoding)
378
if commit.encoding is not None:
379
rev.properties[u'git-explicit-encoding'] = commit.encoding
380
decode_using_encoding(rev, commit, commit.encoding)
382
for encoding in ('utf-8', 'latin1'):
384
decode_using_encoding(rev, commit, encoding)
385
except UnicodeDecodeError:
388
if encoding != 'utf-8':
389
rev.properties[u'git-implicit-encoding'] = encoding
391
if commit.commit_time != commit.author_time:
392
rev.properties[u'author-timestamp'] = str(commit.author_time)
393
if commit.commit_timezone != commit.author_timezone:
394
rev.properties[u'author-timezone'] = "%d" % commit.author_timezone
395
if commit._author_timezone_neg_utc:
396
rev.properties[u'author-timezone-neg-utc'] = ""
397
if commit._commit_timezone_neg_utc:
398
rev.properties[u'commit-timezone-neg-utc'] = ""
400
rev.properties[u'git-gpg-signature'] = commit.gpgsig.decode('ascii')
402
for i, tag in enumerate(commit.mergetag):
403
rev.properties[u'git-mergetag-%d' % i] = tag.as_raw_string()
404
rev.timestamp = commit.commit_time
405
rev.timezone = commit.commit_timezone
406
rev.parent_ids = None
407
if rev.git_metadata is not None:
408
md = rev.git_metadata
409
roundtrip_revid = md.revision_id
410
if md.explicit_parent_ids:
411
rev.parent_ids = md.explicit_parent_ids
412
rev.properties.update(md.properties)
413
verifiers = md.verifiers
415
roundtrip_revid = None
417
if rev.parent_ids is None:
419
for p in commit.parents:
421
parents.append(lookup_parent_revid(p))
423
parents.append(self.revision_id_foreign_to_bzr(p))
424
rev.parent_ids = tuple(parents)
425
unknown_extra_fields = []
427
for k, v in commit.extra:
428
if k == HG_RENAME_SOURCE:
429
extra_lines.append(k + ' ' + v + '\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')
436
unknown_extra_fields.append(k)
437
if unknown_extra_fields:
438
raise UnknownCommitExtra(commit, unknown_extra_fields)
440
rev.properties[u'git-extra'] = ''.join(extra_lines)
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)
459
class BzrGitMappingv1(BzrGitMapping):
460
revid_prefix = 'git-v1'
464
return self.revid_prefix
467
class BzrGitMappingExperimental(BzrGitMappingv1):
468
revid_prefix = 'git-experimental'
472
BZR_FILE_IDS_FILE = '.bzrfileids'
474
BZR_DUMMY_FILE = '.bzrdummy'
476
def _decode_commit_message(self, rev, message, encoding):
477
message = self._extract_hg_metadata(rev, message)
478
message = self._extract_git_svn_metadata(rev, message)
479
message, metadata = self._extract_bzr_metadata(rev, message)
480
return message.decode(encoding), metadata
482
def _encode_commit_message(self, rev, message, encoding):
483
ret = message.encode(encoding)
484
ret += self._generate_hg_message_tail(rev)
485
ret += self._generate_git_svn_metadata(rev, encoding)
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[u'converted_revision'] = "git %s\n" % commit.id
491
return rev, roundtrip_revid, verifiers
494
class GitMappingRegistry(VcsMappingRegistry):
495
"""Registry with available git mappings."""
497
def revision_id_bzr_to_foreign(self, bzr_revid):
498
if bzr_revid == NULL_REVISION:
499
from dulwich.protocol import ZERO_SHA
500
return ZERO_SHA, None
501
if not bzr_revid.startswith("git-"):
502
raise errors.InvalidRevisionId(bzr_revid, None)
503
(mapping_version, git_sha) = bzr_revid.split(":", 1)
504
mapping = self.get(mapping_version)
505
return mapping.revision_id_bzr_to_foreign(bzr_revid)
507
parse_revision_id = revision_id_bzr_to_foreign
510
mapping_registry = GitMappingRegistry()
511
mapping_registry.register_lazy('git-v1', "breezy.plugins.git.mapping",
513
mapping_registry.register_lazy('git-experimental',
514
"breezy.plugins.git.mapping", "BzrGitMappingExperimental")
515
# Uncomment the next line to enable the experimental bzr-git mappings.
516
# This will make sure all bzr metadata is pushed into git, allowing for
517
# full roundtripping later.
518
# NOTE: THIS IS EXPERIMENTAL. IT MAY EAT YOUR DATA OR CORRUPT
519
# YOUR BZR OR GIT REPOSITORIES. USE WITH CARE.
520
#mapping_registry.set_default('git-experimental')
521
mapping_registry.set_default('git-v1')
524
class ForeignGit(ForeignVcs):
525
"""The Git Stupid Content Tracker"""
528
def branch_format(self):
529
from .branch import LocalGitBranchFormat
530
return LocalGitBranchFormat()
533
def repository_format(self):
534
from .repository import GitRepositoryFormat
535
return GitRepositoryFormat()
538
super(ForeignGit, self).__init__(mapping_registry)
539
self.abbreviation = "git"
542
def serialize_foreign_revid(self, foreign_revid):
546
def show_foreign_revid(cls, foreign_revid):
547
return { "git commit": foreign_revid }
550
foreign_vcs_git = ForeignGit()
551
default_mapping = mapping_registry.get_default()()
554
def symlink_to_blob(symlink_target):
555
from dulwich.objects import Blob
557
if isinstance(symlink_target, text_type):
558
symlink_target = symlink_target.encode('utf-8')
559
blob.data = symlink_target
563
def mode_is_executable(mode):
564
"""Check if mode should be considered executable."""
565
return bool(mode & 0o111)
569
"""Determine the Bazaar inventory kind based on Unix file mode."""
572
entry_kind = (mode & 0o700000) / 0o100000
575
elif entry_kind == 1:
576
file_kind = (mode & 0o70000) / 0o10000
582
return 'tree-reference'
584
raise AssertionError(
585
"Unknown file kind %d, perms=%o." % (file_kind, mode,))
587
raise AssertionError(
588
"Unknown kind, perms=%r." % (mode,))
591
def object_mode(kind, executable):
592
if kind == 'directory':
594
elif kind == 'symlink':
600
mode = stat.S_IFREG | 0o644
604
elif kind == 'tree-reference':
605
from dulwich.objects import S_IFGITLINK
611
def entry_mode(entry):
612
"""Determine the git file mode for an inventory entry."""
613
return object_mode(entry.kind, getattr(entry, 'executable', False))
616
def extract_unusual_modes(rev):
618
foreign_revid, mapping = mapping_registry.parse_revision_id(
620
except errors.InvalidRevisionId:
623
return mapping.export_unusual_file_modes(rev)
626
def parse_git_svn_id(text):
627
(head, uuid) = text.rsplit(" ", 1)
628
(full_url, rev) = head.rsplit("@", 1)
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)
678
def needs_roundtripping(repo, revid):
680
mapping_registry.parse_revision_id(revid)
681
except errors.InvalidRevisionId: