/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/plugins/git/repository.py

  • Committer: Martin
  • Date: 2018-07-01 10:53:23 UTC
  • mto: This revision was merged to the branch mainline in revision 7016.
  • Revision ID: gzlist@googlemail.com-20180701105323-dawmz8ngtj3qzdo7
Tweak copyright headers

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
 
2
# Copyright (C) 2007 Canonical Ltd
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
 
 
18
"""An adapter between a Git Repository and a Bazaar Branch"""
 
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
from ... import (
 
23
    check,
 
24
    errors,
 
25
    graph as _mod_graph,
 
26
    lock,
 
27
    repository,
 
28
    revision as _mod_revision,
 
29
    trace,
 
30
    transactions,
 
31
    ui,
 
32
    version_info as breezy_version,
 
33
    )
 
34
from ...decorators import only_raises
 
35
from ...foreign import (
 
36
    ForeignRepository,
 
37
    )
 
38
 
 
39
from .commit import (
 
40
    GitCommitBuilder,
 
41
    )
 
42
from .filegraph import (
 
43
    GitFileLastChangeScanner,
 
44
    GitFileParentProvider,
 
45
    )
 
46
from .mapping import (
 
47
    default_mapping,
 
48
    foreign_vcs_git,
 
49
    mapping_registry,
 
50
    )
 
51
from .tree import (
 
52
    GitRevisionTree,
 
53
    )
 
54
 
 
55
 
 
56
from dulwich.errors import (
 
57
    NotCommitError,
 
58
    )
 
59
from dulwich.objects import (
 
60
    Commit,
 
61
    ZERO_SHA,
 
62
    )
 
63
from dulwich.object_store import (
 
64
    tree_lookup_path,
 
65
    )
 
66
 
 
67
 
 
68
class RepoReconciler(object):
 
69
    """Reconciler that reconciles a repository.
 
70
 
 
71
    """
 
72
 
 
73
    def __init__(self, repo, other=None, thorough=False):
 
74
        """Construct a RepoReconciler.
 
75
 
 
76
        :param thorough: perform a thorough check which may take longer but
 
77
                         will correct non-data loss issues such as incorrect
 
78
                         cached data.
 
79
        """
 
80
        self.repo = repo
 
81
 
 
82
    def reconcile(self):
 
83
        """Perform reconciliation.
 
84
 
 
85
        After reconciliation the following attributes document found issues:
 
86
        inconsistent_parents: The number of revisions in the repository whose
 
87
                              ancestry was being reported incorrectly.
 
88
        garbage_inventories: The number of inventory objects without revisions
 
89
                             that were garbage collected.
 
90
        """
 
91
 
 
92
 
 
93
class GitCheck(check.Check):
 
94
 
 
95
    def __init__(self, repository, check_repo=True):
 
96
        self.repository = repository
 
97
        self.check_repo = check_repo
 
98
        self.checked_rev_cnt = 0
 
99
        self.object_count = None
 
100
        self.problems = []
 
101
 
 
102
    def check(self, callback_refs=None, check_repo=True):
 
103
        if callback_refs is None:
 
104
            callback_refs = {}
 
105
        with self.repository.lock_read(), ui.ui_factory.nested_progress_bar() as self.progress:
 
106
            shas = set(self.repository._git.object_store)
 
107
            self.object_count = len(shas)
 
108
            # TODO(jelmer): Check more things
 
109
            for i, sha in enumerate(shas):
 
110
                self.progress.update('checking objects', i, self.object_count)
 
111
                o = self.repository._git.object_store[sha]
 
112
                try:
 
113
                    o.check()
 
114
                except Exception as e:
 
115
                    self.problems.append((sha, e))
 
116
 
 
117
    def _report_repo_results(self, verbose):
 
118
        trace.note('checked repository {0} format {1}'.format(
 
119
            self.repository.user_url,
 
120
            self.repository._format))
 
121
        trace.note('%6d objects', self.object_count)
 
122
        for sha, problem in self.problems:
 
123
            trace.note('%s: %s', sha, problem)
 
124
 
 
125
    def report_results(self, verbose):
 
126
        if self.check_repo:
 
127
            self._report_repo_results(verbose)
 
128
 
 
129
 
 
130
_optimisers_loaded = False
 
131
 
 
132
def lazy_load_optimisers():
 
133
    global _optimisers_loaded
 
134
    if _optimisers_loaded:
 
135
        return
 
136
    from . import interrepo
 
137
    for optimiser in [interrepo.InterRemoteGitNonGitRepository,
 
138
                      interrepo.InterLocalGitNonGitRepository,
 
139
                      interrepo.InterLocalGitLocalGitRepository,
 
140
                      interrepo.InterRemoteGitLocalGitRepository,
 
141
                      interrepo.InterToLocalGitRepository,
 
142
                      interrepo.InterToRemoteGitRepository,
 
143
                      ]:
 
144
        repository.InterRepository.register_optimiser(optimiser)
 
145
    _optimisers_loaded = True
 
146
 
 
147
 
 
148
class GitRepository(ForeignRepository):
 
149
    """An adapter to git repositories for bzr."""
 
150
 
 
151
    _serializer = None
 
152
    vcs = foreign_vcs_git
 
153
    chk_bytes = None
 
154
 
 
155
    def __init__(self, gitdir):
 
156
        self._transport = gitdir.root_transport
 
157
        super(GitRepository, self).__init__(GitRepositoryFormat(),
 
158
            gitdir, control_files=None)
 
159
        self.base = gitdir.root_transport.base
 
160
        lazy_load_optimisers()
 
161
        self._lock_mode = None
 
162
        self._lock_count = 0
 
163
 
 
164
    def add_fallback_repository(self, basis_url):
 
165
        raise errors.UnstackableRepositoryFormat(self._format,
 
166
            self.control_transport.base)
 
167
 
 
168
    def is_shared(self):
 
169
        return False
 
170
 
 
171
    def get_physical_lock_status(self):
 
172
        return False
 
173
 
 
174
    def lock_write(self):
 
175
        """See Branch.lock_write()."""
 
176
        if self._lock_mode:
 
177
            if self._lock_mode != 'w':
 
178
                raise errors.ReadOnlyError(self)
 
179
            self._lock_count += 1
 
180
        else:
 
181
            self._lock_mode = 'w'
 
182
            self._lock_count = 1
 
183
            self._transaction = transactions.WriteTransaction()
 
184
        return repository.RepositoryWriteLockResult(self.unlock, None)
 
185
 
 
186
    def break_lock(self):
 
187
        raise NotImplementedError(self.break_lock)
 
188
 
 
189
    def dont_leave_lock_in_place(self):
 
190
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
191
 
 
192
    def leave_lock_in_place(self):
 
193
        raise NotImplementedError(self.leave_lock_in_place)
 
194
 
 
195
    def lock_read(self):
 
196
        if self._lock_mode:
 
197
            if self._lock_mode not in ('r', 'w'):
 
198
                raise AssertionError
 
199
            self._lock_count += 1
 
200
        else:
 
201
            self._lock_mode = 'r'
 
202
            self._lock_count = 1
 
203
            self._transaction = transactions.ReadOnlyTransaction()
 
204
        return lock.LogicalLockResult(self.unlock)
 
205
 
 
206
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
207
    def unlock(self):
 
208
        if self._lock_count == 0:
 
209
            raise errors.LockNotHeld(self)
 
210
        if self._lock_count == 1 and self._lock_mode == 'w':
 
211
            if self._write_group is not None:
 
212
                self.abort_write_group()
 
213
                self._lock_count -= 1
 
214
                self._lock_mode = None
 
215
                raise errors.BzrError(
 
216
                    'Must end write groups before releasing write locks.')
 
217
        self._lock_count -= 1
 
218
        if self._lock_count == 0:
 
219
            self._lock_mode = None
 
220
            transaction = self._transaction
 
221
            self._transaction = None
 
222
            transaction.finish()
 
223
 
 
224
    def is_write_locked(self):
 
225
        return (self._lock_mode == 'w')
 
226
 
 
227
    def is_locked(self):
 
228
        return (self._lock_mode is not None)
 
229
 
 
230
    def get_transaction(self):
 
231
        """See Repository.get_transaction()."""
 
232
        if self._transaction is None:
 
233
            return transactions.PassThroughTransaction()
 
234
        else:
 
235
            return self._transaction
 
236
 
 
237
    def reconcile(self, other=None, thorough=False):
 
238
        """Reconcile this repository."""
 
239
        reconciler = RepoReconciler(self, thorough=thorough)
 
240
        reconciler.reconcile()
 
241
        return reconciler
 
242
 
 
243
    def supports_rich_root(self):
 
244
        return True
 
245
 
 
246
    def get_mapping(self):
 
247
        return default_mapping
 
248
 
 
249
    def make_working_trees(self):
 
250
        return not self._git.get_config().get_boolean(("core", ), "bare")
 
251
 
 
252
    def revision_graph_can_have_wrong_parents(self):
 
253
        return False
 
254
 
 
255
    def add_signature_text(self, revid, signature):
 
256
        raise errors.UnsupportedOperation(self.add_signature_text, self)
 
257
 
 
258
    def sign_revision(self, revision_id, gpg_strategy):
 
259
        raise errors.UnsupportedOperation(self.add_signature_text, self)
 
260
 
 
261
 
 
262
class LocalGitRepository(GitRepository):
 
263
    """Git repository on the file system."""
 
264
 
 
265
    def __init__(self, gitdir):
 
266
        GitRepository.__init__(self, gitdir)
 
267
        self._git = gitdir._git
 
268
        self._file_change_scanner = GitFileLastChangeScanner(self)
 
269
        self._transaction = None
 
270
 
 
271
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
272
                           timezone=None, committer=None, revprops=None,
 
273
                           revision_id=None, lossy=False):
 
274
        """Obtain a CommitBuilder for this repository.
 
275
 
 
276
        :param branch: Branch to commit to.
 
277
        :param parents: Revision ids of the parents of the new revision.
 
278
        :param config: Configuration to use.
 
279
        :param timestamp: Optional timestamp recorded for commit.
 
280
        :param timezone: Optional timezone for timestamp.
 
281
        :param committer: Optional committer to set for commit.
 
282
        :param revprops: Optional dictionary of revision properties.
 
283
        :param revision_id: Optional revision id.
 
284
        :param lossy: Whether to discard data that can not be natively
 
285
            represented, when pushing to a foreign VCS
 
286
        """
 
287
        builder = GitCommitBuilder(self, parents, config,
 
288
                timestamp, timezone, committer, revprops, revision_id,
 
289
                lossy)
 
290
        self.start_write_group()
 
291
        return builder
 
292
 
 
293
    def get_file_graph(self):
 
294
        return _mod_graph.Graph(GitFileParentProvider(
 
295
            self._file_change_scanner))
 
296
 
 
297
    def iter_files_bytes(self, desired_files):
 
298
        """Iterate through file versions.
 
299
 
 
300
        Files will not necessarily be returned in the order they occur in
 
301
        desired_files.  No specific order is guaranteed.
 
302
 
 
303
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
304
        value supplied by the caller as part of desired_files.  It should
 
305
        uniquely identify the file version in the caller's context.  (Examples:
 
306
        an index number or a TreeTransform trans_id.)
 
307
 
 
308
        bytes_iterator is an iterable of bytestrings for the file.  The
 
309
        kind of iterable and length of the bytestrings are unspecified, but for
 
310
        this implementation, it is a list of bytes produced by
 
311
        VersionedFile.get_record_stream().
 
312
 
 
313
        :param desired_files: a list of (file_id, revision_id, identifier)
 
314
            triples
 
315
        """
 
316
        per_revision = {}
 
317
        for (file_id, revision_id, identifier) in desired_files:
 
318
            per_revision.setdefault(revision_id, []).append(
 
319
                (file_id, identifier))
 
320
        for revid, files in per_revision.iteritems():
 
321
            try:
 
322
                (commit_id, mapping) = self.lookup_bzr_revision_id(revid)
 
323
            except errors.NoSuchRevision:
 
324
                raise errors.RevisionNotPresent(revid, self)
 
325
            try:
 
326
                commit = self._git.object_store[commit_id]
 
327
            except KeyError:
 
328
                raise errors.RevisionNotPresent(revid, self)
 
329
            root_tree = commit.tree
 
330
            for fileid, identifier in files:
 
331
                try:
 
332
                    path = mapping.parse_file_id(fileid)
 
333
                except ValueError:
 
334
                    raise errors.RevisionNotPresent((fileid, revid), self)
 
335
                try:
 
336
                    obj = tree_lookup_path(
 
337
                        self._git.object_store.__getitem__, root_tree, path)
 
338
                    if isinstance(obj, tuple):
 
339
                        (mode, item_id) = obj
 
340
                        obj = self._git.object_store[item_id]
 
341
                except KeyError:
 
342
                    raise errors.RevisionNotPresent((fileid, revid), self)
 
343
                else:
 
344
                    if obj.type_name == "tree":
 
345
                        yield (identifier, [])
 
346
                    elif obj.type_name == "blob":
 
347
                        yield (identifier, obj.chunked)
 
348
                    else:
 
349
                        raise AssertionError("file text resolved to %r" % obj)
 
350
 
 
351
    def gather_stats(self, revid=None, committers=None):
 
352
        """See Repository.gather_stats()."""
 
353
        result = super(LocalGitRepository, self).gather_stats(revid, committers)
 
354
        revs = []
 
355
        for sha in self._git.object_store:
 
356
            o = self._git.object_store[sha]
 
357
            if o.type_name == "commit":
 
358
                revs.append(o.id)
 
359
        result['revisions'] = len(revs)
 
360
        return result
 
361
 
 
362
    def _iter_revision_ids(self):
 
363
        mapping = self.get_mapping()
 
364
        for sha in self._git.object_store:
 
365
            o = self._git.object_store[sha]
 
366
            if not isinstance(o, Commit):
 
367
                continue
 
368
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
 
369
                mapping.revision_id_foreign_to_bzr)
 
370
            yield o.id, rev.revision_id, roundtrip_revid
 
371
 
 
372
    def all_revision_ids(self):
 
373
        ret = set()
 
374
        for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
 
375
            if roundtrip_revid:
 
376
                ret.add(roundtrip_revid)
 
377
            else:
 
378
                ret.add(revid)
 
379
        return list(ret)
 
380
 
 
381
    def _get_parents(self, revid, no_alternates=False):
 
382
        if type(revid) != bytes:
 
383
            raise ValueError
 
384
        try:
 
385
            (hexsha, mapping) = self.lookup_bzr_revision_id(revid)
 
386
        except errors.NoSuchRevision:
 
387
            return None
 
388
        # FIXME: Honor no_alternates setting
 
389
        try:
 
390
            commit = self._git.object_store[hexsha]
 
391
        except KeyError:
 
392
            return None
 
393
        ret = []
 
394
        for p in commit.parents:
 
395
            try:
 
396
                ret.append(self.lookup_foreign_revision_id(p, mapping))
 
397
            except KeyError:
 
398
                ret.append(mapping.revision_id_foreign_to_bzr(p))
 
399
        return ret
 
400
 
 
401
    def _get_parent_map_no_fallbacks(self, revids):
 
402
        return self.get_parent_map(revids, no_alternates=True)
 
403
 
 
404
    def get_parent_map(self, revids, no_alternates=False):
 
405
        parent_map = {}
 
406
        for revision_id in revids:
 
407
            parents = self._get_parents(revision_id, no_alternates=no_alternates)
 
408
            if revision_id == _mod_revision.NULL_REVISION:
 
409
                parent_map[revision_id] = ()
 
410
                continue
 
411
            if parents is None:
 
412
                continue
 
413
            if len(parents) == 0:
 
414
                parents = [_mod_revision.NULL_REVISION]
 
415
            parent_map[revision_id] = tuple(parents)
 
416
        return parent_map
 
417
 
 
418
    def get_known_graph_ancestry(self, revision_ids):
 
419
        """Return the known graph for a set of revision ids and their ancestors.
 
420
        """
 
421
        pending = set(revision_ids)
 
422
        parent_map = {}
 
423
        while pending:
 
424
            this_parent_map = {}
 
425
            for revid in pending:
 
426
                if revid == _mod_revision.NULL_REVISION:
 
427
                    continue
 
428
                parents = self._get_parents(revid)
 
429
                if parents is not None:
 
430
                    this_parent_map[revid] = parents
 
431
            parent_map.update(this_parent_map)
 
432
            pending = set()
 
433
            map(pending.update, this_parent_map.itervalues())
 
434
            pending = pending.difference(parent_map)
 
435
        return _mod_graph.KnownGraph(parent_map)
 
436
 
 
437
    def get_signature_text(self, revision_id):
 
438
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
439
        try:
 
440
            commit = self._git.object_store[git_commit_id]
 
441
        except KeyError:
 
442
            raise errors.NoSuchRevision(self, revision_id)
 
443
        if commit.gpgsig is None:
 
444
            raise errors.NoSuchRevision(self, revision_id)
 
445
        return commit.gpgsig
 
446
 
 
447
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
448
        result = GitCheck(self, check_repo=check_repo)
 
449
        result.check(callback_refs)
 
450
        return result
 
451
 
 
452
    def pack(self, hint=None, clean_obsolete_packs=False):
 
453
        self._git.object_store.pack_loose_objects()
 
454
 
 
455
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
 
456
        """Lookup a revision id.
 
457
 
 
458
        :param foreign_revid: Foreign revision id to look up
 
459
        :param mapping: Mapping to use (use default mapping if not specified)
 
460
        :raise KeyError: If foreign revision was not found
 
461
        :return: bzr revision id
 
462
        """
 
463
        if type(foreign_revid) is not str:
 
464
            raise TypeError(foreign_revid)
 
465
        if mapping is None:
 
466
            mapping = self.get_mapping()
 
467
        if foreign_revid == ZERO_SHA:
 
468
            return _mod_revision.NULL_REVISION
 
469
        commit = self._git.object_store.peel_sha(foreign_revid)
 
470
        if not isinstance(commit, Commit):
 
471
            raise NotCommitError(commit.id)
 
472
        rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
 
473
            mapping.revision_id_foreign_to_bzr)
 
474
        # FIXME: check testament before doing this?
 
475
        if roundtrip_revid:
 
476
            return roundtrip_revid
 
477
        else:
 
478
            return rev.revision_id
 
479
 
 
480
    def has_signature_for_revision_id(self, revision_id):
 
481
        """Check whether a GPG signature is present for this revision.
 
482
 
 
483
        This is never the case for Git repositories.
 
484
        """
 
485
        try:
 
486
            self.get_signature_text(revision_id)
 
487
        except errors.NoSuchRevision:
 
488
            return False
 
489
        else:
 
490
            return True
 
491
 
 
492
    def verify_revision_signature(self, revision_id, gpg_strategy):
 
493
        """Verify the signature on a revision.
 
494
 
 
495
        :param revision_id: the revision to verify
 
496
        :gpg_strategy: the GPGStrategy object to used
 
497
 
 
498
        :return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
 
499
        """
 
500
        from breezy import gpg
 
501
        with self.lock_read():
 
502
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
503
            try:
 
504
                commit = self._git.object_store[git_commit_id]
 
505
            except KeyError:
 
506
                raise errors.NoSuchRevision(self, revision_id)
 
507
 
 
508
            if commit.gpgsig is None:
 
509
                return gpg.SIGNATURE_NOT_SIGNED, None
 
510
 
 
511
            without_sig = Commit.from_string(commit.as_raw_string())
 
512
            without_sig.gpgsig = None
 
513
 
 
514
            (result, key, plain_text) = gpg_strategy.verify(without_sig.as_raw_string(), commit.gpgsig)
 
515
            return (result, key)
 
516
 
 
517
    def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
 
518
        """Lookup a bzr revision id in a Git repository.
 
519
 
 
520
        :param bzr_revid: Bazaar revision id
 
521
        :param mapping: Optional mapping to use
 
522
        :return: Tuple with git commit id, mapping that was used and supplement
 
523
            details
 
524
        """
 
525
        try:
 
526
            (git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
 
527
        except errors.InvalidRevisionId:
 
528
            if mapping is None:
 
529
                mapping = self.get_mapping()
 
530
            try:
 
531
                return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
 
532
                        mapping)
 
533
            except KeyError:
 
534
                # Update refs from Git commit objects
 
535
                # FIXME: Hitting this a lot will be very inefficient...
 
536
                pb = ui.ui_factory.nested_progress_bar()
 
537
                try:
 
538
                    for i, (git_sha, revid, roundtrip_revid) in enumerate(self._iter_revision_ids()):
 
539
                        if not roundtrip_revid:
 
540
                            continue
 
541
                        pb.update("resolving revision id", i)
 
542
                        refname = mapping.revid_as_refname(roundtrip_revid)
 
543
                        self._git.refs[refname] = git_sha
 
544
                        if roundtrip_revid == bzr_revid:
 
545
                            return git_sha, mapping
 
546
                finally:
 
547
                    pb.finished()
 
548
                raise errors.NoSuchRevision(self, bzr_revid)
 
549
        else:
 
550
            return (git_sha, mapping)
 
551
 
 
552
    def get_revision(self, revision_id):
 
553
        if not isinstance(revision_id, str):
 
554
            raise errors.InvalidRevisionId(revision_id, self)
 
555
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
556
        try:
 
557
            commit = self._git.object_store[git_commit_id]
 
558
        except KeyError:
 
559
            raise errors.NoSuchRevision(self, revision_id)
 
560
        revision, roundtrip_revid, verifiers = mapping.import_commit(
 
561
            commit, self.lookup_foreign_revision_id)
 
562
        if revision is None:
 
563
            raise AssertionError
 
564
        # FIXME: check verifiers ?
 
565
        if roundtrip_revid:
 
566
            revision.revision_id = roundtrip_revid
 
567
        return revision
 
568
 
 
569
    def has_revision(self, revision_id):
 
570
        """See Repository.has_revision."""
 
571
        if revision_id == _mod_revision.NULL_REVISION:
 
572
            return True
 
573
        try:
 
574
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
575
        except errors.NoSuchRevision:
 
576
            return False
 
577
        return (git_commit_id in self._git)
 
578
 
 
579
    def has_revisions(self, revision_ids):
 
580
        """See Repository.has_revisions."""
 
581
        return set(filter(self.has_revision, revision_ids))
 
582
 
 
583
    def iter_revisions(self, revision_ids):
 
584
        """See Repository.get_revisions."""
 
585
        for revid in revision_ids:
 
586
            try:
 
587
                rev = self.get_revision(revid)
 
588
            except errors.NoSuchRevision:
 
589
                rev = None
 
590
            yield (revid, rev)
 
591
 
 
592
    def revision_trees(self, revids):
 
593
        """See Repository.revision_trees."""
 
594
        for revid in revids:
 
595
            yield self.revision_tree(revid)
 
596
 
 
597
    def revision_tree(self, revision_id):
 
598
        """See Repository.revision_tree."""
 
599
        if revision_id is None:
 
600
            raise ValueError('invalid revision id %s' % revision_id)
 
601
        return GitRevisionTree(self, revision_id)
 
602
 
 
603
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
 
604
        """Produce a generator of revision deltas.
 
605
 
 
606
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
607
        Trees will be held in memory until the generator exits.
 
608
        Each delta is relative to the revision's lefthand predecessor.
 
609
 
 
610
        :param specific_fileids: if not None, the result is filtered
 
611
          so that only those file-ids, their parents and their
 
612
          children are included.
 
613
        """
 
614
        # Get the revision-ids of interest
 
615
        required_trees = set()
 
616
        for revision in revisions:
 
617
            required_trees.add(revision.revision_id)
 
618
            required_trees.update(revision.parent_ids[:1])
 
619
 
 
620
        trees = dict((t.get_revision_id(), t) for
 
621
            t in self.revision_trees(required_trees))
 
622
 
 
623
        # Calculate the deltas
 
624
        for revision in revisions:
 
625
            if not revision.parent_ids:
 
626
                old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
 
627
            else:
 
628
                old_tree = trees[revision.parent_ids[0]]
 
629
            new_tree = trees[revision.revision_id]
 
630
            if specific_fileids is not None:
 
631
                specific_files = [new_tree.id2path(fid) for fid in specific_fileids]
 
632
            else:
 
633
                specific_files = None
 
634
            yield new_tree.changes_from(old_tree, specific_files=specific_files)
 
635
 
 
636
    def set_make_working_trees(self, trees):
 
637
        raise errors.UnsupportedOperation(self.set_make_working_trees, self)
 
638
 
 
639
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
 
640
        progress=None, limit=None):
 
641
        return self._git.fetch_objects(determine_wants, graph_walker, progress,
 
642
            limit=limit)
 
643
 
 
644
 
 
645
class GitRepositoryFormat(repository.RepositoryFormat):
 
646
    """Git repository format."""
 
647
 
 
648
    supports_versioned_directories = False
 
649
    supports_tree_reference = True
 
650
    rich_root_data = True
 
651
    supports_leaving_lock = False
 
652
    fast_deltas = True
 
653
    supports_funky_characters = True
 
654
    supports_external_lookups = False
 
655
    supports_full_versioned_files = False
 
656
    supports_revision_signatures = False
 
657
    supports_nesting_repositories = False
 
658
    revision_graph_can_have_wrong_parents = False
 
659
    supports_unreferenced_revisions = True
 
660
    supports_setting_revision_ids = False
 
661
    supports_storing_branch_nick = False
 
662
    supports_overriding_transport = False
 
663
    supports_custom_revision_properties = False
 
664
    records_per_file_revision = False
 
665
 
 
666
    @property
 
667
    def _matchingcontroldir(self):
 
668
        from .dir import LocalGitControlDirFormat
 
669
        return LocalGitControlDirFormat()
 
670
 
 
671
    def get_format_description(self):
 
672
        return "Git Repository"
 
673
 
 
674
    def initialize(self, controldir, shared=False, _internal=False):
 
675
        from .dir import GitDir
 
676
        if not isinstance(controldir, GitDir):
 
677
            raise errors.UninitializableFormat(self)
 
678
        return controldir.open_repository()
 
679
 
 
680
    def check_conversion_target(self, target_repo_format):
 
681
        return target_repo_format.rich_root_data
 
682
 
 
683
    def get_foreign_tests_repository_factory(self):
 
684
        from .tests.test_repository import (
 
685
            ForeignTestsRepositoryFactory,
 
686
            )
 
687
        return ForeignTestsRepositoryFactory()
 
688
 
 
689
    def network_name(self):
 
690
        return b"git"
 
691
 
 
692
 
 
693
def get_extra_interrepo_test_combinations():
 
694
    from ...bzr.groupcompress_repo import RepositoryFormat2a
 
695
    from . import interrepo
 
696
    return [
 
697
            (interrepo.InterLocalGitNonGitRepository, GitRepositoryFormat(), RepositoryFormat2a()),
 
698
            (interrepo.InterLocalGitLocalGitRepository, GitRepositoryFormat(), GitRepositoryFormat()),
 
699
            (interrepo.InterToLocalGitRepository, RepositoryFormat2a(), GitRepositoryFormat()),
 
700
        ]