1
# Copyright (C) 2007 Canonical Ltd
2
# Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
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.
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.
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
18
"""An adapter between a Git Repository and a Bazaar Branch"""
28
version_info as bzrlib_version,
30
from bzrlib.decorators import only_raises
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 (
39
from bzrlib.plugins.git.commit import (
42
from bzrlib.plugins.git.errors import (
45
from bzrlib.plugins.git.filegraph import (
46
GitFileLastChangeScanner,
47
GitFileParentProvider,
49
from bzrlib.plugins.git.mapping import (
54
from bzrlib.plugins.git.tree import (
59
from dulwich.objects import (
64
from dulwich.object_store import (
69
class RepoReconciler(object):
70
"""Reconciler that reconciles a repository.
74
def __init__(self, repo, other=None, thorough=False):
75
"""Construct a RepoReconciler.
77
:param thorough: perform a thorough check which may take longer but
78
will correct non-data loss issues such as incorrect
84
"""Perform reconciliation.
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.
94
class GitCheck(check.Check):
96
def __init__(self, repository, check_repo=True):
97
self.repository = repository
98
self.checked_rev_cnt = 0
100
def check(self, callback_refs=None, check_repo=True):
101
if callback_refs is None:
103
self.repository.lock_read()
104
self.repository.unlock()
106
def report_results(self, verbose):
110
_optimisers_loaded = False
112
def lazy_load_optimisers():
113
global _optimisers_loaded
114
if _optimisers_loaded:
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
126
class GitRepository(ForeignRepository):
127
"""An adapter to git repositories for bzr."""
130
vcs = foreign_vcs_git
133
def __init__(self, gitdir):
134
if bzrlib_version >= (2, 5):
137
class DummyControlFiles(object):
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
149
def add_fallback_repository(self, basis_url):
150
raise errors.UnstackableRepositoryFormat(self._format,
151
self.control_transport.base)
156
def get_physical_lock_status(self):
159
def lock_write(self):
160
"""See Branch.lock_write()."""
162
assert self._lock_mode == 'w'
163
self._lock_count += 1
165
self._lock_mode = 'w'
167
return GitRepositoryLock(self)
169
def dont_leave_lock_in_place(self):
170
raise NotImplementedError(self.dont_leave_lock_in_place)
172
def leave_lock_in_place(self):
173
raise NotImplementedError(self.leave_lock_in_place)
177
assert self._lock_mode in ('r', 'w')
178
self._lock_count += 1
180
self._lock_mode = 'r'
184
@only_raises(errors.LockNotHeld, errors.LockBroken)
186
if self._lock_count == 0:
187
raise errors.LockNotHeld(self)
188
if self._lock_count == 1 and self._lock_mode == 'w':
189
if self._write_group is not None:
190
self.abort_write_group()
191
self._lock_count -= 1
192
self._lock_mode = None
193
raise errors.BzrError(
194
'Must end write groups before releasing write locks.')
195
self._lock_count -= 1
196
if self._lock_count == 0:
197
self._lock_mode = None
199
def is_write_locked(self):
200
return (self._lock_mode == 'w')
203
return (self._lock_mode is not None)
205
def get_transaction(self):
206
"""See Repository.get_transaction()."""
207
if self._write_group is None:
208
return transactions.PassThroughTransaction()
210
return self._write_group
212
def reconcile(self, other=None, thorough=False):
213
"""Reconcile this repository."""
214
reconciler = RepoReconciler(self, thorough=thorough)
215
reconciler.reconcile()
218
def supports_rich_root(self):
221
def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
222
# This class isn't deprecated
225
def get_mapping(self):
226
return default_mapping
228
def make_working_trees(self):
229
return not self._git.bare
231
def revision_graph_can_have_wrong_parents(self):
234
def add_signature_text(self, revid, signature):
235
raise errors.UnsupportedOperation(self.add_signature_text, self)
238
class GitRepositoryLock(object):
239
"""Subversion lock."""
241
def __init__(self, repository):
242
self.repository_token = None
243
self.repository = repository
246
self.repository.unlock()
249
class LocalGitRepository(GitRepository):
250
"""Git repository on the file system."""
252
def __init__(self, gitdir):
253
GitRepository.__init__(self, gitdir)
254
self._git = gitdir._git
255
self._file_change_scanner = GitFileLastChangeScanner(self)
257
def get_commit_builder(self, branch, parents, config, timestamp=None,
258
timezone=None, committer=None, revprops=None,
259
revision_id=None, lossy=False):
260
"""Obtain a CommitBuilder for this repository.
262
:param branch: Branch to commit to.
263
:param parents: Revision ids of the parents of the new revision.
264
:param config: Configuration to use.
265
:param timestamp: Optional timestamp recorded for commit.
266
:param timezone: Optional timezone for timestamp.
267
:param committer: Optional committer to set for commit.
268
:param revprops: Optional dictionary of revision properties.
269
:param revision_id: Optional revision id.
270
:param lossy: Whether to discard data that can not be natively
271
represented, when pushing to a foreign VCS
273
self.start_write_group()
274
return GitCommitBuilder(self, parents, config,
275
timestamp, timezone, committer, revprops, revision_id,
278
def get_file_graph(self):
279
return _mod_graph.Graph(GitFileParentProvider(
280
self._file_change_scanner))
282
def iter_files_bytes(self, desired_files):
283
"""Iterate through file versions.
285
Files will not necessarily be returned in the order they occur in
286
desired_files. No specific order is guaranteed.
288
Yields pairs of identifier, bytes_iterator. identifier is an opaque
289
value supplied by the caller as part of desired_files. It should
290
uniquely identify the file version in the caller's context. (Examples:
291
an index number or a TreeTransform trans_id.)
293
bytes_iterator is an iterable of bytestrings for the file. The
294
kind of iterable and length of the bytestrings are unspecified, but for
295
this implementation, it is a list of bytes produced by
296
VersionedFile.get_record_stream().
298
:param desired_files: a list of (file_id, revision_id, identifier)
302
for (file_id, revision_id, identifier) in desired_files:
303
per_revision.setdefault(revision_id, []).append(
304
(file_id, identifier))
305
for revid, files in per_revision.iteritems():
306
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
308
commit = self._git.object_store[commit_id]
310
raise errors.RevisionNotPresent(revid, self)
311
root_tree = commit.tree
312
for fileid, identifier in files:
313
path = mapping.parse_file_id(fileid)
315
obj = tree_lookup_path(
316
self._git.object_store.__getitem__, root_tree, path)
317
if isinstance(obj, tuple):
318
(mode, item_id) = obj
319
obj = self._git.object_store[item_id]
321
raise errors.RevisionNotPresent((fileid, revid), self)
323
if obj.type_name == "tree":
324
yield (identifier, [])
325
elif obj.type_name == "blob":
326
yield (identifier, obj.chunked)
328
raise AssertionError("file text resolved to %r" % obj)
330
def _iter_revision_ids(self):
331
mapping = self.get_mapping()
332
for sha in self._git.object_store:
333
o = self._git.object_store[sha]
334
if not isinstance(o, Commit):
336
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
337
mapping.revision_id_foreign_to_bzr)
338
yield o.id, rev.revision_id, roundtrip_revid
340
def all_revision_ids(self):
342
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
344
ret.add(roundtrip_revid)
349
def _get_parents(self, revid):
350
if type(revid) != str:
353
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
354
except errors.NoSuchRevision:
357
commit = self._git[hexsha]
361
self.lookup_foreign_revision_id(p, mapping)
362
for p in commit.parents]
364
def get_parent_map(self, revids):
366
for revision_id in revids:
367
parents = self._get_parents(revision_id)
368
if revision_id == revision.NULL_REVISION:
369
parent_map[revision_id] = ()
373
if len(parents) == 0:
374
parents = [revision.NULL_REVISION]
375
parent_map[revision_id] = tuple(parents)
378
def get_known_graph_ancestry(self, revision_ids):
379
"""Return the known graph for a set of revision ids and their ancestors.
381
pending = set(revision_ids)
385
for revid in pending:
386
if revid == revision.NULL_REVISION:
388
parents = self._get_parents(revid)
389
if parents is not None:
390
this_parent_map[revid] = parents
391
parent_map.update(this_parent_map)
393
map(pending.update, this_parent_map.itervalues())
394
pending = pending.difference(parent_map)
395
return _mod_graph.KnownGraph(parent_map)
397
def get_signature_text(self, revision_id):
398
raise errors.NoSuchRevision(self, revision_id)
400
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
401
result = GitCheck(self, check_repo=check_repo)
402
result.check(callback_refs)
405
def pack(self, hint=None, clean_obsolete_packs=False):
406
self._git.object_store.pack_loose_objects()
408
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
409
"""Lookup a revision id.
412
assert type(foreign_revid) is str
414
mapping = self.get_mapping()
415
if foreign_revid == ZERO_SHA:
416
return revision.NULL_REVISION
417
commit = self._git.object_store[foreign_revid]
418
while isinstance(commit, Tag):
419
commit = self._git[commit.object[1]]
420
if not isinstance(commit, Commit):
421
raise NotCommitError(commit.id)
422
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
423
mapping.revision_id_foreign_to_bzr)
424
# FIXME: check testament before doing this?
426
return roundtrip_revid
428
return rev.revision_id
430
def has_signature_for_revision_id(self, revision_id):
431
"""Check whether a GPG signature is present for this revision.
433
This is never the case for Git repositories.
437
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
438
"""Lookup a bzr revision id in a Git repository.
440
:param bzr_revid: Bazaar revision id
441
:param mapping: Optional mapping to use
442
:return: Tuple with git commit id, mapping that was used and supplement
446
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
447
except errors.InvalidRevisionId:
449
mapping = self.get_mapping()
451
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
454
# Update refs from Git commit objects
455
# FIXME: Hitting this a lot will be very inefficient...
456
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
457
if not roundtrip_revid:
459
refname = mapping.revid_as_refname(roundtrip_revid)
460
self._git.refs[refname] = git_sha
461
if roundtrip_revid == bzr_revid:
462
return git_sha, mapping
463
raise errors.NoSuchRevision(self, bzr_revid)
465
return (git_sha, mapping)
467
def get_revision(self, revision_id):
468
if not isinstance(revision_id, str):
469
raise errors.InvalidRevisionId(revision_id, self)
470
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
472
commit = self._git[git_commit_id]
474
raise errors.NoSuchRevision(self, revision_id)
475
revision, roundtrip_revid, verifiers = mapping.import_commit(
476
commit, self.lookup_foreign_revision_id)
477
assert revision is not None
478
# FIXME: check verifiers ?
480
revision.revision_id = roundtrip_revid
483
def has_revision(self, revision_id):
484
"""See Repository.has_revision."""
485
if revision_id == revision.NULL_REVISION:
488
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
489
except errors.NoSuchRevision:
491
return (git_commit_id in self._git)
493
def has_revisions(self, revision_ids):
494
"""See Repository.has_revisions."""
495
return set(filter(self.has_revision, revision_ids))
497
def get_revisions(self, revids):
498
"""See Repository.get_revisions."""
499
return [self.get_revision(r) for r in revids]
501
def revision_trees(self, revids):
502
"""See Repository.revision_trees."""
504
yield self.revision_tree(revid)
506
def revision_tree(self, revision_id):
507
"""See Repository.revision_tree."""
508
revision_id = revision.ensure_null(revision_id)
509
if revision_id == revision.NULL_REVISION:
510
inv = inventory.Inventory(root_id=None)
511
inv.revision_id = revision_id
512
return InventoryRevisionTree(self, inv, revision_id)
513
return GitRevisionTree(self, revision_id)
515
def get_inventory(self, revision_id):
516
raise NotImplementedError(self.get_inventory)
518
def set_make_working_trees(self, trees):
519
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
520
# TODO: Set bare= in the configuration bug=777065
522
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
524
return self._git.fetch_objects(determine_wants, graph_walker, progress)
527
class GitRepositoryFormat(repository.RepositoryFormat):
528
"""Git repository format."""
530
supports_versioned_directories = False
531
supports_tree_reference = False
532
rich_root_data = True
533
supports_leaving_lock = False
535
supports_funky_characters = True
536
supports_external_lookups = False
537
supports_full_versioned_files = False
538
supports_revision_signatures = False
539
supports_nesting_repositories = False
540
revision_graph_can_have_wrong_parents = False
543
def _matchingbzrdir(self):
544
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
545
return LocalGitControlDirFormat()
547
def get_format_description(self):
548
return "Git Repository"
550
def initialize(self, controldir, shared=False, _internal=False):
551
from bzrlib.plugins.git.dir import GitDir
552
if not isinstance(controldir, GitDir):
553
raise errors.UninitializableFormat(self)
554
return controldir.open_repository()
556
def check_conversion_target(self, target_repo_format):
557
return target_repo_format.rich_root_data
559
def get_foreign_tests_repository_factory(self):
560
from bzrlib.plugins.git.tests.test_repository import (
561
ForeignTestsRepositoryFactory,
563
return ForeignTestsRepositoryFactory()
565
def network_name(self):