/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 mapping.py

Merge fixes for SHA1s of symlinks.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
 
19
19
"""Converters, etc for going between Bazaar and Git ids."""
20
20
 
 
21
import base64
21
22
import stat
22
23
 
23
24
from bzrlib import (
35
36
    ROOT_ID,
36
37
    )
37
38
from bzrlib.foreign import (
38
 
    ForeignVcs, 
39
 
    VcsMappingRegistry, 
 
39
    ForeignVcs,
 
40
    VcsMappingRegistry,
40
41
    ForeignRevision,
41
42
    )
 
43
from bzrlib.plugins.git.hg import (
 
44
    format_hg_metadata,
 
45
    extract_hg_metadata,
 
46
    )
42
47
 
43
48
DEFAULT_FILE_MODE = stat.S_IFREG | 0644
44
49
 
83
88
 
84
89
def squash_revision(target_repo, rev):
85
90
    """Remove characters that can't be stored from a revision, if necessary.
86
 
    
 
91
 
87
92
    :param target_repo: Repository in which the revision will be stored
88
93
    :param rev: Revision object, will be modified in-place
89
94
    """
144
149
 
145
150
    def export_unusual_file_modes(self, rev):
146
151
        try:
147
 
            return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(rev.properties['file-modes'])])
 
152
            return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(rev.properties['file-modes'].encode("utf-8"))])
148
153
        except KeyError:
149
154
            return {}
150
155
 
 
156
    def _generate_git_svn_metadata(self, rev):
 
157
        try:
 
158
            return "\ngit-svn-id: %s\n" % rev.properties["git-svn-id"].encode("utf-8")
 
159
        except KeyError:
 
160
            return ""
 
161
 
 
162
    def _generate_hg_message_tail(self, rev):
 
163
        extra = {}
 
164
        renames = []
 
165
        branch = 'default'
 
166
        for name in rev.properties:
 
167
            if name == 'hg:extra:branch':
 
168
                branch = rev.properties['hg:extra:branch']
 
169
            elif name.startswith('hg:extra'):
 
170
                extra[name[len('hg:extra:'):]] = base64.b64decode(rev.properties[name])
 
171
            elif name == 'hg:renames':
 
172
                renames = bencode.bdecode(base64.b64decode(rev.properties['hg:renames']))
 
173
            # TODO: Export other properties as 'bzr:' extras?
 
174
        ret = format_hg_metadata(renames, branch, extra)
 
175
        assert isinstance(ret, str)
 
176
        return ret
 
177
 
 
178
    def _extract_git_svn_metadata(self, rev, message):
 
179
        lines = message.split("\n")
 
180
        if not (lines[-1] == "" and lines[-2].startswith("git-svn-id:")):
 
181
            return message
 
182
        git_svn_id = lines[-2].split(": ", 1)[1]
 
183
        rev.properties['git-svn-id'] = git_svn_id
 
184
        (url, rev, uuid) = parse_git_svn_id(git_svn_id)
 
185
        # FIXME: Convert this to converted-from property somehow..
 
186
        ret = "\n".join(lines[:-2])
 
187
        assert isinstance(ret, str)
 
188
        return ret
 
189
 
 
190
    def _extract_hg_metadata(self, rev, message):
 
191
        (message, renames, branch, extra) = extract_hg_metadata(message)
 
192
        if branch is not None:
 
193
            rev.properties['hg:extra:branch'] = branch
 
194
        for name, value in extra.iteritems():
 
195
            rev.properties['hg:extra:' + name] = base64.b64encode(value)
 
196
        if renames:
 
197
            rev.properties['hg:renames'] = base64.b64encode(bencode.bencode([(new, old) for (old, new) in renames.iteritems()]))
 
198
        return message
 
199
 
 
200
    def _decode_commit_message(self, rev, message):
 
201
        return message.decode("utf-8", "replace")
 
202
 
 
203
    def _encode_commit_message(self, rev, message):
 
204
        return message.encode("utf-8")
 
205
 
 
206
    def export_commit(self, rev, tree_sha, parent_lookup):
 
207
        """Turn a Bazaar revision in to a Git commit
 
208
 
 
209
        :param tree_sha: Tree sha for the commit
 
210
        :param parent_lookup: Function for looking up the GIT sha equiv of a bzr revision
 
211
        :return dulwich.objects.Commit represent the revision:
 
212
        """
 
213
        from dulwich.objects import Commit
 
214
        commit = Commit()
 
215
        commit.tree = tree_sha
 
216
        for p in rev.parent_ids:
 
217
            git_p = parent_lookup(p)
 
218
            if git_p is not None:
 
219
                assert len(git_p) == 40, "unexpected length for %r" % git_p
 
220
                commit.parents.append(git_p)
 
221
        commit.committer = fix_person_identifier(rev.committer.encode("utf-8"))
 
222
        commit.author = fix_person_identifier(rev.get_apparent_authors()[0].encode("utf-8"))
 
223
        commit.commit_time = long(rev.timestamp)
 
224
        if 'author-timestamp' in rev.properties:
 
225
            commit.author_time = long(rev.properties['author-timestamp'])
 
226
        else:
 
227
            commit.author_time = commit.commit_time
 
228
        commit.commit_timezone = rev.timezone
 
229
        if 'author-timezone' in rev.properties:
 
230
            commit.author_timezone = int(rev.properties['author-timezone'])
 
231
        else:
 
232
            commit.author_timezone = commit.commit_timezone
 
233
        commit.message = self._encode_commit_message(rev, rev.message)
 
234
        return commit
 
235
 
151
236
    def import_commit(self, commit):
152
237
        """Convert a git commit to a bzr revision.
153
238
 
157
242
            raise AssertionError("Commit object can't be None")
158
243
        rev = ForeignRevision(commit.id, self, self.revision_id_foreign_to_bzr(commit.id))
159
244
        rev.parent_ids = tuple([self.revision_id_foreign_to_bzr(p) for p in commit.parents])
160
 
        rev.message = commit.message.decode("utf-8", "replace")
161
245
        rev.committer = str(commit.committer).decode("utf-8", "replace")
162
246
        if commit.committer != commit.author:
163
247
            rev.properties['author'] = str(commit.author).decode("utf-8", "replace")
168
252
            rev.properties['author-timezone'] = "%d" % (commit.author_timezone, )
169
253
        rev.timestamp = commit.commit_time
170
254
        rev.timezone = commit.commit_timezone
 
255
        rev.message = self._decode_commit_message(rev, commit.message)
171
256
        return rev
172
257
 
173
258
 
183
268
    revid_prefix = 'git-experimental'
184
269
    experimental = True
185
270
 
 
271
    def _decode_commit_message(self, rev, message):
 
272
        message = self._extract_hg_metadata(rev, message)
 
273
        message = self._extract_git_svn_metadata(rev, message)
 
274
        return message.decode("utf-8", "replace")
 
275
 
 
276
    def _encode_commit_message(self, rev, message):
 
277
        ret = message.encode("utf-8")
 
278
        ret += self._generate_hg_message_tail(rev)
 
279
        ret += self._generate_git_svn_metadata(rev)
 
280
        return ret
 
281
 
 
282
    def import_commit(self, commit):
 
283
        rev = super(BzrGitMappingExperimental, self).import_commit(commit)
 
284
        rev.properties['converted_revision'] = "git %s\n" % commit.id
 
285
        return rev
 
286
 
186
287
 
187
288
class GitMappingRegistry(VcsMappingRegistry):
188
289
    """Registry with available git mappings."""
202
303
                                   "BzrGitMappingv1")
203
304
mapping_registry.register_lazy('git-experimental', "bzrlib.plugins.git.mapping",
204
305
                                   "BzrGitMappingExperimental")
 
306
mapping_registry.set_default('git-v1')
205
307
 
206
308
 
207
309
class ForeignGit(ForeignVcs):
208
310
    """The Git Stupid Content Tracker"""
209
311
 
 
312
    @property
 
313
    def branch_format(self):
 
314
        from bzrlib.plugins.git.branch import GitBranchFormat
 
315
        return GitBranchFormat()
 
316
 
 
317
    @property
 
318
    def repository_format(self):
 
319
        from bzrlib.plugins.git.repository import GitRepositoryFormat
 
320
        return GitRepositoryFormat()
 
321
 
210
322
    def __init__(self):
211
323
        super(ForeignGit, self).__init__(mapping_registry)
 
324
        self.abbreviation = "git"
 
325
 
 
326
    @classmethod
 
327
    def serialize_foreign_revid(self, foreign_revid):
 
328
        return foreign_revid
212
329
 
213
330
    @classmethod
214
331
    def show_foreign_revid(cls, foreign_revid):
216
333
 
217
334
 
218
335
foreign_git = ForeignGit()
219
 
default_mapping = BzrGitMappingv1()
 
336
default_mapping = mapping_registry.get_default()()
220
337
 
221
338
 
222
339
def text_to_blob(texts, entry):
260
377
            "Unknown kind, perms=%r." % (mode,))
261
378
 
262
379
 
263
 
def entry_mode(entry):
264
 
    """Determine the git file mode for an inventory entry."""
265
 
    if entry.kind == 'directory':
 
380
def object_mode(kind, executable):
 
381
    if kind == 'directory':
266
382
        return stat.S_IFDIR
267
 
    elif entry.kind == 'symlink':
 
383
    elif kind == 'symlink':
268
384
        return stat.S_IFLNK
269
 
    elif entry.kind == 'file':
 
385
    elif kind == 'file':
270
386
        mode = stat.S_IFREG | 0644
271
 
        if entry.executable:
 
387
        if executable:
272
388
            mode |= 0111
273
389
        return mode
 
390
    elif kind == 'tree-reference':
 
391
        from dulwich.objects import S_IFGITLINK
 
392
        return S_IFGITLINK
274
393
    else:
275
394
        raise AssertionError
276
395
 
277
396
 
 
397
def entry_mode(entry):
 
398
    """Determine the git file mode for an inventory entry."""
 
399
    return object_mode(entry.kind, entry.executable)
 
400
 
 
401
 
278
402
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes):
279
403
    from dulwich.objects import Tree
280
404
    tree = Tree()
284
408
            mode = unusual_modes[ie.file_id]
285
409
        except KeyError:
286
410
            mode = entry_mode(ie)
287
 
        tree.add(mode, name.encode("utf-8"), lookup_ie_sha1(ie))
 
411
        hexsha = lookup_ie_sha1(ie)
 
412
        if hexsha is not None:
 
413
            tree.add(mode, name.encode("utf-8"), hexsha)
 
414
    if entry.parent_id is not None and len(tree) == 0:
 
415
        # Only the root can be an empty tree
 
416
        return None
288
417
    tree.serialize()
289
418
    return tree
290
419
 
310
439
        cur = ""
311
440
    tree = Tree()
312
441
 
313
 
    # stack contains the set of trees that we haven't 
 
442
    # stack contains the set of trees that we haven't
314
443
    # finished constructing
315
444
    for path, entry in inventory.iter_entries():
316
445
        while stack and not path.startswith(osutils.pathjoin(cur, "")):
353
482
    yield tree.id, tree, cur.encode("utf-8")
354
483
 
355
484
 
356
 
def revision_to_commit(rev, tree_sha, parent_lookup):
357
 
    """Turn a Bazaar revision in to a Git commit
358
 
 
359
 
    :param tree_sha: Tree sha for the commit
360
 
    :param parent_lookup: Function for looking up the GIT sha equiv of a bzr revision
361
 
    :return dulwich.objects.Commit represent the revision:
362
 
    """
363
 
    from dulwich.objects import Commit
364
 
    commit = Commit()
365
 
    commit.tree = tree_sha
366
 
    for p in rev.parent_ids:
367
 
        git_p = parent_lookup(p)
368
 
        if git_p is not None:
369
 
            assert len(git_p) == 40, "unexpected length for %r" % git_p
370
 
            commit.parents.append(git_p)
371
 
    commit.message = rev.message.encode("utf-8")
372
 
    commit.committer = fix_person_identifier(rev.committer.encode("utf-8"))
373
 
    commit.author = fix_person_identifier(rev.get_apparent_authors()[0].encode("utf-8"))
374
 
    commit.commit_time = long(rev.timestamp)
375
 
    if 'author-timestamp' in rev.properties:
376
 
        commit.author_time = long(rev.properties['author-timestamp'])
377
 
    else:
378
 
        commit.author_time = commit.commit_time
379
 
    commit.commit_timezone = rev.timezone
380
 
    if 'author-timezone' in rev.properties:
381
 
        commit.author_timezone = int(rev.properties['author-timezone'])
382
 
    else:
383
 
        commit.author_timezone = commit.commit_timezone 
384
 
    return commit
 
485
def parse_git_svn_id(text):
 
486
    (head, uuid) = text.rsplit(" ", 1)
 
487
    (full_url, rev) = head.rsplit("@", 1)
 
488
    return (full_url, int(rev), uuid)