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

  • Committer: Jelmer Vernooij
  • Date: 2018-04-02 14:59:43 UTC
  • mto: (0.200.1913 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180402145943-s5jmpbvvf1x42pao
Just don't touch the URL if it's already a valid URL.

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