/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

Move git_remote_helper to a python module.

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,
 
27
    transactions,
 
28
    version_info as bzrlib_version,
26
29
    )
 
30
from bzrlib.decorators import only_raises
 
31
try:
 
32
    from bzrlib.revisiontree import InventoryRevisionTree
 
33
except ImportError: # bzr < 2.4
 
34
    from bzrlib.revisiontree import RevisionTree as InventoryRevisionTree
27
35
from bzrlib.foreign import (
28
36
    ForeignRepository,
29
37
    )
31
39
from bzrlib.plugins.git.commit import (
32
40
    GitCommitBuilder,
33
41
    )
 
42
from bzrlib.plugins.git.errors import (
 
43
    NotCommitError,
 
44
    )
 
45
from bzrlib.plugins.git.filegraph import (
 
46
    GitFileLastChangeScanner,
 
47
    GitFileParentProvider,
 
48
    )
34
49
from bzrlib.plugins.git.mapping import (
35
50
    default_mapping,
36
 
    foreign_git,
 
51
    foreign_vcs_git,
37
52
    mapping_registry,
38
53
    )
39
54
from bzrlib.plugins.git.tree import (
40
55
    GitRevisionTree,
41
56
    )
42
 
from bzrlib.plugins.git.versionedfiles import (
43
 
    GitRevisions,
44
 
    GitTexts,
45
 
    )
46
57
 
47
58
 
48
59
from dulwich.objects import (
49
60
    Commit,
50
 
    )
 
61
    ZERO_SHA,
 
62
    )
 
63
from dulwich.object_store import (
 
64
    tree_lookup_path,
 
65
    )
 
66
 
 
67
 
 
68
class RepoReconciler(object):
 
69
    """Reconciler that reconciles a repository.
 
70
 
 
71
    """
 
72
 
 
73
    def __init__(self, repo, other=None, thorough=False):
 
74
        """Construct a RepoReconciler.
 
75
 
 
76
        :param thorough: perform a thorough check which may take longer but
 
77
                         will correct non-data loss issues such as incorrect
 
78
                         cached data.
 
79
        """
 
80
        self.repo = repo
 
81
 
 
82
    def reconcile(self):
 
83
        """Perform reconciliation.
 
84
 
 
85
        After reconciliation the following attributes document found issues:
 
86
        inconsistent_parents: The number of revisions in the repository whose
 
87
                              ancestry was being reported incorrectly.
 
88
        garbage_inventories: The number of inventory objects without revisions
 
89
                             that were garbage collected.
 
90
        """
 
91
 
 
92
 
 
93
class GitCheck(check.Check):
 
94
 
 
95
    def __init__(self, repository, check_repo=True):
 
96
        self.repository = repository
 
97
        self.checked_rev_cnt = 0
 
98
 
 
99
    def check(self, callback_refs=None, check_repo=True):
 
100
        if callback_refs is None:
 
101
            callback_refs = {}
 
102
        self.repository.lock_read()
 
103
        self.repository.unlock()
 
104
 
 
105
    def report_results(self, verbose):
 
106
        pass
 
107
 
 
108
 
 
109
_optimisers_loaded = False
 
110
 
 
111
def lazy_load_optimisers():
 
112
    global _optimisers_loaded
 
113
    if _optimisers_loaded:
 
114
        return
 
115
    from bzrlib.plugins.git import fetch, push
 
116
    for optimiser in [fetch.InterRemoteGitNonGitRepository,
 
117
                      fetch.InterLocalGitNonGitRepository,
 
118
                      fetch.InterGitGitRepository,
 
119
                      push.InterToLocalGitRepository,
 
120
                      push.InterToRemoteGitRepository]:
 
121
        repository.InterRepository.register_optimiser(optimiser)
 
122
    _optimisers_loaded = True
51
123
 
52
124
 
53
125
class GitRepository(ForeignRepository):
54
126
    """An adapter to git repositories for bzr."""
55
127
 
56
128
    _serializer = None
57
 
    _commit_builder_class = GitCommitBuilder
58
 
    vcs = foreign_git
59
 
 
60
 
    def __init__(self, gitdir, lockfiles):
61
 
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir,
62
 
            lockfiles)
63
 
        from bzrlib.plugins.git import fetch, push
64
 
        for optimiser in [fetch.InterRemoteGitNonGitRepository,
65
 
                          fetch.InterLocalGitNonGitRepository,
66
 
                          fetch.InterGitGitRepository,
67
 
                          push.InterToLocalGitRepository,
68
 
                          push.InterToRemoteGitRepository]:
69
 
            repository.InterRepository.register_optimiser(optimiser)
 
129
    vcs = foreign_vcs_git
 
130
    chk_bytes = None
 
131
 
 
132
    def __init__(self, gitdir):
 
133
        if bzrlib_version >= (2, 5):
 
134
            control_files = None
 
135
        else:
 
136
            class DummyControlFiles(object):
 
137
                def __init__(self):
 
138
                    self._transport = gitdir.root_transport
 
139
            control_files = DummyControlFiles()
 
140
        self._transport = gitdir.root_transport
 
141
        super(GitRepository, self).__init__(GitRepositoryFormat(),
 
142
            gitdir, control_files)
 
143
        self.base = gitdir.root_transport.base
 
144
        lazy_load_optimisers()
 
145
        self._lock_mode = None
 
146
        self._lock_count = 0
 
147
 
 
148
    def add_fallback_repository(self, basis_url):
 
149
        raise errors.UnstackableRepositoryFormat(self._format,
 
150
            self.control_transport.base)
70
151
 
71
152
    def is_shared(self):
72
153
        return False
73
154
 
 
155
    def get_physical_lock_status(self):
 
156
        return False
 
157
 
 
158
    def lock_write(self):
 
159
        """See Branch.lock_write()."""
 
160
        if self._lock_mode:
 
161
            assert self._lock_mode == 'w'
 
162
            self._lock_count += 1
 
163
        else:
 
164
            self._lock_mode = 'w'
 
165
            self._lock_count = 1
 
166
        return GitRepositoryLock(self)
 
167
 
 
168
    def break_lock(self):
 
169
        raise NotImplementedError(self.break_lock)
 
170
 
 
171
    def dont_leave_lock_in_place(self):
 
172
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
173
 
 
174
    def leave_lock_in_place(self):
 
175
        raise NotImplementedError(self.leave_lock_in_place)
 
176
 
 
177
    def lock_read(self):
 
178
        if self._lock_mode:
 
179
            assert self._lock_mode in ('r', 'w')
 
180
            self._lock_count += 1
 
181
        else:
 
182
            self._lock_mode = 'r'
 
183
            self._lock_count = 1
 
184
        return self
 
185
 
 
186
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
187
    def unlock(self):
 
188
        if self._lock_count == 0:
 
189
            raise errors.LockNotHeld(self)
 
190
        if self._lock_count == 1 and self._lock_mode == 'w':
 
191
            if self._write_group is not None:
 
192
                self.abort_write_group()
 
193
                self._lock_count -= 1
 
194
                self._lock_mode = None
 
195
                raise errors.BzrError(
 
196
                    'Must end write groups before releasing write locks.')
 
197
        self._lock_count -= 1
 
198
        if self._lock_count == 0:
 
199
            self._lock_mode = None
 
200
 
 
201
    def is_write_locked(self):
 
202
        return (self._lock_mode == 'w')
 
203
 
 
204
    def is_locked(self):
 
205
        return (self._lock_mode is not None)
 
206
 
 
207
    def get_transaction(self):
 
208
        """See Repository.get_transaction()."""
 
209
        if self._write_group is None:
 
210
            return transactions.PassThroughTransaction()
 
211
        else:
 
212
            return self._write_group
 
213
 
 
214
    def reconcile(self, other=None, thorough=False):
 
215
        """Reconcile this repository."""
 
216
        reconciler = RepoReconciler(self, thorough=thorough)
 
217
        reconciler.reconcile()
 
218
        return reconciler
 
219
 
74
220
    def supports_rich_root(self):
75
221
        return True
76
222
 
77
 
    def _warn_if_deprecated(self, branch=None):
 
223
    def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
78
224
        # This class isn't deprecated
79
225
        pass
80
226
 
87
233
    def revision_graph_can_have_wrong_parents(self):
88
234
        return False
89
235
 
90
 
    def dfetch(self, source, stop_revision):
91
 
        interrepo = repository.InterRepository.get(source, self)
92
 
        return interrepo.dfetch(stop_revision)
 
236
    def add_signature_text(self, revid, signature):
 
237
        raise errors.UnsupportedOperation(self.add_signature_text, self)
 
238
 
 
239
    def sign_revision(self, revision_id, gpg_strategy):
 
240
        raise errors.UnsupportedOperation(self.add_signature_text, self)
 
241
 
 
242
 
 
243
class GitRepositoryLock(object):
 
244
    """Subversion lock."""
 
245
 
 
246
    def __init__(self, repository):
 
247
        self.repository_token = None
 
248
        self.repository = repository
 
249
 
 
250
    def unlock(self):
 
251
        self.repository.unlock()
93
252
 
94
253
 
95
254
class LocalGitRepository(GitRepository):
96
255
    """Git repository on the file system."""
97
256
 
98
 
    def __init__(self, gitdir, lockfiles):
99
 
        GitRepository.__init__(self, gitdir, lockfiles)
100
 
        self.base = gitdir.root_transport.base
 
257
    def __init__(self, gitdir):
 
258
        GitRepository.__init__(self, gitdir)
101
259
        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)
 
260
        self._file_change_scanner = GitFileLastChangeScanner(self)
 
261
 
 
262
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
263
                           timezone=None, committer=None, revprops=None,
 
264
                           revision_id=None, lossy=False):
 
265
        """Obtain a CommitBuilder for this repository.
 
266
 
 
267
        :param branch: Branch to commit to.
 
268
        :param parents: Revision ids of the parents of the new revision.
 
269
        :param config: Configuration to use.
 
270
        :param timestamp: Optional timestamp recorded for commit.
 
271
        :param timezone: Optional timezone for timestamp.
 
272
        :param committer: Optional committer to set for commit.
 
273
        :param revprops: Optional dictionary of revision properties.
 
274
        :param revision_id: Optional revision id.
 
275
        :param lossy: Whether to discard data that can not be natively
 
276
            represented, when pushing to a foreign VCS
 
277
        """
 
278
        self.start_write_group()
 
279
        return GitCommitBuilder(self, parents, config,
 
280
            timestamp, timezone, committer, revprops, revision_id,
 
281
            lossy)
 
282
 
 
283
    def get_file_graph(self):
 
284
        return _mod_graph.Graph(GitFileParentProvider(
 
285
            self._file_change_scanner))
 
286
 
 
287
    def iter_files_bytes(self, desired_files):
 
288
        """Iterate through file versions.
 
289
 
 
290
        Files will not necessarily be returned in the order they occur in
 
291
        desired_files.  No specific order is guaranteed.
 
292
 
 
293
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
294
        value supplied by the caller as part of desired_files.  It should
 
295
        uniquely identify the file version in the caller's context.  (Examples:
 
296
        an index number or a TreeTransform trans_id.)
 
297
 
 
298
        bytes_iterator is an iterable of bytestrings for the file.  The
 
299
        kind of iterable and length of the bytestrings are unspecified, but for
 
300
        this implementation, it is a list of bytes produced by
 
301
        VersionedFile.get_record_stream().
 
302
 
 
303
        :param desired_files: a list of (file_id, revision_id, identifier)
 
304
            triples
 
305
        """
 
306
        per_revision = {}
 
307
        for (file_id, revision_id, identifier) in desired_files:
 
308
            per_revision.setdefault(revision_id, []).append(
 
309
                (file_id, identifier))
 
310
        for revid, files in per_revision.iteritems():
 
311
            (commit_id, mapping) = self.lookup_bzr_revision_id(revid)
 
312
            try:
 
313
                commit = self._git.object_store[commit_id]
 
314
            except KeyError:
 
315
                raise errors.RevisionNotPresent(revid, self)
 
316
            root_tree = commit.tree
 
317
            for fileid, identifier in files:
 
318
                path = mapping.parse_file_id(fileid)
 
319
                try:
 
320
                    obj = tree_lookup_path(
 
321
                        self._git.object_store.__getitem__, root_tree, path)
 
322
                    if isinstance(obj, tuple):
 
323
                        (mode, item_id) = obj
 
324
                        obj = self._git.object_store[item_id]
 
325
                except KeyError:
 
326
                    raise errors.RevisionNotPresent((fileid, revid), self)
 
327
                else:
 
328
                    if obj.type_name == "tree":
 
329
                        yield (identifier, [])
 
330
                    elif obj.type_name == "blob":
 
331
                        yield (identifier, obj.chunked)
 
332
                    else:
 
333
                        raise AssertionError("file text resolved to %r" % obj)
106
334
 
107
335
    def _iter_revision_ids(self):
108
336
        mapping = self.get_mapping()
111
339
            if not isinstance(o, Commit):
112
340
                continue
113
341
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
114
 
                self.lookup_foreign_revision_id)
 
342
                mapping.revision_id_foreign_to_bzr)
115
343
            yield o.id, rev.revision_id, roundtrip_revid
116
344
 
117
345
    def all_revision_ids(self):
118
346
        ret = set([])
119
347
        for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
120
 
            ret.add(revid)
121
348
            if roundtrip_revid:
122
349
                ret.add(roundtrip_revid)
 
350
            else:
 
351
                ret.add(revid)
123
352
        return ret
124
353
 
 
354
    def _get_parents(self, revid):
 
355
        if type(revid) != str:
 
356
            raise ValueError
 
357
        try:
 
358
            (hexsha, mapping) = self.lookup_bzr_revision_id(revid)
 
359
        except errors.NoSuchRevision:
 
360
            return None
 
361
        try:
 
362
            commit = self._git[hexsha]
 
363
        except KeyError:
 
364
            return None
 
365
        return [
 
366
            self.lookup_foreign_revision_id(p, mapping)
 
367
            for p in commit.parents]
 
368
 
125
369
    def get_parent_map(self, revids):
126
370
        parent_map = {}
127
371
        for revision_id in revids:
128
 
            assert isinstance(revision_id, str)
 
372
            parents = self._get_parents(revision_id)
129
373
            if revision_id == revision.NULL_REVISION:
130
374
                parent_map[revision_id] = ()
131
375
                continue
132
 
            hexsha, mapping = self.lookup_bzr_revision_id(revision_id)
133
 
            try:
134
 
                commit = self._git[hexsha]
135
 
            except KeyError:
 
376
            if parents is None:
136
377
                continue
137
 
            parent_map[revision_id] = [
138
 
                self.lookup_foreign_revision_id(p, mapping)
139
 
                for p in commit.parents]
 
378
            if len(parents) == 0:
 
379
                parents = [revision.NULL_REVISION]
 
380
            parent_map[revision_id] = tuple(parents)
140
381
        return parent_map
141
382
 
142
 
    def get_ancestry(self, revision_id, topo_sorted=True):
143
 
        """See Repository.get_ancestry().
 
383
    def get_known_graph_ancestry(self, revision_ids):
 
384
        """Return the known graph for a set of revision ids and their ancestors.
144
385
        """
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
 
386
        pending = set(revision_ids)
 
387
        parent_map = {}
 
388
        while pending:
 
389
            this_parent_map = {}
 
390
            for revid in pending:
 
391
                if revid == revision.NULL_REVISION:
 
392
                    continue
 
393
                parents = self._get_parents(revid)
 
394
                if parents is not None:
 
395
                    this_parent_map[revid] = parents
 
396
            parent_map.update(this_parent_map)
 
397
            pending = set()
 
398
            map(pending.update, this_parent_map.itervalues())
 
399
            pending = pending.difference(parent_map)
 
400
        return _mod_graph.KnownGraph(parent_map)
154
401
 
155
402
    def get_signature_text(self, revision_id):
156
403
        raise errors.NoSuchRevision(self, revision_id)
157
404
 
 
405
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
406
        result = GitCheck(self, check_repo=check_repo)
 
407
        result.check(callback_refs)
 
408
        return result
 
409
 
158
410
    def pack(self, hint=None, clean_obsolete_packs=False):
159
411
        self._git.object_store.pack_loose_objects()
160
412
 
161
413
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
162
414
        """Lookup a revision id.
163
415
 
 
416
        :param foreign_revid: Foreign revision id to look up
 
417
        :param mapping: Mapping to use (use default mapping if not specified)
 
418
        :raise KeyError: If foreign revision was not found
 
419
        :return: bzr revision id
164
420
        """
165
421
        assert type(foreign_revid) is str
166
422
        if mapping is None:
167
423
            mapping = self.get_mapping()
168
 
        from dulwich.protocol import (
169
 
            ZERO_SHA,
170
 
            )
171
424
        if foreign_revid == ZERO_SHA:
172
425
            return revision.NULL_REVISION
173
 
        commit = self._git[foreign_revid]
 
426
        commit = self._git.object_store.peel_sha(foreign_revid)
 
427
        if not isinstance(commit, Commit):
 
428
            raise NotCommitError(commit.id)
174
429
        rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
175
 
            lambda x: None)
 
430
            mapping.revision_id_foreign_to_bzr)
176
431
        # FIXME: check testament before doing this?
177
432
        if roundtrip_revid:
178
433
            return roundtrip_revid
180
435
            return rev.revision_id
181
436
 
182
437
    def has_signature_for_revision_id(self, revision_id):
 
438
        """Check whether a GPG signature is present for this revision.
 
439
 
 
440
        This is never the case for Git repositories.
 
441
        """
183
442
        return False
184
443
 
185
444
    def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
 
445
        """Lookup a bzr revision id in a Git repository.
 
446
 
 
447
        :param bzr_revid: Bazaar revision id
 
448
        :param mapping: Optional mapping to use
 
449
        :return: Tuple with git commit id, mapping that was used and supplement
 
450
            details
 
451
        """
186
452
        try:
187
 
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
 
453
            (git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
188
454
        except errors.InvalidRevisionId:
189
455
            if mapping is None:
190
456
                mapping = self.get_mapping()
202
468
                    if roundtrip_revid == bzr_revid:
203
469
                        return git_sha, mapping
204
470
                raise errors.NoSuchRevision(self, bzr_revid)
 
471
        else:
 
472
            return (git_sha, mapping)
205
473
 
206
474
    def get_revision(self, revision_id):
 
475
        if not isinstance(revision_id, str):
 
476
            raise errors.InvalidRevisionId(revision_id, self)
207
477
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
208
478
        try:
209
479
            commit = self._git[git_commit_id]
218
488
        return revision
219
489
 
220
490
    def has_revision(self, revision_id):
 
491
        """See Repository.has_revision."""
 
492
        if revision_id == revision.NULL_REVISION:
 
493
            return True
221
494
        try:
222
495
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
223
496
        except errors.NoSuchRevision:
225
498
        return (git_commit_id in self._git)
226
499
 
227
500
    def has_revisions(self, revision_ids):
 
501
        """See Repository.has_revisions."""
228
502
        return set(filter(self.has_revision, revision_ids))
229
503
 
230
504
    def get_revisions(self, revids):
 
505
        """See Repository.get_revisions."""
231
506
        return [self.get_revision(r) for r in revids]
232
507
 
233
508
    def revision_trees(self, revids):
 
509
        """See Repository.revision_trees."""
234
510
        for revid in revids:
235
511
            yield self.revision_tree(revid)
236
512
 
237
513
    def revision_tree(self, revision_id):
 
514
        """See Repository.revision_tree."""
238
515
        revision_id = revision.ensure_null(revision_id)
239
516
        if revision_id == revision.NULL_REVISION:
240
517
            inv = inventory.Inventory(root_id=None)
241
518
            inv.revision_id = revision_id
242
 
            return revisiontree.RevisionTree(self, inv, revision_id)
 
519
            return InventoryRevisionTree(self, inv, revision_id)
243
520
        return GitRevisionTree(self, revision_id)
244
521
 
245
522
    def get_inventory(self, revision_id):
246
 
        assert revision_id != None
247
 
        return self.revision_tree(revision_id).inventory
 
523
        raise NotImplementedError(self.get_inventory)
248
524
 
249
525
    def set_make_working_trees(self, trees):
250
 
        pass
 
526
        raise errors.UnsupportedOperation(self.set_make_working_trees, self)
 
527
        # TODO: Set bare= in the configuration bug=777065
251
528
 
252
529
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
253
530
        progress=None):
254
531
        return self._git.fetch_objects(determine_wants, graph_walker, progress)
255
532
 
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
533
 
270
534
class GitRepositoryFormat(repository.RepositoryFormat):
271
535
    """Git repository format."""
272
536
 
 
537
    supports_versioned_directories = False
273
538
    supports_tree_reference = False
274
539
    rich_root_data = True
 
540
    supports_leaving_lock = False
 
541
    fast_deltas = True
 
542
    supports_funky_characters = True
 
543
    supports_external_lookups = False
 
544
    supports_full_versioned_files = False
 
545
    supports_revision_signatures = False
 
546
    supports_nesting_repositories = False
 
547
    revision_graph_can_have_wrong_parents = False
 
548
    supports_unreferenced_revisions = True
 
549
 
 
550
    @property
 
551
    def _matchingbzrdir(self):
 
552
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
 
553
        return LocalGitControlDirFormat()
275
554
 
276
555
    def get_format_description(self):
277
556
        return "Git Repository"
278
557
 
279
 
    def initialize(self, url, shared=False, _internal=False):
280
 
        raise errors.UninitializableFormat(self)
 
558
    def initialize(self, controldir, shared=False, _internal=False):
 
559
        from bzrlib.plugins.git.dir import GitDir
 
560
        if not isinstance(controldir, GitDir):
 
561
            raise errors.UninitializableFormat(self)
 
562
        return controldir.open_repository()
281
563
 
282
564
    def check_conversion_target(self, target_repo_format):
283
565
        return target_repo_format.rich_root_data