/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

Tags: bzr-git-0.6.5
ReleaseĀ 0.6.6.

Show diffs side-by-side

added added

removed removed

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