/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: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-11-16 18:59:44 UTC
  • mfrom: (7143.15.15 more-cleanups)
  • Revision ID: breezy.the.bot@gmail.com-20181116185944-biefv1sub37qfybm
Sprinkle some PEP8iness.

Merged from https://code.launchpad.net/~jelmer/brz/more-cleanups/+merge/358611

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