/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

Make GitSmartRemoteNotSupported derive from UnsupportedOperation.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007 Canonical Ltd
 
2
# Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
 
 
18
"""An adapter between a Git Repository and a Bazaar Branch"""
 
19
 
 
20
from bzrlib import (
 
21
    check,
 
22
    errors,
 
23
    graph as _mod_graph,
 
24
    inventory,
 
25
    repository,
 
26
    revision,
 
27
    )
 
28
try:
 
29
    from bzrlib.revisiontree import InventoryRevisionTree
 
30
except ImportError: # bzr < 2.4
 
31
    from bzrlib.revisiontree import RevisionTree as InventoryRevisionTree
 
32
from bzrlib.foreign import (
 
33
    ForeignRepository,
 
34
    )
 
35
 
 
36
from bzrlib.plugins.git.commit import (
 
37
    GitCommitBuilder,
 
38
    )
 
39
from bzrlib.plugins.git.filegraph import (
 
40
    GitFileLastChangeScanner,
 
41
    GitFileParentProvider,
 
42
    )
 
43
from bzrlib.plugins.git.mapping import (
 
44
    default_mapping,
 
45
    foreign_vcs_git,
 
46
    mapping_registry,
 
47
    )
 
48
from bzrlib.plugins.git.tree import (
 
49
    GitRevisionTree,
 
50
    )
 
51
 
 
52
 
 
53
from dulwich.objects import (
 
54
    Commit,
 
55
    Tag,
 
56
    ZERO_SHA,
 
57
    )
 
58
from dulwich.object_store import (
 
59
    tree_lookup_path,
 
60
    )
 
61
 
 
62
 
 
63
class RepoReconciler(object):
 
64
    """Reconciler that reconciles a repository.
 
65
 
 
66
    """
 
67
 
 
68
    def __init__(self, repo, other=None, thorough=False):
 
69
        """Construct a RepoReconciler.
 
70
 
 
71
        :param thorough: perform a thorough check which may take longer but
 
72
                         will correct non-data loss issues such as incorrect
 
73
                         cached data.
 
74
        """
 
75
        self.repo = repo
 
76
 
 
77
    def reconcile(self):
 
78
        """Perform reconciliation.
 
79
 
 
80
        After reconciliation the following attributes document found issues:
 
81
        inconsistent_parents: The number of revisions in the repository whose
 
82
                              ancestry was being reported incorrectly.
 
83
        garbage_inventories: The number of inventory objects without revisions
 
84
                             that were garbage collected.
 
85
        """
 
86
 
 
87
 
 
88
class GitCheck(check.Check):
 
89
 
 
90
    def __init__(self, repository, check_repo=True):
 
91
        self.repository = repository
 
92
        self.checked_rev_cnt = 0
 
93
 
 
94
    def check(self, callback_refs=None, check_repo=True):
 
95
        if callback_refs is None:
 
96
            callback_refs = {}
 
97
        self.repository.lock_read()
 
98
        self.repository.unlock()
 
99
 
 
100
    def report_results(self, verbose):
 
101
        pass
 
102
 
 
103
 
 
104
class GitRepository(ForeignRepository):
 
105
    """An adapter to git repositories for bzr."""
 
106
 
 
107
    _serializer = None
 
108
    vcs = foreign_vcs_git
 
109
    chk_bytes = None
 
110
 
 
111
    def __init__(self, gitdir, lockfiles):
 
112
        super(GitRepository, self).__init__(GitRepositoryFormat(),
 
113
            gitdir, lockfiles)
 
114
        self._transport = lockfiles._transport
 
115
        from bzrlib.plugins.git import fetch, push
 
116
        for optimiser in [fetch.InterRemoteGitNonGitRepository,
 
117
                          fetch.InterLocalGitNonGitRepository,
 
118
                          fetch.InterGitGitRepository,
 
119
                          push.InterToLocalGitRepository,
 
120
                          push.InterToRemoteGitRepository]:
 
121
            repository.InterRepository.register_optimiser(optimiser)
 
122
 
 
123
    def add_fallback_repository(self, basis_url):
 
124
        raise errors.UnstackableRepositoryFormat(self._format,
 
125
            self.control_transport.base)
 
126
 
 
127
    def is_shared(self):
 
128
        return False
 
129
 
 
130
    def reconcile(self, other=None, thorough=False):
 
131
        """Reconcile this repository."""
 
132
        reconciler = RepoReconciler(self, thorough=thorough)
 
133
        reconciler.reconcile()
 
134
        return reconciler
 
135
 
 
136
    def supports_rich_root(self):
 
137
        return True
 
138
 
 
139
    def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
 
140
        # This class isn't deprecated
 
141
        pass
 
142
 
 
143
    def get_mapping(self):
 
144
        return default_mapping
 
145
 
 
146
    def make_working_trees(self):
 
147
        return not self._git.bare
 
148
 
 
149
    def revision_graph_can_have_wrong_parents(self):
 
150
        return False
 
151
 
 
152
    def dfetch(self, source, stop_revision):
 
153
        interrepo = repository.InterRepository.get(source, self)
 
154
        return interrepo.dfetch(stop_revision)
 
155
 
 
156
    def add_signature_text(self, revid, signature):
 
157
        raise errors.UnsupportedOperation(self.add_signature_text, self)
 
158
 
 
159
 
 
160
class LocalGitRepository(GitRepository):
 
161
    """Git repository on the file system."""
 
162
 
 
163
    def __init__(self, gitdir, lockfiles):
 
164
        GitRepository.__init__(self, gitdir, lockfiles)
 
165
        self.base = gitdir.root_transport.base
 
166
        self._git = gitdir._git
 
167
        self._file_change_scanner = GitFileLastChangeScanner(self)
 
168
 
 
169
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
170
                           timezone=None, committer=None, revprops=None,
 
171
                           revision_id=None, lossy=False):
 
172
        """Obtain a CommitBuilder for this repository.
 
173
 
 
174
        :param branch: Branch to commit to.
 
175
        :param parents: Revision ids of the parents of the new revision.
 
176
        :param config: Configuration to use.
 
177
        :param timestamp: Optional timestamp recorded for commit.
 
178
        :param timezone: Optional timezone for timestamp.
 
179
        :param committer: Optional committer to set for commit.
 
180
        :param revprops: Optional dictionary of revision properties.
 
181
        :param revision_id: Optional revision id.
 
182
        :param lossy: Whether to discard data that can not be natively
 
183
            represented, when pushing to a foreign VCS
 
184
        """
 
185
        self.start_write_group()
 
186
        return GitCommitBuilder(self, parents, config,
 
187
            timestamp, timezone, committer, revprops, revision_id,
 
188
            lossy)
 
189
 
 
190
    def get_file_graph(self):
 
191
        return _mod_graph.Graph(GitFileParentProvider(
 
192
            self._file_change_scanner))
 
193
 
 
194
    def iter_files_bytes(self, desired_files):
 
195
        """Iterate through file versions.
 
196
 
 
197
        Files will not necessarily be returned in the order they occur in
 
198
        desired_files.  No specific order is guaranteed.
 
199
 
 
200
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
201
        value supplied by the caller as part of desired_files.  It should
 
202
        uniquely identify the file version in the caller's context.  (Examples:
 
203
        an index number or a TreeTransform trans_id.)
 
204
 
 
205
        bytes_iterator is an iterable of bytestrings for the file.  The
 
206
        kind of iterable and length of the bytestrings are unspecified, but for
 
207
        this implementation, it is a list of bytes produced by
 
208
        VersionedFile.get_record_stream().
 
209
 
 
210
        :param desired_files: a list of (file_id, revision_id, identifier)
 
211
            triples
 
212
        """
 
213
        per_revision = {}
 
214
        for (file_id, revision_id, identifier) in desired_files:
 
215
            per_revision.setdefault(revision_id, []).append(
 
216
                (file_id, identifier))
 
217
        for revid, files in per_revision.iteritems():
 
218
            (commit_id, mapping) = self.lookup_bzr_revision_id(revid)
 
219
            try:
 
220
                commit = self._git.object_store[commit_id]
 
221
            except KeyError:
 
222
                raise errors.RevisionNotPresent(revid, self)
 
223
            root_tree = commit.tree
 
224
            for fileid, identifier in files:
 
225
                path = mapping.parse_file_id(fileid)
 
226
                try:
 
227
                    obj = tree_lookup_path(
 
228
                        self._git.object_store.__getitem__, root_tree, path)
 
229
                    if isinstance(obj, tuple):
 
230
                        (mode, item_id) = obj
 
231
                        obj = self._git.object_store[item_id]
 
232
                except KeyError:
 
233
                    raise errors.RevisionNotPresent((fileid, revid), self)
 
234
                else:
 
235
                    if obj.type_name == "tree":
 
236
                        yield (identifier, [])
 
237
                    elif obj.type_name == "blob":
 
238
                        yield (identifier, obj.chunked)
 
239
                    else:
 
240
                        raise AssertionError("file text resolved to %r" % obj)
 
241
 
 
242
    def _iter_revision_ids(self):
 
243
        mapping = self.get_mapping()
 
244
        for sha in self._git.object_store:
 
245
            o = self._git.object_store[sha]
 
246
            if not isinstance(o, Commit):
 
247
                continue
 
248
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
 
249
                mapping.revision_id_foreign_to_bzr)
 
250
            yield o.id, rev.revision_id, roundtrip_revid
 
251
 
 
252
    def all_revision_ids(self):
 
253
        ret = set([])
 
254
        for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
 
255
            if roundtrip_revid:
 
256
                ret.add(roundtrip_revid)
 
257
            else:
 
258
                ret.add(revid)
 
259
        return ret
 
260
 
 
261
    def _get_parents(self, revid):
 
262
        if type(revid) != str:
 
263
            raise ValueError
 
264
        try:
 
265
            (hexsha, mapping) = self.lookup_bzr_revision_id(revid)
 
266
        except errors.NoSuchRevision:
 
267
            return None
 
268
        try:
 
269
            commit = self._git[hexsha]
 
270
        except KeyError:
 
271
            return None
 
272
        return [
 
273
            self.lookup_foreign_revision_id(p, mapping)
 
274
            for p in commit.parents]
 
275
 
 
276
    def get_parent_map(self, revids):
 
277
        parent_map = {}
 
278
        for revision_id in revids:
 
279
            parents = self._get_parents(revision_id)
 
280
            if revision_id == revision.NULL_REVISION:
 
281
                parent_map[revision_id] = ()
 
282
                continue
 
283
            if parents is None:
 
284
                continue
 
285
            if len(parents) == 0:
 
286
                parents = [revision.NULL_REVISION]
 
287
            parent_map[revision_id] = tuple(parents)
 
288
        return parent_map
 
289
 
 
290
    def get_known_graph_ancestry(self, revision_ids):
 
291
        """Return the known graph for a set of revision ids and their ancestors.
 
292
        """
 
293
        pending = set(revision_ids)
 
294
        parent_map = {}
 
295
        while pending:
 
296
            this_parent_map = {}
 
297
            for revid in pending:
 
298
                if revid == revision.NULL_REVISION:
 
299
                    continue
 
300
                parents = self._get_parents(revid)
 
301
                if parents is not None:
 
302
                    this_parent_map[revid] = parents
 
303
            parent_map.update(this_parent_map)
 
304
            pending = set()
 
305
            map(pending.update, this_parent_map.itervalues())
 
306
            pending = pending.difference(parent_map)
 
307
        return _mod_graph.KnownGraph(parent_map)
 
308
 
 
309
    def get_signature_text(self, revision_id):
 
310
        raise errors.NoSuchRevision(self, revision_id)
 
311
 
 
312
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
313
        result = GitCheck(self, check_repo=check_repo)
 
314
        result.check(callback_refs)
 
315
        return result
 
316
 
 
317
    def pack(self, hint=None, clean_obsolete_packs=False):
 
318
        self._git.object_store.pack_loose_objects()
 
319
 
 
320
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
 
321
        """Lookup a revision id.
 
322
 
 
323
        """
 
324
        assert type(foreign_revid) is str
 
325
        if mapping is None:
 
326
            mapping = self.get_mapping()
 
327
        if foreign_revid == ZERO_SHA:
 
328
            return revision.NULL_REVISION
 
329
        commit = self._git.object_store[foreign_revid]
 
330
        while isinstance(commit, Tag):
 
331
            commit = self._git[commit.object[1]]
 
332
        rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
 
333
            mapping.revision_id_foreign_to_bzr)
 
334
        # FIXME: check testament before doing this?
 
335
        if roundtrip_revid:
 
336
            return roundtrip_revid
 
337
        else:
 
338
            return rev.revision_id
 
339
 
 
340
    def has_signature_for_revision_id(self, revision_id):
 
341
        """Check whether a GPG signature is present for this revision.
 
342
 
 
343
        This is never the case for Git repositories.
 
344
        """
 
345
        return False
 
346
 
 
347
    def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
 
348
        """Lookup a bzr revision id in a Git repository.
 
349
 
 
350
        :param bzr_revid: Bazaar revision id
 
351
        :param mapping: Optional mapping to use
 
352
        :return: Tuple with git commit id, mapping that was used and supplement
 
353
            details
 
354
        """
 
355
        try:
 
356
            (git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
 
357
        except errors.InvalidRevisionId:
 
358
            if mapping is None:
 
359
                mapping = self.get_mapping()
 
360
            try:
 
361
                return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
 
362
                        mapping)
 
363
            except KeyError:
 
364
                # Update refs from Git commit objects
 
365
                # FIXME: Hitting this a lot will be very inefficient...
 
366
                for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
 
367
                    if not roundtrip_revid:
 
368
                        continue
 
369
                    refname = mapping.revid_as_refname(roundtrip_revid)
 
370
                    self._git.refs[refname] = git_sha
 
371
                    if roundtrip_revid == bzr_revid:
 
372
                        return git_sha, mapping
 
373
                raise errors.NoSuchRevision(self, bzr_revid)
 
374
        else:
 
375
            return (git_sha, mapping)
 
376
 
 
377
    def get_revision(self, revision_id):
 
378
        if not isinstance(revision_id, str):
 
379
            raise errors.InvalidRevisionId(revision_id, self)
 
380
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
381
        try:
 
382
            commit = self._git[git_commit_id]
 
383
        except KeyError:
 
384
            raise errors.NoSuchRevision(self, revision_id)
 
385
        revision, roundtrip_revid, verifiers = mapping.import_commit(
 
386
            commit, self.lookup_foreign_revision_id)
 
387
        assert revision is not None
 
388
        # FIXME: check verifiers ?
 
389
        if roundtrip_revid:
 
390
            revision.revision_id = roundtrip_revid
 
391
        return revision
 
392
 
 
393
    def has_revision(self, revision_id):
 
394
        """See Repository.has_revision."""
 
395
        if revision_id == revision.NULL_REVISION:
 
396
            return True
 
397
        try:
 
398
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
399
        except errors.NoSuchRevision:
 
400
            return False
 
401
        return (git_commit_id in self._git)
 
402
 
 
403
    def has_revisions(self, revision_ids):
 
404
        """See Repository.has_revisions."""
 
405
        return set(filter(self.has_revision, revision_ids))
 
406
 
 
407
    def get_revisions(self, revids):
 
408
        """See Repository.get_revisions."""
 
409
        return [self.get_revision(r) for r in revids]
 
410
 
 
411
    def revision_trees(self, revids):
 
412
        """See Repository.revision_trees."""
 
413
        for revid in revids:
 
414
            yield self.revision_tree(revid)
 
415
 
 
416
    def revision_tree(self, revision_id):
 
417
        """See Repository.revision_tree."""
 
418
        revision_id = revision.ensure_null(revision_id)
 
419
        if revision_id == revision.NULL_REVISION:
 
420
            inv = inventory.Inventory(root_id=None)
 
421
            inv.revision_id = revision_id
 
422
            return InventoryRevisionTree(self, inv, revision_id)
 
423
        return GitRevisionTree(self, revision_id)
 
424
 
 
425
    def get_inventory(self, revision_id):
 
426
        raise NotImplementedError(self.get_inventory)
 
427
 
 
428
    def set_make_working_trees(self, trees):
 
429
        raise errors.UnsupportedOperation(self.set_make_working_trees, self)
 
430
        # TODO: Set bare= in the configuration bug=777065
 
431
 
 
432
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
 
433
        progress=None):
 
434
        return self._git.fetch_objects(determine_wants, graph_walker, progress)
 
435
 
 
436
 
 
437
class GitRepositoryFormat(repository.RepositoryFormat):
 
438
    """Git repository format."""
 
439
 
 
440
    supports_versioned_directories = False
 
441
    supports_tree_reference = False
 
442
    rich_root_data = True
 
443
    supports_leaving_lock = False
 
444
    fast_deltas = True
 
445
    supports_funky_characters = True
 
446
    supports_external_lookups = False
 
447
    supports_full_versioned_files = False
 
448
    supports_revision_signatures = False
 
449
    supports_nesting_repositories = False
 
450
    revision_graph_can_have_wrong_parents = False
 
451
 
 
452
    @property
 
453
    def _matchingbzrdir(self):
 
454
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
 
455
        return LocalGitControlDirFormat()
 
456
 
 
457
    def get_format_description(self):
 
458
        return "Git Repository"
 
459
 
 
460
    def initialize(self, controldir, shared=False, _internal=False):
 
461
        from bzrlib.plugins.git.dir import GitDir
 
462
        if not isinstance(controldir, GitDir):
 
463
            raise errors.UninitializableFormat(self)
 
464
        return controldir.open_repository()
 
465
 
 
466
    def check_conversion_target(self, target_repo_format):
 
467
        return target_repo_format.rich_root_data
 
468
 
 
469
    def get_foreign_tests_repository_factory(self):
 
470
        from bzrlib.plugins.git.tests.test_repository import (
 
471
            ForeignTestsRepositoryFactory,
 
472
            )
 
473
        return ForeignTestsRepositoryFactory()
 
474
 
 
475
    def network_name(self):
 
476
        return "git"