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

add basic test for tree_to_objects.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
 
1
# Copyright (C) 2008-2010 Jelmer Vernooij <jelmer@samba.org>
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
from cStringIO import (
18
 
    StringIO,
19
 
    )
20
 
import dulwich as git
21
 
from dulwich.client import (
22
 
    SimpleFetchGraphWalker,
23
 
    )
24
17
from dulwich.objects import (
25
18
    Commit,
26
19
    Tag,
 
20
    Tree,
 
21
    S_ISGITLINK,
27
22
    )
28
23
from dulwich.object_store import (
29
24
    tree_lookup_path,
30
25
    )
 
26
from itertools import (
 
27
    imap,
 
28
    )
 
29
import posixpath
 
30
import re
31
31
import stat
32
32
 
33
33
from bzrlib import (
35
35
    osutils,
36
36
    trace,
37
37
    ui,
38
 
    urlutils,
39
38
    )
40
39
from bzrlib.errors import (
41
 
    InvalidRevisionId,
 
40
    BzrError,
42
41
    NoSuchId,
43
 
    NoSuchRevision,
44
42
    )
45
43
from bzrlib.inventory import (
46
44
    Inventory,
47
45
    InventoryDirectory,
48
46
    InventoryFile,
49
47
    InventoryLink,
50
 
    )
51
 
from bzrlib.lru_cache import (
52
 
    LRUCache,
 
48
    TreeReference,
53
49
    )
54
50
from bzrlib.repository import (
55
51
    InterRepository,
57
53
from bzrlib.revision import (
58
54
    NULL_REVISION,
59
55
    )
 
56
from bzrlib.revisiontree import (
 
57
    RevisionTree,
 
58
    )
60
59
from bzrlib.tsort import (
61
60
    topo_sort,
62
61
    )
 
62
from bzrlib.versionedfile import (
 
63
    ChunkedContentFactory,
 
64
    )
63
65
 
64
 
from bzrlib.plugins.git.converter import (
65
 
    BazaarObjectStore,
66
 
    )
67
66
from bzrlib.plugins.git.mapping import (
68
67
    DEFAULT_FILE_MODE,
69
 
    inventory_to_tree_and_blobs,
70
 
    text_to_blob,
 
68
    mode_is_executable,
 
69
    mode_kind,
 
70
    warn_unusual_mode,
 
71
    )
 
72
from bzrlib.plugins.git.object_store import (
 
73
    BazaarObjectStore,
 
74
    LRUTreeCache,
 
75
    _tree_to_objects,
 
76
    )
 
77
from bzrlib.plugins.git.remote import (
 
78
    RemoteGitRepository,
71
79
    )
72
80
from bzrlib.plugins.git.repository import (
73
 
    LocalGitRepository, 
74
 
    GitRepository, 
 
81
    GitRepository,
75
82
    GitRepositoryFormat,
76
 
    )
77
 
from bzrlib.plugins.git.remote import (
78
 
    RemoteGitRepository,
79
 
    )
80
 
 
81
 
 
82
 
class BzrFetchGraphWalker(object):
83
 
    """GraphWalker implementation that uses a Bazaar repository."""
84
 
 
85
 
    def __init__(self, repository, mapping):
86
 
        self.repository = repository
87
 
        self.mapping = mapping
88
 
        self.done = set()
89
 
        self.heads = set(repository.all_revision_ids())
90
 
        self.parents = {}
91
 
 
92
 
    def __iter__(self):
93
 
        return iter(self.next, None)
94
 
 
95
 
    def ack(self, sha):
96
 
        revid = self.mapping.revision_id_foreign_to_bzr(sha)
97
 
        self.remove(revid)
98
 
 
99
 
    def remove(self, revid):
100
 
        self.done.add(revid)
101
 
        if revid in self.heads:
102
 
            self.heads.remove(revid)
103
 
        if revid in self.parents:
104
 
            for p in self.parents[revid]:
105
 
                self.remove(p)
106
 
 
107
 
    def next(self):
108
 
        while self.heads:
109
 
            ret = self.heads.pop()
110
 
            ps = self.repository.get_parent_map([ret])[ret]
111
 
            self.parents[ret] = ps
112
 
            self.heads.update([p for p in ps if not p in self.done])
113
 
            try:
114
 
                self.done.add(ret)
115
 
                return self.mapping.revision_id_bzr_to_foreign(ret)[0]
116
 
            except InvalidRevisionId:
117
 
                pass
118
 
        return None
119
 
 
120
 
 
121
 
def import_git_blob(texts, mapping, path, hexsha, base_inv, parent_id, 
122
 
    revision_id, parent_invs, shagitmap, lookup_object, executable, symlink):
 
83
    LocalGitRepository,
 
84
    )
 
85
 
 
86
 
 
87
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha), 
 
88
        base_inv, parent_id, revision_id,
 
89
        parent_invs, lookup_object, (base_mode, mode), store_updater,
 
90
        lookup_file_id):
123
91
    """Import a git blob object into a bzr repository.
124
92
 
125
93
    :param texts: VersionedFiles to add to
127
95
    :param blob: A git blob
128
96
    :return: Inventory delta for this file
129
97
    """
130
 
    file_id = mapping.generate_file_id(path)
131
 
    if symlink:
 
98
    if mapping.is_control_file(path):
 
99
        return []
 
100
    if base_hexsha == hexsha and base_mode == mode:
 
101
        # If nothing has changed since the base revision, we're done
 
102
        return []
 
103
    file_id = lookup_file_id(path)
 
104
    if stat.S_ISLNK(mode):
132
105
        cls = InventoryLink
133
106
    else:
134
107
        cls = InventoryFile
135
 
    # We just have to hope this is indeed utf-8:
136
 
    ie = cls(file_id, urlutils.basename(path).decode("utf-8"), parent_id)
137
 
    ie.executable = executable
138
 
    ie.text_id = hexsha
139
 
    # See if this has changed at all
140
 
    try:
141
 
        base_ie = base_inv[file_id]
142
 
    except NoSuchId:
143
 
        base_ie = None
144
 
        base_sha = None
145
 
    else:
146
 
        base_sha = base_ie.text_id
147
 
        try:
148
 
            if base_sha is None:
149
 
                base_sha = shagitmap.lookup_blob(file_id, base_ie.revision)
150
 
        except KeyError:
151
 
            base_sha = None
152
 
        else:
153
 
            if (base_sha == hexsha and base_ie.executable == ie.executable
154
 
                and base_ie.kind == ie.kind):
155
 
                # If nothing has changed since the base revision, we're done
156
 
                return [], []
157
 
    if base_sha == hexsha:
 
108
    ie = cls(file_id, name.decode("utf-8"), parent_id)
 
109
    if ie.kind == "file":
 
110
        ie.executable = mode_is_executable(mode)
 
111
    if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
 
112
        base_ie = base_inv[base_inv.path2id(path)]
158
113
        ie.text_size = base_ie.text_size
159
114
        ie.text_sha1 = base_ie.text_sha1
160
 
        ie.symlink_target = base_ie.symlink_target
161
 
        ie.revision = base_ie.revision
 
115
        if ie.kind == "symlink":
 
116
            ie.symlink_target = base_ie.symlink_target
 
117
        if ie.executable == base_ie.executable:
 
118
            ie.revision = base_ie.revision
 
119
        else:
 
120
            blob = lookup_object(hexsha)
162
121
    else:
163
122
        blob = lookup_object(hexsha)
164
123
        if ie.kind == "symlink":
 
124
            ie.revision = None
165
125
            ie.symlink_target = blob.data
166
 
            ie.text_size = None
167
 
            ie.text_sha1 = None
168
126
        else:
169
 
            ie.text_size = len(blob.data)
170
 
            ie.text_sha1 = osutils.sha_string(blob.data)
 
127
            ie.text_size = sum(imap(len, blob.chunked))
 
128
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
171
129
    # Check what revision we should store
172
130
    parent_keys = []
173
131
    for pinv in parent_invs:
174
 
        if pinv.revision_id == base_inv.revision_id:
175
 
            pie = base_ie
176
 
            if pie is None:
177
 
                continue
178
 
        else:
179
 
            try:
180
 
                pie = pinv[file_id]
181
 
            except NoSuchId:
182
 
                continue
183
 
        if pie.text_sha1 == ie.text_sha1:
 
132
        try:
 
133
            pie = pinv[file_id]
 
134
        except NoSuchId:
 
135
            continue
 
136
        if (pie.text_sha1 == ie.text_sha1 and
 
137
            pie.executable == ie.executable and
 
138
            pie.symlink_target == ie.symlink_target):
184
139
            # found a revision in one of the parents to use
185
140
            ie.revision = pie.revision
186
141
            break
187
 
        parent_keys.append((file_id, pie.revision))
 
142
        parent_key = (file_id, pie.revision)
 
143
        if not parent_key in parent_keys:
 
144
            parent_keys.append(parent_key)
188
145
    if ie.revision is None:
189
146
        # Need to store a new revision
190
147
        ie.revision = revision_id
191
 
        assert file_id is not None
192
148
        assert ie.revision is not None
193
 
        texts.add_lines((file_id, ie.revision), tuple(parent_keys),
194
 
            osutils.split_lines(blob.data))
195
 
        shamap = [(hexsha, "blob", (ie.file_id, ie.revision))]
196
 
    else:
197
 
        shamap = []
198
 
    if file_id in base_inv:
199
 
        old_path = base_inv.id2path(file_id)
 
149
        if ie.kind == 'symlink':
 
150
            chunks = []
 
151
        else: 
 
152
            chunks = blob.chunked
 
153
        texts.insert_record_stream([
 
154
            ChunkedContentFactory((file_id, ie.revision),
 
155
                tuple(parent_keys), ie.text_sha1, chunks)])
 
156
    invdelta = []
 
157
    if base_hexsha is not None:
 
158
        old_path = path.decode("utf-8") # Renames are not supported yet
 
159
        if stat.S_ISDIR(base_mode):
 
160
            invdelta.extend(remove_disappeared_children(base_inv, old_path,
 
161
                lookup_object(base_hexsha), [], lookup_object))
200
162
    else:
201
163
        old_path = None
202
 
    return ([(old_path, path, file_id, ie)], shamap)
203
 
 
204
 
 
205
 
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id, 
206
 
    revision_id, parent_invs, shagitmap, lookup_object):
 
164
    new_path = path.decode("utf-8")
 
165
    invdelta.append((old_path, new_path, file_id, ie))
 
166
    if base_hexsha != hexsha:
 
167
        store_updater.add_object(blob, ie, path)
 
168
    return invdelta
 
169
 
 
170
 
 
171
class SubmodulesRequireSubtrees(BzrError):
 
172
    _fmt = """The repository you are fetching from contains submodules. To continue, upgrade your Bazaar repository to a format that supports nested trees, such as 'development-subtree'."""
 
173
    internal = False
 
174
 
 
175
 
 
176
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
 
177
    base_inv, parent_id, revision_id, parent_invs, lookup_object,
 
178
    (base_mode, mode), store_updater, lookup_file_id):
 
179
    if base_hexsha == hexsha and base_mode == mode:
 
180
        return [], {}
 
181
    file_id = lookup_file_id(path)
 
182
    ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
 
183
    ie.revision = revision_id
 
184
    if base_hexsha is None:
 
185
        oldpath = None
 
186
    else:
 
187
        oldpath = path
 
188
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
 
189
    texts.insert_record_stream([
 
190
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
 
191
    invdelta = [(oldpath, path, file_id, ie)]
 
192
    return invdelta, {}
 
193
 
 
194
 
 
195
def remove_disappeared_children(base_inv, path, base_tree, existing_children,
 
196
        lookup_object):
 
197
    """Generate an inventory delta for removed children.
 
198
 
 
199
    :param base_inv: Base inventory against which to generate the 
 
200
        inventory delta.
 
201
    :param path: Path to process (unicode)
 
202
    :param base_tree: Git Tree base object
 
203
    :param existing_children: Children that still exist
 
204
    :param lookup_object: Lookup a git object by its SHA1
 
205
    :return: Inventory delta, as list
 
206
    """
 
207
    assert type(path) is unicode
 
208
    ret = []
 
209
    for name, mode, hexsha in base_tree.iteritems():
 
210
        if name in existing_children:
 
211
            continue
 
212
        c_path = posixpath.join(path, name.decode("utf-8"))
 
213
        file_id = base_inv.path2id(c_path)
 
214
        assert file_id is not None
 
215
        ret.append((c_path, None, file_id, None))
 
216
        if stat.S_ISDIR(mode):
 
217
            ret.extend(remove_disappeared_children(
 
218
                base_inv, c_path, lookup_object(hexsha), [], lookup_object))
 
219
    return ret
 
220
 
 
221
 
 
222
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
 
223
        base_inv, parent_id, revision_id, parent_invs,
 
224
        lookup_object, (base_mode, mode), store_updater,
 
225
        lookup_file_id, allow_submodules=False):
207
226
    """Import a git tree object into a bzr repository.
208
227
 
209
228
    :param texts: VersionedFiles object to add to
210
 
    :param path: Path in the tree
 
229
    :param path: Path in the tree (str)
 
230
    :param name: Name of the tree (str)
211
231
    :param tree: A git tree object
212
232
    :param base_inv: Base inventory against which to return inventory delta
213
233
    :return: Inventory delta for this subtree
214
234
    """
 
235
    assert type(path) is str
 
236
    assert type(name) is str
 
237
    if base_hexsha == hexsha and base_mode == mode:
 
238
        # If nothing has changed since the base revision, we're done
 
239
        return [], {}
215
240
    invdelta = []
216
 
    file_id = mapping.generate_file_id(path)
 
241
    file_id = lookup_file_id(path)
217
242
    # We just have to hope this is indeed utf-8:
218
 
    ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")), 
219
 
        parent_id)
220
 
    ie.text_id = hexsha
221
 
    try:
222
 
        base_ie = base_inv[file_id]
223
 
    except NoSuchId:
224
 
        # Newly appeared here
225
 
        base_ie = None
 
243
    ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
 
244
    tree = lookup_object(hexsha)
 
245
    if base_hexsha is None:
 
246
        base_tree = None
 
247
        old_path = None # Newly appeared here
 
248
    else:
 
249
        base_tree = lookup_object(base_hexsha)
 
250
        old_path = path.decode("utf-8") # Renames aren't supported yet
 
251
    new_path = path.decode("utf-8")
 
252
    if base_tree is None or type(base_tree) is not Tree:
226
253
        ie.revision = revision_id
227
 
        texts.add_lines((file_id, ie.revision), (), [])
228
 
        invdelta.append((None, path, file_id, ie))
229
 
    else:
230
 
        base_sha = base_ie.text_id
231
 
        # See if this has changed at all
232
 
        try:
233
 
            if base_sha is None:
234
 
                base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
235
 
        except KeyError:
236
 
            pass
237
 
        else:
238
 
            if base_sha == hexsha:
239
 
                # If nothing has changed since the base revision, we're done
240
 
                return [], {}, []
 
254
        invdelta.append((old_path, new_path, ie.file_id, ie))
 
255
        texts.insert_record_stream([
 
256
            ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
241
257
    # Remember for next time
242
258
    existing_children = set()
243
259
    child_modes = {}
244
 
    shamap = []
245
 
    tree = lookup_object(hexsha)
246
 
    for mode, name, child_hexsha in tree.entries():
247
 
        basename = name.decode("utf-8")
248
 
        existing_children.add(basename)
249
 
        child_path = osutils.pathjoin(path, name)
250
 
        if stat.S_ISDIR(mode):
251
 
            subinvdelta, grandchildmodes, subshamap = import_git_tree(texts, 
252
 
                    mapping, child_path, child_hexsha, base_inv, file_id, 
253
 
                    revision_id, parent_invs, shagitmap, lookup_object)
254
 
            invdelta.extend(subinvdelta)
255
 
            child_modes.update(grandchildmodes)
256
 
            shamap.extend(subshamap)
257
 
        else:
258
 
            fs_mode = stat.S_IMODE(mode)
259
 
            symlink = stat.S_ISLNK(mode)
260
 
            subinvdelta, subshamap = import_git_blob(texts, mapping, 
261
 
                    child_path, child_hexsha, base_inv, file_id, revision_id, 
262
 
                    parent_invs, shagitmap, lookup_object, 
263
 
                    bool(fs_mode & 0111), symlink)
264
 
            invdelta.extend(subinvdelta)
265
 
            shamap.extend(subshamap)
266
 
        if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
 
260
    for child_mode, name, child_hexsha in tree.entries():
 
261
        existing_children.add(name)
 
262
        child_path = posixpath.join(path, name)
 
263
        if type(base_tree) is Tree:
 
264
            try:
 
265
                child_base_mode, child_base_hexsha = base_tree[name]
 
266
            except KeyError:
 
267
                child_base_hexsha = None
 
268
                child_base_mode = 0
 
269
        else:
 
270
            child_base_hexsha = None
 
271
            child_base_mode = 0
 
272
        if stat.S_ISDIR(child_mode):
 
273
            subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
 
274
                child_path, name, (child_base_hexsha, child_hexsha), base_inv,
 
275
                file_id, revision_id, parent_invs, lookup_object, 
 
276
                (child_base_mode, child_mode), store_updater, lookup_file_id,
 
277
                allow_submodules=allow_submodules)
 
278
        elif S_ISGITLINK(child_mode): # submodule
 
279
            if not allow_submodules:
 
280
                raise SubmodulesRequireSubtrees()
 
281
            subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
 
282
                child_path, name, (child_base_hexsha, child_hexsha), base_inv,
 
283
                file_id, revision_id, parent_invs, lookup_object,
 
284
                (child_base_mode, child_mode), store_updater, lookup_file_id)
 
285
        else:
 
286
            subinvdelta = import_git_blob(texts, mapping, child_path, name,
 
287
                (child_base_hexsha, child_hexsha), base_inv, file_id,
 
288
                revision_id, parent_invs, lookup_object,
 
289
                (child_base_mode, child_mode), store_updater, lookup_file_id)
 
290
            grandchildmodes = {}
 
291
        child_modes.update(grandchildmodes)
 
292
        invdelta.extend(subinvdelta)
 
293
        if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
267
294
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
268
 
            child_modes[child_path] = mode
 
295
            child_modes[child_path] = child_mode
269
296
    # Remove any children that have disappeared
270
 
    if base_ie is not None:
271
 
        deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
272
 
        while deletable:
273
 
            ie = deletable.pop()
274
 
            invdelta.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
275
 
            if ie.kind == "directory":
276
 
                deletable.extend(ie.children.values())
277
 
    shamap.append((hexsha, "tree", (file_id, revision_id)))
278
 
    return invdelta, child_modes, shamap
279
 
 
280
 
 
281
 
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever, 
282
 
        heads, pb=None):
 
297
    if base_tree is not None and type(base_tree) is Tree:
 
298
        invdelta.extend(remove_disappeared_children(base_inv, old_path,
 
299
            base_tree, existing_children, lookup_object))
 
300
    store_updater.add_object(tree, ie, path)
 
301
    return invdelta, child_modes
 
302
 
 
303
 
 
304
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
 
305
    o, rev, ret_tree, parent_trees, mapping, unusual_modes):
 
306
    new_unusual_modes = mapping.export_unusual_file_modes(rev)
 
307
    if new_unusual_modes != unusual_modes:
 
308
        raise AssertionError("unusual modes don't match: %r != %r" % (
 
309
            unusual_modes, new_unusual_modes))
 
310
    # Verify that we can reconstruct the commit properly
 
311
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True)
 
312
    if rec_o != o:
 
313
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
 
314
            rec_o, o))
 
315
    diff = []
 
316
    new_objs = {}
 
317
    for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
 
318
        target_git_object_retriever._cache.idmap, unusual_modes, mapping.BZR_DUMMY_FILE):
 
319
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
 
320
        new_objs[path] = obj
 
321
        if obj.id != old_obj_id:
 
322
            diff.append((path, lookup_object(old_obj_id), obj))
 
323
    for (path, old_obj, new_obj) in diff:
 
324
        while (old_obj.type_name == "tree" and
 
325
               new_obj.type_name == "tree" and
 
326
               sorted(old_obj) == sorted(new_obj)):
 
327
            for name in old_obj:
 
328
                if old_obj[name][0] != new_obj[name][0]:
 
329
                    raise AssertionError("Modes for %s differ: %o != %o" %
 
330
                        (path, old_obj[name][0], new_obj[name][0]))
 
331
                if old_obj[name][1] != new_obj[name][1]:
 
332
                    # Found a differing child, delve deeper
 
333
                    path = posixpath.join(path, name)
 
334
                    old_obj = lookup_object(old_obj[name][1])
 
335
                    new_obj = new_objs[path]
 
336
                    break
 
337
        raise AssertionError("objects differ for %s: %r != %r" % (path,
 
338
            old_obj, new_obj))
 
339
 
 
340
 
 
341
def import_git_commit(repo, mapping, head, lookup_object,
 
342
                      target_git_object_retriever, trees_cache):
 
343
    o = lookup_object(head)
 
344
    rev = mapping.import_commit(o,
 
345
            lambda x: target_git_object_retriever.lookup_git_sha(x)[1][0])
 
346
    # We have to do this here, since we have to walk the tree and
 
347
    # we need to make sure to import the blobs / trees with the right
 
348
    # path; this may involve adding them more than once.
 
349
    parent_trees = trees_cache.revision_trees(rev.parent_ids)
 
350
    if parent_trees == []:
 
351
        base_inv = Inventory(root_id=None)
 
352
        base_tree = None
 
353
        base_mode = None
 
354
    else:
 
355
        base_inv = parent_trees[0].inventory
 
356
        base_tree = lookup_object(o.parents[0]).tree
 
357
        base_mode = stat.S_IFDIR
 
358
    store_updater = target_git_object_retriever._get_updater(rev)
 
359
    store_updater.add_object(o, None, None)
 
360
    fileid_map = mapping.get_fileid_map(lookup_object, o.tree)
 
361
    inv_delta, unusual_modes = import_git_tree(repo.texts,
 
362
            mapping, "", "", (base_tree, o.tree), base_inv,
 
363
            None, rev.revision_id, [p.inventory for p in parent_trees],
 
364
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
 
365
            fileid_map.lookup_file_id,
 
366
            allow_submodules=getattr(repo._format, "supports_tree_reference", False))
 
367
    store_updater.finish()
 
368
    if unusual_modes != {}:
 
369
        for path, mode in unusual_modes.iteritems():
 
370
            warn_unusual_mode(rev.foreign_revid, path, mode)
 
371
        mapping.import_unusual_file_modes(rev, unusual_modes)
 
372
    try:
 
373
        basis_id = rev.parent_ids[0]
 
374
    except IndexError:
 
375
        basis_id = NULL_REVISION
 
376
        base_inv = None
 
377
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
378
              inv_delta, rev.revision_id, rev.parent_ids, base_inv)
 
379
    ret_tree = RevisionTree(repo, inv, rev.revision_id)
 
380
    trees_cache.add(ret_tree)
 
381
    repo.add_revision(rev.revision_id, rev)
 
382
    if "verify" in debug.debug_flags:
 
383
        verify_commit_reconstruction(target_git_object_retriever, 
 
384
            lookup_object, o, rev, ret_tree, parent_trees, mapping,
 
385
            unusual_modes)
 
386
 
 
387
 
 
388
def import_git_objects(repo, mapping, object_iter,
 
389
    target_git_object_retriever, heads, pb=None, limit=None):
283
390
    """Import a set of git objects into a bzr repository.
284
391
 
285
 
    :param repo: Bazaar repository
 
392
    :param repo: Target Bazaar repository
286
393
    :param mapping: Mapping to use
287
394
    :param object_iter: Iterator over Git objects.
 
395
    :return: Tuple with pack hints and last imported revision id
288
396
    """
289
 
    # TODO: a more (memory-)efficient implementation of this
 
397
    def lookup_object(sha):
 
398
        try:
 
399
            return object_iter[sha]
 
400
        except KeyError:
 
401
            return target_git_object_retriever[sha]
290
402
    graph = []
291
 
    root_trees = {}
292
 
    revisions = {}
293
403
    checked = set()
294
 
    heads = list(heads)
295
 
    parent_invs_cache = LRUCache(50)
 
404
    heads = list(set(heads))
 
405
    trees_cache = LRUTreeCache(repo)
296
406
    # Find and convert commit objects
297
407
    while heads:
298
408
        if pb is not None:
300
410
        head = heads.pop()
301
411
        assert isinstance(head, str)
302
412
        try:
303
 
            o = object_iter[head]
 
413
            o = lookup_object(head)
304
414
        except KeyError:
305
415
            continue
306
416
        if isinstance(o, Commit):
307
 
            rev = mapping.import_commit(o)
 
417
            rev = mapping.import_commit(o, lambda x: None)
308
418
            if repo.has_revision(rev.revision_id):
309
419
                continue
310
 
            root_trees[rev.revision_id] = o.tree
311
 
            revisions[rev.revision_id] = rev
312
 
            graph.append((rev.revision_id, rev.parent_ids))
313
 
            target_git_object_retriever._idmap.add_entry(o.id, "commit", 
314
 
                    (rev.revision_id, o.tree))
 
420
            graph.append((o.id, o.parents))
315
421
            heads.extend([p for p in o.parents if p not in checked])
316
422
        elif isinstance(o, Tag):
317
 
            heads.append(o.object[1])
 
423
            if o.object[1] not in checked:
 
424
                heads.append(o.object[1])
318
425
        else:
319
426
            trace.warning("Unable to import head object %r" % o)
320
 
        checked.add(head)
 
427
        checked.add(o.id)
 
428
    del checked
321
429
    # Order the revisions
322
430
    # Create the inventory objects
323
 
    for i, revid in enumerate(topo_sort(graph)):
324
 
        if pb is not None:
325
 
            pb.update("fetching revisions", i, len(graph))
326
 
        rev = revisions[revid]
327
 
        # We have to do this here, since we have to walk the tree and 
328
 
        # we need to make sure to import the blobs / trees with the right 
329
 
        # path; this may involve adding them more than once.
330
 
        def lookup_object(sha):
331
 
            try:
332
 
                return object_iter[sha]
333
 
            except KeyError:
334
 
                return target_git_object_retriever[sha]
335
 
        parent_invs = []
336
 
        for parent_id in rev.parent_ids:
337
 
            try:
338
 
                parent_invs.append(parent_invs_cache[parent_id])
339
 
            except KeyError:
340
 
                parent_inv = repo.get_inventory(parent_id)
341
 
                parent_invs.append(parent_inv)
342
 
                parent_invs_cache[parent_id] = parent_inv
343
 
        if parent_invs == []:
344
 
            base_inv = Inventory(root_id=None)
 
431
    batch_size = 1000
 
432
    revision_ids = topo_sort(graph)
 
433
    pack_hints = []
 
434
    if limit is not None:
 
435
        revision_ids = revision_ids[:limit]
 
436
    last_imported = None
 
437
    for offset in range(0, len(revision_ids), batch_size):
 
438
        target_git_object_retriever.start_write_group() 
 
439
        try:
 
440
            repo.start_write_group()
 
441
            try:
 
442
                for i, head in enumerate(
 
443
                    revision_ids[offset:offset+batch_size]):
 
444
                    if pb is not None:
 
445
                        pb.update("fetching revisions", offset+i,
 
446
                                  len(revision_ids))
 
447
                    import_git_commit(repo, mapping, head, lookup_object,
 
448
                        target_git_object_retriever, trees_cache)
 
449
                    last_imported = head
 
450
            except:
 
451
                repo.abort_write_group()
 
452
                raise
 
453
            else:
 
454
                hint = repo.commit_write_group()
 
455
                if hint is not None:
 
456
                    pack_hints.extend(hint)
 
457
        except:
 
458
            target_git_object_retriever.abort_write_group()
 
459
            raise
345
460
        else:
346
 
            base_inv = parent_invs[0]
347
 
        inv_delta, unusual_modes, shamap = import_git_tree(repo.texts, 
348
 
                mapping, "", root_trees[revid], base_inv, None, revid, 
349
 
                parent_invs, target_git_object_retriever._idmap, lookup_object)
350
 
        target_git_object_retriever._idmap.add_entries(shamap)
351
 
        if unusual_modes != {}:
352
 
            ret = "unusual modes: \n"
353
 
            for item in unusual_modes.iteritems():
354
 
                ret += "\t%s: %o\n" % item
355
 
            raise AssertionError(ret)
356
 
        try:
357
 
            basis_id = rev.parent_ids[0]
358
 
        except IndexError:
359
 
            basis_id = NULL_REVISION
360
 
        rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
361
 
                  inv_delta, rev.revision_id, rev.parent_ids)
362
 
        parent_invs_cache[rev.revision_id] = inv
363
 
        repo.add_revision(rev.revision_id, rev)
364
 
        if "verify" in debug.debug_flags:
365
 
            objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping)
366
 
            for sha1, newobj, path in objs:
367
 
                assert path is not None
368
 
                oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
369
 
                assert oldobj == newobj, "%r != %r in %s" % (oldobj, newobj, path)
370
 
 
371
 
    target_git_object_retriever._idmap.commit()
372
 
 
373
 
 
374
 
class InterGitNonGitRepository(InterRepository):
375
 
    """Base InterRepository that copies revisions from a Git into a non-Git 
376
 
    repository."""
 
461
            target_git_object_retriever.commit_write_group()
 
462
    return pack_hints, last_imported
 
463
 
 
464
 
 
465
class InterGitRepository(InterRepository):
377
466
 
378
467
    _matching_repo_format = GitRepositoryFormat()
379
468
 
385
474
        """See InterRepository.copy_content."""
386
475
        self.fetch(revision_id, pb, find_ghosts=False)
387
476
 
388
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, mapping=None,
389
 
            fetch_spec=None):
390
 
        self.fetch_refs(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts,
391
 
                mapping=mapping, fetch_spec=fetch_spec)
392
 
 
393
 
    def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False, 
 
477
 
 
478
class InterGitNonGitRepository(InterGitRepository):
 
479
    """Base InterRepository that copies revisions from a Git into a non-Git
 
480
    repository."""
 
481
 
 
482
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
483
        """Fetch objects from a remote server.
 
484
 
 
485
        :param determine_wants: determine_wants callback
 
486
        :param mapping: BzrGitMapping to use
 
487
        :param pb: Optional progress bar
 
488
        :param limit: Maximum number of commits to import.
 
489
        :return: Tuple with pack hint, last imported revision id and remote refs
 
490
        """
 
491
        raise NotImplementedError(self.fetch_objects)
 
492
 
 
493
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
394
494
              mapping=None, fetch_spec=None):
395
495
        if mapping is None:
396
496
            mapping = self.source.get_mapping()
400
500
            interesting_heads = fetch_spec.heads
401
501
        else:
402
502
            interesting_heads = None
403
 
        self._refs = {}
404
503
        def determine_wants(refs):
405
 
            self._refs = refs
406
504
            if interesting_heads is None:
407
505
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
408
506
            else:
409
 
                ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid != NULL_REVISION]
410
 
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
411
 
        self.fetch_objects(determine_wants, mapping, pb)
412
 
        return self._refs
413
 
 
 
507
                ret = [self.source.lookup_bzr_revision_id(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
 
508
            return [rev for rev in ret if not self.target.has_revision(self.source.lookup_foreign_revision_id(rev))]
 
509
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants, mapping, pb)
 
510
        if pack_hint is not None and self.target._format.pack_compresses:
 
511
            self.target.pack(hint=pack_hint)
 
512
        return remote_refs
 
513
 
 
514
 
 
515
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
 
516
def report_git_progress(pb, text):
 
517
    text = text.rstrip("\r\n")
 
518
    g = _GIT_PROGRESS_RE.match(text)
 
519
    if g is not None:
 
520
        (text, pct, current, total) = g.groups()
 
521
        pb.update(text, int(current), int(total))
 
522
    else:
 
523
        pb.update(text, 0, 0)
 
524
 
 
525
 
 
526
class DetermineWantsRecorder(object):
 
527
 
 
528
    def __init__(self, actual):
 
529
        self.actual = actual
 
530
        self.wants = []
 
531
        self.remote_refs = {}
 
532
 
 
533
    def __call__(self, refs):
 
534
        self.remote_refs = refs
 
535
        self.wants = self.actual(refs)
 
536
        return self.wants
414
537
 
415
538
 
416
539
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
417
 
    """InterRepository that copies revisions from a remote Git into a non-Git 
 
540
    """InterRepository that copies revisions from a remote Git into a non-Git
418
541
    repository."""
419
542
 
420
 
    def fetch_objects(self, determine_wants, mapping, pb=None):
 
543
    def get_target_heads(self):
 
544
        # FIXME: This should be more efficient
 
545
        all_revs = self.target.all_revision_ids()
 
546
        parent_map = self.target.get_parent_map(all_revs)
 
547
        all_parents = set()
 
548
        map(all_parents.update, parent_map.itervalues())
 
549
        return set(all_revs) - all_parents
 
550
 
 
551
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
552
        """See `InterGitNonGitRepository`."""
421
553
        def progress(text):
422
 
            pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
423
 
        graph_walker = BzrFetchGraphWalker(self.target, mapping)
424
 
        create_pb = None
425
 
        if pb is None:
426
 
            create_pb = pb = ui.ui_factory.nested_progress_bar()
427
 
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
428
 
        recorded_wants = []
429
 
 
430
 
        def record_determine_wants(heads):
431
 
            wants = determine_wants(heads)
432
 
            recorded_wants.extend(wants)
433
 
            return wants
434
 
        
 
554
            report_git_progress(pb, text)
 
555
        store = BazaarObjectStore(self.target, mapping)
 
556
        self.target.lock_write()
435
557
        try:
436
 
            self.target.lock_write()
 
558
            heads = self.get_target_heads()
 
559
            graph_walker = store.get_graph_walker(
 
560
                    [store._lookup_revision_sha1(head) for head in heads])
 
561
            wants_recorder = DetermineWantsRecorder(determine_wants)
 
562
 
 
563
            create_pb = None
 
564
            if pb is None:
 
565
                create_pb = pb = ui.ui_factory.nested_progress_bar()
437
566
            try:
438
 
                self.target.start_write_group()
439
 
                try:
440
 
                    objects_iter = self.source.fetch_objects(
441
 
                                record_determine_wants, 
442
 
                                graph_walker, 
443
 
                                target_git_object_retriever.get_raw, 
444
 
                                progress)
445
 
                    import_git_objects(self.target, mapping, objects_iter, 
446
 
                            target_git_object_retriever, recorded_wants, pb)
447
 
                finally:
448
 
                    self.target.commit_write_group()
 
567
                objects_iter = self.source.fetch_objects(
 
568
                    wants_recorder, graph_walker, store.get_raw,
 
569
                    progress)
 
570
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
 
571
                    objects_iter, store, wants_recorder.wants, pb, limit)
 
572
                return (pack_hint, last_rev, wants_recorder.remote_refs)
449
573
            finally:
450
 
                self.target.unlock()
 
574
                if create_pb:
 
575
                    create_pb.finished()
451
576
        finally:
452
 
            if create_pb:
453
 
                create_pb.finished()
 
577
            self.target.unlock()
454
578
 
455
579
    @staticmethod
456
580
    def is_compatible(source, target):
457
581
        """Be compatible with GitRepository."""
458
 
        # FIXME: Also check target uses VersionedFile
459
 
        return (isinstance(source, RemoteGitRepository) and 
 
582
        return (isinstance(source, RemoteGitRepository) and
460
583
                target.supports_rich_root() and
461
 
                not isinstance(target, GitRepository))
 
584
                not isinstance(target, GitRepository) and
 
585
                target.texts is not None)
462
586
 
463
587
 
464
588
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
465
 
    """InterRepository that copies revisions from a remote Git into a non-Git 
 
589
    """InterRepository that copies revisions from a local Git into a non-Git
466
590
    repository."""
467
591
 
468
 
    def fetch_objects(self, determine_wants, mapping, pb=None):
469
 
        wants = determine_wants(self.source._git.get_refs())
 
592
    def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
 
593
        """See `InterGitNonGitRepository`."""
 
594
        remote_refs = self.source._git.get_refs()
 
595
        wants = determine_wants(remote_refs)
470
596
        create_pb = None
471
597
        if pb is None:
472
598
            create_pb = pb = ui.ui_factory.nested_progress_bar()
474
600
        try:
475
601
            self.target.lock_write()
476
602
            try:
477
 
                self.target.start_write_group()
478
 
                try:
479
 
                    import_git_objects(self.target, mapping, 
480
 
                            self.source._git.object_store, 
481
 
                            target_git_object_retriever, wants, pb)
482
 
                finally:
483
 
                    self.target.commit_write_group()
 
603
                (pack_hint, last_rev) = import_git_objects(self.target, mapping,
 
604
                    self.source._git.object_store,
 
605
                    target_git_object_retriever, wants, pb, limit)
 
606
                return (pack_hint, last_rev, remote_refs)
484
607
            finally:
485
608
                self.target.unlock()
486
609
        finally:
490
613
    @staticmethod
491
614
    def is_compatible(source, target):
492
615
        """Be compatible with GitRepository."""
493
 
        # FIXME: Also check target uses VersionedFile
494
 
        return (isinstance(source, LocalGitRepository) and 
 
616
        return (isinstance(source, LocalGitRepository) and
495
617
                target.supports_rich_root() and
496
 
                not isinstance(target, GitRepository))
497
 
 
498
 
 
499
 
class InterGitRepository(InterRepository):
 
618
                not isinstance(target, GitRepository) and
 
619
                target.texts is not None)
 
620
 
 
621
 
 
622
class InterGitGitRepository(InterGitRepository):
500
623
    """InterRepository that copies between Git repositories."""
501
624
 
502
 
    _matching_repo_format = GitRepositoryFormat()
503
 
 
504
 
    @staticmethod
505
 
    def _get_repo_format_to_test():
506
 
        return None
507
 
 
508
 
    def copy_content(self, revision_id=None, pb=None):
509
 
        """See InterRepository.copy_content."""
510
 
        self.fetch(revision_id, pb, find_ghosts=False)
511
 
 
512
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, 
513
 
              mapping=None, fetch_spec=None):
 
625
    def fetch_objects(self, determine_wants, mapping, pb=None):
 
626
        def progress(text):
 
627
            trace.note("git: %s", text)
 
628
        graphwalker = self.target._git.get_graph_walker()
 
629
        if (isinstance(self.source, LocalGitRepository) and
 
630
            isinstance(self.target, LocalGitRepository)):
 
631
            refs = self.source._git.fetch(self.target._git, determine_wants,
 
632
                progress)
 
633
            return (None, None, refs)
 
634
        elif (isinstance(self.source, LocalGitRepository) and
 
635
              isinstance(self.target, RemoteGitRepository)):
 
636
            raise NotImplementedError
 
637
        elif (isinstance(self.source, RemoteGitRepository) and
 
638
              isinstance(self.target, LocalGitRepository)):
 
639
            f, commit = self.target._git.object_store.add_thin_pack()
 
640
            try:
 
641
                refs = self.source.bzrdir.root_transport.fetch_pack(
 
642
                    determine_wants, graphwalker, f.write, progress)
 
643
                commit()
 
644
                return (None, None, refs)
 
645
            except:
 
646
                f.close()
 
647
                raise
 
648
        else:
 
649
            raise AssertionError
 
650
 
 
651
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
652
              mapping=None, fetch_spec=None, branches=None):
514
653
        if mapping is None:
515
654
            mapping = self.source.get_mapping()
516
 
        def progress(text):
517
 
            trace.info("git: %s", text)
518
655
        r = self.target._git
519
656
        if revision_id is not None:
520
657
            args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]
521
658
        elif fetch_spec is not None:
522
659
            args = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in fetch_spec.heads]
523
 
        if fetch_spec is None and revision_id is None:
 
660
        if branches is not None:
 
661
            determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store]
 
662
        elif fetch_spec is None and revision_id is None:
524
663
            determine_wants = r.object_store.determine_wants_all
525
664
        else:
526
665
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
527
 
 
528
 
        graphwalker = SimpleFetchGraphWalker(r.heads().values(), r.get_parents)
529
 
        f, commit = r.object_store.add_thin_pack()
530
 
        try:
531
 
            self.source.fetch_pack(determine_wants, graphwalker, f.write, progress)
532
 
            commit()
533
 
        except:
534
 
            f.close()
535
 
            raise
 
666
        self.fetch_objects(determine_wants, mapping)
536
667
 
537
668
    @staticmethod
538
669
    def is_compatible(source, target):
539
670
        """Be compatible with GitRepository."""
540
 
        return (isinstance(source, GitRepository) and 
 
671
        return (isinstance(source, GitRepository) and
541
672
                isinstance(target, GitRepository))