1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
# Copyright (C) 2007 Canonical Ltd
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
"""An adapter between a Git Repository and a Bazaar Branch"""
20
from __future__ import absolute_import
28
revision as _mod_revision,
32
version_info as breezy_version,
34
from ...decorators import only_raises
35
from ...foreign import (
38
from ...sixish import viewvalues
43
from .filegraph import (
44
GitFileLastChangeScanner,
45
GitFileParentProvider,
47
from .mapping import (
57
from dulwich.errors import (
60
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.check_repo = check_repo
99
self.checked_rev_cnt = 0
100
self.object_count = None
103
def check(self, callback_refs=None, check_repo=True):
104
if callback_refs is None:
106
with self.repository.lock_read(), ui.ui_factory.nested_progress_bar() as self.progress:
107
shas = set(self.repository._git.object_store)
108
self.object_count = len(shas)
109
# TODO(jelmer): Check more things
110
for i, sha in enumerate(shas):
111
self.progress.update('checking objects', i, self.object_count)
112
o = self.repository._git.object_store[sha]
115
except Exception as e:
116
self.problems.append((sha, e))
118
def _report_repo_results(self, verbose):
119
trace.note('checked repository {0} format {1}'.format(
120
self.repository.user_url,
121
self.repository._format))
122
trace.note('%6d objects', self.object_count)
123
for sha, problem in self.problems:
124
trace.note('%s: %s', sha, problem)
126
def report_results(self, verbose):
128
self._report_repo_results(verbose)
131
_optimisers_loaded = False
133
def lazy_load_optimisers():
134
global _optimisers_loaded
135
if _optimisers_loaded:
137
from . import interrepo
138
for optimiser in [interrepo.InterRemoteGitNonGitRepository,
139
interrepo.InterLocalGitNonGitRepository,
140
interrepo.InterLocalGitLocalGitRepository,
141
interrepo.InterRemoteGitLocalGitRepository,
142
interrepo.InterToLocalGitRepository,
143
interrepo.InterToRemoteGitRepository,
145
repository.InterRepository.register_optimiser(optimiser)
146
_optimisers_loaded = True
149
class GitRepository(ForeignRepository):
150
"""An adapter to git repositories for bzr."""
153
vcs = foreign_vcs_git
156
def __init__(self, gitdir):
157
self._transport = gitdir.root_transport
158
super(GitRepository, self).__init__(GitRepositoryFormat(),
159
gitdir, control_files=None)
160
self.base = gitdir.root_transport.base
161
lazy_load_optimisers()
162
self._lock_mode = None
165
def add_fallback_repository(self, basis_url):
166
raise errors.UnstackableRepositoryFormat(self._format,
167
self.control_transport.base)
172
def get_physical_lock_status(self):
175
def lock_write(self):
176
"""See Branch.lock_write()."""
178
if self._lock_mode != 'w':
179
raise errors.ReadOnlyError(self)
180
self._lock_count += 1
182
self._lock_mode = 'w'
184
self._transaction = transactions.WriteTransaction()
185
return repository.RepositoryWriteLockResult(self.unlock, None)
187
def break_lock(self):
188
raise NotImplementedError(self.break_lock)
190
def dont_leave_lock_in_place(self):
191
raise NotImplementedError(self.dont_leave_lock_in_place)
193
def leave_lock_in_place(self):
194
raise NotImplementedError(self.leave_lock_in_place)
198
if self._lock_mode not in ('r', 'w'):
200
self._lock_count += 1
202
self._lock_mode = 'r'
204
self._transaction = transactions.ReadOnlyTransaction()
205
return lock.LogicalLockResult(self.unlock)
207
@only_raises(errors.LockNotHeld, errors.LockBroken)
209
if self._lock_count == 0:
210
raise errors.LockNotHeld(self)
211
if self._lock_count == 1 and self._lock_mode == 'w':
212
if self._write_group is not None:
213
self.abort_write_group()
214
self._lock_count -= 1
215
self._lock_mode = None
216
raise errors.BzrError(
217
'Must end write groups before releasing write locks.')
218
self._lock_count -= 1
219
if self._lock_count == 0:
220
self._lock_mode = None
221
transaction = self._transaction
222
self._transaction = None
225
def is_write_locked(self):
226
return (self._lock_mode == 'w')
229
return (self._lock_mode is not None)
231
def get_transaction(self):
232
"""See Repository.get_transaction()."""
233
if self._transaction is None:
234
return transactions.PassThroughTransaction()
236
return self._transaction
238
def reconcile(self, other=None, thorough=False):
239
"""Reconcile this repository."""
240
reconciler = RepoReconciler(self, thorough=thorough)
241
reconciler.reconcile()
244
def supports_rich_root(self):
247
def get_mapping(self):
248
return default_mapping
250
def make_working_trees(self):
251
return not self._git.get_config().get_boolean(("core", ), "bare")
253
def revision_graph_can_have_wrong_parents(self):
256
def add_signature_text(self, revid, signature):
257
raise errors.UnsupportedOperation(self.add_signature_text, self)
259
def sign_revision(self, revision_id, gpg_strategy):
260
raise errors.UnsupportedOperation(self.add_signature_text, self)
263
class LocalGitRepository(GitRepository):
264
"""Git repository on the file system."""
266
def __init__(self, gitdir):
267
GitRepository.__init__(self, gitdir)
268
self._git = gitdir._git
269
self._file_change_scanner = GitFileLastChangeScanner(self)
270
self._transaction = None
272
def get_commit_builder(self, branch, parents, config, timestamp=None,
273
timezone=None, committer=None, revprops=None,
274
revision_id=None, lossy=False):
275
"""Obtain a CommitBuilder for this repository.
277
:param branch: Branch to commit to.
278
:param parents: Revision ids of the parents of the new revision.
279
:param config: Configuration to use.
280
:param timestamp: Optional timestamp recorded for commit.
281
:param timezone: Optional timezone for timestamp.
282
:param committer: Optional committer to set for commit.
283
:param revprops: Optional dictionary of revision properties.
284
:param revision_id: Optional revision id.
285
:param lossy: Whether to discard data that can not be natively
286
represented, when pushing to a foreign VCS
288
builder = GitCommitBuilder(self, parents, config,
289
timestamp, timezone, committer, revprops, revision_id,
291
self.start_write_group()
294
def get_file_graph(self):
295
return _mod_graph.Graph(GitFileParentProvider(
296
self._file_change_scanner))
298
def iter_files_bytes(self, desired_files):
299
"""Iterate through file versions.
301
Files will not necessarily be returned in the order they occur in
302
desired_files. No specific order is guaranteed.
304
Yields pairs of identifier, bytes_iterator. identifier is an opaque
305
value supplied by the caller as part of desired_files. It should
306
uniquely identify the file version in the caller's context. (Examples:
307
an index number or a TreeTransform trans_id.)
309
bytes_iterator is an iterable of bytestrings for the file. The
310
kind of iterable and length of the bytestrings are unspecified, but for
311
this implementation, it is a list of bytes produced by
312
VersionedFile.get_record_stream().
314
:param desired_files: a list of (file_id, revision_id, identifier)
318
for (file_id, revision_id, identifier) in desired_files:
319
per_revision.setdefault(revision_id, []).append(
320
(file_id, identifier))
321
for revid, files in per_revision.iteritems():
323
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
324
except errors.NoSuchRevision:
325
raise errors.RevisionNotPresent(revid, self)
327
commit = self._git.object_store[commit_id]
329
raise errors.RevisionNotPresent(revid, self)
330
root_tree = commit.tree
331
for fileid, identifier in files:
333
path = mapping.parse_file_id(fileid)
335
raise errors.RevisionNotPresent((fileid, revid), self)
337
obj = tree_lookup_path(
338
self._git.object_store.__getitem__, root_tree, path)
339
if isinstance(obj, tuple):
340
(mode, item_id) = obj
341
obj = self._git.object_store[item_id]
343
raise errors.RevisionNotPresent((fileid, revid), self)
345
if obj.type_name == "tree":
346
yield (identifier, [])
347
elif obj.type_name == "blob":
348
yield (identifier, obj.chunked)
350
raise AssertionError("file text resolved to %r" % obj)
352
def gather_stats(self, revid=None, committers=None):
353
"""See Repository.gather_stats()."""
354
result = super(LocalGitRepository, self).gather_stats(revid, committers)
356
for sha in self._git.object_store:
357
o = self._git.object_store[sha]
358
if o.type_name == "commit":
360
result['revisions'] = len(revs)
363
def _iter_revision_ids(self):
364
mapping = self.get_mapping()
365
for sha in self._git.object_store:
366
o = self._git.object_store[sha]
367
if not isinstance(o, Commit):
369
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
370
mapping.revision_id_foreign_to_bzr)
371
yield o.id, rev.revision_id, roundtrip_revid
373
def all_revision_ids(self):
375
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
377
ret.add(roundtrip_revid)
382
def _get_parents(self, revid, no_alternates=False):
383
if type(revid) != bytes:
386
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
387
except errors.NoSuchRevision:
389
# FIXME: Honor no_alternates setting
391
commit = self._git.object_store[hexsha]
395
for p in commit.parents:
397
ret.append(self.lookup_foreign_revision_id(p, mapping))
399
ret.append(mapping.revision_id_foreign_to_bzr(p))
402
def _get_parent_map_no_fallbacks(self, revids):
403
return self.get_parent_map(revids, no_alternates=True)
405
def get_parent_map(self, revids, no_alternates=False):
407
for revision_id in revids:
408
parents = self._get_parents(revision_id, no_alternates=no_alternates)
409
if revision_id == _mod_revision.NULL_REVISION:
410
parent_map[revision_id] = ()
414
if len(parents) == 0:
415
parents = [_mod_revision.NULL_REVISION]
416
parent_map[revision_id] = tuple(parents)
419
def get_known_graph_ancestry(self, revision_ids):
420
"""Return the known graph for a set of revision ids and their ancestors.
422
pending = set(revision_ids)
426
for revid in pending:
427
if revid == _mod_revision.NULL_REVISION:
429
parents = self._get_parents(revid)
430
if parents is not None:
431
this_parent_map[revid] = parents
432
parent_map.update(this_parent_map)
434
map(pending.update, viewvalues(this_parent_map))
435
pending = pending.difference(parent_map)
436
return _mod_graph.KnownGraph(parent_map)
438
def get_signature_text(self, revision_id):
439
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
441
commit = self._git.object_store[git_commit_id]
443
raise errors.NoSuchRevision(self, revision_id)
444
if commit.gpgsig is None:
445
raise errors.NoSuchRevision(self, revision_id)
448
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
449
result = GitCheck(self, check_repo=check_repo)
450
result.check(callback_refs)
453
def pack(self, hint=None, clean_obsolete_packs=False):
454
self._git.object_store.pack_loose_objects()
456
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
457
"""Lookup a revision id.
459
:param foreign_revid: Foreign revision id to look up
460
:param mapping: Mapping to use (use default mapping if not specified)
461
:raise KeyError: If foreign revision was not found
462
:return: bzr revision id
464
if not isinstance(foreign_revid, bytes):
465
raise TypeError(foreign_revid)
467
mapping = self.get_mapping()
468
if foreign_revid == ZERO_SHA:
469
return _mod_revision.NULL_REVISION
470
commit = self._git.object_store.peel_sha(foreign_revid)
471
if not isinstance(commit, Commit):
472
raise NotCommitError(commit.id)
473
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
474
mapping.revision_id_foreign_to_bzr)
475
# FIXME: check testament before doing this?
477
return roundtrip_revid
479
return rev.revision_id
481
def has_signature_for_revision_id(self, revision_id):
482
"""Check whether a GPG signature is present for this revision.
484
This is never the case for Git repositories.
487
self.get_signature_text(revision_id)
488
except errors.NoSuchRevision:
493
def verify_revision_signature(self, revision_id, gpg_strategy):
494
"""Verify the signature on a revision.
496
:param revision_id: the revision to verify
497
:gpg_strategy: the GPGStrategy object to used
499
:return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
501
from breezy import gpg
502
with self.lock_read():
503
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
505
commit = self._git.object_store[git_commit_id]
507
raise errors.NoSuchRevision(self, revision_id)
509
if commit.gpgsig is None:
510
return gpg.SIGNATURE_NOT_SIGNED, None
512
without_sig = Commit.from_string(commit.as_raw_string())
513
without_sig.gpgsig = None
515
(result, key, plain_text) = gpg_strategy.verify(without_sig.as_raw_string(), commit.gpgsig)
518
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
519
"""Lookup a bzr revision id in a Git repository.
521
:param bzr_revid: Bazaar revision id
522
:param mapping: Optional mapping to use
523
:return: Tuple with git commit id, mapping that was used and supplement
527
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
528
except errors.InvalidRevisionId:
530
mapping = self.get_mapping()
532
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
535
# Update refs from Git commit objects
536
# FIXME: Hitting this a lot will be very inefficient...
537
pb = ui.ui_factory.nested_progress_bar()
539
for i, (git_sha, revid, roundtrip_revid) in enumerate(self._iter_revision_ids()):
540
if not roundtrip_revid:
542
pb.update("resolving revision id", i)
543
refname = mapping.revid_as_refname(roundtrip_revid)
544
self._git.refs[refname] = git_sha
545
if roundtrip_revid == bzr_revid:
546
return git_sha, mapping
549
raise errors.NoSuchRevision(self, bzr_revid)
551
return (git_sha, mapping)
553
def get_revision(self, revision_id):
554
if not isinstance(revision_id, bytes):
555
raise errors.InvalidRevisionId(revision_id, self)
556
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
558
commit = self._git.object_store[git_commit_id]
560
raise errors.NoSuchRevision(self, revision_id)
561
revision, roundtrip_revid, verifiers = mapping.import_commit(
562
commit, self.lookup_foreign_revision_id)
565
# FIXME: check verifiers ?
567
revision.revision_id = roundtrip_revid
570
def has_revision(self, revision_id):
571
"""See Repository.has_revision."""
572
if revision_id == _mod_revision.NULL_REVISION:
575
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
576
except errors.NoSuchRevision:
578
return (git_commit_id in self._git)
580
def has_revisions(self, revision_ids):
581
"""See Repository.has_revisions."""
582
return set(filter(self.has_revision, revision_ids))
584
def iter_revisions(self, revision_ids):
585
"""See Repository.get_revisions."""
586
for revid in revision_ids:
588
rev = self.get_revision(revid)
589
except errors.NoSuchRevision:
593
def revision_trees(self, revids):
594
"""See Repository.revision_trees."""
596
yield self.revision_tree(revid)
598
def revision_tree(self, revision_id):
599
"""See Repository.revision_tree."""
600
if revision_id is None:
601
raise ValueError('invalid revision id %s' % revision_id)
602
return GitRevisionTree(self, revision_id)
604
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
605
"""Produce a generator of revision deltas.
607
Note that the input is a sequence of REVISIONS, not revision_ids.
608
Trees will be held in memory until the generator exits.
609
Each delta is relative to the revision's lefthand predecessor.
611
:param specific_fileids: if not None, the result is filtered
612
so that only those file-ids, their parents and their
613
children are included.
615
# Get the revision-ids of interest
616
required_trees = set()
617
for revision in revisions:
618
required_trees.add(revision.revision_id)
619
required_trees.update(revision.parent_ids[:1])
621
trees = dict((t.get_revision_id(), t) for
622
t in self.revision_trees(required_trees))
624
# Calculate the deltas
625
for revision in revisions:
626
if not revision.parent_ids:
627
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
629
old_tree = trees[revision.parent_ids[0]]
630
new_tree = trees[revision.revision_id]
631
if specific_fileids is not None:
632
specific_files = [new_tree.id2path(fid) for fid in specific_fileids]
634
specific_files = None
635
yield new_tree.changes_from(old_tree, specific_files=specific_files)
637
def set_make_working_trees(self, trees):
638
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
640
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
641
progress=None, limit=None):
642
return self._git.fetch_objects(determine_wants, graph_walker, progress,
646
class GitRepositoryFormat(repository.RepositoryFormat):
647
"""Git repository format."""
649
supports_versioned_directories = False
650
supports_tree_reference = True
651
rich_root_data = True
652
supports_leaving_lock = False
654
supports_funky_characters = True
655
supports_external_lookups = False
656
supports_full_versioned_files = False
657
supports_revision_signatures = False
658
supports_nesting_repositories = False
659
revision_graph_can_have_wrong_parents = False
660
supports_unreferenced_revisions = True
661
supports_setting_revision_ids = False
662
supports_storing_branch_nick = False
663
supports_overriding_transport = False
664
supports_custom_revision_properties = False
665
records_per_file_revision = False
668
def _matchingcontroldir(self):
669
from .dir import LocalGitControlDirFormat
670
return LocalGitControlDirFormat()
672
def get_format_description(self):
673
return "Git Repository"
675
def initialize(self, controldir, shared=False, _internal=False):
676
from .dir import GitDir
677
if not isinstance(controldir, GitDir):
678
raise errors.UninitializableFormat(self)
679
return controldir.open_repository()
681
def check_conversion_target(self, target_repo_format):
682
return target_repo_format.rich_root_data
684
def get_foreign_tests_repository_factory(self):
685
from .tests.test_repository import (
686
ForeignTestsRepositoryFactory,
688
return ForeignTestsRepositoryFactory()
690
def network_name(self):
694
def get_extra_interrepo_test_combinations():
695
from ...bzr.groupcompress_repo import RepositoryFormat2a
696
from . import interrepo
698
(interrepo.InterLocalGitNonGitRepository, GitRepositoryFormat(), RepositoryFormat2a()),
699
(interrepo.InterLocalGitLocalGitRepository, GitRepositoryFormat(), GitRepositoryFormat()),
700
(interrepo.InterToLocalGitRepository, RepositoryFormat2a(), GitRepositoryFormat()),