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,
33
from ..decorators import only_raises
34
from ..foreign import (
37
from ..sixish import (
45
from .filegraph import (
46
GitFileLastChangeScanner,
47
GitFileParentProvider,
49
from .mapping import (
59
from dulwich.errors import (
62
from dulwich.objects import (
66
from dulwich.object_store import (
71
class RepoReconciler(object):
72
"""Reconciler that reconciles a repository.
76
def __init__(self, repo, other=None, thorough=False):
77
"""Construct a RepoReconciler.
79
:param thorough: perform a thorough check which may take longer but
80
will correct non-data loss issues such as incorrect
86
"""Perform reconciliation.
88
After reconciliation the following attributes document found issues:
89
inconsistent_parents: The number of revisions in the repository whose
90
ancestry was being reported incorrectly.
91
garbage_inventories: The number of inventory objects without revisions
92
that were garbage collected.
96
class GitCheck(check.Check):
98
def __init__(self, repository, check_repo=True):
99
self.repository = repository
100
self.check_repo = check_repo
101
self.checked_rev_cnt = 0
102
self.object_count = None
105
def check(self, callback_refs=None, check_repo=True):
106
if callback_refs is None:
108
with self.repository.lock_read(), ui.ui_factory.nested_progress_bar() as self.progress:
109
shas = set(self.repository._git.object_store)
110
self.object_count = len(shas)
111
# TODO(jelmer): Check more things
112
for i, sha in enumerate(shas):
113
self.progress.update('checking objects', i, self.object_count)
114
o = self.repository._git.object_store[sha]
117
except Exception as e:
118
self.problems.append((sha, e))
120
def _report_repo_results(self, verbose):
121
trace.note('checked repository {0} format {1}'.format(
122
self.repository.user_url,
123
self.repository._format))
124
trace.note('%6d objects', self.object_count)
125
for sha, problem in self.problems:
126
trace.note('%s: %s', sha, problem)
128
def report_results(self, verbose):
130
self._report_repo_results(verbose)
133
_optimisers_loaded = False
135
def lazy_load_optimisers():
136
global _optimisers_loaded
137
if _optimisers_loaded:
139
from . import interrepo
140
for optimiser in [interrepo.InterRemoteGitNonGitRepository,
141
interrepo.InterLocalGitNonGitRepository,
142
interrepo.InterLocalGitLocalGitRepository,
143
interrepo.InterRemoteGitLocalGitRepository,
144
interrepo.InterToLocalGitRepository,
145
interrepo.InterToRemoteGitRepository,
147
repository.InterRepository.register_optimiser(optimiser)
148
_optimisers_loaded = True
151
class GitRepository(ForeignRepository):
152
"""An adapter to git repositories for bzr."""
155
vcs = foreign_vcs_git
158
def __init__(self, gitdir):
159
self._transport = gitdir.root_transport
160
super(GitRepository, self).__init__(GitRepositoryFormat(),
161
gitdir, control_files=None)
162
self.base = gitdir.root_transport.base
163
lazy_load_optimisers()
164
self._lock_mode = None
167
def add_fallback_repository(self, basis_url):
168
raise errors.UnstackableRepositoryFormat(self._format,
169
self.control_transport.base)
174
def get_physical_lock_status(self):
177
def lock_write(self):
178
"""See Branch.lock_write()."""
180
if self._lock_mode != 'w':
181
raise errors.ReadOnlyError(self)
182
self._lock_count += 1
184
self._lock_mode = 'w'
186
self._transaction = transactions.WriteTransaction()
187
return repository.RepositoryWriteLockResult(self.unlock, None)
189
def break_lock(self):
190
raise NotImplementedError(self.break_lock)
192
def dont_leave_lock_in_place(self):
193
raise NotImplementedError(self.dont_leave_lock_in_place)
195
def leave_lock_in_place(self):
196
raise NotImplementedError(self.leave_lock_in_place)
200
if self._lock_mode not in ('r', 'w'):
202
self._lock_count += 1
204
self._lock_mode = 'r'
206
self._transaction = transactions.ReadOnlyTransaction()
207
return lock.LogicalLockResult(self.unlock)
209
@only_raises(errors.LockNotHeld, errors.LockBroken)
211
if self._lock_count == 0:
212
raise errors.LockNotHeld(self)
213
if self._lock_count == 1 and self._lock_mode == 'w':
214
if self._write_group is not None:
215
self.abort_write_group()
216
self._lock_count -= 1
217
self._lock_mode = None
218
raise errors.BzrError(
219
'Must end write groups before releasing write locks.')
220
self._lock_count -= 1
221
if self._lock_count == 0:
222
self._lock_mode = None
223
transaction = self._transaction
224
self._transaction = None
227
def is_write_locked(self):
228
return (self._lock_mode == 'w')
231
return (self._lock_mode is not None)
233
def get_transaction(self):
234
"""See Repository.get_transaction()."""
235
if self._transaction is None:
236
return transactions.PassThroughTransaction()
238
return self._transaction
240
def reconcile(self, other=None, thorough=False):
241
"""Reconcile this repository."""
242
reconciler = RepoReconciler(self, thorough=thorough)
243
reconciler.reconcile()
246
def supports_rich_root(self):
249
def get_mapping(self):
250
return default_mapping
252
def make_working_trees(self):
253
return not self._git.get_config().get_boolean(("core", ), "bare")
255
def revision_graph_can_have_wrong_parents(self):
258
def add_signature_text(self, revid, signature):
259
raise errors.UnsupportedOperation(self.add_signature_text, self)
261
def sign_revision(self, revision_id, gpg_strategy):
262
raise errors.UnsupportedOperation(self.add_signature_text, self)
265
class LocalGitRepository(GitRepository):
266
"""Git repository on the file system."""
268
def __init__(self, gitdir):
269
GitRepository.__init__(self, gitdir)
270
self._git = gitdir._git
271
self._file_change_scanner = GitFileLastChangeScanner(self)
272
self._transaction = None
274
def get_commit_builder(self, branch, parents, config, timestamp=None,
275
timezone=None, committer=None, revprops=None,
276
revision_id=None, lossy=False):
277
"""Obtain a CommitBuilder for this repository.
279
:param branch: Branch to commit to.
280
:param parents: Revision ids of the parents of the new revision.
281
:param config: Configuration to use.
282
:param timestamp: Optional timestamp recorded for commit.
283
:param timezone: Optional timezone for timestamp.
284
:param committer: Optional committer to set for commit.
285
:param revprops: Optional dictionary of revision properties.
286
:param revision_id: Optional revision id.
287
:param lossy: Whether to discard data that can not be natively
288
represented, when pushing to a foreign VCS
290
builder = GitCommitBuilder(self, parents, config,
291
timestamp, timezone, committer, revprops, revision_id,
293
self.start_write_group()
296
def get_file_graph(self):
297
return _mod_graph.Graph(GitFileParentProvider(
298
self._file_change_scanner))
300
def iter_files_bytes(self, desired_files):
301
"""Iterate through file versions.
303
Files will not necessarily be returned in the order they occur in
304
desired_files. No specific order is guaranteed.
306
Yields pairs of identifier, bytes_iterator. identifier is an opaque
307
value supplied by the caller as part of desired_files. It should
308
uniquely identify the file version in the caller's context. (Examples:
309
an index number or a TreeTransform trans_id.)
311
bytes_iterator is an iterable of bytestrings for the file. The
312
kind of iterable and length of the bytestrings are unspecified, but for
313
this implementation, it is a list of bytes produced by
314
VersionedFile.get_record_stream().
316
:param desired_files: a list of (file_id, revision_id, identifier)
320
for (file_id, revision_id, identifier) in desired_files:
321
per_revision.setdefault(revision_id, []).append(
322
(file_id, identifier))
323
for revid, files in viewitems(per_revision):
325
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
326
except errors.NoSuchRevision:
327
raise errors.RevisionNotPresent(revid, self)
329
commit = self._git.object_store[commit_id]
331
raise errors.RevisionNotPresent(revid, self)
332
root_tree = commit.tree
333
for fileid, identifier in files:
335
path = mapping.parse_file_id(fileid)
337
raise errors.RevisionNotPresent((fileid, revid), self)
339
obj = tree_lookup_path(
340
self._git.object_store.__getitem__, root_tree,
341
path.encode('utf-8'))
342
if isinstance(obj, tuple):
343
(mode, item_id) = obj
344
obj = self._git.object_store[item_id]
346
raise errors.RevisionNotPresent((fileid, revid), self)
348
if obj.type_name == b"tree":
349
yield (identifier, [])
350
elif obj.type_name == b"blob":
351
yield (identifier, obj.chunked)
353
raise AssertionError("file text resolved to %r" % obj)
355
def gather_stats(self, revid=None, committers=None):
356
"""See Repository.gather_stats()."""
357
result = super(LocalGitRepository, self).gather_stats(revid, committers)
359
for sha in self._git.object_store:
360
o = self._git.object_store[sha]
361
if o.type_name == b"commit":
363
result['revisions'] = len(revs)
366
def _iter_revision_ids(self):
367
mapping = self.get_mapping()
368
for sha in self._git.object_store:
369
o = self._git.object_store[sha]
370
if not isinstance(o, Commit):
372
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
373
mapping.revision_id_foreign_to_bzr)
374
yield o.id, rev.revision_id, roundtrip_revid
376
def all_revision_ids(self):
378
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
380
ret.add(roundtrip_revid)
385
def _get_parents(self, revid, no_alternates=False):
386
if type(revid) != bytes:
389
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
390
except errors.NoSuchRevision:
392
# FIXME: Honor no_alternates setting
394
commit = self._git.object_store[hexsha]
398
for p in commit.parents:
400
ret.append(self.lookup_foreign_revision_id(p, mapping))
402
ret.append(mapping.revision_id_foreign_to_bzr(p))
405
def _get_parent_map_no_fallbacks(self, revids):
406
return self.get_parent_map(revids, no_alternates=True)
408
def get_parent_map(self, revids, no_alternates=False):
410
for revision_id in revids:
411
parents = self._get_parents(revision_id, no_alternates=no_alternates)
412
if revision_id == _mod_revision.NULL_REVISION:
413
parent_map[revision_id] = ()
417
if len(parents) == 0:
418
parents = [_mod_revision.NULL_REVISION]
419
parent_map[revision_id] = tuple(parents)
422
def get_known_graph_ancestry(self, revision_ids):
423
"""Return the known graph for a set of revision ids and their ancestors.
425
pending = set(revision_ids)
429
for revid in pending:
430
if revid == _mod_revision.NULL_REVISION:
432
parents = self._get_parents(revid)
433
if parents is not None:
434
this_parent_map[revid] = parents
435
parent_map.update(this_parent_map)
437
for values in viewvalues(this_parent_map):
438
pending.update(values)
439
pending = pending.difference(parent_map)
440
return _mod_graph.KnownGraph(parent_map)
442
def get_signature_text(self, revision_id):
443
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
445
commit = self._git.object_store[git_commit_id]
447
raise errors.NoSuchRevision(self, revision_id)
448
if commit.gpgsig is None:
449
raise errors.NoSuchRevision(self, revision_id)
452
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
453
result = GitCheck(self, check_repo=check_repo)
454
result.check(callback_refs)
457
def pack(self, hint=None, clean_obsolete_packs=False):
458
self._git.object_store.pack_loose_objects()
460
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
461
"""Lookup a revision id.
463
:param foreign_revid: Foreign revision id to look up
464
:param mapping: Mapping to use (use default mapping if not specified)
465
:raise KeyError: If foreign revision was not found
466
:return: bzr revision id
468
if not isinstance(foreign_revid, bytes):
469
raise TypeError(foreign_revid)
471
mapping = self.get_mapping()
472
if foreign_revid == ZERO_SHA:
473
return _mod_revision.NULL_REVISION
474
commit = self._git.object_store.peel_sha(foreign_revid)
475
if not isinstance(commit, Commit):
476
raise NotCommitError(commit.id)
477
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
478
mapping.revision_id_foreign_to_bzr)
479
# FIXME: check testament before doing this?
481
return roundtrip_revid
483
return rev.revision_id
485
def has_signature_for_revision_id(self, revision_id):
486
"""Check whether a GPG signature is present for this revision.
488
This is never the case for Git repositories.
491
self.get_signature_text(revision_id)
492
except errors.NoSuchRevision:
497
def verify_revision_signature(self, revision_id, gpg_strategy):
498
"""Verify the signature on a revision.
500
:param revision_id: the revision to verify
501
:gpg_strategy: the GPGStrategy object to used
503
:return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
505
from breezy import gpg
506
with self.lock_read():
507
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
509
commit = self._git.object_store[git_commit_id]
511
raise errors.NoSuchRevision(self, revision_id)
513
if commit.gpgsig is None:
514
return gpg.SIGNATURE_NOT_SIGNED, None
516
without_sig = Commit.from_string(commit.as_raw_string())
517
without_sig.gpgsig = None
519
(result, key, plain_text) = gpg_strategy.verify(without_sig.as_raw_string(), commit.gpgsig)
522
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
523
"""Lookup a bzr revision id in a Git repository.
525
:param bzr_revid: Bazaar revision id
526
:param mapping: Optional mapping to use
527
:return: Tuple with git commit id, mapping that was used and supplement
531
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
532
except errors.InvalidRevisionId:
534
mapping = self.get_mapping()
536
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
539
# Update refs from Git commit objects
540
# FIXME: Hitting this a lot will be very inefficient...
541
pb = ui.ui_factory.nested_progress_bar()
543
for i, (git_sha, revid, roundtrip_revid) in enumerate(self._iter_revision_ids()):
544
if not roundtrip_revid:
546
pb.update("resolving revision id", i)
547
refname = mapping.revid_as_refname(roundtrip_revid)
548
self._git.refs[refname] = git_sha
549
if roundtrip_revid == bzr_revid:
550
return git_sha, mapping
553
raise errors.NoSuchRevision(self, bzr_revid)
555
return (git_sha, mapping)
557
def get_revision(self, revision_id):
558
if not isinstance(revision_id, bytes):
559
raise errors.InvalidRevisionId(revision_id, self)
560
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
562
commit = self._git.object_store[git_commit_id]
564
raise errors.NoSuchRevision(self, revision_id)
565
revision, roundtrip_revid, verifiers = mapping.import_commit(
566
commit, self.lookup_foreign_revision_id)
569
# FIXME: check verifiers ?
571
revision.revision_id = roundtrip_revid
574
def has_revision(self, revision_id):
575
"""See Repository.has_revision."""
576
if revision_id == _mod_revision.NULL_REVISION:
579
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
580
except errors.NoSuchRevision:
582
return (git_commit_id in self._git)
584
def has_revisions(self, revision_ids):
585
"""See Repository.has_revisions."""
586
return set(filter(self.has_revision, revision_ids))
588
def iter_revisions(self, revision_ids):
589
"""See Repository.get_revisions."""
590
for revid in revision_ids:
592
rev = self.get_revision(revid)
593
except errors.NoSuchRevision:
597
def revision_trees(self, revids):
598
"""See Repository.revision_trees."""
600
yield self.revision_tree(revid)
602
def revision_tree(self, revision_id):
603
"""See Repository.revision_tree."""
604
if revision_id is None:
605
raise ValueError('invalid revision id %s' % revision_id)
606
return GitRevisionTree(self, revision_id)
608
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
609
"""Produce a generator of revision deltas.
611
Note that the input is a sequence of REVISIONS, not revision_ids.
612
Trees will be held in memory until the generator exits.
613
Each delta is relative to the revision's lefthand predecessor.
615
:param specific_fileids: if not None, the result is filtered
616
so that only those file-ids, their parents and their
617
children are included.
619
# Get the revision-ids of interest
620
required_trees = set()
621
for revision in revisions:
622
required_trees.add(revision.revision_id)
623
required_trees.update(revision.parent_ids[:1])
625
trees = dict((t.get_revision_id(), t) for
626
t in self.revision_trees(required_trees))
628
# Calculate the deltas
629
for revision in revisions:
630
if not revision.parent_ids:
631
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
633
old_tree = trees[revision.parent_ids[0]]
634
new_tree = trees[revision.revision_id]
635
if specific_fileids is not None:
636
specific_files = [new_tree.id2path(fid) for fid in specific_fileids]
638
specific_files = None
639
yield new_tree.changes_from(old_tree, specific_files=specific_files)
641
def set_make_working_trees(self, trees):
642
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
644
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
645
progress=None, limit=None):
646
return self._git.fetch_objects(determine_wants, graph_walker, progress,
650
class GitRepositoryFormat(repository.RepositoryFormat):
651
"""Git repository format."""
653
supports_versioned_directories = False
654
supports_tree_reference = True
655
rich_root_data = True
656
supports_leaving_lock = False
658
supports_funky_characters = True
659
supports_external_lookups = False
660
supports_full_versioned_files = False
661
supports_revision_signatures = False
662
supports_nesting_repositories = False
663
revision_graph_can_have_wrong_parents = False
664
supports_unreferenced_revisions = True
665
supports_setting_revision_ids = False
666
supports_storing_branch_nick = False
667
supports_overriding_transport = False
668
supports_custom_revision_properties = False
669
records_per_file_revision = False
672
def _matchingcontroldir(self):
673
from .dir import LocalGitControlDirFormat
674
return LocalGitControlDirFormat()
676
def get_format_description(self):
677
return "Git Repository"
679
def initialize(self, controldir, shared=False, _internal=False):
680
from .dir import GitDir
681
if not isinstance(controldir, GitDir):
682
raise errors.UninitializableFormat(self)
683
return controldir.open_repository()
685
def check_conversion_target(self, target_repo_format):
686
return target_repo_format.rich_root_data
688
def get_foreign_tests_repository_factory(self):
689
from .tests.test_repository import (
690
ForeignTestsRepositoryFactory,
692
return ForeignTestsRepositoryFactory()
694
def network_name(self):
698
def get_extra_interrepo_test_combinations():
699
from ..bzr.groupcompress_repo import RepositoryFormat2a
700
from . import interrepo
702
(interrepo.InterLocalGitNonGitRepository, GitRepositoryFormat(), RepositoryFormat2a()),
703
(interrepo.InterLocalGitLocalGitRepository, GitRepositoryFormat(), GitRepositoryFormat()),
704
(interrepo.InterToLocalGitRepository, RepositoryFormat2a(), GitRepositoryFormat()),