/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/plugins/git/mapping.py

  • Committer: Jelmer Vernooij
  • Date: 2018-05-19 13:16:11 UTC
  • mto: (6968.4.3 git-archive)
  • mto: This revision was merged to the branch mainline in revision 6972.
  • Revision ID: jelmer@jelmer.uk-20180519131611-l9h9ud41j7qg1m03
Move tar/zip to breezy.archive.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
4
4
#
5
5
# This program is free software; you can redistribute it and/or modify
14
14
#
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
18
18
 
19
19
"""Converters, etc for going between Bazaar and Git ids."""
20
20
 
 
21
from __future__ import absolute_import
 
22
 
21
23
import base64
22
24
import stat
23
25
 
24
 
from bzrlib import (
 
26
from ... import (
25
27
    bencode,
26
28
    errors,
27
29
    foreign,
28
30
    trace,
29
31
    )
30
 
from bzrlib.inventory import (
 
32
from ...bzr.inventory import (
31
33
    ROOT_ID,
32
34
    )
33
 
from bzrlib.foreign import (
 
35
from ...foreign import (
34
36
    ForeignVcs,
35
37
    VcsMappingRegistry,
36
38
    ForeignRevision,
37
39
    )
38
 
from bzrlib.revision import (
 
40
from ...revision import (
39
41
    NULL_REVISION,
40
42
    )
41
 
from bzrlib.plugins.git.hg import (
 
43
from .errors import (
 
44
    NoPushSupport,
 
45
    UnknownCommitExtra,
 
46
    UnknownMercurialCommitExtra,
 
47
    )
 
48
from .hg import (
42
49
    format_hg_metadata,
43
50
    extract_hg_metadata,
44
51
    )
45
 
from bzrlib.plugins.git.roundtrip import (
 
52
from .roundtrip import (
46
53
    extract_bzr_metadata,
47
54
    inject_bzr_metadata,
48
 
    BzrGitRevisionMetadata,
 
55
    CommitSupplement,
49
56
    deserialize_fileid_map,
50
57
    serialize_fileid_map,
51
58
    )
52
59
 
53
 
DEFAULT_FILE_MODE = stat.S_IFREG | 0644
 
60
try:
 
61
    from urllib.parse import quote
 
62
except ImportError:
 
63
    from urllib import quote
 
64
 
 
65
DEFAULT_FILE_MODE = stat.S_IFREG | 0o644
 
66
HG_RENAME_SOURCE = "HG:rename-source"
 
67
HG_EXTRA = "HG:extra"
 
68
 
 
69
# This HG extra is used to indicate the commit that this commit was based on.
 
70
HG_EXTRA_AMEND_SOURCE = "amend_source"
 
71
 
 
72
FILE_ID_PREFIX = b'git:'
54
73
 
55
74
 
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')
58
77
 
59
78
 
60
79
def unescape_file_id(file_id):
68
87
                ret.append("_")
69
88
            elif file_id[i+1] == 's':
70
89
                ret.append(" ")
 
90
            elif file_id[i+1] == 'c':
 
91
                ret.append("\x0c")
71
92
            else:
72
 
                raise AssertionError("unknown escape character %s" %
 
93
                raise ValueError("unknown escape character %s" %
73
94
                    file_id[i+1])
74
95
            i += 1
75
96
        i += 1
77
98
 
78
99
 
79
100
def fix_person_identifier(text):
80
 
    if "<" in text and ">" in text:
81
 
        return text
82
 
    return "%s <%s>" % (text, text)
 
101
    if not "<" in text and not ">" in text:
 
102
        username = text
 
103
        email = text
 
104
    else:
 
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)
83
112
 
84
113
 
85
114
def warn_escaped(commit, num_escaped):
100
129
 
101
130
    BZR_DUMMY_FILE = None
102
131
 
 
132
    def is_special_file(self, filename):
 
133
        return (filename in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE))
 
134
 
103
135
    def __init__(self):
104
 
        super(BzrGitMapping, self).__init__(foreign_git)
 
136
        super(BzrGitMapping, self).__init__(foreign_vcs_git)
105
137
 
106
138
    def __eq__(self, other):
107
139
        return (type(self) == type(other) and
129
161
            return ROOT_ID
130
162
        if type(path) is unicode:
131
163
            path = path.encode("utf-8")
132
 
        return escape_file_id(path)
133
 
 
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)
136
165
 
137
166
    def parse_file_id(self, file_id):
138
167
        if file_id == ROOT_ID:
139
168
            return ""
140
 
        return unescape_file_id(file_id)
 
169
        if not file_id.startswith(FILE_ID_PREFIX):
 
170
            raise ValueError
 
171
        return unescape_file_id(file_id[len(FILE_ID_PREFIX):])
141
172
 
142
173
    def revid_as_refname(self, revid):
143
 
        import urllib
144
 
        return "refs/bzr/%s" % urllib.quote(revid)
 
174
        return "refs/bzr/%s" % quote(revid)
145
175
 
146
176
    def import_unusual_file_modes(self, rev, unusual_file_modes):
147
177
        if unusual_file_modes:
155
185
        except KeyError:
156
186
            return {}
157
187
        else:
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")))
159
189
 
160
190
    def _generate_git_svn_metadata(self, rev, encoding):
161
191
        try:
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:
 
214
            raise TypeError(ret)
184
215
        return ret
185
216
 
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)
196
 
        return ret
 
225
        return "\n".join(lines[:-2])
197
226
 
198
227
    def _extract_hg_metadata(self, rev, message):
199
228
        (message, renames, branch, extra) = extract_hg_metadata(message)
211
240
        return message, metadata
212
241
 
213
242
    def _decode_commit_message(self, rev, message, encoding):
214
 
        return message.decode(encoding), BzrGitRevisionMetadata()
 
243
        return message.decode(encoding), CommitSupplement()
215
244
 
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.
221
250
 
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)
224
253
        """
225
254
        from dulwich.objects import Blob
226
255
        b = Blob()
227
256
        b.set_raw_chunks(serialize_fileid_map(fileid_map))
228
257
        return b
229
258
 
230
 
    def export_commit(self, rev, tree_sha, parent_lookup, roundtrip,
 
259
    def export_commit(self, rev, tree_sha, parent_lookup, lossy,
231
260
                      verifiers):
232
261
        """Turn a Bazaar revision in to a Git commit
233
262
 
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
236
265
            bzr revision
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:
240
269
        """
241
 
        from dulwich.objects import Commit
 
270
        from dulwich.objects import Commit, Tag
242
271
        commit = Commit()
243
272
        commit.tree = tree_sha
244
 
        if roundtrip:
245
 
            metadata = BzrGitRevisionMetadata()
 
273
        if not lossy:
 
274
            metadata = CommitSupplement()
246
275
            metadata.verifiers = verifiers
247
276
        else:
248
277
            metadata = None
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
 
287
                if len(git_p) != 40:
 
288
                    raise AssertionError("unexpected length for %r" % git_p)
259
289
                parents.append(git_p)
260
290
        commit.parents = parents
261
291
        try:
262
292
            encoding = rev.properties['git-explicit-encoding']
263
293
        except KeyError:
264
294
            encoding = rev.properties.get('git-implicit-encoding', 'utf-8')
265
 
        commit.encoding = rev.properties.get('git-explicit-encoding')
 
295
        try:
 
296
            commit.encoding = rev.properties['git-explicit-encoding'].encode('ascii')
 
297
        except KeyError:
 
298
            pass
266
299
        commit.committer = fix_person_identifier(rev.committer.encode(
267
300
            encoding))
268
301
        commit.author = fix_person_identifier(
279
312
            commit.author_timezone = int(rev.properties['author-timezone'])
280
313
        else:
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,
283
318
            encoding)
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:
286
322
            try:
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, 
299
 
                                                 encoding)
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,
 
337
                                                     encoding)
 
338
            else:
 
339
                raise NoPushSupport()
 
340
        if type(commit.message) is not str:
 
341
            raise TypeError(commit.message)
 
342
        i = 0
 
343
        propname = 'git-mergetag-0'
 
344
        while propname in rev.properties:
 
345
            commit.mergetag.append(Tag.from_string(rev.properties[propname].encode(encoding)))
 
346
            i += 1
 
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()])
301
350
        return commit
302
351
 
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.
313
362
 
314
 
        :return: a `bzrlib.revision.Revision` object, foreign revid and a
 
363
        :return: a `breezy.revision.Revision` object, foreign revid and a
315
364
            testament sha1
316
365
        """
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'] = ""
 
398
        if commit.gpgsig:
 
399
            rev.properties['git-gpg-signature'] = commit.gpgsig.decode('ascii')
 
400
        if commit.mergetag:
 
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
359
413
        else:
360
414
            roundtrip_revid = None
361
415
            verifiers = {}
 
416
        if rev.parent_ids is None:
 
417
            parents = []
 
418
            for p in commit.parents:
 
419
                try:
 
420
                    parents.append(lookup_parent_revid(p))
 
421
                except KeyError:
 
422
                    parents.append(self.revision_id_foreign_to_bzr(p))
 
423
            rev.parent_ids = tuple(parents)
 
424
        unknown_extra_fields = []
 
425
        extra_lines = []
 
426
        for k, v in commit.extra:
 
427
            if k == HG_RENAME_SOURCE:
 
428
                extra_lines.append(k + ' ' + v + '\n')
 
429
            elif k == HG_EXTRA:
 
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')
 
434
            else:
 
435
                unknown_extra_fields.append(k)
 
436
        if unknown_extra_fields:
 
437
            raise UnknownCommitExtra(commit, unknown_extra_fields)
 
438
        if extra_lines:
 
439
            rev.properties['git-extra'] = ''.join(extra_lines)
362
440
        return rev, roundtrip_revid, verifiers
363
441
 
364
442
    def get_fileid_map(self, lookup_object, tree_sha):
429
507
 
430
508
 
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')
437
521
 
438
522
 
441
525
 
442
526
    @property
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()
446
530
 
447
531
    @property
448
532
    def repository_format(self):
449
 
        from bzrlib.plugins.git.repository import GitRepositoryFormat
 
533
        from .repository import GitRepositoryFormat
450
534
        return GitRepositoryFormat()
451
535
 
452
536
    def __init__(self):
462
546
        return { "git commit": foreign_revid }
463
547
 
464
548
 
465
 
foreign_git = ForeignGit()
 
549
foreign_vcs_git = ForeignGit()
466
550
default_mapping = mapping_registry.get_default()()
467
551
 
468
552
 
469
 
def symlink_to_blob(entry):
 
553
def symlink_to_blob(symlink_target):
470
554
    from dulwich.objects import Blob
471
555
    blob = 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
478
561
 
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)
482
565
 
483
566
 
484
567
def mode_kind(mode):
485
568
    """Determine the Bazaar inventory kind based on Unix file mode."""
486
 
    entry_kind = (mode & 0700000) / 0100000
 
569
    if mode is None:
 
570
        return None
 
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:
492
577
            return 'file'
493
578
        elif file_kind == 2:
508
593
    elif kind == 'symlink':
509
594
        mode = stat.S_IFLNK
510
595
        if executable:
511
 
            mode |= 0111
 
596
            mode |= 0o111
512
597
        return mode
513
598
    elif kind == 'file':
514
 
        mode = stat.S_IFREG | 0644
 
599
        mode = stat.S_IFREG | 0o644
515
600
        if executable:
516
 
            mode |= 0111
 
601
            mode |= 0o111
517
602
        return mode
518
603
    elif kind == 'tree-reference':
519
604
        from dulwich.objects import S_IFGITLINK
524
609
 
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)
528
 
 
529
 
 
530
 
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes, empty_file_name):
531
 
    """Create a Git Tree object from a Bazaar directory.
532
 
 
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.
538
 
    """
539
 
    from dulwich.objects import Blob, Tree
540
 
    tree = Tree()
541
 
    for name, value in entry.children.iteritems():
542
 
        ie = entry.children[name]
543
 
        try:
544
 
            mode = unusual_modes[ie.file_id]
545
 
        except KeyError:
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, 
554
 
                Blob().id)
555
 
        else:
556
 
            return None
557
 
    return tree
 
612
    return object_mode(entry.kind, getattr(entry, 'executable', False))
558
613
 
559
614
 
560
615
def extract_unusual_modes(rev):
580
635
        self.paths = None
581
636
        self.mapping = mapping
582
637
 
 
638
    def all_file_ids(self):
 
639
        return self.file_ids.values()
 
640
 
 
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
 
647
 
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)
585
651
        try:
586
652
            file_id = self.file_ids[path]
587
653
        except KeyError:
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)
590
657
        return file_id
591
658
 
592
659
    def lookup_path(self, file_id):
599
666
        except KeyError:
600
667
            return self.mapping.parse_file_id(file_id)
601
668
        else:
602
 
            assert type(path) is str
 
669
            if type(path) is not str:
 
670
                raise TypeError(path)
603
671
            return path
 
672
 
 
673
    def copy(self):
 
674
        return self.__class__(dict(self.file_ids), self.mapping)
 
675
 
 
676
 
 
677
def needs_roundtripping(repo, revid):
 
678
    try:
 
679
        mapping_registry.parse_revision_id(revid)
 
680
    except errors.InvalidRevisionId:
 
681
        return True
 
682
    else:
 
683
        return False