1
# Copyright (C) 2007 Canonical Ltd
2
# Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""An adapter between a Git Repository and a Bazaar Branch"""
20
from __future__ import absolute_import
28
revision as _mod_revision,
31
version_info as breezy_version,
33
from ...decorators import only_raises
34
from ...foreign import (
41
from .filegraph import (
42
GitFileLastChangeScanner,
43
GitFileParentProvider,
45
from .mapping import (
55
from dulwich.errors import (
58
from dulwich.objects import (
62
from dulwich.object_store import (
67
class RepoReconciler(object):
68
"""Reconciler that reconciles a repository.
72
def __init__(self, repo, other=None, thorough=False):
73
"""Construct a RepoReconciler.
75
:param thorough: perform a thorough check which may take longer but
76
will correct non-data loss issues such as incorrect
82
"""Perform reconciliation.
84
After reconciliation the following attributes document found issues:
85
inconsistent_parents: The number of revisions in the repository whose
86
ancestry was being reported incorrectly.
87
garbage_inventories: The number of inventory objects without revisions
88
that were garbage collected.
92
class GitCheck(check.Check):
94
def __init__(self, repository, check_repo=True):
95
self.repository = repository
96
self.checked_rev_cnt = 0
98
def check(self, callback_refs=None, check_repo=True):
99
if callback_refs is None:
101
with self.repository.lock_read():
102
# TODO(jelmer): Check some things
105
def report_results(self, verbose):
109
_optimisers_loaded = False
111
def lazy_load_optimisers():
112
global _optimisers_loaded
113
if _optimisers_loaded:
115
from . import fetch, push
116
for optimiser in [fetch.InterRemoteGitNonGitRepository,
117
fetch.InterLocalGitNonGitRepository,
118
fetch.InterGitGitRepository,
119
push.InterToLocalGitRepository,
120
push.InterToRemoteGitRepository]:
121
repository.InterRepository.register_optimiser(optimiser)
122
_optimisers_loaded = True
125
class GitRepository(ForeignRepository):
126
"""An adapter to git repositories for bzr."""
129
vcs = foreign_vcs_git
132
def __init__(self, gitdir):
133
self._transport = gitdir.root_transport
134
super(GitRepository, self).__init__(GitRepositoryFormat(),
135
gitdir, control_files=None)
136
self.base = gitdir.root_transport.base
137
lazy_load_optimisers()
138
self._lock_mode = None
141
def add_fallback_repository(self, basis_url):
142
raise errors.UnstackableRepositoryFormat(self._format,
143
self.control_transport.base)
148
def get_physical_lock_status(self):
151
def lock_write(self):
152
"""See Branch.lock_write()."""
154
assert self._lock_mode == 'w'
155
self._lock_count += 1
157
self._lock_mode = 'w'
159
self._transaction = transactions.WriteTransaction()
160
return repository.RepositoryWriteLockResult(self.unlock, None)
162
def break_lock(self):
163
raise NotImplementedError(self.break_lock)
165
def dont_leave_lock_in_place(self):
166
raise NotImplementedError(self.dont_leave_lock_in_place)
168
def leave_lock_in_place(self):
169
raise NotImplementedError(self.leave_lock_in_place)
173
assert self._lock_mode in ('r', 'w')
174
self._lock_count += 1
176
self._lock_mode = 'r'
178
self._transaction = transactions.ReadOnlyTransaction()
179
return lock.LogicalLockResult(self.unlock)
181
@only_raises(errors.LockNotHeld, errors.LockBroken)
183
if self._lock_count == 0:
184
raise errors.LockNotHeld(self)
185
if self._lock_count == 1 and self._lock_mode == 'w':
186
if self._write_group is not None:
187
self.abort_write_group()
188
self._lock_count -= 1
189
self._lock_mode = None
190
raise errors.BzrError(
191
'Must end write groups before releasing write locks.')
192
self._lock_count -= 1
193
if self._lock_count == 0:
194
self._lock_mode = None
195
transaction = self._transaction
196
self._transaction = None
199
def is_write_locked(self):
200
return (self._lock_mode == 'w')
203
return (self._lock_mode is not None)
205
def get_transaction(self):
206
"""See Repository.get_transaction()."""
207
if self._transaction is None:
208
return transactions.PassThroughTransaction()
210
return self._transaction
212
def reconcile(self, other=None, thorough=False):
213
"""Reconcile this repository."""
214
reconciler = RepoReconciler(self, thorough=thorough)
215
reconciler.reconcile()
218
def supports_rich_root(self):
221
def get_mapping(self):
222
return default_mapping
224
def make_working_trees(self):
225
return not self._git.get_config().get_boolean(("core", ), "bare")
227
def revision_graph_can_have_wrong_parents(self):
230
def add_signature_text(self, revid, signature):
231
raise errors.UnsupportedOperation(self.add_signature_text, self)
233
def sign_revision(self, revision_id, gpg_strategy):
234
raise errors.UnsupportedOperation(self.add_signature_text, self)
237
class LocalGitRepository(GitRepository):
238
"""Git repository on the file system."""
240
def __init__(self, gitdir):
241
GitRepository.__init__(self, gitdir)
242
self._git = gitdir._git
243
self._file_change_scanner = GitFileLastChangeScanner(self)
244
self._transaction = None
246
def get_commit_builder(self, branch, parents, config, timestamp=None,
247
timezone=None, committer=None, revprops=None,
248
revision_id=None, lossy=False):
249
"""Obtain a CommitBuilder for this repository.
251
:param branch: Branch to commit to.
252
:param parents: Revision ids of the parents of the new revision.
253
:param config: Configuration to use.
254
:param timestamp: Optional timestamp recorded for commit.
255
:param timezone: Optional timezone for timestamp.
256
:param committer: Optional committer to set for commit.
257
:param revprops: Optional dictionary of revision properties.
258
:param revision_id: Optional revision id.
259
:param lossy: Whether to discard data that can not be natively
260
represented, when pushing to a foreign VCS
262
builder = GitCommitBuilder(self, parents, config,
263
timestamp, timezone, committer, revprops, revision_id,
265
self.start_write_group()
268
def get_file_graph(self):
269
return _mod_graph.Graph(GitFileParentProvider(
270
self._file_change_scanner))
272
def iter_files_bytes(self, desired_files):
273
"""Iterate through file versions.
275
Files will not necessarily be returned in the order they occur in
276
desired_files. No specific order is guaranteed.
278
Yields pairs of identifier, bytes_iterator. identifier is an opaque
279
value supplied by the caller as part of desired_files. It should
280
uniquely identify the file version in the caller's context. (Examples:
281
an index number or a TreeTransform trans_id.)
283
bytes_iterator is an iterable of bytestrings for the file. The
284
kind of iterable and length of the bytestrings are unspecified, but for
285
this implementation, it is a list of bytes produced by
286
VersionedFile.get_record_stream().
288
:param desired_files: a list of (file_id, revision_id, identifier)
292
for (file_id, revision_id, identifier) in desired_files:
293
per_revision.setdefault(revision_id, []).append(
294
(file_id, identifier))
295
for revid, files in per_revision.iteritems():
297
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
298
except errors.NoSuchRevision:
299
raise errors.RevisionNotPresent(revid, self)
301
commit = self._git.object_store[commit_id]
303
raise errors.RevisionNotPresent(revid, self)
304
root_tree = commit.tree
305
for fileid, identifier in files:
307
path = mapping.parse_file_id(fileid)
309
raise errors.RevisionNotPresent((fileid, revid), self)
311
obj = tree_lookup_path(
312
self._git.object_store.__getitem__, root_tree, path)
313
if isinstance(obj, tuple):
314
(mode, item_id) = obj
315
obj = self._git.object_store[item_id]
317
raise errors.RevisionNotPresent((fileid, revid), self)
319
if obj.type_name == "tree":
320
yield (identifier, [])
321
elif obj.type_name == "blob":
322
yield (identifier, obj.chunked)
324
raise AssertionError("file text resolved to %r" % obj)
326
def gather_stats(self, revid=None, committers=None):
327
"""See Repository.gather_stats()."""
328
result = super(LocalGitRepository, self).gather_stats(revid, committers)
330
for sha in self._git.object_store:
331
o = self._git.object_store[sha]
332
if o.type_name == "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
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
344
mapping.revision_id_foreign_to_bzr)
345
yield o.id, rev.revision_id, roundtrip_revid
347
def all_revision_ids(self):
349
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
351
ret.add(roundtrip_revid)
356
def _get_parents(self, revid, no_alternates=False):
357
if type(revid) != bytes:
360
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
361
except errors.NoSuchRevision:
363
# FIXME: Honor no_alternates setting
365
commit = self._git.object_store[hexsha]
369
self.lookup_foreign_revision_id(p, mapping)
370
for p in commit.parents]
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(revision_id, no_alternates=no_alternates)
379
if revision_id == _mod_revision.NULL_REVISION:
380
parent_map[revision_id] = ()
384
if len(parents) == 0:
385
parents = [_mod_revision.NULL_REVISION]
386
parent_map[revision_id] = tuple(parents)
389
def get_known_graph_ancestry(self, revision_ids):
390
"""Return the known graph for a set of revision ids and their ancestors.
392
pending = set(revision_ids)
396
for revid in pending:
397
if revid == _mod_revision.NULL_REVISION:
399
parents = self._get_parents(revid)
400
if parents is not None:
401
this_parent_map[revid] = parents
402
parent_map.update(this_parent_map)
404
map(pending.update, this_parent_map.itervalues())
405
pending = pending.difference(parent_map)
406
return _mod_graph.KnownGraph(parent_map)
408
def get_signature_text(self, revision_id):
409
raise errors.NoSuchRevision(self, revision_id)
411
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
412
result = GitCheck(self, check_repo=check_repo)
413
result.check(callback_refs)
416
def pack(self, hint=None, clean_obsolete_packs=False):
417
self._git.object_store.pack_loose_objects()
419
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
420
"""Lookup a revision id.
422
:param foreign_revid: Foreign revision id to look up
423
:param mapping: Mapping to use (use default mapping if not specified)
424
:raise KeyError: If foreign revision was not found
425
:return: bzr revision id
427
assert type(foreign_revid) is str
429
mapping = self.get_mapping()
430
if foreign_revid == ZERO_SHA:
431
return _mod_revision.NULL_REVISION
432
commit = self._git.object_store.peel_sha(foreign_revid)
433
if not isinstance(commit, Commit):
434
raise NotCommitError(commit.id)
435
rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
436
mapping.revision_id_foreign_to_bzr)
437
# FIXME: check testament before doing this?
439
return roundtrip_revid
441
return rev.revision_id
443
def has_signature_for_revision_id(self, revision_id):
444
"""Check whether a GPG signature is present for this revision.
446
This is never the case for Git repositories.
450
def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
451
"""Lookup a bzr revision id in a Git repository.
453
:param bzr_revid: Bazaar revision id
454
:param mapping: Optional mapping to use
455
:return: Tuple with git commit id, mapping that was used and supplement
459
(git_sha, mapping) = mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
460
except errors.InvalidRevisionId:
462
mapping = self.get_mapping()
464
return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
467
# Update refs from Git commit objects
468
# FIXME: Hitting this a lot will be very inefficient...
469
pb = ui.ui_factory.nested_progress_bar()
471
for i, (git_sha, revid, roundtrip_revid) in enumerate(self._iter_revision_ids()):
472
if not roundtrip_revid:
474
pb.update("resolving revision id", i)
475
refname = mapping.revid_as_refname(roundtrip_revid)
476
self._git.refs[refname] = git_sha
477
if roundtrip_revid == bzr_revid:
478
return git_sha, mapping
481
raise errors.NoSuchRevision(self, bzr_revid)
483
return (git_sha, mapping)
485
def get_revision(self, revision_id):
486
if not isinstance(revision_id, str):
487
raise errors.InvalidRevisionId(revision_id, self)
488
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
490
commit = self._git.object_store[git_commit_id]
492
raise errors.NoSuchRevision(self, revision_id)
493
revision, roundtrip_revid, verifiers = mapping.import_commit(
494
commit, self.lookup_foreign_revision_id)
495
assert revision is not None
496
# FIXME: check verifiers ?
498
revision.revision_id = roundtrip_revid
501
def has_revision(self, revision_id):
502
"""See Repository.has_revision."""
503
if revision_id == _mod_revision.NULL_REVISION:
506
git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
507
except errors.NoSuchRevision:
509
return (git_commit_id in self._git)
511
def has_revisions(self, revision_ids):
512
"""See Repository.has_revisions."""
513
return set(filter(self.has_revision, revision_ids))
515
def iter_revisions(self, revision_ids):
516
"""See Repository.get_revisions."""
517
for revid in revision_ids:
519
rev = self.get_revision(revid)
520
except errors.NoSuchRevision:
524
def revision_trees(self, revids):
525
"""See Repository.revision_trees."""
527
yield self.revision_tree(revid)
529
def revision_tree(self, revision_id):
530
"""See Repository.revision_tree."""
531
if revision_id is None:
532
raise ValueError('invalid revision id %s' % revision_id)
533
return GitRevisionTree(self, revision_id)
535
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
536
"""Produce a generator of revision deltas.
538
Note that the input is a sequence of REVISIONS, not revision_ids.
539
Trees will be held in memory until the generator exits.
540
Each delta is relative to the revision's lefthand predecessor.
542
:param specific_fileids: if not None, the result is filtered
543
so that only those file-ids, their parents and their
544
children are included.
546
# Get the revision-ids of interest
547
required_trees = set()
548
for revision in revisions:
549
required_trees.add(revision.revision_id)
550
required_trees.update(revision.parent_ids[:1])
552
trees = dict((t.get_revision_id(), t) for
553
t in self.revision_trees(required_trees))
555
# Calculate the deltas
556
for revision in revisions:
557
if not revision.parent_ids:
558
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
560
old_tree = trees[revision.parent_ids[0]]
561
new_tree = trees[revision.revision_id]
562
if specific_fileids is not None:
563
specific_files = [new_tree.id2path(fid) for fid in specific_fileids]
565
specific_files = None
566
yield new_tree.changes_from(old_tree, specific_files=specific_files)
568
def get_inventory(self, revision_id):
569
raise NotImplementedError(self.get_inventory)
571
def set_make_working_trees(self, trees):
572
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
574
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
575
progress=None, limit=None):
576
return self._git.fetch_objects(determine_wants, graph_walker, progress,
580
class GitRepositoryFormat(repository.RepositoryFormat):
581
"""Git repository format."""
583
supports_versioned_directories = False
584
supports_tree_reference = False
585
rich_root_data = True
586
supports_leaving_lock = False
588
supports_funky_characters = True
589
supports_external_lookups = False
590
supports_full_versioned_files = False
591
supports_revision_signatures = False
592
supports_nesting_repositories = False
593
revision_graph_can_have_wrong_parents = False
594
supports_unreferenced_revisions = True
595
supports_setting_revision_ids = False
596
supports_storing_branch_nick = False
597
supports_overriding_transport = False
598
supports_custom_revision_properties = False
601
def _matchingcontroldir(self):
602
from .dir import LocalGitControlDirFormat
603
return LocalGitControlDirFormat()
605
def get_format_description(self):
606
return "Git Repository"
608
def initialize(self, controldir, shared=False, _internal=False):
609
from .dir import GitDir
610
if not isinstance(controldir, GitDir):
611
raise errors.UninitializableFormat(self)
612
return controldir.open_repository()
614
def check_conversion_target(self, target_repo_format):
615
return target_repo_format.rich_root_data
617
def get_foreign_tests_repository_factory(self):
618
from .tests.test_repository import (
619
ForeignTestsRepositoryFactory,
621
return ForeignTestsRepositoryFactory()
623
def network_name(self):