/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-06-30 23:59:51 UTC
  • mto: This revision was merged to the branch mainline in revision 7014.
  • Revision ID: jelmer@jelmer.uk-20180630235951-7n0k1j4a8sc6xpra
Don't require ColorFeature for grep tests.

Testing this functionality doesn't actually require color support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
 
2
# Copyright (C) 2007 Canonical Ltd
 
3
# Copyright (C) 2008 John Carr
 
4
#
 
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.
 
9
#
 
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.
 
14
#
 
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
 
18
 
 
19
"""Converters, etc for going between Bazaar and Git ids."""
 
20
 
 
21
from __future__ import absolute_import
 
22
 
 
23
import base64
 
24
import stat
 
25
 
 
26
from ... import (
 
27
    bencode,
 
28
    errors,
 
29
    foreign,
 
30
    trace,
 
31
    )
 
32
from ...bzr.inventory import (
 
33
    ROOT_ID,
 
34
    )
 
35
from ...foreign import (
 
36
    ForeignVcs,
 
37
    VcsMappingRegistry,
 
38
    ForeignRevision,
 
39
    )
 
40
from ...revision import (
 
41
    NULL_REVISION,
 
42
    )
 
43
from ...sixish import text_type
 
44
from .errors import (
 
45
    NoPushSupport,
 
46
    UnknownCommitExtra,
 
47
    UnknownMercurialCommitExtra,
 
48
    )
 
49
from .hg import (
 
50
    format_hg_metadata,
 
51
    extract_hg_metadata,
 
52
    )
 
53
from .roundtrip import (
 
54
    extract_bzr_metadata,
 
55
    inject_bzr_metadata,
 
56
    CommitSupplement,
 
57
    deserialize_fileid_map,
 
58
    serialize_fileid_map,
 
59
    )
 
60
 
 
61
try:
 
62
    from urllib.parse import quote
 
63
except ImportError:
 
64
    from urllib import quote
 
65
 
 
66
DEFAULT_FILE_MODE = stat.S_IFREG | 0o644
 
67
HG_RENAME_SOURCE = "HG:rename-source"
 
68
HG_EXTRA = "HG:extra"
 
69
 
 
70
# This HG extra is used to indicate the commit that this commit was based on.
 
71
HG_EXTRA_AMEND_SOURCE = "amend_source"
 
72
 
 
73
FILE_ID_PREFIX = b'git:'
 
74
 
 
75
 
 
76
def escape_file_id(file_id):
 
77
    return file_id.replace('_', '__').replace(' ', '_s').replace('\x0c', '_c')
 
78
 
 
79
 
 
80
def unescape_file_id(file_id):
 
81
    ret = []
 
82
    i = 0
 
83
    while i < len(file_id):
 
84
        if file_id[i] != '_':
 
85
            ret.append(file_id[i])
 
86
        else:
 
87
            if file_id[i+1] == '_':
 
88
                ret.append("_")
 
89
            elif file_id[i+1] == 's':
 
90
                ret.append(" ")
 
91
            elif file_id[i+1] == 'c':
 
92
                ret.append("\x0c")
 
93
            else:
 
94
                raise ValueError("unknown escape character %s" %
 
95
                    file_id[i+1])
 
96
            i += 1
 
97
        i += 1
 
98
    return "".join(ret)
 
99
 
 
100
 
 
101
def fix_person_identifier(text):
 
102
    if not "<" in text and not ">" in text:
 
103
        username = text
 
104
        email = text
 
105
    else:
 
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)
 
113
 
 
114
 
 
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)
 
118
 
 
119
 
 
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)
 
123
 
 
124
 
 
125
class BzrGitMapping(foreign.VcsMapping):
 
126
    """Class that maps between Git and Bazaar semantics."""
 
127
    experimental = False
 
128
 
 
129
    BZR_FILE_IDS_FILE = None
 
130
 
 
131
    BZR_DUMMY_FILE = None
 
132
 
 
133
    def is_special_file(self, filename):
 
134
        return (filename in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE))
 
135
 
 
136
    def __init__(self):
 
137
        super(BzrGitMapping, self).__init__(foreign_vcs_git)
 
138
 
 
139
    def __eq__(self, other):
 
140
        return (type(self) == type(other) and
 
141
                self.revid_prefix == other.revid_prefix)
 
142
 
 
143
    @classmethod
 
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:
 
148
            return NULL_REVISION
 
149
        return "%s:%s" % (cls.revid_prefix, git_rev_id)
 
150
 
 
151
    @classmethod
 
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()
 
157
 
 
158
    def generate_file_id(self, path):
 
159
        # Git paths are just bytestrings
 
160
        # We must just hope they are valid UTF-8..
 
161
        if path == "":
 
162
            return ROOT_ID
 
163
        if isinstance(path, text_type):
 
164
            path = path.encode("utf-8")
 
165
        return FILE_ID_PREFIX + escape_file_id(path)
 
166
 
 
167
    def parse_file_id(self, file_id):
 
168
        if file_id == ROOT_ID:
 
169
            return ""
 
170
        if not file_id.startswith(FILE_ID_PREFIX):
 
171
            raise ValueError
 
172
        return unescape_file_id(file_id[len(FILE_ID_PREFIX):])
 
173
 
 
174
    def revid_as_refname(self, revid):
 
175
        return "refs/bzr/%s" % quote(revid)
 
176
 
 
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)
 
182
 
 
183
    def export_unusual_file_modes(self, rev):
 
184
        try:
 
185
            file_modes = rev.properties[u'file-modes']
 
186
        except KeyError:
 
187
            return {}
 
188
        else:
 
189
            return dict(bencode.bdecode(file_modes.encode("utf-8")))
 
190
 
 
191
    def _generate_git_svn_metadata(self, rev, encoding):
 
192
        try:
 
193
            git_svn_id = rev.properties[u"git-svn-id"]
 
194
        except KeyError:
 
195
            return ""
 
196
        else:
 
197
            return "\ngit-svn-id: %s\n" % git_svn_id.encode(encoding)
 
198
 
 
199
    def _generate_hg_message_tail(self, rev):
 
200
        extra = {}
 
201
        renames = []
 
202
        branch = 'default'
 
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:
 
215
            raise TypeError(ret)
 
216
        return ret
 
217
 
 
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:")):
 
221
            return message
 
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])
 
227
 
 
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)
 
234
        if renames:
 
235
            rev.properties[u'hg:renames'] = base64.b64encode(bencode.bencode(
 
236
                [(new, old) for (old, new) in renames.iteritems()]))
 
237
        return message
 
238
 
 
239
    def _extract_bzr_metadata(self, rev, message):
 
240
        (message, metadata) = extract_bzr_metadata(message)
 
241
        return message, metadata
 
242
 
 
243
    def _decode_commit_message(self, rev, message, encoding):
 
244
        return message.decode(encoding), CommitSupplement()
 
245
 
 
246
    def _encode_commit_message(self, rev, message, encoding):
 
247
        return message.encode(encoding)
 
248
 
 
249
    def export_fileid_map(self, fileid_map):
 
250
        """Export a file id map to a fileid map.
 
251
 
 
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)
 
254
        """
 
255
        from dulwich.objects import Blob
 
256
        b = Blob()
 
257
        b.set_raw_chunks(serialize_fileid_map(fileid_map))
 
258
        return b
 
259
 
 
260
    def export_commit(self, rev, tree_sha, parent_lookup, lossy,
 
261
                      verifiers):
 
262
        """Turn a Bazaar revision in to a Git commit
 
263
 
 
264
        :param tree_sha: Tree sha for the commit
 
265
        :param parent_lookup: Function for looking up the GIT sha equiv of a
 
266
            bzr revision
 
267
        :param lossy: Whether to store roundtripping information.
 
268
        :param verifiers: Verifiers info
 
269
        :return dulwich.objects.Commit represent the revision:
 
270
        """
 
271
        from dulwich.objects import Commit, Tag
 
272
        commit = Commit()
 
273
        commit.tree = tree_sha
 
274
        if not lossy:
 
275
            metadata = CommitSupplement()
 
276
            metadata.verifiers = verifiers
 
277
        else:
 
278
            metadata = None
 
279
        parents = []
 
280
        for p in rev.parent_ids:
 
281
            try:
 
282
                git_p = parent_lookup(p)
 
283
            except KeyError:
 
284
                git_p = None
 
285
                if metadata is not None:
 
286
                    metadata.explicit_parent_ids = rev.parent_ids
 
287
            if git_p is not None:
 
288
                if len(git_p) != 40:
 
289
                    raise AssertionError("unexpected length for %r" % git_p)
 
290
                parents.append(git_p)
 
291
        commit.parents = parents
 
292
        try:
 
293
            encoding = rev.properties[u'git-explicit-encoding']
 
294
        except KeyError:
 
295
            encoding = rev.properties.get(u'git-implicit-encoding', 'utf-8')
 
296
        try:
 
297
            commit.encoding = rev.properties[u'git-explicit-encoding'].encode('ascii')
 
298
        except KeyError:
 
299
            pass
 
300
        commit.committer = fix_person_identifier(rev.committer.encode(
 
301
            encoding))
 
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'])
 
307
        else:
 
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'])
 
314
        else:
 
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,
 
319
            encoding)
 
320
        if type(commit.message) is not str:
 
321
            raise TypeError(commit.message)
 
322
        if metadata is not None:
 
323
            try:
 
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,
 
338
                                                     encoding)
 
339
            else:
 
340
                raise NoPushSupport(None, None, self, revision_id=rev.revision_id)
 
341
        if type(commit.message) is not str:
 
342
            raise TypeError(commit.message)
 
343
        i = 0
 
344
        propname = u'git-mergetag-0'
 
345
        while propname in rev.properties:
 
346
            commit.mergetag.append(Tag.from_string(rev.properties[propname].encode(encoding)))
 
347
            i += 1
 
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()])
 
351
        return commit
 
352
 
 
353
    def import_fileid_map(self, blob):
 
354
        """Convert a git file id map blob.
 
355
 
 
356
        :param blob: Git blob object with fileid map
 
357
        :return: Dictionary mapping paths to file ids
 
358
        """
 
359
        return deserialize_fileid_map(blob.data)
 
360
 
 
361
    def import_commit(self, commit, lookup_parent_revid):
 
362
        """Convert a git commit to a bzr revision.
 
363
 
 
364
        :return: a `breezy.revision.Revision` object, foreign revid and a
 
365
            testament sha1
 
366
        """
 
367
        if commit is None:
 
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)
 
381
        else:
 
382
            for encoding in ('utf-8', 'latin1'):
 
383
                try:
 
384
                    decode_using_encoding(rev, commit, encoding)
 
385
                except UnicodeDecodeError:
 
386
                    pass
 
387
                else:
 
388
                    if encoding != 'utf-8':
 
389
                        rev.properties[u'git-implicit-encoding'] = encoding
 
390
                    break
 
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'] = ""
 
399
        if commit.gpgsig:
 
400
            rev.properties[u'git-gpg-signature'] = commit.gpgsig.decode('ascii')
 
401
        if commit.mergetag:
 
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
 
414
        else:
 
415
            roundtrip_revid = None
 
416
            verifiers = {}
 
417
        if rev.parent_ids is None:
 
418
            parents = []
 
419
            for p in commit.parents:
 
420
                try:
 
421
                    parents.append(lookup_parent_revid(p))
 
422
                except KeyError:
 
423
                    parents.append(self.revision_id_foreign_to_bzr(p))
 
424
            rev.parent_ids = tuple(parents)
 
425
        unknown_extra_fields = []
 
426
        extra_lines = []
 
427
        for k, v in commit.extra:
 
428
            if k == HG_RENAME_SOURCE:
 
429
                extra_lines.append(k + ' ' + v + '\n')
 
430
            elif k == HG_EXTRA:
 
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')
 
435
            else:
 
436
                unknown_extra_fields.append(k)
 
437
        if unknown_extra_fields:
 
438
            raise UnknownCommitExtra(commit, unknown_extra_fields)
 
439
        if extra_lines:
 
440
            rev.properties[u'git-extra'] = ''.join(extra_lines)
 
441
        return rev, roundtrip_revid, verifiers
 
442
 
 
443
    def get_fileid_map(self, lookup_object, tree_sha):
 
444
        """Obtain a fileid map for a particular tree.
 
445
 
 
446
        :param lookup_object: Function for looking up an object
 
447
        :param tree_sha: SHA of the root tree
 
448
        :return: GitFileIdMap instance
 
449
        """
 
450
        try:
 
451
            file_id_map_sha = lookup_object(tree_sha)[self.BZR_FILE_IDS_FILE][1]
 
452
        except KeyError:
 
453
            file_ids = {}
 
454
        else:
 
455
            file_ids = self.import_fileid_map(lookup_object(file_id_map_sha))
 
456
        return GitFileIdMap(file_ids, self)
 
457
 
 
458
 
 
459
class BzrGitMappingv1(BzrGitMapping):
 
460
    revid_prefix = 'git-v1'
 
461
    experimental = False
 
462
 
 
463
    def __str__(self):
 
464
        return self.revid_prefix
 
465
 
 
466
 
 
467
class BzrGitMappingExperimental(BzrGitMappingv1):
 
468
    revid_prefix = 'git-experimental'
 
469
    experimental = True
 
470
    roundtripping = True
 
471
 
 
472
    BZR_FILE_IDS_FILE = '.bzrfileids'
 
473
 
 
474
    BZR_DUMMY_FILE = '.bzrdummy'
 
475
 
 
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
 
481
 
 
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)
 
486
        return ret
 
487
 
 
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
 
492
 
 
493
 
 
494
class GitMappingRegistry(VcsMappingRegistry):
 
495
    """Registry with available git mappings."""
 
496
 
 
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)
 
506
 
 
507
    parse_revision_id = revision_id_bzr_to_foreign
 
508
 
 
509
 
 
510
mapping_registry = GitMappingRegistry()
 
511
mapping_registry.register_lazy('git-v1', "breezy.plugins.git.mapping",
 
512
    "BzrGitMappingv1")
 
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')
 
522
 
 
523
 
 
524
class ForeignGit(ForeignVcs):
 
525
    """The Git Stupid Content Tracker"""
 
526
 
 
527
    @property
 
528
    def branch_format(self):
 
529
        from .branch import LocalGitBranchFormat
 
530
        return LocalGitBranchFormat()
 
531
 
 
532
    @property
 
533
    def repository_format(self):
 
534
        from .repository import GitRepositoryFormat
 
535
        return GitRepositoryFormat()
 
536
 
 
537
    def __init__(self):
 
538
        super(ForeignGit, self).__init__(mapping_registry)
 
539
        self.abbreviation = "git"
 
540
 
 
541
    @classmethod
 
542
    def serialize_foreign_revid(self, foreign_revid):
 
543
        return foreign_revid
 
544
 
 
545
    @classmethod
 
546
    def show_foreign_revid(cls, foreign_revid):
 
547
        return { "git commit": foreign_revid }
 
548
 
 
549
 
 
550
foreign_vcs_git = ForeignGit()
 
551
default_mapping = mapping_registry.get_default()()
 
552
 
 
553
 
 
554
def symlink_to_blob(symlink_target):
 
555
    from dulwich.objects import Blob
 
556
    blob = Blob()
 
557
    if isinstance(symlink_target, text_type):
 
558
        symlink_target = symlink_target.encode('utf-8')
 
559
    blob.data = symlink_target
 
560
    return blob
 
561
 
 
562
 
 
563
def mode_is_executable(mode):
 
564
    """Check if mode should be considered executable."""
 
565
    return bool(mode & 0o111)
 
566
 
 
567
 
 
568
def mode_kind(mode):
 
569
    """Determine the Bazaar inventory kind based on Unix file mode."""
 
570
    if mode is None:
 
571
        return None
 
572
    entry_kind = (mode & 0o700000) / 0o100000
 
573
    if entry_kind == 0:
 
574
        return 'directory'
 
575
    elif entry_kind == 1:
 
576
        file_kind = (mode & 0o70000) / 0o10000
 
577
        if file_kind == 0:
 
578
            return 'file'
 
579
        elif file_kind == 2:
 
580
            return 'symlink'
 
581
        elif file_kind == 6:
 
582
            return 'tree-reference'
 
583
        else:
 
584
            raise AssertionError(
 
585
                "Unknown file kind %d, perms=%o." % (file_kind, mode,))
 
586
    else:
 
587
        raise AssertionError(
 
588
            "Unknown kind, perms=%r." % (mode,))
 
589
 
 
590
 
 
591
def object_mode(kind, executable):
 
592
    if kind == 'directory':
 
593
        return stat.S_IFDIR
 
594
    elif kind == 'symlink':
 
595
        mode = stat.S_IFLNK
 
596
        if executable:
 
597
            mode |= 0o111
 
598
        return mode
 
599
    elif kind == 'file':
 
600
        mode = stat.S_IFREG | 0o644
 
601
        if executable:
 
602
            mode |= 0o111
 
603
        return mode
 
604
    elif kind == 'tree-reference':
 
605
        from dulwich.objects import S_IFGITLINK
 
606
        return S_IFGITLINK
 
607
    else:
 
608
        raise AssertionError
 
609
 
 
610
 
 
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))
 
614
 
 
615
 
 
616
def extract_unusual_modes(rev):
 
617
    try:
 
618
        foreign_revid, mapping = mapping_registry.parse_revision_id(
 
619
            rev.revision_id)
 
620
    except errors.InvalidRevisionId:
 
621
        return {}
 
622
    else:
 
623
        return mapping.export_unusual_file_modes(rev)
 
624
 
 
625
 
 
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)
 
630
 
 
631
 
 
632
class GitFileIdMap(object):
 
633
 
 
634
    def __init__(self, file_ids, mapping):
 
635
        self.file_ids = file_ids
 
636
        self.paths = None
 
637
        self.mapping = mapping
 
638
 
 
639
    def all_file_ids(self):
 
640
        return self.file_ids.values()
 
641
 
 
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
 
648
 
 
649
    def lookup_file_id(self, path):
 
650
        if type(path) is not str:
 
651
            raise TypeError(path)
 
652
        try:
 
653
            file_id = self.file_ids[path]
 
654
        except KeyError:
 
655
            file_id = self.mapping.generate_file_id(path)
 
656
        if type(file_id) is not str:
 
657
            raise TypeError(file_id)
 
658
        return file_id
 
659
 
 
660
    def lookup_path(self, file_id):
 
661
        if self.paths is None:
 
662
            self.paths = {}
 
663
            for k, v in self.file_ids.iteritems():
 
664
                self.paths[v] = k
 
665
        try:
 
666
            path = self.paths[file_id]
 
667
        except KeyError:
 
668
            return self.mapping.parse_file_id(file_id)
 
669
        else:
 
670
            if type(path) is not str:
 
671
                raise TypeError(path)
 
672
            return path
 
673
 
 
674
    def copy(self):
 
675
        return self.__class__(dict(self.file_ids), self.mapping)
 
676
 
 
677
 
 
678
def needs_roundtripping(repo, revid):
 
679
    try:
 
680
        mapping_registry.parse_revision_id(revid)
 
681
    except errors.InvalidRevisionId:
 
682
        return True
 
683
    else:
 
684
        return False