/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

Implement to_files() for git merge directives.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2007 Canonical Ltd
2
 
# Copyright (C) 2008-2010 Jelmer Vernooij <jelmer@samba.org>
 
2
# Copyright (C) 2008-2009 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
24
24
from bzrlib import (
25
25
    errors,
26
26
    foreign,
 
27
    osutils,
27
28
    trace,
 
29
    urlutils,
28
30
    )
29
31
try:
30
32
    from bzrlib import bencode
45
47
    format_hg_metadata,
46
48
    extract_hg_metadata,
47
49
    )
48
 
from bzrlib.plugins.git.roundtrip import (
49
 
    extract_bzr_metadata,
50
 
    inject_bzr_metadata,
51
 
    BzrGitRevisionMetadata,
52
 
    deserialize_fileid_map,
53
 
    serialize_fileid_map,
54
 
    )
55
50
 
56
51
DEFAULT_FILE_MODE = stat.S_IFREG | 0644
57
52
 
72
67
            elif file_id[i+1] == 's':
73
68
                ret.append(" ")
74
69
            else:
75
 
                raise AssertionError("unknown escape character %s" %
76
 
                    file_id[i+1])
 
70
                raise AssertionError("unknown escape character %s" % file_id[i+1])
77
71
            i += 1
78
72
        i += 1
79
73
    return "".join(ret)
91
85
 
92
86
 
93
87
def warn_unusual_mode(commit, path, mode):
94
 
    trace.mutter("Unusual file mode %o for %s in %s. Storing as revision "
95
 
                 "property. ", mode, path, commit)
 
88
    trace.mutter("Unusual file mode %o for %s in %s. Storing as revision property. ",
 
89
                 mode, path, commit)
96
90
 
97
91
 
98
92
def squash_revision(target_repo, rev):
121
115
    """Class that maps between Git and Bazaar semantics."""
122
116
    experimental = False
123
117
 
124
 
    BZR_FILE_IDS_FILE = '.bzrfileids'
125
 
 
126
 
    BZR_DUMMY_FILE = '.bzrdummy'
127
 
 
128
118
    def __init__(self):
129
119
        super(BzrGitMapping, self).__init__(foreign_git)
130
120
 
135
125
    @classmethod
136
126
    def revision_id_foreign_to_bzr(cls, git_rev_id):
137
127
        """Convert a git revision id handle to a Bazaar revision id."""
138
 
        from dulwich.protocol import ZERO_SHA
139
 
        if git_rev_id == ZERO_SHA:
140
 
            return NULL_REVISION
141
128
        return "%s:%s" % (cls.revid_prefix, git_rev_id)
142
129
 
143
130
    @classmethod
154
141
            return ROOT_ID
155
142
        return escape_file_id(path)
156
143
 
157
 
    def is_control_file(self, path):
158
 
        return path in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE)
159
 
 
160
144
    def parse_file_id(self, file_id):
161
145
        if file_id == ROOT_ID:
162
146
            return ""
163
147
        return unescape_file_id(file_id)
164
148
 
165
 
    def revid_as_refname(self, revid):
166
 
        import urllib
167
 
        return "refs/bzr/%s" % urllib.quote(revid)
168
 
 
169
149
    def import_unusual_file_modes(self, rev, unusual_file_modes):
170
150
        if unusual_file_modes:
171
 
            ret = [(path, unusual_file_modes[path])
172
 
                   for path in sorted(unusual_file_modes.keys())]
 
151
            ret = [(name, unusual_file_modes[name])
 
152
                   for name in sorted(unusual_file_modes.keys())]
173
153
            rev.properties['file-modes'] = bencode.bencode(ret)
174
154
 
175
155
    def export_unusual_file_modes(self, rev):
176
156
        try:
177
 
            file_modes = rev.properties['file-modes']
 
157
            return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(rev.properties['file-modes'].encode("utf-8"))])
178
158
        except KeyError:
179
159
            return {}
180
 
        else:
181
 
            return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(file_modes.encode("utf-8"))])
182
160
 
183
161
    def _generate_git_svn_metadata(self, rev, encoding):
184
162
        try:
185
 
            git_svn_id = rev.properties["git-svn-id"]
 
163
            return "\ngit-svn-id: %s\n" % rev.properties["git-svn-id"].encode(encoding)
186
164
        except KeyError:
187
165
            return ""
188
 
        else:
189
 
            return "\ngit-svn-id: %s\n" % git_svn_id.encode(encoding)
190
166
 
191
167
    def _generate_hg_message_tail(self, rev):
192
168
        extra = {}
196
172
            if name == 'hg:extra:branch':
197
173
                branch = rev.properties['hg:extra:branch']
198
174
            elif name.startswith('hg:extra'):
199
 
                extra[name[len('hg:extra:'):]] = base64.b64decode(
200
 
                    rev.properties[name])
 
175
                extra[name[len('hg:extra:'):]] = base64.b64decode(rev.properties[name])
201
176
            elif name == 'hg:renames':
202
 
                renames = bencode.bdecode(base64.b64decode(
203
 
                    rev.properties['hg:renames']))
 
177
                renames = bencode.bdecode(base64.b64decode(rev.properties['hg:renames']))
204
178
            # TODO: Export other properties as 'bzr:' extras?
205
179
        ret = format_hg_metadata(renames, branch, extra)
206
180
        assert isinstance(ret, str)
225
199
        for name, value in extra.iteritems():
226
200
            rev.properties['hg:extra:' + name] = base64.b64encode(value)
227
201
        if renames:
228
 
            rev.properties['hg:renames'] = base64.b64encode(bencode.bencode(
229
 
                [(new, old) for (old, new) in renames.iteritems()]))
 
202
            rev.properties['hg:renames'] = base64.b64encode(bencode.bencode([(new, old) for (old, new) in renames.iteritems()]))
230
203
        return message
231
204
 
232
 
    def _extract_bzr_metadata(self, rev, message):
233
 
        (message, metadata) = extract_bzr_metadata(message)
234
 
        return message, metadata
235
 
 
236
205
    def _decode_commit_message(self, rev, message, encoding):
237
 
        message, metadata = self._extract_bzr_metadata(rev, message)
238
 
        return message.decode(encoding), metadata
 
206
        return message.decode(encoding)
239
207
 
240
208
    def _encode_commit_message(self, rev, message, encoding):
241
209
        return message.encode(encoding)
242
210
 
243
 
    def export_fileid_map(self, fileid_map):
244
 
        """Export a file id map to a fileid map.
245
 
 
246
 
        :param fileid_map: File id map, mapping paths to file ids
247
 
        :return: A Git blob object
248
 
        """
249
 
        from dulwich.objects import Blob
250
 
        b = Blob()
251
 
        b.set_raw_chunks(serialize_fileid_map(fileid_map))
252
 
        return b
253
 
 
254
 
    def export_commit(self, rev, tree_sha, parent_lookup, roundtrip):
 
211
    def export_commit(self, rev, tree_sha, parent_lookup):
255
212
        """Turn a Bazaar revision in to a Git commit
256
213
 
257
214
        :param tree_sha: Tree sha for the commit
258
 
        :param parent_lookup: Function for looking up the GIT sha equiv of a
259
 
            bzr revision
 
215
        :param parent_lookup: Function for looking up the GIT sha equiv of a bzr revision
260
216
        :return dulwich.objects.Commit represent the revision:
261
217
        """
262
218
        from dulwich.objects import Commit
263
219
        commit = Commit()
264
220
        commit.tree = tree_sha
265
 
        if roundtrip:
266
 
            metadata = BzrGitRevisionMetadata()
267
 
        else:
268
 
            metadata = None
269
221
        for p in rev.parent_ids:
270
222
            try:
271
223
                git_p = parent_lookup(p)
272
224
            except KeyError:
273
225
                git_p = None
274
 
                if metadata is not None:
275
 
                    metadata.explicit_parent_ids = rev.parent_ids
276
226
            if git_p is not None:
277
227
                assert len(git_p) == 40, "unexpected length for %r" % git_p
278
228
                commit.parents.append(git_p)
290
240
            commit.author_time = long(rev.properties['author-timestamp'])
291
241
        else:
292
242
            commit.author_time = commit.commit_time
293
 
        commit._commit_timezone_neg_utc = "commit-timezone-neg-utc" in rev.properties
294
243
        commit.commit_timezone = rev.timezone
295
 
        commit._author_timezone_neg_utc = "author-timezone-neg-utc" in rev.properties
296
244
        if 'author-timezone' in rev.properties:
297
245
            commit.author_timezone = int(rev.properties['author-timezone'])
298
246
        else:
299
247
            commit.author_timezone = commit.commit_timezone
300
248
        commit.message = self._encode_commit_message(rev, rev.message, 
301
249
            encoding)
302
 
        if metadata is not None:
303
 
            try:
304
 
                mapping_registry.parse_revision_id(rev.revision_id)
305
 
            except errors.InvalidRevisionId:
306
 
                metadata.revision_id = rev.revision_id
307
 
            mapping_properties = set(
308
 
                ['author', 'author-timezone', 'author-timezone-neg-utc',
309
 
                 'commit-timezone-neg-utc', 'git-implicit-encoding',
310
 
                 'git-explicit-encoding', 'author-timestamp', 'file-modes'])
311
 
            for k, v in rev.properties.iteritems():
312
 
                if not k in mapping_properties:
313
 
                    metadata.properties[k] = v
314
 
        commit.message = inject_bzr_metadata(commit.message, metadata)
315
250
        return commit
316
251
 
317
 
    def import_fileid_map(self, blob):
318
 
        """Convert a git file id map blob.
319
 
 
320
 
        :param blob: Git blob object with fileid map
321
 
        :return: Dictionary mapping paths to file ids
322
 
        """
323
 
        return deserialize_fileid_map(blob.data)
324
 
 
325
252
    def import_commit(self, commit):
326
253
        """Convert a git commit to a bzr revision.
327
254
 
328
 
        :return: a `bzrlib.revision.Revision` object and a 
329
 
            dictionary of path -> file ids
 
255
        :return: a `bzrlib.revision.Revision` object.
330
256
        """
331
257
        if commit is None:
332
258
            raise AssertionError("Commit object can't be None")
333
 
        rev = ForeignRevision(commit.id, self,
334
 
                self.revision_id_foreign_to_bzr(commit.id))
 
259
        rev = ForeignRevision(commit.id, self, self.revision_id_foreign_to_bzr(commit.id))
335
260
        rev.parent_ids = tuple([self.revision_id_foreign_to_bzr(p) for p in commit.parents])
336
 
        rev.git_metadata = None
337
261
        def decode_using_encoding(rev, commit, encoding):
338
262
            rev.committer = str(commit.committer).decode(encoding)
339
263
            if commit.committer != commit.author:
340
264
                rev.properties['author'] = str(commit.author).decode(encoding)
341
 
            rev.message, rev.git_metadata = self._decode_commit_message(
342
 
                rev, commit.message, encoding)
 
265
            rev.message = self._decode_commit_message(rev, commit.message, 
 
266
                encoding)
343
267
        if commit.encoding is not None:
344
268
            rev.properties['git-explicit-encoding'] = commit.encoding
345
269
            decode_using_encoding(rev, commit, commit.encoding)
356
280
        if commit.commit_time != commit.author_time:
357
281
            rev.properties['author-timestamp'] = str(commit.author_time)
358
282
        if commit.commit_timezone != commit.author_timezone:
359
 
            rev.properties['author-timezone'] = "%d" % commit.author_timezone
360
 
        if commit._author_timezone_neg_utc:
361
 
            rev.properties['author-timezone-neg-utc'] = ""
362
 
        if commit._commit_timezone_neg_utc:
363
 
            rev.properties['commit-timezone-neg-utc'] = ""
 
283
            rev.properties['author-timezone'] = "%d" % (commit.author_timezone, )
364
284
        rev.timestamp = commit.commit_time
365
285
        rev.timezone = commit.commit_timezone
366
 
        if rev.git_metadata is not None:
367
 
            md = rev.git_metadata
368
 
            if md.revision_id:
369
 
                rev.revision_id = md.revision_id
370
 
            if md.explicit_parent_ids:
371
 
                rev.parent_ids = md.explicit_parent_ids
372
 
            rev.properties.update(md.properties)
373
286
        return rev
374
287
 
375
288
 
388
301
    def _decode_commit_message(self, rev, message, encoding):
389
302
        message = self._extract_hg_metadata(rev, message)
390
303
        message = self._extract_git_svn_metadata(rev, message)
391
 
        message, metadata = self._extract_bzr_metadata(rev, message)
392
 
        return message.decode(encoding), metadata
 
304
        return message.decode(encoding)
393
305
 
394
306
    def _encode_commit_message(self, rev, message, encoding):
395
307
        ret = message.encode(encoding)
398
310
        return ret
399
311
 
400
312
    def import_commit(self, commit):
401
 
        rev, file_ids = super(BzrGitMappingExperimental, self).import_commit(commit)
 
313
        rev = super(BzrGitMappingExperimental, self).import_commit(commit)
402
314
        rev.properties['converted_revision'] = "git %s\n" % commit.id
403
 
        return rev, file_ids
 
315
        return rev
404
316
 
405
317
 
406
318
class GitMappingRegistry(VcsMappingRegistry):
408
320
 
409
321
    def revision_id_bzr_to_foreign(self, bzr_revid):
410
322
        if bzr_revid == NULL_REVISION:
411
 
            from dulwich.protocol import ZERO_SHA
412
 
            return ZERO_SHA, None
 
323
            return "0" * 20, None
413
324
        if not bzr_revid.startswith("git-"):
414
325
            raise errors.InvalidRevisionId(bzr_revid, None)
415
326
        (mapping_version, git_sha) = bzr_revid.split(":", 1)
421
332
 
422
333
mapping_registry = GitMappingRegistry()
423
334
mapping_registry.register_lazy('git-v1', "bzrlib.plugins.git.mapping",
424
 
    "BzrGitMappingv1")
425
 
mapping_registry.register_lazy('git-experimental',
426
 
    "bzrlib.plugins.git.mapping", "BzrGitMappingExperimental")
 
335
                                   "BzrGitMappingv1")
 
336
mapping_registry.register_lazy('git-experimental', "bzrlib.plugins.git.mapping",
 
337
                                   "BzrGitMappingExperimental")
427
338
mapping_registry.set_default('git-v1')
428
339
 
429
340
 
457
368
default_mapping = mapping_registry.get_default()()
458
369
 
459
370
 
 
371
def text_to_blob(texts, entry):
 
372
    from dulwich.objects import Blob
 
373
    text = texts.get_record_stream([(entry.file_id, entry.revision)], 'unordered', True).next().get_bytes_as('fulltext')
 
374
    blob = Blob()
 
375
    blob._text = text
 
376
    return blob
 
377
 
 
378
 
460
379
def symlink_to_blob(entry):
461
380
    from dulwich.objects import Blob
462
381
    blob = Blob()
463
 
    symlink_target = entry.symlink_target
464
 
    if type(symlink_target) == unicode:
465
 
        symlink_target = symlink_target.encode('utf-8')
466
 
    blob.data = symlink_target
 
382
    blob._text = entry.symlink_target
467
383
    return blob
468
384
 
469
385
 
518
434
    return object_mode(entry.kind, entry.executable)
519
435
 
520
436
 
521
 
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes, empty_file_name):
522
 
    """Create a Git Tree object from a Bazaar directory.
523
 
 
524
 
    :param entry: Inventory entry
525
 
    :param lookup_ie_sha1: Lookup the Git SHA1 for a inventory entry
526
 
    :param unusual_modes: Dictionary with unusual file modes by file ids
527
 
    :param empty_file_name: Name to use for dummy files in empty directories,
528
 
        None to ignore empty directories.
529
 
    """
530
 
    from dulwich.objects import Blob, Tree
 
437
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes):
 
438
    from dulwich.objects import Tree
531
439
    tree = Tree()
532
 
    for name, value in entry.children.iteritems():
 
440
    for name in sorted(entry.children.keys()):
533
441
        ie = entry.children[name]
534
442
        try:
535
443
            mode = unusual_modes[ie.file_id]
540
448
            tree.add(mode, name.encode("utf-8"), hexsha)
541
449
    if entry.parent_id is not None and len(tree) == 0:
542
450
        # Only the root can be an empty tree
543
 
        if empty_file_name is not None:
544
 
            tree.add(stat.S_IFREG | 0644, empty_file_name, 
545
 
                Blob().id)
546
 
        else:
547
 
            return None
 
451
        return None
 
452
    tree.serialize()
548
453
    return tree
549
454
 
550
455
 
551
456
def extract_unusual_modes(rev):
552
457
    try:
553
 
        foreign_revid, mapping = mapping_registry.parse_revision_id(
554
 
            rev.revision_id)
 
458
        foreign_revid, mapping = mapping_registry.parse_revision_id(rev.revision_id)
555
459
    except errors.InvalidRevisionId:
556
460
        return {}
557
461
    else:
558
462
        return mapping.export_unusual_file_modes(rev)
559
463
 
560
464
 
 
465
def inventory_to_tree_and_blobs(inventory, texts, mapping, unusual_modes, cur=None):
 
466
    """Convert a Bazaar tree to a Git tree.
 
467
 
 
468
    :return: Yields tuples with object sha1, object and path
 
469
    """
 
470
    from dulwich.objects import Tree
 
471
    import stat
 
472
    stack = []
 
473
    if cur is None:
 
474
        cur = ""
 
475
    tree = Tree()
 
476
 
 
477
    # stack contains the set of trees that we haven't
 
478
    # finished constructing
 
479
    for path, entry in inventory.iter_entries():
 
480
        while stack and not path.startswith(osutils.pathjoin(cur, "")):
 
481
            # We've hit a file that's not a child of the previous path
 
482
            tree.serialize()
 
483
            sha = tree.id
 
484
            yield sha, tree, cur.encode("utf-8")
 
485
            mode = unusual_modes.get(cur.encode("utf-8"), stat.S_IFDIR)
 
486
            t = (mode, urlutils.basename(cur).encode('UTF-8'), sha)
 
487
            cur, tree = stack.pop()
 
488
            tree.add(*t)
 
489
 
 
490
        if entry.kind == "directory":
 
491
            stack.append((cur, tree))
 
492
            cur = path
 
493
            tree = Tree()
 
494
        else:
 
495
            if entry.kind == "file":
 
496
                blob = text_to_blob(texts, entry)
 
497
            elif entry.kind == "symlink":
 
498
                blob = symlink_to_blob(entry)
 
499
            else:
 
500
                raise AssertionError("Unknown kind %s" % entry.kind)
 
501
            sha = blob.id
 
502
            yield sha, blob, path.encode("utf-8")
 
503
            name = urlutils.basename(path).encode("utf-8")
 
504
            mode = unusual_modes.get(path.encode("utf-8"), entry_mode(entry))
 
505
            tree.add(mode, name, sha)
 
506
 
 
507
    while len(stack) > 1:
 
508
        tree.serialize()
 
509
        sha = tree.id
 
510
        yield sha, tree, cur.encode("utf-8")
 
511
        mode = unusual_modes.get(cur.encode('utf-8'), stat.S_IFDIR)
 
512
        t = (mode, urlutils.basename(cur).encode('UTF-8'), sha)
 
513
        cur, tree = stack.pop()
 
514
        tree.add(*t)
 
515
 
 
516
    tree.serialize()
 
517
    yield tree.id, tree, cur.encode("utf-8")
 
518
 
 
519
 
561
520
def parse_git_svn_id(text):
562
521
    (head, uuid) = text.rsplit(" ", 1)
563
522
    (full_url, rev) = head.rsplit("@", 1)
564
523
    return (full_url, int(rev), uuid)
565
 
 
566
 
 
567
 
class GitFileIdMap(object):
568
 
 
569
 
    def __init__(self, file_ids, mapping):
570
 
        self.file_ids = file_ids
571
 
        self.paths = None
572
 
        self.mapping = mapping
573
 
 
574
 
    def lookup_file_id(self, path):
575
 
        try:
576
 
            return self.file_ids[path]
577
 
        except KeyError:
578
 
            return self.mapping.generate_file_id(path)
579
 
 
580
 
    def lookup_path(self, file_id):
581
 
        if self.paths is None:
582
 
            self.paths = {}
583
 
            for k, v in self.file_ids.iteritems():
584
 
                self.paths[v] = k
585
 
        try:
586
 
            return self.paths[file_id]
587
 
        except KeyError:
588
 
            return self.mapping.parse_file_id(file_id)