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 (
46
from .filegraph import (
47
GitFileLastChangeScanner,
48
GitFileParentProvider,
50
from .mapping import (
60
from dulwich.errors import (
63
from dulwich.objects import (
67
from dulwich.object_store import (
72
class RepoReconciler(object):
73
"""Reconciler that reconciles a repository.
77
def __init__(self, repo, other=None, thorough=False):
78
"""Construct a RepoReconciler.
80
:param thorough: perform a thorough check which may take longer but
81
will correct non-data loss issues such as incorrect
87
"""Perform reconciliation.
89
After reconciliation the following attributes document found issues:
90
inconsistent_parents: The number of revisions in the repository whose
91
ancestry was being reported incorrectly.
92
garbage_inventories: The number of inventory objects without revisions
93
that were garbage collected.
97
class GitCheck(check.Check):
99
def __init__(self, repository, check_repo=True):
100
self.repository = repository
101
self.check_repo = check_repo
102
self.checked_rev_cnt = 0
103
self.object_count = None
106
def check(self, callback_refs=None, check_repo=True):
107
if callback_refs is None:
109
with self.repository.lock_read(), ui.ui_factory.nested_progress_bar() as self.progress:
110
shas = set(self.repository._git.object_store)
111
self.object_count = len(shas)
112
# TODO(jelmer): Check more things
113
for i, sha in enumerate(shas):
114
self.progress.update('checking objects', i, self.object_count)
115
o = self.repository._git.object_store[sha]
118
except Exception as e:
119
self.problems.append((sha, e))
121
def _report_repo_results(self, verbose):
122
trace.note('checked repository {0} format {1}'.format(
123
self.repository.user_url,
124
self.repository._format))
125
trace.note('%6d objects', self.object_count)
126
for sha, problem in self.problems:
127
trace.note('%s: %s', sha, problem)
129
def report_results(self, verbose):
131
self._report_repo_results(verbose)
134
_optimisers_loaded = False
136
def lazy_load_optimisers():
137
global _optimisers_loaded
138
if _optimisers_loaded:
140
from . import interrepo
141
for optimiser in [interrepo.InterRemoteGitNonGitRepository,
142
interrepo.InterLocalGitNonGitRepository,
143
interrepo.InterLocalGitLocalGitRepository,
144
interrepo.InterRemoteGitLocalGitRepository,
145
interrepo.InterToLocalGitRepository,
146
interrepo.InterToRemoteGitRepository,
148
repository.InterRepository.register_optimiser(optimiser)
149
_optimisers_loaded = True
152
class GitRepository(ForeignRepository):
153
"""An adapter to git repositories for bzr."""
156
vcs = foreign_vcs_git
159
def __init__(self, gitdir):
160
self._transport = gitdir.root_transport
161
super(GitRepository, self).__init__(GitRepositoryFormat(),
162
gitdir, control_files=None)
163
self.base = gitdir.root_transport.base
164
lazy_load_optimisers()
165
self._lock_mode = None
168
def add_fallback_repository(self, basis_url):
169
raise errors.UnstackableRepositoryFormat(self._format,
170
self.control_transport.base)
175
def get_physical_lock_status(self):
178
def lock_write(self):
179
"""See Branch.lock_write()."""
181
if self._lock_mode != 'w':
182
raise errors.ReadOnlyError(self)
183
self._lock_count += 1
185
self._lock_mode = 'w'
187
self._transaction = transactions.WriteTransaction()
188
return repository.RepositoryWriteLockResult(self.unlock, None)
190
def break_lock(self):
191
raise NotImplementedError(self.break_lock)
193
def dont_leave_lock_in_place(self):
194
raise NotImplementedError(self.dont_leave_lock_in_place)
196
def leave_lock_in_place(self):
197
raise NotImplementedError(self.leave_lock_in_place)
201
if self._lock_mode not in ('r', 'w'):
203
self._lock_count += 1
205
self._lock_mode = 'r'
207
self._transaction = transactions.ReadOnlyTransaction()
208
return lock.LogicalLockResult(self.unlock)
210
@only_raises(errors.LockNotHeld, errors.LockBroken)
212
if self._lock_count == 0:
213
raise errors.LockNotHeld(self)
214
if self._lock_count == 1 and self._lock_mode == 'w':
215
if self._write_group is not None:
216
self.abort_write_group()
217
self._lock_count -= 1
218
self._lock_mode = None
219
raise errors.BzrError(
220
'Must end write groups before releasing write locks.')
221
self._lock_count -= 1
222
if self._lock_count == 0:
223
self._lock_mode = None
224
transaction = self._transaction
225
self._transaction = None
228
def is_write_locked(self):
229
return (self._lock_mode == 'w')
232
return (self._lock_mode is not None)
234
def get_transaction(self):
235
"""See Repository.get_transaction()."""
236
if self._transaction is None:
237
return transactions.PassThroughTransaction()
239
return self._transaction
241
def reconcile(self, other=None, thorough=False):
242
"""Reconcile this repository."""
243
reconciler = RepoReconciler(self, thorough=thorough)
244
reconciler.reconcile()
247
def supports_rich_root(self):
250
def get_mapping(self):
251
return default_mapping
253
def make_working_trees(self):
254
return not self._git.get_config().get_boolean(("core", ), "bare")
256
def revision_graph_can_have_wrong_parents(self):
259
def add_signature_text(self, revid, signature):
260
raise errors.UnsupportedOperation(self.add_signature_text, self)
262
def sign_revision(self, revision_id, gpg_strategy):
263
raise errors.UnsupportedOperation(self.add_signature_text, self)
266
class LocalGitRepository(GitRepository):
267
"""Git repository on the file system."""
269
def __init__(self, gitdir):
270
GitRepository.__init__(self, gitdir)
271
self._git = gitdir._git
272
self._file_change_scanner = GitFileLastChangeScanner(self)
273
self._transaction = None
275
def get_commit_builder(self, branch, parents, config, timestamp=None,
276
timezone=None, committer=None, revprops=None,
277
revision_id=None, lossy=False):
278
"""Obtain a CommitBuilder for this repository.
280
:param branch: Branch to commit to.
281
:param parents: Revision ids of the parents of the new revision.
282
:param config: Configuration to use.
283
:param timestamp: Optional timestamp recorded for commit.
284
:param timezone: Optional timezone for timestamp.
285
:param committer: Optional committer to set for commit.
286
:param revprops: Optional dictionary of revision properties.
287
:param revision_id: Optional revision id.
288
:param lossy: Whether to discard data that can not be natively
289
represented, when pushing to a foreign VCS
291
builder = GitCommitBuilder(self, parents, config,
292
timestamp, timezone, committer, revprops, revision_id,
294
self.start_write_group()
297
def get_file_graph(self):
298
return _mod_graph.Graph(GitFileParentProvider(
299
self._file_change_scanner))
301
def iter_files_bytes(self, desired_files):
302
"""Iterate through file versions.
304
Files will not necessarily be returned in the order they occur in
305
desired_files. No specific order is guaranteed.
307
Yields pairs of identifier, bytes_iterator. identifier is an opaque
308
value supplied by the caller as part of desired_files. It should
309
uniquely identify the file version in the caller's context. (Examples:
310
an index number or a TreeTransform trans_id.)
312
bytes_iterator is an iterable of bytestrings for the file. The
313
kind of iterable and length of the bytestrings are unspecified, but for
314
this implementation, it is a list of bytes produced by
315
VersionedFile.get_record_stream().
317
:param desired_files: a list of (file_id, revision_id, identifier)
321
for (file_id, revision_id, identifier) in desired_files:
322
per_revision.setdefault(revision_id, []).append(
323
(file_id, identifier))
324
for revid, files in viewitems(per_revision):
326
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
327
except errors.NoSuchRevision:
328
raise errors.RevisionNotPresent(revid, self)
330
commit = self._git.object_store[commit_id]
332
raise errors.RevisionNotPresent(revid, self)
333
root_tree = commit.tree
334
for fileid, identifier in files:
336
path = mapping.parse_file_id(fileid)
338
raise errors.RevisionNotPresent((fileid, revid), self)
340
obj = tree_lookup_path(
341
self._git.object_store.__getitem__, root_tree,
342
path.encode('utf-8'))
343
if isinstance(obj, tuple):
344
(mode, item_id) = obj
345
obj = self._git.object_store[item_id]
347
raise errors.RevisionNotPresent((fileid, revid), self)
349
if obj.type_name == b"tree":
350
yield (identifier, [])
351
elif obj.type_name == b"blob":
352
yield (identifier, obj.chunked)
354
raise AssertionError("file text resolved to %r" % obj)
356
def gather_stats(self, revid=None, committers=None):
357
"""See Repository.gather_stats()."""
358
result = super(LocalGitRepository, self).gather_stats(revid, committers)
360
for sha in self._git.object_store:
361
o = self._git.object_store[sha]
362
if o.type_name == b"commit":
364
result['revisions'] = len(revs)
367
def _iter_revision_ids(self):
368
mapping = self.get_mapping()
369
for sha in self._git.object_store:
370
o = self._git.object_store[sha]
371
if not isinstance(o, Commit):
373
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
374
mapping.revision_id_foreign_to_bzr)
375
yield o.id, rev.revision_id, roundtrip_revid
377
def all_revision_ids(self):
379
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
381
ret.add(roundtrip_revid)
386
def _get_parents(self, revid, no_alternates=False):
387
if type(revid) != bytes:
390
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
391
except errors.NoSuchRevision:
393
# FIXME: Honor no_alternates setting
395
commit = self._git.object_store[hexsha]
399
for p in commit.parents:
401
ret.append(self.lookup_foreign_revision_id(p, mapping))
403
ret.append(mapping.revision_id_foreign_to_bzr(p))
406
def _get_parent_map_no_fallbacks(self, revids):
407
return self.get_parent_map(revids, no_alternates=True)
409
def get_parent_map(self, revids, no_alternates=False):
411
for revision_id in revids:
412
parents = self._get_parents(revision_id, no_alternates=no_alternates)
413
if revision_id == _mod_revision.NULL_REVISION:
414
parent_map[revision_id] = ()
418
if len(parents) == 0:
419
parents = [_mod_revision.NULL_REVISION]
420
parent_map[revision_id] = tuple(parents)
423
def get_known_graph_ancestry(self, revision_ids):
424
"""Return the known graph for a set of revision ids and their ancestors.
426
pending = set(revision_ids)
430
for revid in pending:
431
if revid == _mod_revision.NULL_REVISION:
433
parents = self._get_parents(revid)
434
if parents is not None:
435
this_parent_map[revid] = parents
436
parent_map.update(this_parent_map)
438
for values in viewvalues(this_parent_map):
439
pending.update(values)
440
pending = pending.difference(parent_map)
441
return _mod_graph.KnownGraph(parent_map)
443
def get_signature_text(self, revision_id):
444
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
446
commit = self._git.object_store[git_commit_id]
448
raise errors.NoSuchRevision(self, revision_id)
449
if commit.gpgsig is None:
450
raise errors.NoSuchRevision(self, revision_id)
453
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
454
result = GitCheck(self, check_repo=check_repo)
455
result.check(callback_refs)
458
def pack(self, hint=None, clean_obsolete_packs=False):
459
self._git.object_store.pack_loose_objects()
461
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
462
"""Lookup a revision id.
464
:param foreign_revid: Foreign revision id to look up
465
:param mapping: Mapping to use (use default mapping if not specified)
466
:raise KeyError: If foreign revision was not found
467
:return: bzr revision id
469
if not isinstance(foreign_revid, bytes):
470
raise TypeError(foreign_revid)
472
mapping = self.get_mapping()
473
if foreign_revid == ZERO_SHA:
474
return _mod_revision.NULL_REVISION
475
commit = self._git.object_store.peel_sha(foreign_revid)
476
if not isinstance(commit, Commit):
477
raise NotCommitError(commit.id)
478
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
479
mapping.revision_id_foreign_to_bzr)
480
# FIXME: check testament before doing this?
482
return roundtrip_revid
484
return rev.revision_id
486
def has_signature_for_revision_id(self, revision_id):
487
"""Check whether a GPG signature is present for this revision.
489
This is never the case for Git repositories.
492
self.get_signature_text(revision_id)
493
except errors.NoSuchRevision:
498
def verify_revision_signature(self, revision_id, gpg_strategy):
499
"""Verify the signature on a revision.
501
:param revision_id: the revision to verify
502
:gpg_strategy: the GPGStrategy object to used
504
:return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
506
from breezy import gpg
507
with self.lock_read():
508
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
510
commit = self._git.object_store[git_commit_id]
512
raise errors.NoSuchRevision(self, revision_id)
514
if commit.gpgsig is None:
515
return gpg.SIGNATURE_NOT_SIGNED, None
517
without_sig = Commit.from_string(commit.as_raw_string())
518
without_sig.gpgsig = None
520
(result, key, plain_text) = gpg_strategy.verify(without_sig.as_raw_string(), commit.gpgsig)
523
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
524
"""Lookup a bzr revision id in a Git repository.
526
:param bzr_revid: Bazaar revision id
527
:param mapping: Optional mapping to use
528
:return: Tuple with git commit id, mapping that was used and supplement
532
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
533
except errors.InvalidRevisionId:
535
mapping = self.get_mapping()
537
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
540
# Update refs from Git commit objects
541
# FIXME: Hitting this a lot will be very inefficient...
542
pb = ui.ui_factory.nested_progress_bar()
544
for i, (git_sha, revid, roundtrip_revid) in enumerate(self._iter_revision_ids()):
545
if not roundtrip_revid:
547
pb.update("resolving revision id", i)
548
refname = mapping.revid_as_refname(roundtrip_revid)
549
self._git.refs[refname] = git_sha
550
if roundtrip_revid == bzr_revid:
551
return git_sha, mapping
554
raise errors.NoSuchRevision(self, bzr_revid)
556
return (git_sha, mapping)
558
def get_revision(self, revision_id):
559
if not isinstance(revision_id, bytes):
560
raise errors.InvalidRevisionId(revision_id, self)
561
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
563
commit = self._git.object_store[git_commit_id]
565
raise errors.NoSuchRevision(self, revision_id)
566
revision, roundtrip_revid, verifiers = mapping.import_commit(
567
commit, self.lookup_foreign_revision_id)
570
# FIXME: check verifiers ?
572
revision.revision_id = roundtrip_revid
575
def has_revision(self, revision_id):
576
"""See Repository.has_revision."""
577
if revision_id == _mod_revision.NULL_REVISION:
580
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
581
except errors.NoSuchRevision:
583
return (git_commit_id in self._git)
585
def has_revisions(self, revision_ids):
586
"""See Repository.has_revisions."""
587
return set(filter(self.has_revision, revision_ids))
589
def iter_revisions(self, revision_ids):
590
"""See Repository.get_revisions."""
591
for revid in revision_ids:
593
rev = self.get_revision(revid)
594
except errors.NoSuchRevision:
598
def revision_trees(self, revids):
599
"""See Repository.revision_trees."""
601
yield self.revision_tree(revid)
603
def revision_tree(self, revision_id):
604
"""See Repository.revision_tree."""
605
if revision_id is None:
606
raise ValueError('invalid revision id %s' % revision_id)
607
return GitRevisionTree(self, revision_id)
609
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
610
"""Produce a generator of revision deltas.
612
Note that the input is a sequence of REVISIONS, not revision_ids.
613
Trees will be held in memory until the generator exits.
614
Each delta is relative to the revision's lefthand predecessor.
616
:param specific_fileids: if not None, the result is filtered
617
so that only those file-ids, their parents and their
618
children are included.
620
# Get the revision-ids of interest
621
required_trees = set()
622
for revision in revisions:
623
required_trees.add(revision.revision_id)
624
required_trees.update(revision.parent_ids[:1])
626
trees = dict((t.get_revision_id(), t) for
627
t in self.revision_trees(required_trees))
629
# Calculate the deltas
630
for revision in revisions:
631
if not revision.parent_ids:
632
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
634
old_tree = trees[revision.parent_ids[0]]
635
new_tree = trees[revision.revision_id]
636
if specific_fileids is not None:
637
specific_files = [new_tree.id2path(fid) for fid in specific_fileids]
639
specific_files = None
640
yield new_tree.changes_from(old_tree, specific_files=specific_files)
642
def set_make_working_trees(self, trees):
643
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
645
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
646
progress=None, limit=None):
647
return self._git.fetch_objects(determine_wants, graph_walker, progress,
651
class GitRepositoryFormat(repository.RepositoryFormat):
652
"""Git repository format."""
654
supports_versioned_directories = False
655
supports_tree_reference = True
656
rich_root_data = True
657
supports_leaving_lock = False
659
supports_funky_characters = True
660
supports_external_lookups = False
661
supports_full_versioned_files = False
662
supports_revision_signatures = False
663
supports_nesting_repositories = False
664
revision_graph_can_have_wrong_parents = False
665
supports_unreferenced_revisions = True
666
supports_setting_revision_ids = False
667
supports_storing_branch_nick = False
668
supports_overriding_transport = False
669
supports_custom_revision_properties = False
670
records_per_file_revision = False
673
def _matchingcontroldir(self):
674
from .dir import LocalGitControlDirFormat
675
return LocalGitControlDirFormat()
677
def get_format_description(self):
678
return "Git Repository"
680
def initialize(self, controldir, shared=False, _internal=False):
681
from .dir import GitDir
682
if not isinstance(controldir, GitDir):
683
raise errors.UninitializableFormat(self)
684
return controldir.open_repository()
686
def check_conversion_target(self, target_repo_format):
687
return target_repo_format.rich_root_data
689
def get_foreign_tests_repository_factory(self):
690
from .tests.test_repository import (
691
ForeignTestsRepositoryFactory,
693
return ForeignTestsRepositoryFactory()
695
def network_name(self):
699
def get_extra_interrepo_test_combinations():
700
from ..bzr.groupcompress_repo import RepositoryFormat2a
701
from . import interrepo
703
(interrepo.InterLocalGitNonGitRepository, GitRepositoryFormat(), RepositoryFormat2a()),
704
(interrepo.InterLocalGitLocalGitRepository, GitRepositoryFormat(), GitRepositoryFormat()),
705
(interrepo.InterToLocalGitRepository, RepositoryFormat2a(), GitRepositoryFormat()),