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

  • Committer: Jelmer Vernooij
  • Date: 2018-03-30 21:27:44 UTC
  • mto: (0.200.1905 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180330212744-k60bo2l6ycft26hd
Move all InterRepository implementations into interrepo.

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