/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

Update NEWS about submodules.

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