/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

Add docstring.

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:
 
128
        if git_rev_id == "0" * 40:
140
129
            return NULL_REVISION
141
130
        return "%s:%s" % (cls.revid_prefix, git_rev_id)
142
131
 
154
143
            return ROOT_ID
155
144
        return escape_file_id(path)
156
145
 
157
 
    def is_control_file(self, path):
158
 
        return path in (self.BZR_FILE_IDS_FILE, self.BZR_DUMMY_FILE)
159
 
 
160
146
    def parse_file_id(self, file_id):
161
147
        if file_id == ROOT_ID:
162
148
            return ""
163
149
        return unescape_file_id(file_id)
164
150
 
165
 
    def revid_as_refname(self, revid):
166
 
        import urllib
167
 
        return "refs/bzr/%s" % urllib.quote(revid)
168
 
 
169
151
    def import_unusual_file_modes(self, rev, unusual_file_modes):
170
152
        if unusual_file_modes:
171
 
            ret = [(path, unusual_file_modes[path])
172
 
                   for path in sorted(unusual_file_modes.keys())]
 
153
            ret = [(name, unusual_file_modes[name])
 
154
                   for name in sorted(unusual_file_modes.keys())]
173
155
            rev.properties['file-modes'] = bencode.bencode(ret)
174
156
 
175
157
    def export_unusual_file_modes(self, rev):
176
158
        try:
177
 
            file_modes = rev.properties['file-modes']
 
159
            return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(rev.properties['file-modes'].encode("utf-8"))])
178
160
        except KeyError:
179
161
            return {}
180
 
        else:
181
 
            return dict([(self.generate_file_id(path), mode) for (path, mode) in bencode.bdecode(file_modes.encode("utf-8"))])
182
162
 
183
163
    def _generate_git_svn_metadata(self, rev, encoding):
184
164
        try:
185
 
            git_svn_id = rev.properties["git-svn-id"]
 
165
            return "\ngit-svn-id: %s\n" % rev.properties["git-svn-id"].encode(encoding)
186
166
        except KeyError:
187
167
            return ""
188
 
        else:
189
 
            return "\ngit-svn-id: %s\n" % git_svn_id.encode(encoding)
190
168
 
191
169
    def _generate_hg_message_tail(self, rev):
192
170
        extra = {}
196
174
            if name == 'hg:extra:branch':
197
175
                branch = rev.properties['hg:extra:branch']
198
176
            elif name.startswith('hg:extra'):
199
 
                extra[name[len('hg:extra:'):]] = base64.b64decode(
200
 
                    rev.properties[name])
 
177
                extra[name[len('hg:extra:'):]] = base64.b64decode(rev.properties[name])
201
178
            elif name == 'hg:renames':
202
 
                renames = bencode.bdecode(base64.b64decode(
203
 
                    rev.properties['hg:renames']))
 
179
                renames = bencode.bdecode(base64.b64decode(rev.properties['hg:renames']))
204
180
            # TODO: Export other properties as 'bzr:' extras?
205
181
        ret = format_hg_metadata(renames, branch, extra)
206
182
        assert isinstance(ret, str)
225
201
        for name, value in extra.iteritems():
226
202
            rev.properties['hg:extra:' + name] = base64.b64encode(value)
227
203
        if renames:
228
 
            rev.properties['hg:renames'] = base64.b64encode(bencode.bencode(
229
 
                [(new, old) for (old, new) in renames.iteritems()]))
 
204
            rev.properties['hg:renames'] = base64.b64encode(bencode.bencode([(new, old) for (old, new) in renames.iteritems()]))
230
205
        return message
231
206
 
232
 
    def _extract_bzr_metadata(self, rev, message):
233
 
        (message, metadata) = extract_bzr_metadata(message)
234
 
        return message, metadata
235
 
 
236
207
    def _decode_commit_message(self, rev, message, encoding):
237
 
        message, metadata = self._extract_bzr_metadata(rev, message)
238
 
        return message.decode(encoding), metadata
 
208
        return message.decode(encoding)
239
209
 
240
210
    def _encode_commit_message(self, rev, message, encoding):
241
211
        return message.encode(encoding)
242
212
 
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):
 
213
    def export_commit(self, rev, tree_sha, parent_lookup):
255
214
        """Turn a Bazaar revision in to a Git commit
256
215
 
257
216
        :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
 
217
        :param parent_lookup: Function for looking up the GIT sha equiv of a bzr revision
260
218
        :return dulwich.objects.Commit represent the revision:
261
219
        """
262
220
        from dulwich.objects import Commit
263
221
        commit = Commit()
264
222
        commit.tree = tree_sha
265
 
        if roundtrip:
266
 
            metadata = BzrGitRevisionMetadata()
267
 
        else:
268
 
            metadata = None
269
223
        for p in rev.parent_ids:
270
224
            try:
271
225
                git_p = parent_lookup(p)
272
226
            except KeyError:
273
227
                git_p = None
274
 
                if metadata is not None:
275
 
                    metadata.explicit_parent_ids = rev.parent_ids
276
228
            if git_p is not None:
277
229
                assert len(git_p) == 40, "unexpected length for %r" % git_p
278
230
                commit.parents.append(git_p)
290
242
            commit.author_time = long(rev.properties['author-timestamp'])
291
243
        else:
292
244
            commit.author_time = commit.commit_time
293
 
        commit._commit_timezone_neg_utc = "commit-timezone-neg-utc" in rev.properties
294
245
        commit.commit_timezone = rev.timezone
295
 
        commit._author_timezone_neg_utc = "author-timezone-neg-utc" in rev.properties
296
246
        if 'author-timezone' in rev.properties:
297
247
            commit.author_timezone = int(rev.properties['author-timezone'])
298
248
        else:
299
249
            commit.author_timezone = commit.commit_timezone
300
250
        commit.message = self._encode_commit_message(rev, rev.message, 
301
251
            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
252
        return commit
316
253
 
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
254
    def import_commit(self, commit):
326
255
        """Convert a git commit to a bzr revision.
327
256
 
328
 
        :return: a `bzrlib.revision.Revision` object and a 
329
 
            dictionary of path -> file ids
 
257
        :return: a `bzrlib.revision.Revision` object.
330
258
        """
331
259
        if commit is None:
332
260
            raise AssertionError("Commit object can't be None")
333
 
        rev = ForeignRevision(commit.id, self,
334
 
                self.revision_id_foreign_to_bzr(commit.id))
 
261
        rev = ForeignRevision(commit.id, self, self.revision_id_foreign_to_bzr(commit.id))
335
262
        rev.parent_ids = tuple([self.revision_id_foreign_to_bzr(p) for p in commit.parents])
336
 
        rev.git_metadata = None
337
263
        def decode_using_encoding(rev, commit, encoding):
338
264
            rev.committer = str(commit.committer).decode(encoding)
339
265
            if commit.committer != commit.author:
340
266
                rev.properties['author'] = str(commit.author).decode(encoding)
341
 
            rev.message, rev.git_metadata = self._decode_commit_message(
342
 
                rev, commit.message, encoding)
 
267
            rev.message = self._decode_commit_message(rev, commit.message, 
 
268
                encoding)
343
269
        if commit.encoding is not None:
344
270
            rev.properties['git-explicit-encoding'] = commit.encoding
345
271
            decode_using_encoding(rev, commit, commit.encoding)
356
282
        if commit.commit_time != commit.author_time:
357
283
            rev.properties['author-timestamp'] = str(commit.author_time)
358
284
        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'] = ""
 
285
            rev.properties['author-timezone'] = "%d" % (commit.author_timezone, )
364
286
        rev.timestamp = commit.commit_time
365
287
        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
288
        return rev
374
289
 
375
290
 
388
303
    def _decode_commit_message(self, rev, message, encoding):
389
304
        message = self._extract_hg_metadata(rev, message)
390
305
        message = self._extract_git_svn_metadata(rev, message)
391
 
        message, metadata = self._extract_bzr_metadata(rev, message)
392
 
        return message.decode(encoding), metadata
 
306
        return message.decode(encoding)
393
307
 
394
308
    def _encode_commit_message(self, rev, message, encoding):
395
309
        ret = message.encode(encoding)
398
312
        return ret
399
313
 
400
314
    def import_commit(self, commit):
401
 
        rev, file_ids = super(BzrGitMappingExperimental, self).import_commit(commit)
 
315
        rev = super(BzrGitMappingExperimental, self).import_commit(commit)
402
316
        rev.properties['converted_revision'] = "git %s\n" % commit.id
403
 
        return rev, file_ids
 
317
        return rev
404
318
 
405
319
 
406
320
class GitMappingRegistry(VcsMappingRegistry):
408
322
 
409
323
    def revision_id_bzr_to_foreign(self, bzr_revid):
410
324
        if bzr_revid == NULL_REVISION:
411
 
            from dulwich.protocol import ZERO_SHA
412
 
            return ZERO_SHA, None
 
325
            return "0" * 20, None
413
326
        if not bzr_revid.startswith("git-"):
414
327
            raise errors.InvalidRevisionId(bzr_revid, None)
415
328
        (mapping_version, git_sha) = bzr_revid.split(":", 1)
421
334
 
422
335
mapping_registry = GitMappingRegistry()
423
336
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")
 
337
                                   "BzrGitMappingv1")
 
338
mapping_registry.register_lazy('git-experimental', "bzrlib.plugins.git.mapping",
 
339
                                   "BzrGitMappingExperimental")
427
340
mapping_registry.set_default('git-v1')
428
341
 
429
342
 
457
370
default_mapping = mapping_registry.get_default()()
458
371
 
459
372
 
 
373
def text_to_blob(texts, entry):
 
374
    from dulwich.objects import Blob
 
375
    text = texts.get_record_stream([(entry.file_id, entry.revision)], 'unordered', True).next().get_bytes_as('fulltext')
 
376
    blob = Blob()
 
377
    blob._text = text
 
378
    return blob
 
379
 
 
380
 
460
381
def symlink_to_blob(entry):
461
382
    from dulwich.objects import Blob
462
383
    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
 
384
    blob._text = entry.symlink_target
467
385
    return blob
468
386
 
469
387
 
518
436
    return object_mode(entry.kind, entry.executable)
519
437
 
520
438
 
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
 
439
def directory_to_tree(entry, lookup_ie_sha1, unusual_modes):
 
440
    from dulwich.objects import Tree
531
441
    tree = Tree()
532
 
    for name, value in entry.children.iteritems():
 
442
    for name in sorted(entry.children.keys()):
533
443
        ie = entry.children[name]
534
444
        try:
535
445
            mode = unusual_modes[ie.file_id]
536
446
        except KeyError:
537
447
            mode = entry_mode(ie)
538
 
        hexsha = lookup_ie_sha1(ie)
 
448
        if ie.kind == 'directory':
 
449
            subtree = directory_to_tree(ie, lookup_ie_sha1, unusual_modes)
 
450
            if subtree is None:
 
451
                hexsha = None
 
452
            else:
 
453
                hexsha = subtree.id
 
454
        else:
 
455
            hexsha = lookup_ie_sha1(ie)
539
456
        if hexsha is not None:
540
457
            tree.add(mode, name.encode("utf-8"), hexsha)
541
458
    if entry.parent_id is not None and len(tree) == 0:
542
459
        # 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
 
460
        return None
 
461
    tree.serialize()
548
462
    return tree
549
463
 
550
464
 
551
465
def extract_unusual_modes(rev):
552
466
    try:
553
 
        foreign_revid, mapping = mapping_registry.parse_revision_id(
554
 
            rev.revision_id)
 
467
        foreign_revid, mapping = mapping_registry.parse_revision_id(rev.revision_id)
555
468
    except errors.InvalidRevisionId:
556
469
        return {}
557
470
    else:
558
471
        return mapping.export_unusual_file_modes(rev)
559
472
 
560
473
 
 
474
def inventory_to_tree_and_blobs(inventory, texts, mapping, unusual_modes, cur=None):
 
475
    """Convert a Bazaar tree to a Git tree.
 
476
 
 
477
    :return: Yields tuples with object sha1, object and path
 
478
    """
 
479
    from dulwich.objects import Tree
 
480
    import stat
 
481
    stack = []
 
482
    if cur is None:
 
483
        cur = ""
 
484
    tree = Tree()
 
485
 
 
486
    # stack contains the set of trees that we haven't
 
487
    # finished constructing
 
488
    for path, entry in inventory.iter_entries():
 
489
        while stack and not path.startswith(osutils.pathjoin(cur, "")):
 
490
            # We've hit a file that's not a child of the previous path
 
491
            tree.serialize()
 
492
            sha = tree.id
 
493
            yield sha, tree, cur.encode("utf-8")
 
494
            mode = unusual_modes.get(cur.encode("utf-8"), stat.S_IFDIR)
 
495
            t = (mode, urlutils.basename(cur).encode('UTF-8'), sha)
 
496
            cur, tree = stack.pop()
 
497
            tree.add(*t)
 
498
 
 
499
        if entry.kind == "directory":
 
500
            stack.append((cur, tree))
 
501
            cur = path
 
502
            tree = Tree()
 
503
        else:
 
504
            if entry.kind == "file":
 
505
                blob = text_to_blob(texts, entry)
 
506
            elif entry.kind == "symlink":
 
507
                blob = symlink_to_blob(entry)
 
508
            else:
 
509
                raise AssertionError("Unknown kind %s" % entry.kind)
 
510
            sha = blob.id
 
511
            yield sha, blob, path.encode("utf-8")
 
512
            name = urlutils.basename(path).encode("utf-8")
 
513
            mode = unusual_modes.get(path.encode("utf-8"), entry_mode(entry))
 
514
            tree.add(mode, name, sha)
 
515
 
 
516
    while len(stack) > 1:
 
517
        tree.serialize()
 
518
        sha = tree.id
 
519
        yield sha, tree, cur.encode("utf-8")
 
520
        mode = unusual_modes.get(cur.encode('utf-8'), stat.S_IFDIR)
 
521
        t = (mode, urlutils.basename(cur).encode('UTF-8'), sha)
 
522
        cur, tree = stack.pop()
 
523
        tree.add(*t)
 
524
 
 
525
    tree.serialize()
 
526
    yield tree.id, tree, cur.encode("utf-8")
 
527
 
 
528
 
561
529
def parse_git_svn_id(text):
562
530
    (head, uuid) = text.rsplit(" ", 1)
563
531
    (full_url, rev) = head.rsplit("@", 1)
564
532
    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)