/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.401.2 by Jelmer Vernooij
Move all InterRepository implementations into interrepo.
1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17
"""InterRepository operations."""
18
19
from __future__ import absolute_import
20
21
from io import BytesIO
22
23
from dulwich.errors import (
24
    NotCommitError,
25
    )
26
from dulwich.object_store import (
27
    ObjectStoreGraphWalker,
28
    )
29
from dulwich.protocol import (
30
    CAPABILITY_THIN_PACK,
31
    ZERO_SHA,
32
    )
33
from dulwich.walk import Walker
34
35
from ...errors import (
36
    FetchLimitUnsupported,
37
    InvalidRevisionId,
38
    LossyPushToSameVCS,
39
    NoRoundtrippingSupport,
40
    NoSuchRevision,
41
    )
42
from ...repository import (
43
    InterRepository,
44
    )
45
from ...revision import (
46
    NULL_REVISION,
47
    )
48
from ... import (
49
    trace,
50
    ui,
51
    )
52
53
from .errors import (
54
    NoPushSupport,
55
    )
56
from .fetch import (
57
    import_git_objects,
58
    report_git_progress,
59
    DetermineWantsRecorder,
60
    )
61
from .mapping import (
62
    needs_roundtripping,
63
    )
64
from .object_store import (
65
    get_object_store,
66
    _tree_to_objects,
67
    )
68
from .push import (
69
    MissingObjectsIterator,
70
    )
71
from .refs import (
72
    is_tag,
73
    )
74
from .repository import (
75
    GitRepository,
76
    LocalGitRepository,
77
    GitRepositoryFormat,
78
    )
79
from .remote import (
80
    RemoteGitRepository,
81
    )
82
from .unpeel_map import (
83
    UnpeelMap,
84
    )
85
86
87
class InterToGitRepository(InterRepository):
88
    """InterRepository that copies into a Git repository."""
89
90
    _matching_repo_format = GitRepositoryFormat()
91
92
    def __init__(self, source, target):
93
        super(InterToGitRepository, self).__init__(source, target)
94
        self.mapping = self.target.get_mapping()
95
        self.source_store = get_object_store(self.source, self.mapping)
96
97
    @staticmethod
98
    def _get_repo_format_to_test():
99
        return None
100
101
    def copy_content(self, revision_id=None, pb=None):
102
        """See InterRepository.copy_content."""
103
        self.fetch(revision_id, pb, find_ghosts=False)
104
105
    def fetch_refs(self, update_refs, lossy):
106
        """Fetch possibly roundtripped revisions into the target repository
107
        and update refs.
108
109
        :param update_refs: Generate refs to fetch. Receives dictionary
110
            with old refs (git shas), returns dictionary of new names to
111
            git shas.
112
        :param lossy: Whether to roundtrip
113
        :return: old refs, new refs
114
        """
115
        raise NotImplementedError(self.fetch_refs)
116
117
    def search_missing_revision_ids(self,
118
            find_ghosts=True, revision_ids=None, if_present_ids=None,
119
            limit=None):
120
        if limit is not None:
121
            raise FetchLimitUnsupported(self)
122
        git_shas = []
123
        todo = []
124
        if revision_ids:
125
            todo.extend(revision_ids)
126
        if if_present_ids:
127
            todo.extend(revision_ids)
128
        with self.source_store.lock_read():
129
            for revid in revision_ids:
130
                if revid == NULL_REVISION:
131
                    continue
132
                git_sha = self.source_store._lookup_revision_sha1(revid)
133
                git_shas.append(git_sha)
134
            walker = Walker(self.source_store,
0.401.3 by Jelmer Vernooij
Formatting fixes.
135
                include=git_shas, exclude=[
136
                    sha for sha in self.target.controldir.get_refs_container().as_dict().values()
137
                    if sha != ZERO_SHA])
0.401.2 by Jelmer Vernooij
Move all InterRepository implementations into interrepo.
138
            missing_revids = set()
139
            for entry in walker:
140
                for (kind, type_data) in self.source_store.lookup_git_sha(entry.commit.id):
141
                    if kind == "commit":
142
                        missing_revids.add(type_data[0])
143
        return self.source.revision_ids_to_search_result(missing_revids)
144
145
    def _warn_slow(self):
146
        trace.warning(
147
            'Pushing from a Bazaar to a Git repository. '
148
            'For better performance, push into a Bazaar repository.')
149
150
151
class InterToLocalGitRepository(InterToGitRepository):
152
    """InterBranch implementation between a Bazaar and a Git repository."""
153
154
    def __init__(self, source, target):
155
        super(InterToLocalGitRepository, self).__init__(source, target)
156
        self.target_store = self.target.controldir._git.object_store
157
        self.target_refs = self.target.controldir._git.refs
158
159
    def _commit_needs_fetching(self, sha_id):
160
        try:
161
            return (sha_id not in self.target_store)
162
        except NoSuchRevision:
163
            # Ghost, can't push
164
            return False
165
166
    def _revision_needs_fetching(self, sha_id, revid):
167
        if revid == NULL_REVISION:
168
            return False
169
        if sha_id is None:
170
            try:
171
                sha_id = self.source_store._lookup_revision_sha1(revid)
172
            except KeyError:
173
                return False
174
        return self._commit_needs_fetching(sha_id)
175
176
    def missing_revisions(self, stop_revisions):
177
        """Find the revisions that are missing from the target repository.
178
179
        :param stop_revisions: Revisions to check for (tuples with
180
            Git SHA1, bzr revid)
181
        :return: sequence of missing revisions, in topological order
182
        :raise: NoSuchRevision if the stop_revisions are not present in
183
            the source
184
        """
185
        revid_sha_map = {}
186
        stop_revids = []
187
        for (sha1, revid) in stop_revisions:
188
            if sha1 is not None and revid is not None:
189
                revid_sha_map[revid] = sha1
190
                stop_revids.append(revid)
191
            elif sha1 is not None:
192
                if self._commit_needs_fetching(sha1):
193
                    for (kind, (revid, tree_sha, verifiers)) in self.source_store.lookup_git_sha(sha1):
194
                        revid_sha_map[revid] = sha1
195
                        stop_revids.append(revid)
196
            else:
197
                if revid is None:
198
                    raise AssertionError
199
                stop_revids.append(revid)
200
        missing = set()
201
        graph = self.source.get_graph()
202
        pb = ui.ui_factory.nested_progress_bar()
203
        try:
204
            while stop_revids:
205
                new_stop_revids = []
206
                for revid in stop_revids:
207
                    sha1 = revid_sha_map.get(revid)
208
                    if (not revid in missing and
209
                        self._revision_needs_fetching(sha1, revid)):
210
                        missing.add(revid)
211
                        new_stop_revids.append(revid)
212
                stop_revids = set()
213
                parent_map = graph.get_parent_map(new_stop_revids)
214
                for parent_revids in parent_map.itervalues():
215
                    stop_revids.update(parent_revids)
216
                pb.update("determining revisions to fetch", len(missing))
217
        finally:
218
            pb.finished()
219
        return graph.iter_topo_order(missing)
220
221
    def _get_target_bzr_refs(self):
222
        """Return a dictionary with references.
223
224
        :return: Dictionary with reference names as keys and tuples
225
            with Git SHA, Bazaar revid as values.
226
        """
227
        bzr_refs = {}
228
        refs = {}
229
        for k in self.target._git.refs.allkeys():
230
            try:
231
                v = self.target._git.refs[k]
232
            except KeyError:
233
                # broken symref?
234
                continue
235
            try:
236
                for (kind, type_data) in self.source_store.lookup_git_sha(v):
237
                    if kind == "commit" and self.source.has_revision(type_data[0]):
238
                        revid = type_data[0]
239
                        break
240
                else:
241
                    revid = None
242
            except KeyError:
243
                revid = None
244
            bzr_refs[k] = (v, revid)
245
        return bzr_refs
246
247
    def fetch_refs(self, update_refs, lossy):
248
        with self.source_store.lock_read():
249
            old_refs = self._get_target_bzr_refs()
250
            new_refs = update_refs(old_refs)
251
            revidmap = self.fetch_objects(
252
                [(git_sha, bzr_revid) for (git_sha, bzr_revid) in new_refs.values() if git_sha is None or not git_sha.startswith('ref:')], lossy=lossy)
253
            for name, (gitid, revid) in new_refs.iteritems():
254
                if gitid is None:
255
                    try:
256
                        gitid = revidmap[revid][0]
257
                    except KeyError:
258
                        gitid = self.source_store._lookup_revision_sha1(revid)
259
                if len(gitid) != 40 and not gitid.startswith('ref: '):
260
                    raise AssertionError("invalid ref contents: %r" % gitid)
261
                self.target_refs[name] = gitid
262
        return revidmap, old_refs, new_refs
263
264
    def fetch_objects(self, revs, lossy, limit=None):
265
        if not lossy and not self.mapping.roundtripping:
266
            for git_sha, bzr_revid in revs:
267
                if bzr_revid is not None and needs_roundtripping(self.source, bzr_revid):
268
                    raise NoPushSupport(self.source, self.target, self.mapping,
269
                                        bzr_revid)
270
        with self.source_store.lock_read():
271
            todo = list(self.missing_revisions(revs))[:limit]
272
            revidmap = {}
273
            pb = ui.ui_factory.nested_progress_bar()
274
            try:
275
                object_generator = MissingObjectsIterator(
276
                    self.source_store, self.source, pb)
277
                for (old_revid, git_sha) in object_generator.import_revisions(
278
                    todo, lossy=lossy):
279
                    if lossy:
280
                        new_revid = self.mapping.revision_id_foreign_to_bzr(git_sha)
281
                    else:
282
                        new_revid = old_revid
283
                        try:
284
                            self.mapping.revision_id_bzr_to_foreign(old_revid)
285
                        except InvalidRevisionId:
286
                            refname = self.mapping.revid_as_refname(old_revid)
287
                            self.target_refs[refname] = git_sha
288
                    revidmap[old_revid] = (git_sha, new_revid)
289
                self.target_store.add_objects(object_generator)
290
                return revidmap
291
            finally:
292
                pb.finished()
293
294
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
295
            fetch_spec=None, mapped_refs=None):
296
        if mapped_refs is not None:
297
            stop_revisions = mapped_refs
298
        elif revision_id is not None:
299
            stop_revisions = [(None, revision_id)]
300
        elif fetch_spec is not None:
301
            recipe = fetch_spec.get_recipe()
302
            if recipe[0] in ("search", "proxy-search"):
303
                stop_revisions = [(None, revid) for revid in recipe[1]]
304
            else:
305
                raise AssertionError("Unsupported search result type %s" % recipe[0])
306
        else:
307
            stop_revisions = [(None, revid) for revid in self.source.all_revision_ids()]
308
        self._warn_slow()
309
        try:
310
            self.fetch_objects(stop_revisions, lossy=False)
311
        except NoPushSupport:
312
            raise NoRoundtrippingSupport(self.source, self.target)
313
314
    @staticmethod
315
    def is_compatible(source, target):
316
        """Be compatible with GitRepository."""
317
        return (not isinstance(source, GitRepository) and
318
                isinstance(target, LocalGitRepository))
319
320
321
class InterToRemoteGitRepository(InterToGitRepository):
322
323
    def fetch_refs(self, update_refs, lossy):
324
        """Import the gist of the ancestry of a particular revision."""
325
        if not lossy and not self.mapping.roundtripping:
326
            raise NoPushSupport(self.source, self.target, self.mapping)
327
        unpeel_map = UnpeelMap.from_repository(self.source)
328
        revidmap = {}
329
        def determine_wants(old_refs):
330
            ret = {}
331
            self.old_refs = dict([(k, (v, None)) for (k, v) in old_refs.iteritems()])
332
            self.new_refs = update_refs(self.old_refs)
333
            for name, (gitid, revid) in self.new_refs.iteritems():
334
                if gitid is None:
335
                    git_sha = self.source_store._lookup_revision_sha1(revid)
336
                    ret[name] = unpeel_map.re_unpeel_tag(git_sha, old_refs.get(name))
337
                else:
338
                    ret[name] = gitid
339
            return ret
340
        self._warn_slow()
341
        with self.source_store.lock_read():
342
            new_refs = self.target.send_pack(determine_wants,
343
                    self.source_store.generate_lossy_pack_data)
344
        # FIXME: revidmap?
345
        return revidmap, self.old_refs, self.new_refs
346
347
    @staticmethod
348
    def is_compatible(source, target):
349
        """Be compatible with GitRepository."""
350
        return (not isinstance(source, GitRepository) and
351
                isinstance(target, RemoteGitRepository))
352
353
354
class InterFromGitRepository(InterRepository):
355
356
    _matching_repo_format = GitRepositoryFormat()
357
358
    def _target_has_shas(self, shas):
359
        raise NotImplementedError(self._target_has_shas)
360
361
    def get_determine_wants_heads(self, wants, include_tags=False):
362
        wants = set(wants)
363
        def determine_wants(refs):
364
            potential = set(wants)
365
            if include_tags:
366
                for k, unpeeled in refs.iteritems():
367
                    if k.endswith("^{}"):
368
                        continue
369
                    if not is_tag(k):
370
                        continue
371
                    if unpeeled == ZERO_SHA:
372
                        continue
373
                    potential.add(unpeeled)
374
            return list(potential - self._target_has_shas(potential))
375
        return determine_wants
376
377
    def determine_wants_all(self, refs):
378
        raise NotImplementedError(self.determine_wants_all)
379
380
    @staticmethod
381
    def _get_repo_format_to_test():
382
        return None
383
384
    def copy_content(self, revision_id=None):
385
        """See InterRepository.copy_content."""
386
        self.fetch(revision_id, find_ghosts=False)
387
388
    def search_missing_revision_ids(self,
389
            find_ghosts=True, revision_ids=None, if_present_ids=None,
390
            limit=None):
391
        if limit is not None:
392
            raise FetchLimitUnsupported(self)
393
        git_shas = []
394
        todo = []
395
        if revision_ids:
396
            todo.extend(revision_ids)
397
        if if_present_ids:
398
            todo.extend(revision_ids)
0.401.3 by Jelmer Vernooij
Formatting fixes.
399
        with self.lock_read():
400
            for revid in revision_ids:
401
                if revid == NULL_REVISION:
402
                    continue
403
                git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
404
                git_shas.append(git_sha)
405
            walker = Walker(self.source._git.object_store,
406
                include=git_shas, exclude=[
407
                    sha for sha in self.target.controldir.get_refs_container().as_dict().values()
408
                    if sha != ZERO_SHA])
409
            missing_revids = set()
410
            for entry in walker:
411
                missing_revids.add(self.source.lookup_foreign_revision_id(entry.commit.id))
412
            return self.source.revision_ids_to_search_result(missing_revids)
0.401.2 by Jelmer Vernooij
Move all InterRepository implementations into interrepo.
413
414
415
class InterGitNonGitRepository(InterFromGitRepository):
416
    """Base InterRepository that copies revisions from a Git into a non-Git
417
    repository."""
418
419
    def _target_has_shas(self, shas):
420
        revids = {}
421
        for sha in shas:
422
            try:
423
                revid = self.source.lookup_foreign_revision_id(sha)
424
            except NotCommitError:
425
                # Commit is definitely not present
426
                continue
427
            else:
428
                revids[revid] = sha
429
        return set([revids[r] for r in self.target.has_revisions(revids)])
430
431
    def determine_wants_all(self, refs):
432
        potential = set()
433
        for k, v in refs.iteritems():
434
            # For non-git target repositories, only worry about peeled
435
            if v == ZERO_SHA:
436
                continue
437
            potential.add(self.source.controldir.get_peeled(k) or v)
438
        return list(potential - self._target_has_shas(potential))
439
440
    def get_determine_wants_heads(self, wants, include_tags=False):
441
        wants = set(wants)
442
        def determine_wants(refs):
443
            potential = set(wants)
444
            if include_tags:
445
                for k, unpeeled in refs.iteritems():
446
                    if not is_tag(k):
447
                        continue
448
                    if unpeeled == ZERO_SHA:
449
                        continue
450
                    potential.add(self.source.controldir.get_peeled(k) or unpeeled)
451
            return list(potential - self._target_has_shas(potential))
452
        return determine_wants
453
454
    def _warn_slow(self):
455
        trace.warning(
456
            'Fetching from Git to Bazaar repository. '
457
            'For better performance, fetch into a Git repository.')
458
459
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
460
        """Fetch objects from a remote server.
461
462
        :param determine_wants: determine_wants callback
463
        :param mapping: BzrGitMapping to use
464
        :param limit: Maximum number of commits to import.
465
        :return: Tuple with pack hint, last imported revision id and remote refs
466
        """
467
        raise NotImplementedError(self.fetch_objects)
468
469
    def get_determine_wants_revids(self, revids, include_tags=False):
470
        wants = set()
471
        for revid in set(revids):
472
            if self.target.has_revision(revid):
473
                continue
474
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
475
            wants.add(git_sha)
476
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
477
478
    def fetch(self, revision_id=None, find_ghosts=False,
479
              mapping=None, fetch_spec=None, include_tags=False):
480
        if mapping is None:
481
            mapping = self.source.get_mapping()
482
        if revision_id is not None:
483
            interesting_heads = [revision_id]
484
        elif fetch_spec is not None:
485
            recipe = fetch_spec.get_recipe()
486
            if recipe[0] in ("search", "proxy-search"):
487
                interesting_heads = recipe[1]
488
            else:
489
                raise AssertionError("Unsupported search result type %s" %
490
                        recipe[0])
491
        else:
492
            interesting_heads = None
493
494
        if interesting_heads is not None:
495
            determine_wants = self.get_determine_wants_revids(
496
                interesting_heads, include_tags=include_tags)
497
        else:
498
            determine_wants = self.determine_wants_all
499
500
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
501
            mapping)
502
        if pack_hint is not None and self.target._format.pack_compresses:
503
            self.target.pack(hint=pack_hint)
504
        return remote_refs
505
506
507
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
508
    """InterRepository that copies revisions from a remote Git into a non-Git
509
    repository."""
510
511
    def get_target_heads(self):
512
        # FIXME: This should be more efficient
513
        all_revs = self.target.all_revision_ids()
514
        parent_map = self.target.get_parent_map(all_revs)
515
        all_parents = set()
516
        map(all_parents.update, parent_map.itervalues())
517
        return set(all_revs) - all_parents
518
519
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
520
        """See `InterGitNonGitRepository`."""
521
        self._warn_slow()
522
        store = get_object_store(self.target, mapping)
523
        with store.lock_write():
524
            heads = self.get_target_heads()
525
            graph_walker = ObjectStoreGraphWalker(
526
                [store._lookup_revision_sha1(head) for head in heads],
527
                lambda sha: store[sha].parents)
528
            wants_recorder = DetermineWantsRecorder(determine_wants)
529
530
            pb = ui.ui_factory.nested_progress_bar()
531
            try:
532
                objects_iter = self.source.fetch_objects(
533
                    wants_recorder, graph_walker, store.get_raw,
534
                    progress=lambda text: report_git_progress(pb, text),)
535
                trace.mutter("Importing %d new revisions",
536
                             len(wants_recorder.wants))
537
                (pack_hint, last_rev) = import_git_objects(self.target,
538
                    mapping, objects_iter, store, wants_recorder.wants, pb,
539
                    limit)
540
                return (pack_hint, last_rev, wants_recorder.remote_refs)
541
            finally:
542
                pb.finished()
543
544
    @staticmethod
545
    def is_compatible(source, target):
546
        """Be compatible with GitRepository."""
547
        if not isinstance(source, RemoteGitRepository):
548
            return False
549
        if not target.supports_rich_root():
550
            return False
551
        if isinstance(target, GitRepository):
552
            return False
553
        if not getattr(target._format, "supports_full_versioned_files", True):
554
            return False
555
        return True
556
557
558
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
559
    """InterRepository that copies revisions from a local Git into a non-Git
560
    repository."""
561
562
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
563
        """See `InterGitNonGitRepository`."""
564
        self._warn_slow()
565
        remote_refs = self.source.controldir.get_refs_container().as_dict()
566
        wants = determine_wants(remote_refs)
567
        create_pb = None
568
        pb = ui.ui_factory.nested_progress_bar()
569
        target_git_object_retriever = get_object_store(self.target, mapping)
570
        try:
571
            target_git_object_retriever.lock_write()
572
            try:
573
                (pack_hint, last_rev) = import_git_objects(self.target,
574
                    mapping, self.source._git.object_store,
575
                    target_git_object_retriever, wants, pb, limit)
576
                return (pack_hint, last_rev, remote_refs)
577
            finally:
578
                target_git_object_retriever.unlock()
579
        finally:
580
            pb.finished()
581
582
    @staticmethod
583
    def is_compatible(source, target):
584
        """Be compatible with GitRepository."""
585
        if not isinstance(source, LocalGitRepository):
586
            return False
587
        if not target.supports_rich_root():
588
            return False
589
        if isinstance(target, GitRepository):
590
            return False
591
        if not getattr(target._format, "supports_full_versioned_files", True):
592
            return False
593
        return True
594
595
596
class InterGitGitRepository(InterFromGitRepository):
597
    """InterRepository that copies between Git repositories."""
598
0.401.3 by Jelmer Vernooij
Formatting fixes.
599
    def fetch_refs(self, update_refs, lossy):
0.401.2 by Jelmer Vernooij
Move all InterRepository implementations into interrepo.
600
        if lossy:
601
            raise LossyPushToSameVCS(self.source, self.target)
602
        old_refs = self.target.controldir.get_refs_container()
603
        ref_changes = {}
604
        def determine_wants(heads):
605
            old_refs = dict([(k, (v, None)) for (k, v) in heads.as_dict().iteritems()])
606
            new_refs = update_refs(old_refs)
607
            ref_changes.update(new_refs)
608
            return [sha1 for (sha1, bzr_revid) in new_refs.itervalues()]
609
        self.fetch_objects(determine_wants, lossy=lossy)
610
        for k, (git_sha, bzr_revid) in ref_changes.iteritems():
611
            self.target._git.refs[k] = git_sha
612
        new_refs = self.target.controldir.get_refs_container()
613
        return None, old_refs, new_refs
614
615
    def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
616
        raise NotImplementedError(self.fetch_objects)
617
618
    def _target_has_shas(self, shas):
619
        return set([sha for sha in shas if sha in self.target._git.object_store])
620
621
    def fetch(self, revision_id=None, find_ghosts=False,
622
              mapping=None, fetch_spec=None, branches=None, limit=None, include_tags=False):
623
        if mapping is None:
624
            mapping = self.source.get_mapping()
625
        if revision_id is not None:
626
            args = [revision_id]
627
        elif fetch_spec is not None:
628
            recipe = fetch_spec.get_recipe()
629
            if recipe[0] in ("search", "proxy-search"):
630
                heads = recipe[1]
631
            else:
632
                raise AssertionError(
633
                    "Unsupported search result type %s" % recipe[0])
634
            args = heads
635
        if branches is not None:
636
            def determine_wants(refs):
637
                ret = []
638
                for name, value in refs.iteritems():
639
                    if value == ZERO_SHA:
640
                        continue
641
642
                    if name in branches or (include_tags and is_tag(name)):
643
                        ret.append(value)
644
                return ret
645
        elif fetch_spec is None and revision_id is None:
646
            determine_wants = self.determine_wants_all
647
        else:
648
            determine_wants = self.get_determine_wants_revids(args, include_tags=include_tags)
649
        wants_recorder = DetermineWantsRecorder(determine_wants)
650
        self.fetch_objects(wants_recorder, mapping, limit=limit)
651
        return wants_recorder.remote_refs
652
653
    def get_determine_wants_revids(self, revids, include_tags=False):
654
        wants = set()
655
        for revid in set(revids):
656
            if revid == NULL_REVISION:
657
                continue
658
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
659
            wants.add(git_sha)
660
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
661
662
    def determine_wants_all(self, refs):
663
        potential = set([v for v in refs.values() if not v == ZERO_SHA])
664
        return list(potential - self._target_has_shas(potential))
665
666
667
class InterLocalGitLocalGitRepository(InterGitGitRepository):
668
669
    def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
670
        if lossy:
671
            raise LossyPushToSameVCS(self.source, self.target)
672
        if limit is not None:
673
            raise FetchLimitUnsupported(self)
674
        pb = ui.ui_factory.nested_progress_bar()
675
        try:
676
            refs = self.source._git.fetch(self.target._git, determine_wants,
677
                lambda text: report_git_progress(pb, text))
678
        finally:
679
            pb.finished()
680
        return (None, None, refs)
681
682
    @staticmethod
683
    def is_compatible(source, target):
684
        """Be compatible with GitRepository."""
685
        return (isinstance(source, LocalGitRepository) and
686
                isinstance(target, LocalGitRepository))
687
688
689
class InterRemoteGitLocalGitRepository(InterGitGitRepository):
690
691
    def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
692
        if lossy:
693
            raise LossyPushToSameVCS(self.source, self.target)
694
        if limit is not None:
695
            raise FetchLimitUnsupported(self)
696
        graphwalker = self.target._git.get_graph_walker()
697
        pb = ui.ui_factory.nested_progress_bar()
698
        try:
699
            if CAPABILITY_THIN_PACK in self.source.controldir._client._fetch_capabilities:
700
                # TODO(jelmer): Avoid reading entire file into memory and
701
                # only processing it after the whole file has been fetched.
702
                f = BytesIO()
703
704
                def commit():
705
                    if f.tell():
706
                        f.seek(0)
707
                        self.target._git.object_store.move_in_thin_pack(f)
708
709
                def abort():
710
                    pass
711
            else:
712
                f, commit, abort = self.target._git.object_store.add_pack()
713
            try:
714
                refs = self.source.controldir.fetch_pack(
715
                    determine_wants, graphwalker, f.write,
716
                    lambda text: report_git_progress(pb, text))
717
                commit()
718
                return (None, None, refs)
719
            except BaseException:
720
                abort()
721
                raise
722
        finally:
723
            pb.finished()
724
725
    @staticmethod
726
    def is_compatible(source, target):
727
        """Be compatible with GitRepository."""
728
        return (isinstance(source, RemoteGitRepository) and
729
                isinstance(target, LocalGitRepository))