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
class GitRepository(ForeignRepository):
111
"""An adapter to git repositories for bzr."""
114
vcs = foreign_vcs_git
117
def __init__(self, gitdir):
118
if bzrlib_version >= (2, 5):
121
class DummyControlFiles(object):
123
self._transport = gitdir.root_transport
124
control_files = DummyControlFiles()
125
super(GitRepository, self).__init__(GitRepositoryFormat(),
126
gitdir, control_files)
127
self._transport = gitdir.root_transport
128
from bzrlib.plugins.git import fetch, push
129
for optimiser in [fetch.InterRemoteGitNonGitRepository,
130
fetch.InterLocalGitNonGitRepository,
131
fetch.InterGitGitRepository,
132
push.InterToLocalGitRepository,
133
push.InterToRemoteGitRepository]:
134
repository.InterRepository.register_optimiser(optimiser)
135
self._lock_mode = None
138
def add_fallback_repository(self, basis_url):
139
raise errors.UnstackableRepositoryFormat(self._format,
140
self.control_transport.base)
145
def get_physical_lock_status(self):
148
def lock_write(self):
149
"""See Branch.lock_write()."""
151
assert self._lock_mode == 'w'
152
self._lock_count += 1
154
self._lock_mode = 'w'
156
return GitRepositoryLock(self)
158
def dont_leave_lock_in_place(self):
159
raise NotImplementedError(self.dont_leave_lock_in_place)
161
def leave_lock_in_place(self):
162
raise NotImplementedError(self.leave_lock_in_place)
166
assert self._lock_mode in ('r', 'w')
167
self._lock_count += 1
169
self._lock_mode = 'r'
173
@only_raises(errors.LockNotHeld, errors.LockBroken)
175
if self._lock_count == 0:
176
raise errors.LockNotHeld(self)
177
if self._lock_count == 1 and self._lock_mode == 'w':
178
if self._write_group is not None:
179
self.abort_write_group()
180
self._lock_count -= 1
181
self._lock_mode = None
182
raise errors.BzrError(
183
'Must end write groups before releasing write locks.')
184
self._lock_count -= 1
185
if self._lock_count == 0:
186
self._lock_mode = None
188
def is_write_locked(self):
189
return (self._lock_mode == 'w')
192
return (self._lock_mode is not None)
194
def get_transaction(self):
195
"""See Repository.get_transaction()."""
196
if self._write_group is None:
197
return transactions.PassThroughTransaction()
199
return self._write_group
201
def reconcile(self, other=None, thorough=False):
202
"""Reconcile this repository."""
203
reconciler = RepoReconciler(self, thorough=thorough)
204
reconciler.reconcile()
207
def supports_rich_root(self):
210
def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
211
# This class isn't deprecated
214
def get_mapping(self):
215
return default_mapping
217
def make_working_trees(self):
218
return not self._git.bare
220
def revision_graph_can_have_wrong_parents(self):
223
def add_signature_text(self, revid, signature):
224
raise errors.UnsupportedOperation(self.add_signature_text, self)
227
class GitRepositoryLock(object):
228
"""Subversion lock."""
230
def __init__(self, repository):
231
self.repository_token = None
232
self.repository = repository
235
self.repository.unlock()
238
class LocalGitRepository(GitRepository):
239
"""Git repository on the file system."""
241
def __init__(self, gitdir):
242
GitRepository.__init__(self, gitdir)
243
self.base = gitdir.root_transport.base
244
self._git = gitdir._git
245
self._file_change_scanner = GitFileLastChangeScanner(self)
248
return self._git.get_refs()
250
def get_commit_builder(self, branch, parents, config, timestamp=None,
251
timezone=None, committer=None, revprops=None,
252
revision_id=None, lossy=False):
253
"""Obtain a CommitBuilder for this repository.
255
:param branch: Branch to commit to.
256
:param parents: Revision ids of the parents of the new revision.
257
:param config: Configuration to use.
258
:param timestamp: Optional timestamp recorded for commit.
259
:param timezone: Optional timezone for timestamp.
260
:param committer: Optional committer to set for commit.
261
:param revprops: Optional dictionary of revision properties.
262
:param revision_id: Optional revision id.
263
:param lossy: Whether to discard data that can not be natively
264
represented, when pushing to a foreign VCS
266
self.start_write_group()
267
return GitCommitBuilder(self, parents, config,
268
timestamp, timezone, committer, revprops, revision_id,
271
def get_file_graph(self):
272
return _mod_graph.Graph(GitFileParentProvider(
273
self._file_change_scanner))
275
def iter_files_bytes(self, desired_files):
276
"""Iterate through file versions.
278
Files will not necessarily be returned in the order they occur in
279
desired_files. No specific order is guaranteed.
281
Yields pairs of identifier, bytes_iterator. identifier is an opaque
282
value supplied by the caller as part of desired_files. It should
283
uniquely identify the file version in the caller's context. (Examples:
284
an index number or a TreeTransform trans_id.)
286
bytes_iterator is an iterable of bytestrings for the file. The
287
kind of iterable and length of the bytestrings are unspecified, but for
288
this implementation, it is a list of bytes produced by
289
VersionedFile.get_record_stream().
291
:param desired_files: a list of (file_id, revision_id, identifier)
295
for (file_id, revision_id, identifier) in desired_files:
296
per_revision.setdefault(revision_id, []).append(
297
(file_id, identifier))
298
for revid, files in per_revision.iteritems():
299
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
301
commit = self._git.object_store[commit_id]
303
raise errors.RevisionNotPresent(revid, self)
304
root_tree = commit.tree
305
for fileid, identifier in files:
306
path = mapping.parse_file_id(fileid)
308
obj = tree_lookup_path(
309
self._git.object_store.__getitem__, root_tree, path)
310
if isinstance(obj, tuple):
311
(mode, item_id) = obj
312
obj = self._git.object_store[item_id]
314
raise errors.RevisionNotPresent((fileid, revid), self)
316
if obj.type_name == "tree":
317
yield (identifier, [])
318
elif obj.type_name == "blob":
319
yield (identifier, obj.chunked)
321
raise AssertionError("file text resolved to %r" % obj)
323
def _iter_revision_ids(self):
324
mapping = self.get_mapping()
325
for sha in self._git.object_store:
326
o = self._git.object_store[sha]
327
if not isinstance(o, Commit):
329
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
330
mapping.revision_id_foreign_to_bzr)
331
yield o.id, rev.revision_id, roundtrip_revid
333
def all_revision_ids(self):
335
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
337
ret.add(roundtrip_revid)
342
def _get_parents(self, revid):
343
if type(revid) != str:
346
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
347
except errors.NoSuchRevision:
350
commit = self._git[hexsha]
354
self.lookup_foreign_revision_id(p, mapping)
355
for p in commit.parents]
357
def get_parent_map(self, revids):
359
for revision_id in revids:
360
parents = self._get_parents(revision_id)
361
if revision_id == revision.NULL_REVISION:
362
parent_map[revision_id] = ()
366
if len(parents) == 0:
367
parents = [revision.NULL_REVISION]
368
parent_map[revision_id] = tuple(parents)
371
def get_known_graph_ancestry(self, revision_ids):
372
"""Return the known graph for a set of revision ids and their ancestors.
374
pending = set(revision_ids)
378
for revid in pending:
379
if revid == revision.NULL_REVISION:
381
parents = self._get_parents(revid)
382
if parents is not None:
383
this_parent_map[revid] = parents
384
parent_map.update(this_parent_map)
386
map(pending.update, this_parent_map.itervalues())
387
pending = pending.difference(parent_map)
388
return _mod_graph.KnownGraph(parent_map)
390
def get_signature_text(self, revision_id):
391
raise errors.NoSuchRevision(self, revision_id)
393
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
394
result = GitCheck(self, check_repo=check_repo)
395
result.check(callback_refs)
398
def pack(self, hint=None, clean_obsolete_packs=False):
399
self._git.object_store.pack_loose_objects()
401
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
402
"""Lookup a revision id.
405
assert type(foreign_revid) is str
407
mapping = self.get_mapping()
408
if foreign_revid == ZERO_SHA:
409
return revision.NULL_REVISION
410
commit = self._git.object_store[foreign_revid]
411
while isinstance(commit, Tag):
412
commit = self._git[commit.object[1]]
413
if not isinstance(commit, Commit):
414
raise NotCommitError(commit.id)
415
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
416
mapping.revision_id_foreign_to_bzr)
417
# FIXME: check testament before doing this?
419
return roundtrip_revid
421
return rev.revision_id
423
def has_signature_for_revision_id(self, revision_id):
424
"""Check whether a GPG signature is present for this revision.
426
This is never the case for Git repositories.
430
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
431
"""Lookup a bzr revision id in a Git repository.
433
:param bzr_revid: Bazaar revision id
434
:param mapping: Optional mapping to use
435
:return: Tuple with git commit id, mapping that was used and supplement
439
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
440
except errors.InvalidRevisionId:
442
mapping = self.get_mapping()
444
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
447
# Update refs from Git commit objects
448
# FIXME: Hitting this a lot will be very inefficient...
449
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
450
if not roundtrip_revid:
452
refname = mapping.revid_as_refname(roundtrip_revid)
453
self._git.refs[refname] = git_sha
454
if roundtrip_revid == bzr_revid:
455
return git_sha, mapping
456
raise errors.NoSuchRevision(self, bzr_revid)
458
return (git_sha, mapping)
460
def get_revision(self, revision_id):
461
if not isinstance(revision_id, str):
462
raise errors.InvalidRevisionId(revision_id, self)
463
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
465
commit = self._git[git_commit_id]
467
raise errors.NoSuchRevision(self, revision_id)
468
revision, roundtrip_revid, verifiers = mapping.import_commit(
469
commit, self.lookup_foreign_revision_id)
470
assert revision is not None
471
# FIXME: check verifiers ?
473
revision.revision_id = roundtrip_revid
476
def has_revision(self, revision_id):
477
"""See Repository.has_revision."""
478
if revision_id == revision.NULL_REVISION:
481
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
482
except errors.NoSuchRevision:
484
return (git_commit_id in self._git)
486
def has_revisions(self, revision_ids):
487
"""See Repository.has_revisions."""
488
return set(filter(self.has_revision, revision_ids))
490
def get_revisions(self, revids):
491
"""See Repository.get_revisions."""
492
return [self.get_revision(r) for r in revids]
494
def revision_trees(self, revids):
495
"""See Repository.revision_trees."""
497
yield self.revision_tree(revid)
499
def revision_tree(self, revision_id):
500
"""See Repository.revision_tree."""
501
revision_id = revision.ensure_null(revision_id)
502
if revision_id == revision.NULL_REVISION:
503
inv = inventory.Inventory(root_id=None)
504
inv.revision_id = revision_id
505
return InventoryRevisionTree(self, inv, revision_id)
506
return GitRevisionTree(self, revision_id)
508
def get_inventory(self, revision_id):
509
raise NotImplementedError(self.get_inventory)
511
def set_make_working_trees(self, trees):
512
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
513
# TODO: Set bare= in the configuration bug=777065
515
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
517
return self._git.fetch_objects(determine_wants, graph_walker, progress)
520
class GitRepositoryFormat(repository.RepositoryFormat):
521
"""Git repository format."""
523
supports_versioned_directories = False
524
supports_tree_reference = False
525
rich_root_data = True
526
supports_leaving_lock = False
528
supports_funky_characters = True
529
supports_external_lookups = False
530
supports_full_versioned_files = False
531
supports_revision_signatures = False
532
supports_nesting_repositories = False
533
revision_graph_can_have_wrong_parents = False
536
def _matchingbzrdir(self):
537
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
538
return LocalGitControlDirFormat()
540
def get_format_description(self):
541
return "Git Repository"
543
def initialize(self, controldir, shared=False, _internal=False):
544
from bzrlib.plugins.git.dir import GitDir
545
if not isinstance(controldir, GitDir):
546
raise errors.UninitializableFormat(self)
547
return controldir.open_repository()
549
def check_conversion_target(self, target_repo_format):
550
return target_repo_format.rich_root_data
552
def get_foreign_tests_repository_factory(self):
553
from bzrlib.plugins.git.tests.test_repository import (
554
ForeignTestsRepositoryFactory,
556
return ForeignTestsRepositoryFactory()
558
def network_name(self):