/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 breezy/git/interrepo.py

  • Committer: Jelmer Vernooij
  • Date: 2020-06-28 23:13:22 UTC
  • mto: (7490.40.37 work)
  • mto: This revision was merged to the branch mainline in revision 7519.
  • Revision ID: jelmer@jelmer.uk-20200628231322-6h0upmtsh8ec7504
some refactoring.

Show diffs side-by-side

added added

removed removed

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