/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

Support pushing from git -> empty git repo.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008 Canonical Ltd
 
1
# Copyright (C) 2008 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 bzrlib import osutils, ui, urlutils
18
 
from bzrlib.errors import InvalidRevisionId
19
 
from bzrlib.inventory import Inventory
20
 
from bzrlib.repository import InterRepository
21
 
from bzrlib.trace import info
22
 
from bzrlib.tsort import topo_sort
23
 
 
24
 
from bzrlib.plugins.git import git
 
17
from cStringIO import (
 
18
    StringIO,
 
19
    )
 
20
import dulwich as git
 
21
from dulwich.objects import (
 
22
    Commit,
 
23
    Tag,
 
24
    S_ISGITLINK,
 
25
    )
 
26
from dulwich.object_store import (
 
27
    tree_lookup_path,
 
28
    )
 
29
import stat
 
30
 
 
31
from bzrlib import (
 
32
    debug,
 
33
    osutils,
 
34
    trace,
 
35
    ui,
 
36
    urlutils,
 
37
    )
 
38
from bzrlib.errors import (
 
39
    InvalidRevisionId,
 
40
    NoSuchId,
 
41
    NoSuchRevision,
 
42
    )
 
43
from bzrlib.inventory import (
 
44
    Inventory,
 
45
    InventoryDirectory,
 
46
    InventoryFile,
 
47
    InventoryLink,
 
48
    )
 
49
from bzrlib.lru_cache import (
 
50
    LRUCache,
 
51
    )
 
52
from bzrlib.repository import (
 
53
    InterRepository,
 
54
    )
 
55
from bzrlib.revision import (
 
56
    NULL_REVISION,
 
57
    )
 
58
from bzrlib.tsort import (
 
59
    topo_sort,
 
60
    )
 
61
from bzrlib.versionedfile import (
 
62
    FulltextContentFactory,
 
63
    )
 
64
 
 
65
from bzrlib.plugins.git.mapping import (
 
66
    DEFAULT_FILE_MODE,
 
67
    inventory_to_tree_and_blobs,
 
68
    mode_is_executable,
 
69
    text_to_blob,
 
70
    warn_unusual_mode,
 
71
    )
 
72
from bzrlib.plugins.git.object_store import (
 
73
    BazaarObjectStore,
 
74
    )
 
75
from bzrlib.plugins.git.remote import (
 
76
    RemoteGitRepository,
 
77
    )
25
78
from bzrlib.plugins.git.repository import (
26
 
        LocalGitRepository, 
27
 
        GitRepository, 
28
 
        GitFormat,
29
 
        )
30
 
from bzrlib.plugins.git.remote import RemoteGitRepository
31
 
 
32
 
from dulwich.client import SimpleFetchGraphWalker
33
 
from dulwich.objects import Commit
34
 
 
35
 
from cStringIO import StringIO
36
 
 
37
 
 
38
 
class BzrFetchGraphWalker(object):
39
 
 
40
 
    def __init__(self, repository, mapping):
41
 
        self.repository = repository
42
 
        self.mapping = mapping
43
 
        self.done = set()
44
 
        self.heads = set(repository.all_revision_ids())
45
 
        self.parents = {}
46
 
 
47
 
    def ack(self, sha):
48
 
        revid = self.mapping.revision_id_foreign_to_bzr(sha)
49
 
        self.remove(revid)
50
 
 
51
 
    def remove(self, revid):
52
 
        self.done.add(revid)
53
 
        if revid in self.heads:
54
 
            self.heads.remove(revid)
55
 
        if revid in self.parents:
56
 
            for p in self.parents[revid]:
57
 
                self.remove(p)
58
 
 
59
 
    def next(self):
60
 
        while self.heads:
61
 
            ret = self.heads.pop()
62
 
            ps = self.repository.get_parent_map([ret])[ret]
63
 
            self.parents[ret] = ps
64
 
            self.heads.update([p for p in ps if not p in self.done])
65
 
            try:
66
 
                self.done.add(ret)
67
 
                return self.mapping.revision_id_bzr_to_foreign(ret)
68
 
            except InvalidRevisionId:
69
 
                pass
70
 
        return None
71
 
 
72
 
 
73
 
def import_git_blob(repo, mapping, path, blob, inv, parent_invs, executable):
 
79
    GitRepository, 
 
80
    GitRepositoryFormat,
 
81
    LocalGitRepository,
 
82
    )
 
83
 
 
84
 
 
85
def import_git_blob(texts, mapping, path, hexsha, base_inv, parent_id, 
 
86
    revision_id, parent_invs, shagitmap, lookup_object, executable, symlink):
74
87
    """Import a git blob object into a bzr repository.
75
88
 
76
 
    :param repo: bzr repository
 
89
    :param texts: VersionedFiles to add to
77
90
    :param path: Path in the tree
78
91
    :param blob: A git blob
 
92
    :return: Inventory delta for this file
79
93
    """
80
94
    file_id = mapping.generate_file_id(path)
81
 
    text_revision = inv.revision_id
82
 
    repo.texts.add_lines((file_id, text_revision),
83
 
        [(file_id, p[file_id].revision) for p in parent_invs if file_id in p],
84
 
        osutils.split_lines(blob.data))
85
 
    ie = inv.add_path(path, "file", file_id)
86
 
    ie.revision = text_revision
87
 
    ie.text_size = len(blob.data)
88
 
    ie.text_sha1 = osutils.sha_string(blob.data)
 
95
    if symlink:
 
96
        cls = InventoryLink
 
97
    else:
 
98
        cls = InventoryFile
 
99
    # We just have to hope this is indeed utf-8:
 
100
    ie = cls(file_id, urlutils.basename(path).decode("utf-8"), parent_id)
89
101
    ie.executable = executable
90
 
 
91
 
 
92
 
def import_git_tree(repo, mapping, path, tree, inv, parent_invs, lookup_object):
 
102
    ie.text_id = hexsha
 
103
    # See if this has changed at all
 
104
    try:
 
105
        base_ie = base_inv[file_id]
 
106
    except NoSuchId:
 
107
        base_ie = None
 
108
        base_sha = None
 
109
    else:
 
110
        base_sha = base_ie.text_id
 
111
        try:
 
112
            if base_sha is None:
 
113
                base_sha = shagitmap.lookup_blob(file_id, base_ie.revision)
 
114
        except KeyError:
 
115
            base_sha = None
 
116
        else:
 
117
            if (base_sha == hexsha and base_ie.executable == ie.executable
 
118
                and base_ie.kind == ie.kind):
 
119
                # If nothing has changed since the base revision, we're done
 
120
                return [], []
 
121
    if base_sha == hexsha and base_ie.kind == ie.kind:
 
122
        ie.text_size = base_ie.text_size
 
123
        ie.text_sha1 = base_ie.text_sha1
 
124
        ie.symlink_target = base_ie.symlink_target
 
125
        if ie.executable == base_ie.executable:
 
126
            ie.revision = base_ie.revision
 
127
        else:
 
128
            blob = lookup_object(hexsha)
 
129
    else:
 
130
        blob = lookup_object(hexsha)
 
131
        if ie.kind == "symlink":
 
132
            ie.symlink_target = blob.data
 
133
            ie.text_size = None
 
134
            ie.text_sha1 = None
 
135
        else:
 
136
            ie.text_size = len(blob.data)
 
137
            ie.text_sha1 = osutils.sha_string(blob.data)
 
138
    # Check what revision we should store
 
139
    parent_keys = []
 
140
    for pinv in parent_invs:
 
141
        if pinv.revision_id == base_inv.revision_id:
 
142
            pie = base_ie
 
143
            if pie is None:
 
144
                continue
 
145
        else:
 
146
            try:
 
147
                pie = pinv[file_id]
 
148
            except NoSuchId:
 
149
                continue
 
150
        if pie.text_sha1 == ie.text_sha1 and pie.executable == ie.executable:
 
151
            # found a revision in one of the parents to use
 
152
            ie.revision = pie.revision
 
153
            break
 
154
        parent_keys.append((file_id, pie.revision))
 
155
    if ie.revision is None:
 
156
        # Need to store a new revision
 
157
        ie.revision = revision_id
 
158
        assert file_id is not None
 
159
        assert ie.revision is not None
 
160
        texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, blob.data)])
 
161
        shamap = [(hexsha, "blob", (ie.file_id, ie.revision))]
 
162
    else:
 
163
        shamap = []
 
164
    if file_id in base_inv:
 
165
        old_path = base_inv.id2path(file_id)
 
166
    else:
 
167
        old_path = None
 
168
    return ([(old_path, path, file_id, ie)], shamap)
 
169
 
 
170
 
 
171
def import_git_submodule(texts, mapping, path, hexsha, base_inv, parent_id, 
 
172
    revision_id, parent_invs, shagitmap, lookup_object):
 
173
    raise NotImplementedError(import_git_submodule)
 
174
 
 
175
 
 
176
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id, 
 
177
    revision_id, parent_invs, shagitmap, lookup_object):
93
178
    """Import a git tree object into a bzr repository.
94
179
 
95
 
    :param repo: A Bzr repository object
 
180
    :param texts: VersionedFiles object to add to
96
181
    :param path: Path in the tree
97
182
    :param tree: A git tree object
98
 
    :param inv: Inventory object
 
183
    :param base_inv: Base inventory against which to return inventory delta
 
184
    :return: Inventory delta for this subtree
99
185
    """
 
186
    invdelta = []
100
187
    file_id = mapping.generate_file_id(path)
101
 
    text_revision = inv.revision_id
102
 
    repo.texts.add_lines((file_id, text_revision),
103
 
        [(file_id, p[file_id].revision) for p in parent_invs if file_id in p],
104
 
        [])
105
 
    ie = inv.add_path(path, "directory", file_id)
106
 
    ie.revision = text_revision
107
 
    for mode, name, hexsha in tree.entries():
108
 
        entry_kind = (mode & 0700000) / 0100000
 
188
    # We just have to hope this is indeed utf-8:
 
189
    ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")), 
 
190
        parent_id)
 
191
    ie.text_id = hexsha
 
192
    try:
 
193
        base_ie = base_inv[file_id]
 
194
    except NoSuchId:
 
195
        # Newly appeared here
 
196
        base_ie = None
 
197
        ie.revision = revision_id
 
198
        texts.add_lines((file_id, ie.revision), (), [])
 
199
        invdelta.append((None, path, file_id, ie))
 
200
    else:
 
201
        base_sha = base_ie.text_id
 
202
        # See if this has changed at all
 
203
        try:
 
204
            if base_sha is None:
 
205
                base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
 
206
        except KeyError:
 
207
            pass
 
208
        else:
 
209
            if base_sha == hexsha:
 
210
                # If nothing has changed since the base revision, we're done
 
211
                return [], {}, []
 
212
    # Remember for next time
 
213
    existing_children = set()
 
214
    child_modes = {}
 
215
    shamap = []
 
216
    tree = lookup_object(hexsha)
 
217
    for mode, name, child_hexsha in tree.entries():
109
218
        basename = name.decode("utf-8")
110
 
        if path == "":
111
 
            child_path = name
112
 
        else:
113
 
            child_path = urlutils.join(path, name)
114
 
        if entry_kind == 0:
115
 
            tree = lookup_object(hexsha)
116
 
            import_git_tree(repo, mapping, child_path, tree, inv, parent_invs, lookup_object)
117
 
        elif entry_kind == 1:
118
 
            blob = lookup_object(hexsha)
119
 
            fs_mode = mode & 0777
120
 
            import_git_blob(repo, mapping, child_path, blob, inv, parent_invs, bool(fs_mode & 0111))
121
 
        else:
122
 
            raise AssertionError("Unknown blob kind, perms=%r." % (mode,))
123
 
 
124
 
 
125
 
def import_git_objects(repo, mapping, num_objects, object_iter, pb=None):
 
219
        existing_children.add(basename)
 
220
        child_path = osutils.pathjoin(path, name)
 
221
        if stat.S_ISDIR(mode):
 
222
            subinvdelta, grandchildmodes, subshamap = import_git_tree(texts, 
 
223
                    mapping, child_path, child_hexsha, base_inv, file_id, 
 
224
                    revision_id, parent_invs, shagitmap, lookup_object)
 
225
            invdelta.extend(subinvdelta)
 
226
            child_modes.update(grandchildmodes)
 
227
            shamap.extend(subshamap)
 
228
        elif S_ISGITLINK(mode): # submodule
 
229
            subinvdelta, grandchildmodes, subshamap = import_git_submodule(
 
230
                    texts, mapping, child_path, child_hexsha, base_inv,
 
231
                    file_id, revision_id, parent_invs, shagitmap, lookup_object)
 
232
            invdelta.extend(subinvdelta)
 
233
            child_modes.update(grandchildmodes)
 
234
            shamap.extend(subshamap)
 
235
        else:
 
236
            subinvdelta, subshamap = import_git_blob(texts, mapping, 
 
237
                    child_path, child_hexsha, base_inv, file_id, revision_id, 
 
238
                    parent_invs, shagitmap, lookup_object, 
 
239
                    mode_is_executable(mode), stat.S_ISLNK(mode))
 
240
            invdelta.extend(subinvdelta)
 
241
            shamap.extend(subshamap)
 
242
        if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
 
243
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
 
244
            child_modes[child_path] = mode
 
245
    # Remove any children that have disappeared
 
246
    if base_ie is not None and base_ie.kind == 'directory':
 
247
        deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
 
248
        while deletable:
 
249
            ie = deletable.pop()
 
250
            invdelta.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
 
251
            if ie.kind == "directory":
 
252
                deletable.extend(ie.children.values())
 
253
    shamap.append((hexsha, "tree", (file_id, revision_id)))
 
254
    return invdelta, child_modes, shamap
 
255
 
 
256
 
 
257
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever, 
 
258
        heads, pb=None):
126
259
    """Import a set of git objects into a bzr repository.
127
260
 
128
 
    :param repo: Bazaar repository
 
261
    :param repo: Target Bazaar repository
129
262
    :param mapping: Mapping to use
130
 
    :param num_objects: Number of objects.
131
263
    :param object_iter: Iterator over Git objects.
132
264
    """
 
265
    def lookup_object(sha):
 
266
        try:
 
267
            return object_iter[sha]
 
268
        except KeyError:
 
269
            return target_git_object_retriever[sha]
133
270
    # TODO: a more (memory-)efficient implementation of this
134
 
    objects = {}
135
 
    for i, o in enumerate(object_iter):
136
 
        if pb is not None:
137
 
            pb.update("fetching objects", i, num_objects) 
138
 
        objects[o.id] = o
139
271
    graph = []
140
272
    root_trees = {}
141
273
    revisions = {}
 
274
    checked = set()
 
275
    heads = list(heads)
 
276
    parent_invs_cache = LRUCache(50)
142
277
    # Find and convert commit objects
143
 
    for o in objects.itervalues():
 
278
    while heads:
 
279
        if pb is not None:
 
280
            pb.update("finding revisions to fetch", len(graph), None)
 
281
        head = heads.pop()
 
282
        assert isinstance(head, str)
 
283
        try:
 
284
            o = lookup_object(head)
 
285
        except KeyError:
 
286
            continue
144
287
        if isinstance(o, Commit):
145
288
            rev = mapping.import_commit(o)
146
 
            root_trees[rev.revision_id] = objects[o.tree]
 
289
            if repo.has_revision(rev.revision_id):
 
290
                continue
 
291
            root_trees[rev.revision_id] = o.tree
147
292
            revisions[rev.revision_id] = rev
148
293
            graph.append((rev.revision_id, rev.parent_ids))
 
294
            target_git_object_retriever._idmap.add_entry(o.id, "commit", 
 
295
                    (rev.revision_id, o.tree))
 
296
            heads.extend([p for p in o.parents if p not in checked])
 
297
        elif isinstance(o, Tag):
 
298
            heads.append(o.object[1])
 
299
        else:
 
300
            trace.warning("Unable to import head object %r" % o)
 
301
        checked.add(head)
149
302
    # Order the revisions
150
303
    # Create the inventory objects
151
304
    for i, revid in enumerate(topo_sort(graph)):
152
305
        if pb is not None:
153
306
            pb.update("fetching revisions", i, len(graph))
154
 
        root_tree = root_trees[revid]
155
307
        rev = revisions[revid]
156
308
        # We have to do this here, since we have to walk the tree and 
157
 
        # we need to make sure to import the blobs / trees with the riht 
 
309
        # we need to make sure to import the blobs / trees with the right 
158
310
        # path; this may involve adding them more than once.
159
 
        inv = Inventory()
160
 
        inv.revision_id = rev.revision_id
161
 
        def lookup_object(sha):
162
 
            if sha in objects:
163
 
                return objects[sha]
164
 
            return reconstruct_git_object(repo, mapping, sha)
165
 
        parent_invs = [repo.get_inventory(r) for r in rev.parent_ids]
166
 
        import_git_tree(repo, mapping, "", root_tree, inv, parent_invs, 
167
 
            lookup_object)
168
 
        repo.add_revision(rev.revision_id, rev, inv)
169
 
 
170
 
 
171
 
def reconstruct_git_commit(repo, rev):
172
 
    raise NotImplementedError(self.reconstruct_git_commit)
173
 
 
174
 
 
175
 
def reconstruct_git_object(repo, mapping, sha):
176
 
    # Commit
177
 
    revid = mapping.revision_id_foreign_to_bzr(sha)
178
 
    try:
179
 
        rev = repo.get_revision(revid)
180
 
    except NoSuchRevision:
181
 
        pass
182
 
    else:
183
 
        return reconstruct_git_commit(rev)
184
 
 
185
 
    # TODO: Tree
186
 
    # TODO: Blob
187
 
    raise KeyError("No such object %s" % sha)
188
 
 
189
 
 
190
 
class InterGitNonGitRepository(InterRepository):
191
 
 
192
 
    _matching_repo_format = GitFormat()
 
311
        parent_invs = []
 
312
        for parent_id in rev.parent_ids:
 
313
            try:
 
314
                parent_invs.append(parent_invs_cache[parent_id])
 
315
            except KeyError:
 
316
                parent_inv = repo.get_inventory(parent_id)
 
317
                parent_invs.append(parent_inv)
 
318
                parent_invs_cache[parent_id] = parent_inv
 
319
        if parent_invs == []:
 
320
            base_inv = Inventory(root_id=None)
 
321
        else:
 
322
            base_inv = parent_invs[0]
 
323
        inv_delta, unusual_modes, shamap = import_git_tree(repo.texts, 
 
324
                mapping, "", root_trees[revid], base_inv, None, revid, 
 
325
                parent_invs, target_git_object_retriever._idmap, lookup_object)
 
326
        target_git_object_retriever._idmap.add_entries(shamap)
 
327
        if unusual_modes != {}:
 
328
            for path, mode in unusual_modes.iteritems():
 
329
                warn_unusual_mode(rev.foreign_revid, path, mode)
 
330
        try:
 
331
            basis_id = rev.parent_ids[0]
 
332
        except IndexError:
 
333
            basis_id = NULL_REVISION
 
334
        rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
335
                  inv_delta, rev.revision_id, rev.parent_ids)
 
336
        parent_invs_cache[rev.revision_id] = inv
 
337
        repo.add_revision(rev.revision_id, rev)
 
338
        if "verify" in debug.debug_flags:
 
339
            objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping)
 
340
            for sha1, newobj, path in objs:
 
341
                assert path is not None
 
342
                oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
 
343
                assert oldobj == newobj, "%r != %r in %s" % (oldobj, newobj, path)
 
344
 
 
345
    target_git_object_retriever._idmap.commit()
 
346
 
 
347
 
 
348
class InterGitRepository(InterRepository):
 
349
 
 
350
    _matching_repo_format = GitRepositoryFormat()
193
351
 
194
352
    @staticmethod
195
353
    def _get_repo_format_to_test():
199
357
        """See InterRepository.copy_content."""
200
358
        self.fetch(revision_id, pb, find_ghosts=False)
201
359
 
202
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, 
203
 
              mapping=None):
 
360
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, mapping=None,
 
361
            fetch_spec=None):
 
362
        self.fetch_refs(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts,
 
363
                mapping=mapping, fetch_spec=fetch_spec)
 
364
 
 
365
 
 
366
class InterGitNonGitRepository(InterGitRepository):
 
367
    """Base InterRepository that copies revisions from a Git into a non-Git 
 
368
    repository."""
 
369
 
 
370
    def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False, 
 
371
              mapping=None, fetch_spec=None):
204
372
        if mapping is None:
205
373
            mapping = self.source.get_mapping()
206
 
        def progress(text):
207
 
            pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
208
 
        def determine_wants(heads):
209
 
            if revision_id is None:
210
 
                ret = heads.values()
 
374
        if revision_id is not None:
 
375
            interesting_heads = [revision_id]
 
376
        elif fetch_spec is not None:
 
377
            interesting_heads = fetch_spec.heads
 
378
        else:
 
379
            interesting_heads = None
 
380
        self._refs = {}
 
381
        def determine_wants(refs):
 
382
            self._refs = refs
 
383
            if interesting_heads is None:
 
384
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
211
385
            else:
212
 
                ret = [mapping.revision_id_bzr_to_foreign(revision_id)]
 
386
                ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
213
387
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
214
 
        graph_walker = BzrFetchGraphWalker(self.target, mapping)
 
388
        self.fetch_objects(determine_wants, mapping, pb)
 
389
        return self._refs
 
390
 
 
391
 
 
392
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
 
393
    """InterRepository that copies revisions from a remote Git into a non-Git 
 
394
    repository."""
 
395
 
 
396
    def fetch_objects(self, determine_wants, mapping, pb=None):
 
397
        def progress(text):
 
398
            pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
 
399
        store = BazaarObjectStore(self.target, mapping)
 
400
        self.target.lock_write()
 
401
        try:
 
402
            heads = self.target.get_graph().heads(self.target.all_revision_ids())
 
403
            graph_walker = store.get_graph_walker(
 
404
                    [store._lookup_revision_sha1(head) for head in heads])
 
405
            recorded_wants = []
 
406
 
 
407
            def record_determine_wants(heads):
 
408
                wants = determine_wants(heads)
 
409
                recorded_wants.extend(wants)
 
410
                return wants
 
411
        
 
412
            create_pb = None
 
413
            if pb is None:
 
414
                create_pb = pb = ui.ui_factory.nested_progress_bar()
 
415
            try:
 
416
                self.target.start_write_group()
 
417
                try:
 
418
                    objects_iter = self.source.fetch_objects(
 
419
                                record_determine_wants, graph_walker, 
 
420
                                store.get_raw, progress)
 
421
                    import_git_objects(self.target, mapping, objects_iter, 
 
422
                            store, recorded_wants, pb)
 
423
                finally:
 
424
                    self.target.commit_write_group()
 
425
            finally:
 
426
                if create_pb:
 
427
                    create_pb.finished()
 
428
        finally:
 
429
            self.target.unlock()
 
430
 
 
431
    @staticmethod
 
432
    def is_compatible(source, target):
 
433
        """Be compatible with GitRepository."""
 
434
        # FIXME: Also check target uses VersionedFile
 
435
        return (isinstance(source, RemoteGitRepository) and 
 
436
                target.supports_rich_root() and
 
437
                not isinstance(target, GitRepository))
 
438
 
 
439
 
 
440
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
 
441
    """InterRepository that copies revisions from a local Git into a non-Git 
 
442
    repository."""
 
443
 
 
444
    def fetch_objects(self, determine_wants, mapping, pb=None):
 
445
        wants = determine_wants(self.source._git.get_refs())
215
446
        create_pb = None
216
447
        if pb is None:
217
448
            create_pb = pb = ui.ui_factory.nested_progress_bar()
 
449
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
218
450
        try:
219
451
            self.target.lock_write()
220
452
            try:
221
453
                self.target.start_write_group()
222
454
                try:
223
 
                    (num_objects, objects_iter) = \
224
 
                            self.source.fetch_objects(determine_wants, 
225
 
                                graph_walker, progress)
226
 
                    import_git_objects(self.target, mapping, num_objects, 
227
 
                                       objects_iter, pb)
 
455
                    import_git_objects(self.target, mapping, 
 
456
                            self.source._git.object_store, 
 
457
                            target_git_object_retriever, wants, pb)
228
458
                finally:
229
459
                    self.target.commit_write_group()
230
460
            finally:
237
467
    def is_compatible(source, target):
238
468
        """Be compatible with GitRepository."""
239
469
        # FIXME: Also check target uses VersionedFile
240
 
        return (isinstance(source, GitRepository) and 
 
470
        return (isinstance(source, LocalGitRepository) and 
241
471
                target.supports_rich_root() and
242
472
                not isinstance(target, GitRepository))
243
473
 
244
474
 
245
 
class InterGitRepository(InterRepository):
246
 
 
247
 
    _matching_repo_format = GitFormat()
248
 
 
249
 
    @staticmethod
250
 
    def _get_repo_format_to_test():
251
 
        return None
252
 
 
253
 
    def copy_content(self, revision_id=None, pb=None):
254
 
        """See InterRepository.copy_content."""
255
 
        self.fetch(revision_id, pb, find_ghosts=False)
256
 
 
257
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, 
258
 
              mapping=None):
 
475
class InterGitGitRepository(InterGitRepository):
 
476
    """InterRepository that copies between Git repositories."""
 
477
 
 
478
    def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False, 
 
479
              mapping=None, fetch_spec=None, branches=None):
259
480
        if mapping is None:
260
481
            mapping = self.source.get_mapping()
261
482
        def progress(text):
262
 
            info("git: %s", text)
 
483
            trace.info("git: %s", text)
263
484
        r = self.target._git
264
 
        if revision_id is None:
265
 
            determine_wants = lambda x: [y for y in x.values() if not y in r.object_store]
 
485
        if revision_id is not None:
 
486
            args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]
 
487
        elif fetch_spec is not None:
 
488
            args = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in fetch_spec.heads]
 
489
        if branches is not None:
 
490
            determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store]
 
491
        elif fetch_spec is None and revision_id is None:
 
492
            determine_wants = r.object_store.determine_wants_all
266
493
        else:
267
 
            args = [mapping.revision_id_bzr_to_foreign(revision_id)]
268
494
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
269
495
 
270
 
        graphwalker = SimpleFetchGraphWalker(r.heads().values(), r.get_parents)
271
 
        f, commit = r.object_store.add_pack()
 
496
        graphwalker = r.get_graph_walker()
 
497
        f, commit = r.object_store.add_thin_pack()
272
498
        try:
273
 
            self.source._git.fetch_pack(path, determine_wants, graphwalker, f.write, progress)
274
 
            f.close()
 
499
            refs = self.source.fetch_pack(determine_wants, graphwalker,
 
500
                                          f.write, progress)
275
501
            commit()
 
502
            return refs
276
503
        except:
277
504
            f.close()
278
505
            raise