/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

break_lock is not implemented for git control directories.

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