/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

More work on roundtrip push support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
"""An adapter between a Git Repository and a Bazaar Branch"""
19
19
 
20
20
from bzrlib import (
21
 
    check,
22
21
    errors,
23
 
    graph as _mod_graph,
24
22
    inventory,
25
23
    repository,
26
24
    revision,
 
25
    revisiontree,
27
26
    )
28
 
try:
29
 
    from bzrlib.revisiontree import InventoryRevisionTree
30
 
except ImportError: # bzr < 2.4
31
 
    from bzrlib.revisiontree import RevisionTree as InventoryRevisionTree
32
27
from bzrlib.foreign import (
33
28
    ForeignRepository,
34
29
    )
36
31
from bzrlib.plugins.git.commit import (
37
32
    GitCommitBuilder,
38
33
    )
39
 
from bzrlib.plugins.git.filegraph import (
40
 
    GitFileLastChangeScanner,
41
 
    GitFileParentProvider,
42
 
    )
43
34
from bzrlib.plugins.git.mapping import (
44
35
    default_mapping,
45
 
    foreign_vcs_git,
 
36
    foreign_git,
46
37
    mapping_registry,
47
38
    )
48
39
from bzrlib.plugins.git.tree import (
49
40
    GitRevisionTree,
50
41
    )
 
42
from bzrlib.plugins.git.versionedfiles import (
 
43
    GitRevisions,
 
44
    GitTexts,
 
45
    )
51
46
 
52
47
 
53
48
from dulwich.objects import (
54
49
    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
 
50
    )
102
51
 
103
52
 
104
53
class GitRepository(ForeignRepository):
105
54
    """An adapter to git repositories for bzr."""
106
55
 
107
56
    _serializer = None
108
 
    vcs = foreign_vcs_git
109
 
    chk_bytes = None
 
57
    _commit_builder_class = GitCommitBuilder
 
58
    vcs = foreign_git
110
59
 
111
60
    def __init__(self, gitdir, lockfiles):
112
 
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir, lockfiles)
 
61
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir,
 
62
            lockfiles)
113
63
        from bzrlib.plugins.git import fetch, push
114
64
        for optimiser in [fetch.InterRemoteGitNonGitRepository,
115
65
                          fetch.InterLocalGitNonGitRepository,
118
68
                          push.InterToRemoteGitRepository]:
119
69
            repository.InterRepository.register_optimiser(optimiser)
120
70
 
121
 
    def add_fallback_repository(self, basis_url):
122
 
        raise errors.UnstackableRepositoryFormat(self._format, self.control_transport.base)
123
 
 
124
71
    def is_shared(self):
125
72
        return False
126
73
 
127
 
    def reconcile(self, other=None, thorough=False):
128
 
        """Reconcile this repository."""
129
 
        reconciler = RepoReconciler(self, thorough=thorough)
130
 
        reconciler.reconcile()
131
 
        return reconciler
132
 
 
133
74
    def supports_rich_root(self):
134
75
        return True
135
76
 
136
 
    def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
 
77
    def _warn_if_deprecated(self, branch=None):
137
78
        # This class isn't deprecated
138
79
        pass
139
80
 
150
91
        interrepo = repository.InterRepository.get(source, self)
151
92
        return interrepo.dfetch(stop_revision)
152
93
 
153
 
    def add_signature_text(self, revid, signature):
154
 
        raise errors.UnsupportedOperation(self.add_signature_text, self)
155
 
 
156
94
 
157
95
class LocalGitRepository(GitRepository):
158
96
    """Git repository on the file system."""
161
99
        GitRepository.__init__(self, gitdir, lockfiles)
162
100
        self.base = gitdir.root_transport.base
163
101
        self._git = gitdir._git
164
 
        self._file_change_scanner = GitFileLastChangeScanner(self)
165
 
 
166
 
    def get_commit_builder(self, branch, parents, config, timestamp=None,
167
 
                           timezone=None, committer=None, revprops=None,
168
 
                           revision_id=None, lossy=False):
169
 
        """Obtain a CommitBuilder for this repository.
170
 
 
171
 
        :param branch: Branch to commit to.
172
 
        :param parents: Revision ids of the parents of the new revision.
173
 
        :param config: Configuration to use.
174
 
        :param timestamp: Optional timestamp recorded for commit.
175
 
        :param timezone: Optional timezone for timestamp.
176
 
        :param committer: Optional committer to set for commit.
177
 
        :param revprops: Optional dictionary of revision properties.
178
 
        :param revision_id: Optional revision id.
179
 
        :param lossy: Whether to discard data that can not be natively
180
 
            represented, when pushing to a foreign VCS
181
 
        """
182
 
        self.start_write_group()
183
 
        return GitCommitBuilder(self, parents, config,
184
 
            timestamp, timezone, committer, revprops, revision_id,
185
 
            lossy)
186
 
 
187
 
    def get_file_graph(self):
188
 
        return _mod_graph.Graph(GitFileParentProvider(self._file_change_scanner))
189
 
 
190
 
    def iter_files_bytes(self, desired_files):
191
 
        """Iterate through file versions.
192
 
 
193
 
        Files will not necessarily be returned in the order they occur in
194
 
        desired_files.  No specific order is guaranteed.
195
 
 
196
 
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
197
 
        value supplied by the caller as part of desired_files.  It should
198
 
        uniquely identify the file version in the caller's context.  (Examples:
199
 
        an index number or a TreeTransform trans_id.)
200
 
 
201
 
        bytes_iterator is an iterable of bytestrings for the file.  The
202
 
        kind of iterable and length of the bytestrings are unspecified, but for
203
 
        this implementation, it is a list of bytes produced by
204
 
        VersionedFile.get_record_stream().
205
 
 
206
 
        :param desired_files: a list of (file_id, revision_id, identifier)
207
 
            triples
208
 
        """
209
 
        per_revision = {}
210
 
        for (file_id, revision_id, identifier) in desired_files:
211
 
            per_revision.setdefault(revision_id, []).append((file_id, identifier))
212
 
        for revid, files in per_revision.iteritems():
213
 
            (commit_id, mapping) = self.lookup_bzr_revision_id(revid)
214
 
            try:
215
 
                commit = self._git.object_store[commit_id]
216
 
            except KeyError:
217
 
                raise errors.RevisionNotPresent(revid, self)
218
 
            root_tree = commit.tree
219
 
            for fileid, identifier in files:
220
 
                path = mapping.parse_file_id(fileid)
221
 
                try:
222
 
                    obj = tree_lookup_path(
223
 
                        self._git.object_store.__getitem__, root_tree, path)
224
 
                    if isinstance(obj, tuple):
225
 
                        (mode, item_id) = obj
226
 
                        obj = self._git.object_store[item_id]
227
 
                except KeyError:
228
 
                    raise errors.RevisionNotPresent((fileid, revid), self)
229
 
                else:
230
 
                    if obj.type_name == "tree":
231
 
                        yield (identifier, [])
232
 
                    elif obj.type_name == "blob":
233
 
                        yield (identifier, obj.chunked)
234
 
                    else:
235
 
                        raise AssertionError("file text resolved to %r" % obj)
236
 
 
 
102
        self.signatures = None
 
103
        self.revisions = GitRevisions(self, self._git.object_store)
 
104
        self.inventories = None
 
105
        self.texts = GitTexts(self)
237
106
 
238
107
    def _iter_revision_ids(self):
239
108
        mapping = self.get_mapping()
242
111
            if not isinstance(o, Commit):
243
112
                continue
244
113
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
245
 
                mapping.revision_id_foreign_to_bzr)
 
114
                self.lookup_foreign_revision_id)
246
115
            yield o.id, rev.revision_id, roundtrip_revid
247
116
 
248
117
    def all_revision_ids(self):
265
134
                commit = self._git[hexsha]
266
135
            except KeyError:
267
136
                continue
268
 
            parents = [
 
137
            parent_map[revision_id] = [
269
138
                self.lookup_foreign_revision_id(p, mapping)
270
139
                for p in commit.parents]
271
 
            if parents == []:
272
 
                parents = [revision.NULL_REVISION]
273
 
            parent_map[revision_id] = tuple(parents)
274
140
        return parent_map
275
141
 
276
 
    def get_known_graph_ancestry(self, revision_ids):
277
 
        """Return the known graph for a set of revision ids and their ancestors.
 
142
    def get_ancestry(self, revision_id, topo_sorted=True):
 
143
        """See Repository.get_ancestry().
278
144
        """
279
 
        pending = set(revision_ids)
280
 
        parent_map = {}
281
 
        while pending:
282
 
            this_parent_map = self.get_parent_map(pending)
283
 
            parent_map.update(this_parent_map)
284
 
            pending = set()
285
 
            map(pending.update, this_parent_map.itervalues())
286
 
            pending = pending.difference(parent_map)
287
 
        return _mod_graph.KnownGraph(parent_map)
 
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
288
154
 
289
155
    def get_signature_text(self, revision_id):
290
156
        raise errors.NoSuchRevision(self, revision_id)
291
157
 
292
 
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
293
 
        result = GitCheck(self, check_repo=check_repo)
294
 
        result.check(callback_refs)
295
 
        return result
296
 
 
297
158
    def pack(self, hint=None, clean_obsolete_packs=False):
298
159
        self._git.object_store.pack_loose_objects()
299
160
 
304
165
        assert type(foreign_revid) is str
305
166
        if mapping is None:
306
167
            mapping = self.get_mapping()
 
168
        from dulwich.protocol import (
 
169
            ZERO_SHA,
 
170
            )
307
171
        if foreign_revid == ZERO_SHA:
308
172
            return revision.NULL_REVISION
309
 
        commit = self._git.object_store[foreign_revid]
310
 
        while isinstance(commit, Tag):
311
 
            commit = self._git[commit.object[1]]
 
173
        commit = self._git[foreign_revid]
312
174
        rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
313
 
            mapping.revision_id_foreign_to_bzr)
 
175
            lambda x: None)
314
176
        # FIXME: check testament before doing this?
315
177
        if roundtrip_revid:
316
178
            return roundtrip_revid
327
189
            if mapping is None:
328
190
                mapping = self.get_mapping()
329
191
            try:
330
 
                return (self._git.refs[mapping.revid_as_refname(bzr_revid)], mapping)
 
192
                return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
 
193
                        mapping)
331
194
            except KeyError:
332
195
                # Update refs from Git commit objects
333
196
                # FIXME: Hitting this a lot will be very inefficient...
341
204
                raise errors.NoSuchRevision(self, bzr_revid)
342
205
 
343
206
    def get_revision(self, revision_id):
344
 
        if not isinstance(revision_id, str):
345
 
            raise errors.InvalidRevisionId(revision_id, self)
346
207
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
347
208
        try:
348
209
            commit = self._git[git_commit_id]
357
218
        return revision
358
219
 
359
220
    def has_revision(self, revision_id):
360
 
        """See Repository.has_revision."""
361
 
        if revision_id == revision.NULL_REVISION:
362
 
            return True
363
221
        try:
364
222
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
365
223
        except errors.NoSuchRevision:
367
225
        return (git_commit_id in self._git)
368
226
 
369
227
    def has_revisions(self, revision_ids):
370
 
        """See Repository.has_revisions."""
371
228
        return set(filter(self.has_revision, revision_ids))
372
229
 
373
230
    def get_revisions(self, revids):
374
 
        """See Repository.get_revisions."""
375
231
        return [self.get_revision(r) for r in revids]
376
232
 
377
233
    def revision_trees(self, revids):
378
 
        """See Repository.revision_trees."""
379
234
        for revid in revids:
380
235
            yield self.revision_tree(revid)
381
236
 
382
237
    def revision_tree(self, revision_id):
383
 
        """See Repository.revision_tree."""
384
238
        revision_id = revision.ensure_null(revision_id)
385
239
        if revision_id == revision.NULL_REVISION:
386
240
            inv = inventory.Inventory(root_id=None)
387
241
            inv.revision_id = revision_id
388
 
            return InventoryRevisionTree(self, inv, revision_id)
 
242
            return revisiontree.RevisionTree(self, inv, revision_id)
389
243
        return GitRevisionTree(self, revision_id)
390
244
 
391
245
    def get_inventory(self, revision_id):
392
 
        raise NotImplementedError(self.get_inventory)
 
246
        assert revision_id != None
 
247
        return self.revision_tree(revision_id).inventory
393
248
 
394
249
    def set_make_working_trees(self, trees):
395
 
        # TODO: Set bare= in the configuration bug=777065
396
 
        raise NotImplementedError(self.set_make_working_trees)
 
250
        pass
397
251
 
398
252
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
399
253
        progress=None):
400
254
        return self._git.fetch_objects(determine_wants, graph_walker, progress)
401
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 {}, []
 
268
 
402
269
 
403
270
class GitRepositoryFormat(repository.RepositoryFormat):
404
271
    """Git repository format."""
405
272
 
406
 
    supports_versioned_directories = False
407
273
    supports_tree_reference = False
408
274
    rich_root_data = True
409
 
    supports_leaving_lock = False
410
 
    fast_deltas = True
411
 
    supports_funky_characters = True
412
 
    supports_external_lookups = False
413
 
    supports_full_versioned_files = False
414
 
    supports_revision_signatures = False
415
 
    revision_graph_can_have_wrong_parents = False
416
 
 
417
 
    @property
418
 
    def _matchingbzrdir(self):
419
 
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
420
 
        return LocalGitControlDirFormat()
421
275
 
422
276
    def get_format_description(self):
423
277
        return "Git Repository"
424
278
 
425
 
    def initialize(self, controldir, shared=False, _internal=False):
426
 
        from bzrlib.plugins.git.dir import GitDir
427
 
        if not isinstance(controldir, GitDir):
428
 
            raise errors.UninitializableFormat(self)
429
 
        return controldir.open_repository()
 
279
    def initialize(self, url, shared=False, _internal=False):
 
280
        raise errors.UninitializableFormat(self)
430
281
 
431
282
    def check_conversion_target(self, target_repo_format):
432
283
        return target_repo_format.rich_root_data