31
39
from bzrlib.plugins.git.commit import (
42
from bzrlib.plugins.git.errors import (
45
from bzrlib.plugins.git.filegraph import (
46
GitFileLastChangeScanner,
47
GitFileParentProvider,
34
49
from bzrlib.plugins.git.mapping import (
39
54
from bzrlib.plugins.git.tree import (
42
from bzrlib.plugins.git.versionedfiles import (
48
59
from dulwich.objects import (
64
from dulwich.object_store import (
69
class RepoReconciler(object):
70
"""Reconciler that reconciles a repository.
74
def __init__(self, repo, other=None, thorough=False):
75
"""Construct a RepoReconciler.
77
:param thorough: perform a thorough check which may take longer but
78
will correct non-data loss issues such as incorrect
84
"""Perform reconciliation.
86
After reconciliation the following attributes document found issues:
87
inconsistent_parents: The number of revisions in the repository whose
88
ancestry was being reported incorrectly.
89
garbage_inventories: The number of inventory objects without revisions
90
that were garbage collected.
94
class GitCheck(check.Check):
96
def __init__(self, repository, check_repo=True):
97
self.repository = repository
98
self.checked_rev_cnt = 0
100
def check(self, callback_refs=None, check_repo=True):
101
if callback_refs is None:
103
self.repository.lock_read()
104
self.repository.unlock()
106
def report_results(self, verbose):
110
_optimisers_loaded = False
112
def lazy_load_optimisers():
113
global _optimisers_loaded
114
if _optimisers_loaded:
116
from bzrlib.plugins.git import fetch, push
117
for optimiser in [fetch.InterRemoteGitNonGitRepository,
118
fetch.InterLocalGitNonGitRepository,
119
fetch.InterGitGitRepository,
120
push.InterToLocalGitRepository,
121
push.InterToRemoteGitRepository]:
122
repository.InterRepository.register_optimiser(optimiser)
123
_optimisers_loaded = True
53
126
class GitRepository(ForeignRepository):
54
127
"""An adapter to git repositories for bzr."""
56
129
_serializer = None
57
_commit_builder_class = GitCommitBuilder
60
def __init__(self, gitdir, lockfiles):
61
ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir,
63
from bzrlib.plugins.git import fetch, push
64
for optimiser in [fetch.InterRemoteGitNonGitRepository,
65
fetch.InterLocalGitNonGitRepository,
66
fetch.InterGitGitRepository,
67
push.InterToLocalGitRepository,
68
push.InterToRemoteGitRepository]:
69
repository.InterRepository.register_optimiser(optimiser)
130
vcs = foreign_vcs_git
133
def __init__(self, gitdir):
134
if bzrlib_version >= (2, 5):
137
class DummyControlFiles(object):
139
self._transport = gitdir.root_transport
140
control_files = DummyControlFiles()
141
self._transport = gitdir.root_transport
142
super(GitRepository, self).__init__(GitRepositoryFormat(),
143
gitdir, control_files)
144
self.base = gitdir.root_transport.base
145
lazy_load_optimisers()
146
self._lock_mode = None
149
def add_fallback_repository(self, basis_url):
150
raise errors.UnstackableRepositoryFormat(self._format,
151
self.control_transport.base)
71
153
def is_shared(self):
156
def get_physical_lock_status(self):
159
def lock_write(self):
160
"""See Branch.lock_write()."""
162
assert self._lock_mode == 'w'
163
self._lock_count += 1
165
self._lock_mode = 'w'
167
return GitRepositoryLock(self)
169
def break_lock(self):
170
raise NotImplementedError(self.break_lock)
172
def dont_leave_lock_in_place(self):
173
raise NotImplementedError(self.dont_leave_lock_in_place)
175
def leave_lock_in_place(self):
176
raise NotImplementedError(self.leave_lock_in_place)
180
assert self._lock_mode in ('r', 'w')
181
self._lock_count += 1
183
self._lock_mode = 'r'
187
@only_raises(errors.LockNotHeld, errors.LockBroken)
189
if self._lock_count == 0:
190
raise errors.LockNotHeld(self)
191
if self._lock_count == 1 and self._lock_mode == 'w':
192
if self._write_group is not None:
193
self.abort_write_group()
194
self._lock_count -= 1
195
self._lock_mode = None
196
raise errors.BzrError(
197
'Must end write groups before releasing write locks.')
198
self._lock_count -= 1
199
if self._lock_count == 0:
200
self._lock_mode = None
202
def is_write_locked(self):
203
return (self._lock_mode == 'w')
206
return (self._lock_mode is not None)
208
def get_transaction(self):
209
"""See Repository.get_transaction()."""
210
if self._write_group is None:
211
return transactions.PassThroughTransaction()
213
return self._write_group
215
def reconcile(self, other=None, thorough=False):
216
"""Reconcile this repository."""
217
reconciler = RepoReconciler(self, thorough=thorough)
218
reconciler.reconcile()
74
221
def supports_rich_root(self):
77
def _warn_if_deprecated(self, branch=None):
224
def _warn_if_deprecated(self, branch=None): # for bzr < 2.4
78
225
# This class isn't deprecated
87
234
def revision_graph_can_have_wrong_parents(self):
90
def dfetch(self, source, stop_revision):
91
interrepo = repository.InterRepository.get(source, self)
92
return interrepo.dfetch(stop_revision)
237
def add_signature_text(self, revid, signature):
238
raise errors.UnsupportedOperation(self.add_signature_text, self)
240
def sign_revision(self, revision_id, gpg_strategy):
241
raise errors.UnsupportedOperation(self.add_signature_text, self)
244
class GitRepositoryLock(object):
245
"""Subversion lock."""
247
def __init__(self, repository):
248
self.repository_token = None
249
self.repository = repository
252
self.repository.unlock()
95
255
class LocalGitRepository(GitRepository):
96
256
"""Git repository on the file system."""
98
def __init__(self, gitdir, lockfiles):
99
GitRepository.__init__(self, gitdir, lockfiles)
100
self.base = gitdir.root_transport.base
258
def __init__(self, gitdir):
259
GitRepository.__init__(self, gitdir)
101
260
self._git = gitdir._git
102
self.signatures = None
103
self.revisions = GitRevisions(self, self._git.object_store)
104
self.inventories = None
105
self.texts = GitTexts(self)
261
self._file_change_scanner = GitFileLastChangeScanner(self)
263
def get_commit_builder(self, branch, parents, config, timestamp=None,
264
timezone=None, committer=None, revprops=None,
265
revision_id=None, lossy=False):
266
"""Obtain a CommitBuilder for this repository.
268
:param branch: Branch to commit to.
269
:param parents: Revision ids of the parents of the new revision.
270
:param config: Configuration to use.
271
:param timestamp: Optional timestamp recorded for commit.
272
:param timezone: Optional timezone for timestamp.
273
:param committer: Optional committer to set for commit.
274
:param revprops: Optional dictionary of revision properties.
275
:param revision_id: Optional revision id.
276
:param lossy: Whether to discard data that can not be natively
277
represented, when pushing to a foreign VCS
279
self.start_write_group()
280
return GitCommitBuilder(self, parents, config,
281
timestamp, timezone, committer, revprops, revision_id,
284
def get_file_graph(self):
285
return _mod_graph.Graph(GitFileParentProvider(
286
self._file_change_scanner))
288
def iter_files_bytes(self, desired_files):
289
"""Iterate through file versions.
291
Files will not necessarily be returned in the order they occur in
292
desired_files. No specific order is guaranteed.
294
Yields pairs of identifier, bytes_iterator. identifier is an opaque
295
value supplied by the caller as part of desired_files. It should
296
uniquely identify the file version in the caller's context. (Examples:
297
an index number or a TreeTransform trans_id.)
299
bytes_iterator is an iterable of bytestrings for the file. The
300
kind of iterable and length of the bytestrings are unspecified, but for
301
this implementation, it is a list of bytes produced by
302
VersionedFile.get_record_stream().
304
:param desired_files: a list of (file_id, revision_id, identifier)
308
for (file_id, revision_id, identifier) in desired_files:
309
per_revision.setdefault(revision_id, []).append(
310
(file_id, identifier))
311
for revid, files in per_revision.iteritems():
312
(commit_id, mapping) = self.lookup_bzr_revision_id(revid)
314
commit = self._git.object_store[commit_id]
316
raise errors.RevisionNotPresent(revid, self)
317
root_tree = commit.tree
318
for fileid, identifier in files:
319
path = mapping.parse_file_id(fileid)
321
obj = tree_lookup_path(
322
self._git.object_store.__getitem__, root_tree, path)
323
if isinstance(obj, tuple):
324
(mode, item_id) = obj
325
obj = self._git.object_store[item_id]
327
raise errors.RevisionNotPresent((fileid, revid), self)
329
if obj.type_name == "tree":
330
yield (identifier, [])
331
elif obj.type_name == "blob":
332
yield (identifier, obj.chunked)
334
raise AssertionError("file text resolved to %r" % obj)
107
336
def _iter_revision_ids(self):
108
337
mapping = self.get_mapping()
111
340
if not isinstance(o, Commit):
113
342
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
114
self.lookup_foreign_revision_id)
343
mapping.revision_id_foreign_to_bzr)
115
344
yield o.id, rev.revision_id, roundtrip_revid
117
346
def all_revision_ids(self):
119
348
for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
121
349
if roundtrip_revid:
122
350
ret.add(roundtrip_revid)
355
def _get_parents(self, revid):
356
if type(revid) != str:
359
(hexsha, mapping) = self.lookup_bzr_revision_id(revid)
360
except errors.NoSuchRevision:
363
commit = self._git[hexsha]
367
self.lookup_foreign_revision_id(p, mapping)
368
for p in commit.parents]
125
370
def get_parent_map(self, revids):
127
372
for revision_id in revids:
128
assert isinstance(revision_id, str)
373
parents = self._get_parents(revision_id)
129
374
if revision_id == revision.NULL_REVISION:
130
375
parent_map[revision_id] = ()
132
hexsha, mapping = self.lookup_bzr_revision_id(revision_id)
134
commit = self._git[hexsha]
137
parent_map[revision_id] = [
138
self.lookup_foreign_revision_id(p, mapping)
139
for p in commit.parents]
379
if len(parents) == 0:
380
parents = [revision.NULL_REVISION]
381
parent_map[revision_id] = tuple(parents)
140
382
return parent_map
142
def get_ancestry(self, revision_id, topo_sorted=True):
143
"""See Repository.get_ancestry().
384
def get_known_graph_ancestry(self, revision_ids):
385
"""Return the known graph for a set of revision ids and their ancestors.
145
if revision_id is None:
146
return [None, revision.NULL_REVISION] + self._all_revision_ids()
147
assert isinstance(revision_id, str)
149
graph = self.get_graph()
150
for rev, parents in graph.iter_ancestry([revision_id]):
153
return [None] + ancestry
387
pending = set(revision_ids)
391
for revid in pending:
392
if revid == revision.NULL_REVISION:
394
parents = self._get_parents(revid)
395
if parents is not None:
396
this_parent_map[revid] = parents
397
parent_map.update(this_parent_map)
399
map(pending.update, this_parent_map.itervalues())
400
pending = pending.difference(parent_map)
401
return _mod_graph.KnownGraph(parent_map)
155
403
def get_signature_text(self, revision_id):
156
404
raise errors.NoSuchRevision(self, revision_id)
406
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
407
result = GitCheck(self, check_repo=check_repo)
408
result.check(callback_refs)
158
411
def pack(self, hint=None, clean_obsolete_packs=False):
159
412
self._git.object_store.pack_loose_objects()
225
497
return (git_commit_id in self._git)
227
499
def has_revisions(self, revision_ids):
500
"""See Repository.has_revisions."""
228
501
return set(filter(self.has_revision, revision_ids))
230
503
def get_revisions(self, revids):
504
"""See Repository.get_revisions."""
231
505
return [self.get_revision(r) for r in revids]
233
507
def revision_trees(self, revids):
508
"""See Repository.revision_trees."""
234
509
for revid in revids:
235
510
yield self.revision_tree(revid)
237
512
def revision_tree(self, revision_id):
513
"""See Repository.revision_tree."""
238
514
revision_id = revision.ensure_null(revision_id)
239
515
if revision_id == revision.NULL_REVISION:
240
516
inv = inventory.Inventory(root_id=None)
241
517
inv.revision_id = revision_id
242
return revisiontree.RevisionTree(self, inv, revision_id)
518
return InventoryRevisionTree(self, inv, revision_id)
243
519
return GitRevisionTree(self, revision_id)
245
521
def get_inventory(self, revision_id):
246
assert revision_id != None
247
return self.revision_tree(revision_id).inventory
522
raise NotImplementedError(self.get_inventory)
249
524
def set_make_working_trees(self, trees):
525
raise errors.UnsupportedOperation(self.set_make_working_trees, self)
526
# TODO: Set bare= in the configuration bug=777065
252
528
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
254
530
return self._git.fetch_objects(determine_wants, graph_walker, progress)
256
def _get_versioned_file_checker(self, text_key_references=None,
258
return GitVersionedFileChecker(self,
259
text_key_references=text_key_references, ancestors=ancestors)
262
class GitVersionedFileChecker(repository._VersionedFileChecker):
266
def _check_file_version_parents(self, texts, progress_bar):
270
533
class GitRepositoryFormat(repository.RepositoryFormat):
271
534
"""Git repository format."""
536
supports_versioned_directories = False
273
537
supports_tree_reference = False
274
538
rich_root_data = True
539
supports_leaving_lock = False
541
supports_funky_characters = True
542
supports_external_lookups = False
543
supports_full_versioned_files = False
544
supports_revision_signatures = False
545
supports_nesting_repositories = False
546
revision_graph_can_have_wrong_parents = False
549
def _matchingbzrdir(self):
550
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
551
return LocalGitControlDirFormat()
276
553
def get_format_description(self):
277
554
return "Git Repository"
279
def initialize(self, url, shared=False, _internal=False):
280
raise errors.UninitializableFormat(self)
556
def initialize(self, controldir, shared=False, _internal=False):
557
from bzrlib.plugins.git.dir import GitDir
558
if not isinstance(controldir, GitDir):
559
raise errors.UninitializableFormat(self)
560
return controldir.open_repository()
282
562
def check_conversion_target(self, target_repo_format):
283
563
return target_repo_format.rich_root_data