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"""
29
from bzrlib.decorators import only_raises
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 (
38
from bzrlib.plugins.git.commit import (
41
from bzrlib.plugins.git.errors import (
44
from bzrlib.plugins.git.filegraph import (
45
GitFileLastChangeScanner,
46
GitFileParentProvider,
48
from bzrlib.plugins.git.mapping import (
53
from bzrlib.plugins.git.tree import (
58
from dulwich.objects import (
63
from dulwich.object_store import (
68
class RepoReconciler(object):
69
"""Reconciler that reconciles a repository.
73
def __init__(self, repo, other=None, thorough=False):
74
"""Construct a RepoReconciler.
76
:param thorough: perform a thorough check which may take longer but
77
will correct non-data loss issues such as incorrect
83
"""Perform reconciliation.
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.
93
class GitCheck(check.Check):
95
def __init__(self, repository, check_repo=True):
96
self.repository = repository
97
self.checked_rev_cnt = 0
99
def check(self, callback_refs=None, check_repo=True):
100
if callback_refs is None:
102
self.repository.lock_read()
103
self.repository.unlock()
105
def report_results(self, verbose):
109
class GitRepository(ForeignRepository):
110
"""An adapter to git repositories for bzr."""
113
vcs = foreign_vcs_git
116
def __init__(self, gitdir):
117
super(GitRepository, self).__init__(GitRepositoryFormat(),
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
130
def add_fallback_repository(self, basis_url):
131
raise errors.UnstackableRepositoryFormat(self._format,
132
self.control_transport.base)
137
def get_physical_lock_status(self):
140
def lock_write(self):
141
"""See Branch.lock_write()."""
143
assert self._lock_mode == 'w'
144
self._lock_count += 1
146
self._lock_mode = 'w'
148
return GitRepositoryLock(self)
150
def dont_leave_lock_in_place(self):
151
raise NotImplementedError(self.dont_leave_lock_in_place)
153
def leave_lock_in_place(self):
154
raise NotImplementedError(self.leave_lock_in_place)
158
assert self._lock_mode in ('r', 'w')
159
self._lock_count += 1
161
self._lock_mode = 'r'
165
@only_raises(errors.LockNotHeld, errors.LockBroken)
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
180
def is_write_locked(self):
181
return (self._lock_mode == 'w')
184
return (self._lock_mode is not None)
186
def get_transaction(self):
187
"""See Repository.get_transaction()."""
188
if self._write_group is None:
189
return transactions.PassThroughTransaction()
191
return self._write_group
193
def reconcile(self, other=None, thorough=False):
194
"""Reconcile this repository."""
195
reconciler = RepoReconciler(self, thorough=thorough)
196
reconciler.reconcile()
199
def supports_rich_root(self):
202
def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
203
# This class isn't deprecated
206
def get_mapping(self):
207
return default_mapping
209
def make_working_trees(self):
210
return not self._git.bare
212
def revision_graph_can_have_wrong_parents(self):
215
def dfetch(self, source, stop_revision):
216
interrepo = repository.InterRepository.get(source, self)
217
return interrepo.dfetch(stop_revision)
219
def add_signature_text(self, revid, signature):
220
raise errors.UnsupportedOperation(self.add_signature_text, self)
223
class GitRepositoryLock(object):
224
"""Subversion lock."""
226
def __init__(self, repository):
227
self.repository_token = None
228
self.repository = repository
231
self.repository.unlock()
234
class LocalGitRepository(GitRepository):
235
"""Git repository on the file system."""
237
def __init__(self, gitdir):
238
GitRepository.__init__(self, gitdir)
239
self.base = gitdir.root_transport.base
240
self._git = gitdir._git
241
self._file_change_scanner = GitFileLastChangeScanner(self)
243
def get_commit_builder(self, branch, parents, config, timestamp=None,
244
timezone=None, committer=None, revprops=None,
245
revision_id=None, lossy=False):
246
"""Obtain a CommitBuilder for this repository.
248
:param branch: Branch to commit to.
249
:param parents: Revision ids of the parents of the new revision.
250
:param config: Configuration to use.
251
:param timestamp: Optional timestamp recorded for commit.
252
:param timezone: Optional timezone for timestamp.
253
:param committer: Optional committer to set for commit.
254
:param revprops: Optional dictionary of revision properties.
255
:param revision_id: Optional revision id.
256
:param lossy: Whether to discard data that can not be natively
257
represented, when pushing to a foreign VCS
259
self.start_write_group()
260
return GitCommitBuilder(self, parents, config,
261
timestamp, timezone, committer, revprops, revision_id,
264
def get_file_graph(self):
265
return _mod_graph.Graph(GitFileParentProvider(
266
self._file_change_scanner))
268
def iter_files_bytes(self, desired_files):
269
"""Iterate through file versions.
271
Files will not necessarily be returned in the order they occur in
272
desired_files. No specific order is guaranteed.
274
Yields pairs of identifier, bytes_iterator. identifier is an opaque
275
value supplied by the caller as part of desired_files. It should
276
uniquely identify the file version in the caller's context. (Examples:
277
an index number or a TreeTransform trans_id.)
279
bytes_iterator is an iterable of bytestrings for the file. The
280
kind of iterable and length of the bytestrings are unspecified, but for
281
this implementation, it is a list of bytes produced by
282
VersionedFile.get_record_stream().
284
:param desired_files: a list of (file_id, revision_id, identifier)
288
for (file_id, revision_id, identifier) in desired_files:
289
per_revision.setdefault(revision_id, []).append(
290
(file_id, identifier))
291
for revid, files in per_revision.iteritems():
292
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
294
commit = self._git.object_store[commit_id]
296
raise errors.RevisionNotPresent(revid, self)
297
root_tree = commit.tree
298
for fileid, identifier in files:
299
path = mapping.parse_file_id(fileid)
301
obj = tree_lookup_path(
302
self._git.object_store.__getitem__, root_tree, path)
303
if isinstance(obj, tuple):
304
(mode, item_id) = obj
305
obj = self._git.object_store[item_id]
307
raise errors.RevisionNotPresent((fileid, revid), self)
309
if obj.type_name == "tree":
310
yield (identifier, [])
311
elif obj.type_name == "blob":
312
yield (identifier, obj.chunked)
314
raise AssertionError("file text resolved to %r" % obj)
316
def _iter_revision_ids(self):
317
mapping = self.get_mapping()
318
for sha in self._git.object_store:
319
o = self._git.object_store[sha]
320
if not isinstance(o, Commit):
322
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
323
mapping.revision_id_foreign_to_bzr)
324
yield o.id, rev.revision_id, roundtrip_revid
326
def all_revision_ids(self):
328
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
330
ret.add(roundtrip_revid)
335
def _get_parents(self, revid):
336
if type(revid) != str:
339
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
340
except errors.NoSuchRevision:
343
commit = self._git[hexsha]
347
self.lookup_foreign_revision_id(p, mapping)
348
for p in commit.parents]
350
def get_parent_map(self, revids):
352
for revision_id in revids:
353
parents = self._get_parents(revision_id)
354
if revision_id == revision.NULL_REVISION:
355
parent_map[revision_id] = ()
359
if len(parents) == 0:
360
parents = [revision.NULL_REVISION]
361
parent_map[revision_id] = tuple(parents)
364
def get_known_graph_ancestry(self, revision_ids):
365
"""Return the known graph for a set of revision ids and their ancestors.
367
pending = set(revision_ids)
371
for revid in pending:
372
if revid == revision.NULL_REVISION:
374
parents = self._get_parents(revid)
375
if parents is not None:
376
this_parent_map[revid] = parents
377
parent_map.update(this_parent_map)
379
map(pending.update, this_parent_map.itervalues())
380
pending = pending.difference(parent_map)
381
return _mod_graph.KnownGraph(parent_map)
383
def get_signature_text(self, revision_id):
384
raise errors.NoSuchRevision(self, revision_id)
386
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
387
result = GitCheck(self, check_repo=check_repo)
388
result.check(callback_refs)
391
def pack(self, hint=None, clean_obsolete_packs=False):
392
self._git.object_store.pack_loose_objects()
394
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
395
"""Lookup a revision id.
398
assert type(foreign_revid) is str
400
mapping = self.get_mapping()
401
if foreign_revid == ZERO_SHA:
402
return revision.NULL_REVISION
403
commit = self._git.object_store[foreign_revid]
404
while isinstance(commit, Tag):
405
commit = self._git[commit.object[1]]
406
if not isinstance(commit, Commit):
407
raise NotCommitError(commit.id)
408
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
409
mapping.revision_id_foreign_to_bzr)
410
# FIXME: check testament before doing this?
412
return roundtrip_revid
414
return rev.revision_id
416
def has_signature_for_revision_id(self, revision_id):
417
"""Check whether a GPG signature is present for this revision.
419
This is never the case for Git repositories.
423
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
424
"""Lookup a bzr revision id in a Git repository.
426
:param bzr_revid: Bazaar revision id
427
:param mapping: Optional mapping to use
428
:return: Tuple with git commit id, mapping that was used and supplement
432
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
433
except errors.InvalidRevisionId:
435
mapping = self.get_mapping()
437
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
440
# Update refs from Git commit objects
441
# FIXME: Hitting this a lot will be very inefficient...
442
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
443
if not roundtrip_revid:
445
refname = mapping.revid_as_refname(roundtrip_revid)
446
self._git.refs[refname] = git_sha
447
if roundtrip_revid == bzr_revid:
448
return git_sha, mapping
449
raise errors.NoSuchRevision(self, bzr_revid)
451
return (git_sha, mapping)
453
def get_revision(self, revision_id):
454
if not isinstance(revision_id, str):
455
raise errors.InvalidRevisionId(revision_id, self)
456
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
458
commit = self._git[git_commit_id]
460
raise errors.NoSuchRevision(self, revision_id)
461
revision, roundtrip_revid, verifiers = mapping.import_commit(
462
commit, self.lookup_foreign_revision_id)
463
assert revision is not None
464
# FIXME: check verifiers ?
466
revision.revision_id = roundtrip_revid
469
def has_revision(self, revision_id):
470
"""See Repository.has_revision."""
471
if revision_id == revision.NULL_REVISION:
474
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
475
except errors.NoSuchRevision:
477
return (git_commit_id in self._git)
479
def has_revisions(self, revision_ids):
480
"""See Repository.has_revisions."""
481
return set(filter(self.has_revision, revision_ids))
483
def get_revisions(self, revids):
484
"""See Repository.get_revisions."""
485
return [self.get_revision(r) for r in revids]
487
def revision_trees(self, revids):
488
"""See Repository.revision_trees."""
490
yield self.revision_tree(revid)
492
def revision_tree(self, revision_id):
493
"""See Repository.revision_tree."""
494
revision_id = revision.ensure_null(revision_id)
495
if revision_id == revision.NULL_REVISION:
496
inv = inventory.Inventory(root_id=None)
497
inv.revision_id = revision_id
498
return InventoryRevisionTree(self, inv, revision_id)
499
return GitRevisionTree(self, revision_id)
501
def get_inventory(self, revision_id):
502
raise NotImplementedError(self.get_inventory)
504
def set_make_working_trees(self, trees):
505
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
506
# TODO: Set bare= in the configuration bug=777065
508
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
510
return self._git.fetch_objects(determine_wants, graph_walker, progress)
513
class GitRepositoryFormat(repository.RepositoryFormat):
514
"""Git repository format."""
516
supports_versioned_directories = False
517
supports_tree_reference = False
518
rich_root_data = True
519
supports_leaving_lock = False
521
supports_funky_characters = True
522
supports_external_lookups = False
523
supports_full_versioned_files = False
524
supports_revision_signatures = False
525
supports_nesting_repositories = False
526
revision_graph_can_have_wrong_parents = False
529
def _matchingbzrdir(self):
530
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
531
return LocalGitControlDirFormat()
533
def get_format_description(self):
534
return "Git Repository"
536
def initialize(self, controldir, shared=False, _internal=False):
537
from bzrlib.plugins.git.dir import GitDir
538
if not isinstance(controldir, GitDir):
539
raise errors.UninitializableFormat(self)
540
return controldir.open_repository()
542
def check_conversion_target(self, target_repo_format):
543
return target_repo_format.rich_root_data
545
def get_foreign_tests_repository_factory(self):
546
from bzrlib.plugins.git.tests.test_repository import (
547
ForeignTestsRepositoryFactory,
549
return ForeignTestsRepositoryFactory()
551
def network_name(self):