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