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 (
42
from .filegraph import (
43
GitFileLastChangeScanner,
44
GitFileParentProvider,
46
from .mapping import (
57
from dulwich.errors import (
60
from dulwich.objects import (
64
from dulwich.object_store import (
69
class GitCheck(check.Check):
71
def __init__(self, repository, check_repo=True):
72
self.repository = repository
73
self.check_repo = check_repo
74
self.checked_rev_cnt = 0
75
self.object_count = None
78
def check(self, callback_refs=None, check_repo=True):
79
if callback_refs is None:
81
with self.repository.lock_read(), \
82
ui.ui_factory.nested_progress_bar() as self.progress:
83
shas = set(self.repository._git.object_store)
84
self.object_count = len(shas)
85
# TODO(jelmer): Check more things
86
for i, sha in enumerate(shas):
87
self.progress.update('checking objects', i, self.object_count)
88
o = self.repository._git.object_store[sha]
91
except Exception as e:
92
self.problems.append((sha, e))
94
def _report_repo_results(self, verbose):
95
trace.note('checked repository {0} format {1}'.format(
96
self.repository.user_url,
97
self.repository._format))
98
trace.note('%6d objects', self.object_count)
99
for sha, problem in self.problems:
100
trace.note('%s: %s', sha, problem)
102
def report_results(self, verbose):
104
self._report_repo_results(verbose)
107
for optimiser in ['InterRemoteGitNonGitRepository',
108
'InterLocalGitNonGitRepository',
109
'InterLocalGitLocalGitRepository',
110
'InterRemoteGitLocalGitRepository',
111
'InterToLocalGitRepository',
112
'InterToRemoteGitRepository',
114
repository.InterRepository.register_lazy_optimiser(
115
'breezy.git.interrepo', optimiser)
118
class GitRepository(ForeignRepository):
119
"""An adapter to git repositories for bzr."""
122
vcs = foreign_vcs_git
125
def __init__(self, gitdir):
126
self._transport = gitdir.root_transport
127
super(GitRepository, self).__init__(GitRepositoryFormat(),
128
gitdir, control_files=None)
129
self.base = gitdir.root_transport.base
130
self._lock_mode = None
133
def add_fallback_repository(self, basis_url):
134
raise errors.UnstackableRepositoryFormat(self._format,
135
self.control_transport.base)
140
def get_physical_lock_status(self):
143
def lock_write(self):
144
"""See Branch.lock_write()."""
146
if self._lock_mode != 'w':
147
raise errors.ReadOnlyError(self)
148
self._lock_count += 1
150
self._lock_mode = 'w'
152
self._transaction = transactions.WriteTransaction()
153
return repository.RepositoryWriteLockResult(self.unlock, None)
155
def break_lock(self):
156
raise NotImplementedError(self.break_lock)
158
def dont_leave_lock_in_place(self):
159
raise NotImplementedError(self.dont_leave_lock_in_place)
161
def leave_lock_in_place(self):
162
raise NotImplementedError(self.leave_lock_in_place)
166
if self._lock_mode not in ('r', 'w'):
168
self._lock_count += 1
170
self._lock_mode = 'r'
172
self._transaction = transactions.ReadOnlyTransaction()
173
return lock.LogicalLockResult(self.unlock)
175
@only_raises(errors.LockNotHeld, errors.LockBroken)
177
if self._lock_count == 0:
178
raise errors.LockNotHeld(self)
179
if self._lock_count == 1 and self._lock_mode == 'w':
180
if self._write_group is not None:
181
self.abort_write_group()
182
self._lock_count -= 1
183
self._lock_mode = None
184
raise errors.BzrError(
185
'Must end write groups before releasing write locks.')
186
self._lock_count -= 1
187
if self._lock_count == 0:
188
self._lock_mode = None
189
transaction = self._transaction
190
self._transaction = None
193
def is_write_locked(self):
194
return (self._lock_mode == 'w')
197
return (self._lock_mode is not None)
199
def get_transaction(self):
200
"""See Repository.get_transaction()."""
201
if self._transaction is None:
202
return transactions.PassThroughTransaction()
204
return self._transaction
206
def reconcile(self, other=None, thorough=False):
207
"""Reconcile this repository."""
208
from ..reconcile import ReconcileResult
209
ret = ReconcileResult()
213
def supports_rich_root(self):
216
def get_mapping(self):
217
return default_mapping
219
def make_working_trees(self):
220
return not self._git.get_config().get_boolean(("core", ), "bare")
222
def revision_graph_can_have_wrong_parents(self):
225
def add_signature_text(self, revid, signature):
226
raise errors.UnsupportedOperation(self.add_signature_text, self)
228
def sign_revision(self, revision_id, gpg_strategy):
229
raise errors.UnsupportedOperation(self.add_signature_text, self)
232
class LocalGitRepository(GitRepository):
233
"""Git repository on the file system."""
235
def __init__(self, gitdir):
236
GitRepository.__init__(self, gitdir)
237
self._git = gitdir._git
238
self._file_change_scanner = GitFileLastChangeScanner(self)
239
self._transaction = None
241
def get_commit_builder(self, branch, parents, config, timestamp=None,
242
timezone=None, committer=None, revprops=None,
243
revision_id=None, lossy=False):
244
"""Obtain a CommitBuilder for this repository.
246
:param branch: Branch to commit to.
247
:param parents: Revision ids of the parents of the new revision.
248
:param config: Configuration to use.
249
:param timestamp: Optional timestamp recorded for commit.
250
:param timezone: Optional timezone for timestamp.
251
:param committer: Optional committer to set for commit.
252
:param revprops: Optional dictionary of revision properties.
253
:param revision_id: Optional revision id.
254
:param lossy: Whether to discard data that can not be natively
255
represented, when pushing to a foreign VCS
257
from .commit import (
260
builder = GitCommitBuilder(
261
self, parents, config, timestamp, timezone, committer, revprops,
263
self.start_write_group()
266
def get_file_graph(self):
267
return _mod_graph.Graph(GitFileParentProvider(
268
self._file_change_scanner))
270
def iter_files_bytes(self, desired_files):
271
"""Iterate through file versions.
273
Files will not necessarily be returned in the order they occur in
274
desired_files. No specific order is guaranteed.
276
Yields pairs of identifier, bytes_iterator. identifier is an opaque
277
value supplied by the caller as part of desired_files. It should
278
uniquely identify the file version in the caller's context. (Examples:
279
an index number or a TreeTransform trans_id.)
281
bytes_iterator is an iterable of bytestrings for the file. The
282
kind of iterable and length of the bytestrings are unspecified, but for
283
this implementation, it is a list of bytes produced by
284
VersionedFile.get_record_stream().
286
:param desired_files: a list of (file_id, revision_id, identifier)
290
for (file_id, revision_id, identifier) in desired_files:
291
per_revision.setdefault(revision_id, []).append(
292
(file_id, identifier))
293
for revid, files in viewitems(per_revision):
295
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
296
except errors.NoSuchRevision:
297
raise errors.RevisionNotPresent(revid, self)
299
commit = self._git.object_store[commit_id]
301
raise errors.RevisionNotPresent(revid, self)
302
root_tree = commit.tree
303
for fileid, identifier in files:
305
path = mapping.parse_file_id(fileid)
307
raise errors.RevisionNotPresent((fileid, revid), self)
309
obj = tree_lookup_path(
310
self._git.object_store.__getitem__, root_tree,
311
encode_git_path(path))
312
if isinstance(obj, tuple):
313
(mode, item_id) = obj
314
obj = self._git.object_store[item_id]
316
raise errors.RevisionNotPresent((fileid, revid), self)
318
if obj.type_name == b"tree":
319
yield (identifier, [])
320
elif obj.type_name == b"blob":
321
yield (identifier, obj.chunked)
323
raise AssertionError("file text resolved to %r" % obj)
325
def gather_stats(self, revid=None, committers=None):
326
"""See Repository.gather_stats()."""
327
result = super(LocalGitRepository, self).gather_stats(
330
for sha in self._git.object_store:
331
o = self._git.object_store[sha]
332
if o.type_name == b"commit":
334
result['revisions'] = len(revs)
337
def _iter_revision_ids(self):
338
mapping = self.get_mapping()
339
for sha in self._git.object_store:
340
o = self._git.object_store[sha]
341
if not isinstance(o, Commit):
343
revid = mapping.revision_id_foreign_to_bzr(o.id)
346
def all_revision_ids(self):
348
for git_sha, revid in self._iter_revision_ids():
352
def _get_parents(self, revid, no_alternates=False):
353
if type(revid) != bytes:
356
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
357
except errors.NoSuchRevision:
359
# FIXME: Honor no_alternates setting
361
commit = self._git.object_store[hexsha]
365
for p in commit.parents:
367
ret.append(self.lookup_foreign_revision_id(p, mapping))
369
ret.append(mapping.revision_id_foreign_to_bzr(p))
372
def _get_parent_map_no_fallbacks(self, revids):
373
return self.get_parent_map(revids, no_alternates=True)
375
def get_parent_map(self, revids, no_alternates=False):
377
for revision_id in revids:
378
parents = self._get_parents(
379
revision_id, no_alternates=no_alternates)
380
if revision_id == _mod_revision.NULL_REVISION:
381
parent_map[revision_id] = ()
385
if len(parents) == 0:
386
parents = [_mod_revision.NULL_REVISION]
387
parent_map[revision_id] = tuple(parents)
390
def get_known_graph_ancestry(self, revision_ids):
391
"""Return the known graph for a set of revision ids and their ancestors.
393
pending = set(revision_ids)
397
for revid in pending:
398
if revid == _mod_revision.NULL_REVISION:
400
parents = self._get_parents(revid)
401
if parents is not None:
402
this_parent_map[revid] = parents
403
parent_map.update(this_parent_map)
405
for values in viewvalues(this_parent_map):
406
pending.update(values)
407
pending = pending.difference(parent_map)
408
return _mod_graph.KnownGraph(parent_map)
410
def get_signature_text(self, revision_id):
411
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
413
commit = self._git.object_store[git_commit_id]
415
raise errors.NoSuchRevision(self, revision_id)
416
if commit.gpgsig is None:
417
raise errors.NoSuchRevision(self, revision_id)
420
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
421
result = GitCheck(self, check_repo=check_repo)
422
result.check(callback_refs)
425
def pack(self, hint=None, clean_obsolete_packs=False):
426
self._git.object_store.pack_loose_objects()
428
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
429
"""Lookup a revision id.
431
:param foreign_revid: Foreign revision id to look up
432
:param mapping: Mapping to use (use default mapping if not specified)
433
:raise KeyError: If foreign revision was not found
434
:return: bzr revision id
436
if not isinstance(foreign_revid, bytes):
437
raise TypeError(foreign_revid)
439
mapping = self.get_mapping()
440
if foreign_revid == ZERO_SHA:
441
return _mod_revision.NULL_REVISION
442
commit = self._git.object_store.peel_sha(foreign_revid)
443
if not isinstance(commit, Commit):
444
raise NotCommitError(commit.id)
445
revid = mapping.get_revision_id(commit)
446
# FIXME: check testament before doing this?
449
def has_signature_for_revision_id(self, revision_id):
450
"""Check whether a GPG signature is present for this revision.
452
This is never the case for Git repositories.
455
self.get_signature_text(revision_id)
456
except errors.NoSuchRevision:
461
def verify_revision_signature(self, revision_id, gpg_strategy):
462
"""Verify the signature on a revision.
464
:param revision_id: the revision to verify
465
:gpg_strategy: the GPGStrategy object to used
467
:return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
469
from breezy import gpg
470
with self.lock_read():
471
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
473
commit = self._git.object_store[git_commit_id]
475
raise errors.NoSuchRevision(self, revision_id)
477
if commit.gpgsig is None:
478
return gpg.SIGNATURE_NOT_SIGNED, None
480
without_sig = Commit.from_string(commit.as_raw_string())
481
without_sig.gpgsig = None
483
(result, key, plain_text) = gpg_strategy.verify(
484
without_sig.as_raw_string(), commit.gpgsig)
487
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
488
"""Lookup a bzr revision id in a Git repository.
490
:param bzr_revid: Bazaar revision id
491
:param mapping: Optional mapping to use
492
:return: Tuple with git commit id, mapping that was used and supplement
496
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(
498
except errors.InvalidRevisionId:
499
raise errors.NoSuchRevision(self, bzr_revid)
501
return (git_sha, mapping)
503
def get_revision(self, revision_id):
504
if not isinstance(revision_id, bytes):
505
raise errors.InvalidRevisionId(revision_id, self)
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)
511
revision, roundtrip_revid, verifiers = mapping.import_commit(
512
commit, self.lookup_foreign_revision_id, strict=False)
515
# FIXME: check verifiers ?
517
revision.revision_id = roundtrip_revid
520
def has_revision(self, revision_id):
521
"""See Repository.has_revision."""
522
if revision_id == _mod_revision.NULL_REVISION:
525
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
526
except errors.NoSuchRevision:
528
return (git_commit_id in self._git)
530
def has_revisions(self, revision_ids):
531
"""See Repository.has_revisions."""
532
return set(filter(self.has_revision, revision_ids))
534
def iter_revisions(self, revision_ids):
535
"""See Repository.get_revisions."""
536
for revid in revision_ids:
538
rev = self.get_revision(revid)
539
except errors.NoSuchRevision:
543
def revision_trees(self, revids):
544
"""See Repository.revision_trees."""
546
yield self.revision_tree(revid)
548
def revision_tree(self, revision_id):
549
"""See Repository.revision_tree."""
550
if revision_id is None:
551
raise ValueError('invalid revision id %s' % revision_id)
552
return GitRevisionTree(self, revision_id)
554
def set_make_working_trees(self, trees):
555
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
557
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
558
progress=None, limit=None):
559
return self._git.fetch_objects(determine_wants, graph_walker, progress,
563
class GitRepositoryFormat(repository.RepositoryFormat):
564
"""Git repository format."""
566
supports_versioned_directories = False
567
supports_tree_reference = True
568
rich_root_data = True
569
supports_leaving_lock = False
571
supports_funky_characters = True
572
supports_external_lookups = False
573
supports_full_versioned_files = False
574
supports_revision_signatures = False
575
supports_nesting_repositories = False
576
revision_graph_can_have_wrong_parents = False
577
supports_unreferenced_revisions = True
578
supports_setting_revision_ids = False
579
supports_storing_branch_nick = False
580
supports_overriding_transport = False
581
supports_custom_revision_properties = False
582
records_per_file_revision = False
585
def _matchingcontroldir(self):
586
from .dir import LocalGitControlDirFormat
587
return LocalGitControlDirFormat()
589
def get_format_description(self):
590
return "Git Repository"
592
def initialize(self, controldir, shared=False, _internal=False):
593
from .dir import GitDir
594
if not isinstance(controldir, GitDir):
595
raise errors.UninitializableFormat(self)
596
return controldir.open_repository()
598
def check_conversion_target(self, target_repo_format):
599
return target_repo_format.rich_root_data
601
def get_foreign_tests_repository_factory(self):
602
from .tests.test_repository import (
603
ForeignTestsRepositoryFactory,
605
return ForeignTestsRepositoryFactory()
607
def network_name(self):
611
def get_extra_interrepo_test_combinations():
612
from ..bzr.groupcompress_repo import RepositoryFormat2a
613
from . import interrepo
615
(interrepo.InterLocalGitNonGitRepository,
616
GitRepositoryFormat(), RepositoryFormat2a()),
617
(interrepo.InterLocalGitLocalGitRepository,
618
GitRepositoryFormat(), GitRepositoryFormat()),
619
(interrepo.InterToLocalGitRepository,
620
RepositoryFormat2a(), GitRepositoryFormat()),