1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
1
2
# Copyright (C) 2007 Canonical Ltd
2
# Copyright (C) 2008-2010 Jelmer Vernooij <jelmer@samba.org>
3
3
# Copyright (C) 2008 John Carr
5
5
# This program is free software; you can redistribute it and/or modify
15
15
# You should have received a copy of the GNU General Public License
16
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
19
"""Converters, etc for going between Bazaar and Git ids."""
21
from __future__ import absolute_import
30
from bzrlib.inventory import (
32
from ...bzr.inventory import (
33
from bzrlib.foreign import (
35
from ...foreign import (
35
37
VcsMappingRegistry,
38
from bzrlib.revision import (
40
from ...revision import (
41
from bzrlib.plugins.git.hg import (
46
UnknownMercurialCommitExtra,
42
49
format_hg_metadata,
43
50
extract_hg_metadata,
45
from bzrlib.plugins.git.roundtrip import (
52
from .roundtrip import (
46
53
extract_bzr_metadata,
47
54
inject_bzr_metadata,
48
BzrGitRevisionMetadata,
49
56
deserialize_fileid_map,
50
57
serialize_fileid_map,
53
DEFAULT_FILE_MODE = stat.S_IFREG | 0644
61
from urllib.parse import quote
63
from urllib import quote
65
DEFAULT_FILE_MODE = stat.S_IFREG | 0o644
66
HG_RENAME_SOURCE = "HG:rename-source"
69
# This HG extra is used to indicate the commit that this commit was based on.
70
HG_EXTRA_AMEND_SOURCE = "amend_source"
72
FILE_ID_PREFIX = b'git:'
56
75
def escape_file_id(file_id):
57
return file_id.replace('_', '__').replace(' ', '_s')
76
return file_id.replace('_', '__').replace(' ', '_s').replace('\x0c', '_c')
60
79
def unescape_file_id(file_id):
79
100
def fix_person_identifier(text):
80
if "<" in text and ">" in text:
82
return "%s <%s>" % (text, text)
101
if not "<" in text and not ">" in text:
105
if text.rindex(">") < text.rindex("<"):
106
raise ValueError(text)
107
username, email = text.split("<", 2)[-2:]
108
email = email.split(">", 1)[0]
109
if username.endswith(" "):
110
username = username[:-1]
111
return "%s <%s>" % (username, email)
85
114
def warn_escaped(commit, num_escaped):
101
130
BZR_DUMMY_FILE = None
132
def is_special_file(self, filename):
133
return (filename in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE))
103
135
def __init__(self):
104
super(BzrGitMapping, self).__init__(foreign_git)
136
super(BzrGitMapping, self).__init__(foreign_vcs_git)
106
138
def __eq__(self, other):
107
139
return (type(self) == type(other) and
130
162
if type(path) is unicode:
131
163
path = path.encode("utf-8")
132
return escape_file_id(path)
134
def is_control_file(self, path):
135
return path in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE)
164
return FILE_ID_PREFIX + escape_file_id(path)
137
166
def parse_file_id(self, file_id):
138
167
if file_id == ROOT_ID:
140
return unescape_file_id(file_id)
169
if not file_id.startswith(FILE_ID_PREFIX):
171
return unescape_file_id(file_id[len(FILE_ID_PREFIX):])
142
173
def revid_as_refname(self, revid):
144
return "refs/bzr/%s" % urllib.quote(revid)
174
return "refs/bzr/%s" % quote(revid)
146
176
def import_unusual_file_modes(self, rev, unusual_file_modes):
147
177
if unusual_file_modes:
158
return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(file_modes.encode("utf-8"))])
188
return dict(bencode.bdecode(file_modes.encode("utf-8")))
160
190
def _generate_git_svn_metadata(self, rev, encoding):
180
210
rev.properties['hg:renames']))
181
211
# TODO: Export other properties as 'bzr:' extras?
182
212
ret = format_hg_metadata(renames, branch, extra)
183
assert isinstance(ret, str)
213
if type(ret) is not str:
186
217
def _extract_git_svn_metadata(self, rev, message):
191
222
rev.properties['git-svn-id'] = git_svn_id
192
223
(url, rev, uuid) = parse_git_svn_id(git_svn_id)
193
224
# FIXME: Convert this to converted-from property somehow..
194
ret = "\n".join(lines[:-2])
195
assert isinstance(ret, str)
225
return "\n".join(lines[:-2])
198
227
def _extract_hg_metadata(self, rev, message):
199
228
(message, renames, branch, extra) = extract_hg_metadata(message)
211
240
return message, metadata
213
242
def _decode_commit_message(self, rev, message, encoding):
214
return message.decode(encoding), BzrGitRevisionMetadata()
243
return message.decode(encoding), CommitSupplement()
216
245
def _encode_commit_message(self, rev, message, encoding):
217
246
return message.encode(encoding)
220
249
"""Export a file id map to a fileid map.
222
251
:param fileid_map: File id map, mapping paths to file ids
223
:return: A Git blob object
252
:return: A Git blob object (or None if there are no entries)
225
254
from dulwich.objects import Blob
227
256
b.set_raw_chunks(serialize_fileid_map(fileid_map))
230
def export_commit(self, rev, tree_sha, parent_lookup, roundtrip,
259
def export_commit(self, rev, tree_sha, parent_lookup, lossy,
232
261
"""Turn a Bazaar revision in to a Git commit
234
263
:param tree_sha: Tree sha for the commit
235
264
:param parent_lookup: Function for looking up the GIT sha equiv of a
237
:param roundtrip: Whether to store roundtripping information.
266
:param lossy: Whether to store roundtripping information.
238
267
:param verifiers: Verifiers info
239
268
:return dulwich.objects.Commit represent the revision:
241
from dulwich.objects import Commit
270
from dulwich.objects import Commit, Tag
242
271
commit = Commit()
243
272
commit.tree = tree_sha
245
metadata = BzrGitRevisionMetadata()
274
metadata = CommitSupplement()
246
275
metadata.verifiers = verifiers
255
284
if metadata is not None:
256
285
metadata.explicit_parent_ids = rev.parent_ids
257
286
if git_p is not None:
258
assert len(git_p) == 40, "unexpected length for %r" % git_p
288
raise AssertionError("unexpected length for %r" % git_p)
259
289
parents.append(git_p)
260
290
commit.parents = parents
262
292
encoding = rev.properties['git-explicit-encoding']
264
294
encoding = rev.properties.get('git-implicit-encoding', 'utf-8')
265
commit.encoding = rev.properties.get('git-explicit-encoding')
296
commit.encoding = rev.properties['git-explicit-encoding'].encode('ascii')
266
299
commit.committer = fix_person_identifier(rev.committer.encode(
268
301
commit.author = fix_person_identifier(
279
312
commit.author_timezone = int(rev.properties['author-timezone'])
281
314
commit.author_timezone = commit.commit_timezone
282
commit.message = self._encode_commit_message(rev, rev.message,
315
if 'git-gpg-signature' in rev.properties:
316
commit.gpgsig = rev.properties['git-gpg-signature'].encode('ascii')
317
commit.message = self._encode_commit_message(rev, rev.message,
284
assert type(commit.message) == str
319
if type(commit.message) is not str:
320
raise TypeError(commit.message)
285
321
if metadata is not None:
287
323
mapping_registry.parse_revision_id(rev.revision_id)
290
326
mapping_properties = set(
291
327
['author', 'author-timezone', 'author-timezone-neg-utc',
292
328
'commit-timezone-neg-utc', 'git-implicit-encoding',
293
'git-explicit-encoding', 'author-timestamp', 'file-modes'])
329
'git-gpg-signature', 'git-explicit-encoding',
330
'author-timestamp', 'file-modes'])
294
331
for k, v in rev.properties.iteritems():
295
332
if not k in mapping_properties:
296
333
metadata.properties[k] = v
297
if self.roundtripping:
298
commit.message = inject_bzr_metadata(commit.message, metadata,
300
assert type(commit.message) == str
334
if not lossy and metadata:
335
if self.roundtripping:
336
commit.message = inject_bzr_metadata(commit.message, metadata,
339
raise NoPushSupport()
340
if type(commit.message) is not str:
341
raise TypeError(commit.message)
343
propname = 'git-mergetag-0'
344
while propname in rev.properties:
345
commit.mergetag.append(Tag.from_string(rev.properties[propname].encode(encoding)))
347
propname = 'git-mergetag-%d' % i
348
if 'git-extra' in rev.properties:
349
commit.extra.extend([l.split(' ', 1) for l in rev.properties['git-extra'].splitlines()])
303
352
def import_fileid_map(self, blob):
311
360
def import_commit(self, commit, lookup_parent_revid):
312
361
"""Convert a git commit to a bzr revision.
314
:return: a `bzrlib.revision.Revision` object, foreign revid and a
363
:return: a `breezy.revision.Revision` object, foreign revid and a
317
366
if commit is None:
318
367
raise AssertionError("Commit object can't be None")
319
368
rev = ForeignRevision(commit.id, self,
320
369
self.revision_id_foreign_to_bzr(commit.id))
321
rev.parent_ids = tuple([lookup_parent_revid(p) for p in commit.parents])
322
370
rev.git_metadata = None
323
371
def decode_using_encoding(rev, commit, encoding):
324
372
rev.committer = str(commit.committer).decode(encoding)
347
395
rev.properties['author-timezone-neg-utc'] = ""
348
396
if commit._commit_timezone_neg_utc:
349
397
rev.properties['commit-timezone-neg-utc'] = ""
399
rev.properties['git-gpg-signature'] = commit.gpgsig.decode('ascii')
401
for i, tag in enumerate(commit.mergetag):
402
rev.properties['git-mergetag-%d' % i] = tag.as_raw_string()
350
403
rev.timestamp = commit.commit_time
351
404
rev.timezone = commit.commit_timezone
405
rev.parent_ids = None
352
406
if rev.git_metadata is not None:
353
407
md = rev.git_metadata
354
408
roundtrip_revid = md.revision_id
360
414
roundtrip_revid = None
416
if rev.parent_ids is None:
418
for p in commit.parents:
420
parents.append(lookup_parent_revid(p))
422
parents.append(self.revision_id_foreign_to_bzr(p))
423
rev.parent_ids = tuple(parents)
424
unknown_extra_fields = []
426
for k, v in commit.extra:
427
if k == HG_RENAME_SOURCE:
428
extra_lines.append(k + ' ' + v + '\n')
430
hgk, hgv = v.split(':', 1)
431
if hgk not in (HG_EXTRA_AMEND_SOURCE, ):
432
raise UnknownMercurialCommitExtra(commit, hgk)
433
extra_lines.append(k + ' ' + v + '\n')
435
unknown_extra_fields.append(k)
436
if unknown_extra_fields:
437
raise UnknownCommitExtra(commit, unknown_extra_fields)
439
rev.properties['git-extra'] = ''.join(extra_lines)
362
440
return rev, roundtrip_revid, verifiers
364
442
def get_fileid_map(self, lookup_object, tree_sha):
431
509
mapping_registry = GitMappingRegistry()
432
mapping_registry.register_lazy('git-v1', "bzrlib.plugins.git.mapping",
510
mapping_registry.register_lazy('git-v1', "breezy.plugins.git.mapping",
433
511
"BzrGitMappingv1")
434
512
mapping_registry.register_lazy('git-experimental',
435
"bzrlib.plugins.git.mapping", "BzrGitMappingExperimental")
513
"breezy.plugins.git.mapping", "BzrGitMappingExperimental")
514
# Uncomment the next line to enable the experimental bzr-git mappings.
515
# This will make sure all bzr metadata is pushed into git, allowing for
516
# full roundtripping later.
517
# NOTE: THIS IS EXPERIMENTAL. IT MAY EAT YOUR DATA OR CORRUPT
518
# YOUR BZR OR GIT REPOSITORIES. USE WITH CARE.
519
#mapping_registry.set_default('git-experimental')
436
520
mapping_registry.set_default('git-v1')
443
527
def branch_format(self):
444
from bzrlib.plugins.git.branch import GitBranchFormat
445
return GitBranchFormat()
528
from .branch import LocalGitBranchFormat
529
return LocalGitBranchFormat()
448
532
def repository_format(self):
449
from bzrlib.plugins.git.repository import GitRepositoryFormat
533
from .repository import GitRepositoryFormat
450
534
return GitRepositoryFormat()
452
536
def __init__(self):
462
546
return { "git commit": foreign_revid }
465
foreign_git = ForeignGit()
549
foreign_vcs_git = ForeignGit()
466
550
default_mapping = mapping_registry.get_default()()
469
def symlink_to_blob(entry):
553
def symlink_to_blob(symlink_target):
470
554
from dulwich.objects import Blob
472
symlink_target = entry.symlink_target
473
556
if type(symlink_target) == unicode:
474
557
symlink_target = symlink_target.encode('utf-8')
475
558
blob.data = symlink_target
479
562
def mode_is_executable(mode):
480
563
"""Check if mode should be considered executable."""
481
return bool(mode & 0111)
564
return bool(mode & 0o111)
484
567
def mode_kind(mode):
485
568
"""Determine the Bazaar inventory kind based on Unix file mode."""
486
entry_kind = (mode & 0700000) / 0100000
571
entry_kind = (mode & 0o700000) / 0o100000
487
572
if entry_kind == 0:
488
573
return 'directory'
489
574
elif entry_kind == 1:
490
file_kind = (mode & 070000) / 010000
575
file_kind = (mode & 0o70000) / 0o10000
491
576
if file_kind == 0:
493
578
elif file_kind == 2:
525
610
def entry_mode(entry):
526
611
"""Determine the git file mode for an inventory entry."""
527
return object_mode(entry.kind, entry.executable)
530
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes, empty_file_name):
531
"""Create a Git Tree object from a Bazaar directory.
533
:param entry: Inventory entry
534
:param lookup_ie_sha1: Lookup the Git SHA1 for a inventory entry
535
:param unusual_modes: Dictionary with unusual file modes by file ids
536
:param empty_file_name: Name to use for dummy files in empty directories,
537
None to ignore empty directories.
539
from dulwich.objects import Blob, Tree
541
for name, value in entry.children.iteritems():
542
ie = entry.children[name]
544
mode = unusual_modes[ie.file_id]
546
mode = entry_mode(ie)
547
hexsha = lookup_ie_sha1(ie)
548
if hexsha is not None:
549
tree.add(mode, name.encode("utf-8"), hexsha)
550
if entry.parent_id is not None and len(tree) == 0:
551
# Only the root can be an empty tree
552
if empty_file_name is not None:
553
tree.add(stat.S_IFREG | 0644, empty_file_name,
612
return object_mode(entry.kind, getattr(entry, 'executable', False))
560
615
def extract_unusual_modes(rev):
580
635
self.paths = None
581
636
self.mapping = mapping
638
def all_file_ids(self):
639
return self.file_ids.values()
641
def set_file_id(self, path, file_id):
642
if type(path) is not str:
643
raise TypeError(path)
644
if type(file_id) is not str:
645
raise TypeError(file_id)
646
self.file_ids[path] = file_id
583
648
def lookup_file_id(self, path):
584
assert type(path) is str
649
if type(path) is not str:
650
raise TypeError(path)
586
652
file_id = self.file_ids[path]
588
654
file_id = self.mapping.generate_file_id(path)
589
assert type(file_id) is str
655
if type(file_id) is not str:
656
raise TypeError(file_id)
592
659
def lookup_path(self, file_id):
600
667
return self.mapping.parse_file_id(file_id)
602
assert type(path) is str
669
if type(path) is not str:
670
raise TypeError(path)
674
return self.__class__(dict(self.file_ids), self.mapping)
677
def needs_roundtripping(repo, revid):
679
mapping_registry.parse_revision_id(revid)
680
except errors.InvalidRevisionId: