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 viewitmes(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, path)
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 == "tree":
349
yield (identifier, [])
350
elif obj.type_name == "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 == "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
map(pending.update, viewvalues(this_parent_map))
438
pending = pending.difference(parent_map)
439
return _mod_graph.KnownGraph(parent_map)
441
def get_signature_text(self, revision_id):
442
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
444
commit = self._git.object_store[git_commit_id]
446
raise errors.NoSuchRevision(self, revision_id)
447
if commit.gpgsig is None:
448
raise errors.NoSuchRevision(self, revision_id)
451
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
452
result = GitCheck(self, check_repo=check_repo)
453
result.check(callback_refs)
456
def pack(self, hint=None, clean_obsolete_packs=False):
457
self._git.object_store.pack_loose_objects()
459
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
460
"""Lookup a revision id.
462
:param foreign_revid: Foreign revision id to look up
463
:param mapping: Mapping to use (use default mapping if not specified)
464
:raise KeyError: If foreign revision was not found
465
:return: bzr revision id
467
if not isinstance(foreign_revid, bytes):
468
raise TypeError(foreign_revid)
470
mapping = self.get_mapping()
471
if foreign_revid == ZERO_SHA:
472
return _mod_revision.NULL_REVISION
473
commit = self._git.object_store.peel_sha(foreign_revid)
474
if not isinstance(commit, Commit):
475
raise NotCommitError(commit.id)
476
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
477
mapping.revision_id_foreign_to_bzr)
478
# FIXME: check testament before doing this?
480
return roundtrip_revid
482
return rev.revision_id
484
def has_signature_for_revision_id(self, revision_id):
485
"""Check whether a GPG signature is present for this revision.
487
This is never the case for Git repositories.
490
self.get_signature_text(revision_id)
491
except errors.NoSuchRevision:
496
def verify_revision_signature(self, revision_id, gpg_strategy):
497
"""Verify the signature on a revision.
499
:param revision_id: the revision to verify
500
:gpg_strategy: the GPGStrategy object to used
502
:return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
504
from breezy import gpg
505
with self.lock_read():
506
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
508
commit = self._git.object_store[git_commit_id]
510
raise errors.NoSuchRevision(self, revision_id)
512
if commit.gpgsig is None:
513
return gpg.SIGNATURE_NOT_SIGNED, None
515
without_sig = Commit.from_string(commit.as_raw_string())
516
without_sig.gpgsig = None
518
(result, key, plain_text) = gpg_strategy.verify(without_sig.as_raw_string(), commit.gpgsig)
521
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
522
"""Lookup a bzr revision id in a Git repository.
524
:param bzr_revid: Bazaar revision id
525
:param mapping: Optional mapping to use
526
:return: Tuple with git commit id, mapping that was used and supplement
530
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
531
except errors.InvalidRevisionId:
533
mapping = self.get_mapping()
535
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
538
# Update refs from Git commit objects
539
# FIXME: Hitting this a lot will be very inefficient...
540
pb = ui.ui_factory.nested_progress_bar()
542
for i, (git_sha, revid, roundtrip_revid) in enumerate(self._iter_revision_ids()):
543
if not roundtrip_revid:
545
pb.update("resolving revision id", i)
546
refname = mapping.revid_as_refname(roundtrip_revid)
547
self._git.refs[refname] = git_sha
548
if roundtrip_revid == bzr_revid:
549
return git_sha, mapping
552
raise errors.NoSuchRevision(self, bzr_revid)
554
return (git_sha, mapping)
556
def get_revision(self, revision_id):
557
if not isinstance(revision_id, bytes):
558
raise errors.InvalidRevisionId(revision_id, self)
559
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
561
commit = self._git.object_store[git_commit_id]
563
raise errors.NoSuchRevision(self, revision_id)
564
revision, roundtrip_revid, verifiers = mapping.import_commit(
565
commit, self.lookup_foreign_revision_id)
568
# FIXME: check verifiers ?
570
revision.revision_id = roundtrip_revid
573
def has_revision(self, revision_id):
574
"""See Repository.has_revision."""
575
if revision_id == _mod_revision.NULL_REVISION:
578
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
579
except errors.NoSuchRevision:
581
return (git_commit_id in self._git)
583
def has_revisions(self, revision_ids):
584
"""See Repository.has_revisions."""
585
return set(filter(self.has_revision, revision_ids))
587
def iter_revisions(self, revision_ids):
588
"""See Repository.get_revisions."""
589
for revid in revision_ids:
591
rev = self.get_revision(revid)
592
except errors.NoSuchRevision:
596
def revision_trees(self, revids):
597
"""See Repository.revision_trees."""
599
yield self.revision_tree(revid)
601
def revision_tree(self, revision_id):
602
"""See Repository.revision_tree."""
603
if revision_id is None:
604
raise ValueError('invalid revision id %s' % revision_id)
605
return GitRevisionTree(self, revision_id)
607
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
608
"""Produce a generator of revision deltas.
610
Note that the input is a sequence of REVISIONS, not revision_ids.
611
Trees will be held in memory until the generator exits.
612
Each delta is relative to the revision's lefthand predecessor.
614
:param specific_fileids: if not None, the result is filtered
615
so that only those file-ids, their parents and their
616
children are included.
618
# Get the revision-ids of interest
619
required_trees = set()
620
for revision in revisions:
621
required_trees.add(revision.revision_id)
622
required_trees.update(revision.parent_ids[:1])
624
trees = dict((t.get_revision_id(), t) for
625
t in self.revision_trees(required_trees))
627
# Calculate the deltas
628
for revision in revisions:
629
if not revision.parent_ids:
630
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
632
old_tree = trees[revision.parent_ids[0]]
633
new_tree = trees[revision.revision_id]
634
if specific_fileids is not None:
635
specific_files = [new_tree.id2path(fid) for fid in specific_fileids]
637
specific_files = None
638
yield new_tree.changes_from(old_tree, specific_files=specific_files)
640
def set_make_working_trees(self, trees):
641
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
643
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
644
progress=None, limit=None):
645
return self._git.fetch_objects(determine_wants, graph_walker, progress,
649
class GitRepositoryFormat(repository.RepositoryFormat):
650
"""Git repository format."""
652
supports_versioned_directories = False
653
supports_tree_reference = True
654
rich_root_data = True
655
supports_leaving_lock = False
657
supports_funky_characters = True
658
supports_external_lookups = False
659
supports_full_versioned_files = False
660
supports_revision_signatures = False
661
supports_nesting_repositories = False
662
revision_graph_can_have_wrong_parents = False
663
supports_unreferenced_revisions = True
664
supports_setting_revision_ids = False
665
supports_storing_branch_nick = False
666
supports_overriding_transport = False
667
supports_custom_revision_properties = False
668
records_per_file_revision = False
671
def _matchingcontroldir(self):
672
from .dir import LocalGitControlDirFormat
673
return LocalGitControlDirFormat()
675
def get_format_description(self):
676
return "Git Repository"
678
def initialize(self, controldir, shared=False, _internal=False):
679
from .dir import GitDir
680
if not isinstance(controldir, GitDir):
681
raise errors.UninitializableFormat(self)
682
return controldir.open_repository()
684
def check_conversion_target(self, target_repo_format):
685
return target_repo_format.rich_root_data
687
def get_foreign_tests_repository_factory(self):
688
from .tests.test_repository import (
689
ForeignTestsRepositoryFactory,
691
return ForeignTestsRepositoryFactory()
693
def network_name(self):
697
def get_extra_interrepo_test_combinations():
698
from ...bzr.groupcompress_repo import RepositoryFormat2a
699
from . import interrepo
701
(interrepo.InterLocalGitNonGitRepository, GitRepositoryFormat(), RepositoryFormat2a()),
702
(interrepo.InterLocalGitLocalGitRepository, GitRepositoryFormat(), GitRepositoryFormat()),
703
(interrepo.InterToLocalGitRepository, RepositoryFormat2a(), GitRepositoryFormat()),