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