/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

Fix two mistakes in 'bzr help git'.

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
    )
33
37
    )
34
38
from bzrlib.plugins.git.mapping import (
35
39
    default_mapping,
36
 
    foreign_git,
 
40
    foreign_vcs_git,
37
41
    mapping_registry,
38
42
    )
39
43
from bzrlib.plugins.git.tree import (
40
44
    GitRevisionTree,
41
45
    )
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
 
    )
 
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
51
97
 
52
98
 
53
99
class GitRepository(ForeignRepository):
54
100
    """An adapter to git repositories for bzr."""
55
101
 
56
102
    _serializer = None
57
 
    _commit_builder_class = GitCommitBuilder
58
 
    vcs = foreign_git
 
103
    vcs = foreign_vcs_git
 
104
    chk_bytes = None
59
105
 
60
106
    def __init__(self, gitdir, lockfiles):
61
 
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir,
62
 
            lockfiles)
 
107
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir, lockfiles)
63
108
        from bzrlib.plugins.git import fetch, push
64
109
        for optimiser in [fetch.InterRemoteGitNonGitRepository,
65
110
                          fetch.InterLocalGitNonGitRepository,
68
113
                          push.InterToRemoteGitRepository]:
69
114
            repository.InterRepository.register_optimiser(optimiser)
70
115
 
 
116
    def add_fallback_repository(self, basis_url):
 
117
        raise errors.UnstackableRepositoryFormat(self._format, self.control_transport.base)
 
118
 
71
119
    def is_shared(self):
72
120
        return False
73
121
 
 
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
 
74
128
    def supports_rich_root(self):
75
129
        return True
76
130
 
77
 
    def _warn_if_deprecated(self, branch=None):
 
131
    def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
78
132
        # This class isn't deprecated
79
133
        pass
80
134
 
91
145
        interrepo = repository.InterRepository.get(source, self)
92
146
        return interrepo.dfetch(stop_revision)
93
147
 
 
148
    def add_signature_text(self, revid, signature):
 
149
        raise errors.UnsupportedOperation(self.add_signature_text, self)
 
150
 
94
151
 
95
152
class LocalGitRepository(GitRepository):
96
153
    """Git repository on the file system."""
100
157
        self.base = gitdir.root_transport.base
101
158
        self._git = gitdir._git
102
159
        self.signatures = None
103
 
        self.revisions = GitRevisions(self, self._git.object_store)
 
160
        self.revisions = None
104
161
        self.inventories = None
105
 
        self.texts = GitTexts(self)
 
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
 
106
232
 
107
233
    def _iter_revision_ids(self):
108
234
        mapping = self.get_mapping()
111
237
            if not isinstance(o, Commit):
112
238
                continue
113
239
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
114
 
                self.lookup_foreign_revision_id)
 
240
                mapping.revision_id_foreign_to_bzr)
115
241
            yield o.id, rev.revision_id, roundtrip_revid
116
242
 
117
243
    def all_revision_ids(self):
134
260
                commit = self._git[hexsha]
135
261
            except KeyError:
136
262
                continue
137
 
            parent_map[revision_id] = [
 
263
            parents = [
138
264
                self.lookup_foreign_revision_id(p, mapping)
139
265
                for p in commit.parents]
 
266
            if parents == []:
 
267
                parents = [revision.NULL_REVISION]
 
268
            parent_map[revision_id] = tuple(parents)
140
269
        return parent_map
141
270
 
142
271
    def get_ancestry(self, revision_id, topo_sorted=True):
149
278
        graph = self.get_graph()
150
279
        for rev, parents in graph.iter_ancestry([revision_id]):
151
280
            ancestry.append(rev)
 
281
        if revision.NULL_REVISION in ancestry:
 
282
            ancestry.remove(revision.NULL_REVISION)
152
283
        ancestry.reverse()
153
284
        return [None] + ancestry
154
285
 
155
286
    def get_signature_text(self, revision_id):
156
287
        raise errors.NoSuchRevision(self, revision_id)
157
288
 
 
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
 
158
294
    def pack(self, hint=None, clean_obsolete_packs=False):
159
295
        self._git.object_store.pack_loose_objects()
160
296
 
165
301
        assert type(foreign_revid) is str
166
302
        if mapping is None:
167
303
            mapping = self.get_mapping()
168
 
        from dulwich.protocol import (
169
 
            ZERO_SHA,
170
 
            )
171
304
        if foreign_revid == ZERO_SHA:
172
305
            return revision.NULL_REVISION
173
 
        commit = self._git[foreign_revid]
 
306
        commit = self._git.object_store[foreign_revid]
 
307
        while isinstance(commit, Tag):
 
308
            commit = self._git[commit.object[1]]
174
309
        rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
175
 
            lambda x: None)
 
310
            mapping.revision_id_foreign_to_bzr)
176
311
        # FIXME: check testament before doing this?
177
312
        if roundtrip_revid:
178
313
            return roundtrip_revid
189
324
            if mapping is None:
190
325
                mapping = self.get_mapping()
191
326
            try:
192
 
                return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
193
 
                        mapping)
 
327
                return (self._git.refs[mapping.revid_as_refname(bzr_revid)], mapping)
194
328
            except KeyError:
195
329
                # Update refs from Git commit objects
196
330
                # FIXME: Hitting this a lot will be very inefficient...
204
338
                raise errors.NoSuchRevision(self, bzr_revid)
205
339
 
206
340
    def get_revision(self, revision_id):
 
341
        if not isinstance(revision_id, str):
 
342
            raise errors.InvalidRevisionId(revision_id, self)
207
343
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
208
344
        try:
209
345
            commit = self._git[git_commit_id]
218
354
        return revision
219
355
 
220
356
    def has_revision(self, revision_id):
 
357
        """See Repository.has_revision."""
 
358
        if revision_id == revision.NULL_REVISION:
 
359
            return True
221
360
        try:
222
361
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
223
362
        except errors.NoSuchRevision:
225
364
        return (git_commit_id in self._git)
226
365
 
227
366
    def has_revisions(self, revision_ids):
 
367
        """See Repository.has_revisions."""
228
368
        return set(filter(self.has_revision, revision_ids))
229
369
 
230
370
    def get_revisions(self, revids):
 
371
        """See Repository.get_revisions."""
231
372
        return [self.get_revision(r) for r in revids]
232
373
 
233
374
    def revision_trees(self, revids):
 
375
        """See Repository.revision_trees."""
234
376
        for revid in revids:
235
377
            yield self.revision_tree(revid)
236
378
 
237
379
    def revision_tree(self, revision_id):
 
380
        """See Repository.revision_tree."""
238
381
        revision_id = revision.ensure_null(revision_id)
239
382
        if revision_id == revision.NULL_REVISION:
240
383
            inv = inventory.Inventory(root_id=None)
241
384
            inv.revision_id = revision_id
242
 
            return revisiontree.RevisionTree(self, inv, revision_id)
 
385
            return InventoryRevisionTree(self, inv, revision_id)
243
386
        return GitRevisionTree(self, revision_id)
244
387
 
245
388
    def get_inventory(self, revision_id):
246
 
        assert revision_id != None
247
 
        return self.revision_tree(revision_id).inventory
 
389
        raise NotImplementedError(self.get_inventory)
248
390
 
249
391
    def set_make_working_trees(self, trees):
250
 
        pass
 
392
        # TODO: Set bare= in the configuration bug=777065
 
393
        raise NotImplementedError(self.set_make_working_trees)
251
394
 
252
395
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
253
396
        progress=None):
254
397
        return self._git.fetch_objects(determine_wants, graph_walker, progress)
255
398
 
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
399
 
270
400
class GitRepositoryFormat(repository.RepositoryFormat):
271
401
    """Git repository format."""
272
402
 
273
403
    supports_tree_reference = False
274
404
    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()
275
417
 
276
418
    def get_format_description(self):
277
419
        return "Git Repository"
278
420
 
279
 
    def initialize(self, url, shared=False, _internal=False):
280
 
        raise errors.UninitializableFormat(self)
 
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()
281
426
 
282
427
    def check_conversion_target(self, target_repo_format):
283
428
        return target_repo_format.rich_root_data