/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

More tests for sha maps, fix cache misses in tdb.

Show diffs side-by-side

added added

removed removed

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