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

  • Committer: Martin
  • Date: 2018-11-16 16:38:22 UTC
  • mto: This revision was merged to the branch mainline in revision 7172.
  • Revision ID: gzlist@googlemail.com-20181116163822-yg1h1cdng6w7w9kn
Make --profile-imports work on Python 3

Also tweak heading to line up correctly.

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