/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

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