/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-05-19 13:16:11 UTC
  • mto: (6968.4.3 git-archive)
  • mto: This revision was merged to the branch mainline in revision 6972.
  • Revision ID: jelmer@jelmer.uk-20180519131611-l9h9ud41j7qg1m03
Move tar/zip to breezy.archive.

Show diffs side-by-side

added added

removed removed

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