/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# Copyright (C) 2008 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from bzrlib import osutils, urlutils
from bzrlib.errors import InvalidRevisionId
from bzrlib.inventory import Inventory
from bzrlib.repository import InterRepository
from bzrlib.trace import info

from bzrlib.plugins.git import git
from bzrlib.plugins.git.repository import LocalGitRepository, GitRepository, GitFormat
from bzrlib.plugins.git.remote import RemoteGitRepository

from dulwich.objects import Commit

from cStringIO import StringIO


class BzrFetchGraphWalker(object):

    def __init__(self, repository, mapping):
        self.repository = repository
        self.mapping = mapping
        self.done = set()
        self.heads = set(repository.all_revision_ids())
        self.parents = {}

    def ack(self, sha):
        revid = self.mapping.revision_id_foreign_to_bzr(sha)
        self.remove(revid)

    def remove(self, revid):
        self.done.add(revid)
        if ref in self.heads:
            self.heads.remove(revid)
        if revid in self.parents:
            for p in self.parents[revid]:
                self.remove(p)

    def next(self):
        while self.heads:
            ret = self.heads.pop()
            ps = self.repository.get_parent_map([ret])[ret]
            self.parents[ret] = ps
            self.heads.update([p for p in ps if not p in self.done])
            try:
                self.done.add(ret)
                return self.mapping.revision_id_bzr_to_foreign(ret)
            except InvalidRevisionId:
                pass
        return None


def import_git_blob(repo, mapping, path, blob, inv):
    """Import a git blob object into a bzr repository.

    :param repo: bzr repository
    :param path: Path in the tree
    :param blob: A git blob
    """
    file_id = mapping.generate_file_id(path)
    repo.texts.add_lines((file_id, blob.id),
        [], #FIXME 
        osutils.split_lines(blob.data))
    ie = inv.add_path(path, "file", file_id)


def import_git_tree(repo, mapping, path, tree, inv, lookup_object):
    """Import a git tree object into a bzr repository.

    :param repo: A Bzr repository object
    :param path: Path in the tree
    :param tree: A git tree object
    :param inv: Inventory object
    """
    file_id = mapping.generate_file_id(path)
    repo.texts.add_lines((file_id, tree.id),
        [], #FIXME 
        [])
    inv.add_path(path, "directory", file_id)
    for mode, name, hexsha in tree.entries():
        entry_kind = (mode & 0700000) / 0100000
        basename = name.decode("utf-8")
        if path == "":
            child_path = name
        else:
            child_path = urlutils.join(path, name)
        if entry_kind == 0:
            tree = lookup_object(hexsha)
            import_git_tree(repo, mapping, child_path, tree, inv, lookup_object)
        elif entry_kind == 1:
            blob = lookup_object(hexsha)
            import_git_blob(repo, mapping, child_path, blob, inv)
        else:
            raise AssertionError("Unknown blob kind, perms=%r." % (mode,))


def import_git_objects(repo, mapping, object_iter):
    """Import a set of git objects into a bzr repository.

    :param repo: Bazaar repository
    :param mapping: Mapping to use
    :param object_iter: Iterator over Git objects.
    """
    # TODO: a more (memory-)efficient implementation of this
    objects = {}
    for o in object_iter:
        objects[o.id] = o
    root_trees = {}
    # Find and convert commit objects
    for o in objects.itervalues():
        if isinstance(o, Commit):
            rev = mapping.import_commit(o)
            root_trees[rev] = objects[o.tree]
    # Create the inventory objects
    for rev, root_tree in root_trees.iteritems():
        # We have to do this here, since we have to walk the tree and 
        # we need to make sure to import the blobs / trees with the riht 
        # path; this may involve adding them more than once.
        inv = Inventory()
        inv.revision_id = rev.revision_id
        def lookup_object(sha):
            if sha in objects:
                return objects[sha]
            return reconstruct_git_object(repo, mapping, sha)
        import_git_tree(repo, mapping, "", root_tree, inv, lookup_object)
        repo.add_revision(rev.revision_id, rev, inv)


def reconstruct_git_commit(repo, rev):
    raise NotImplementedError(self.reconstruct_git_commit)


def reconstruct_git_object(repo, mapping, sha):
    # Commit
    revid = mapping.revision_id_foreign_to_bzr(sha)
    try:
        rev = repo.get_revision(revid)
    except NoSuchRevision:
        pass
    else:
        return reconstruct_git_commit(rev)

    # TODO: Tree
    # TODO: Blob
    raise KeyError("No such object %s" % sha)


class InterGitRepository(InterRepository):

    _matching_repo_format = GitFormat()

    @staticmethod
    def _get_repo_format_to_test():
        return None

    def copy_content(self, revision_id=None, pb=None):
        """See InterRepository.copy_content."""
        self.fetch(revision_id, pb, find_ghosts=False)

    def fetch(self, revision_id=None, pb=None, find_ghosts=False, 
              mapping=None):
        if mapping is None:
            mapping = self.source.get_mapping()
        def progress(text):
            if pb is not None:
                pb.note("git: %s" % text)
            else:
                info("git: %s" % text)
        def determine_wants(heads):
            if revision_id is None:
                ret = heads.values()
            else:
                ret = [mapping.revision_id_bzr_to_foreign(revision_id)]
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
        graph_walker = BzrFetchGraphWalker(self.target, mapping)
        self.target.lock_write()
        try:
            self.target.start_write_group()
            try:
                import_git_objects(self.target, mapping,
                    iter(self.source.fetch_objects(determine_wants, graph_walker, 
                        progress)))
            finally:
                self.target.commit_write_group()
        finally:
            self.target.unlock()

    @staticmethod
    def is_compatible(source, target):
        """Be compatible with GitRepository."""
        # FIXME: Also check target uses VersionedFile
        return (isinstance(source, LocalGitRepository) and 
                target.supports_rich_root())