/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 determining revisions to fetch when fetching to git repo.

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