/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: Jelmer Vernooij
  • Date: 2018-07-08 14:45:27 UTC
  • mto: This revision was merged to the branch mainline in revision 7036.
  • Revision ID: jelmer@jelmer.uk-20180708144527-codhlvdcdg9y0nji
Fix a bunch of merge tests.

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