56
52
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
57
53
from bzrlib.symbol_versioning import (
60
from bzrlib.trace import mutter, mutter_callsite, note, warning
57
from bzrlib.trace import mutter, note, warning
63
60
# Old formats display a warning, but only once
64
61
_deprecation_warning_done = False
67
class CommitBuilder(object):
68
"""Provides an interface to build up a commit.
70
This allows describing a tree to be committed without needing to
71
know the internals of the format of the repository.
74
# all clients should supply tree roots.
75
record_root_entry = True
76
# the default CommitBuilder does not manage trees whose root is versioned.
77
_versioned_root = False
79
def __init__(self, repository, parents, config, timestamp=None,
80
timezone=None, committer=None, revprops=None,
82
"""Initiate a CommitBuilder.
84
:param repository: Repository to commit to.
85
:param parents: Revision ids of the parents of the new revision.
86
:param config: Configuration to use.
87
:param timestamp: Optional timestamp recorded for commit.
88
:param timezone: Optional timezone for timestamp.
89
:param committer: Optional committer to set for commit.
90
:param revprops: Optional dictionary of revision properties.
91
:param revision_id: Optional revision id.
96
self._committer = self._config.username()
98
assert isinstance(committer, basestring), type(committer)
99
self._committer = committer
101
self.new_inventory = Inventory(None)
102
self._new_revision_id = revision_id
103
self.parents = parents
104
self.repository = repository
107
if revprops is not None:
108
self._revprops.update(revprops)
110
if timestamp is None:
111
timestamp = time.time()
112
# Restrict resolution to 1ms
113
self._timestamp = round(timestamp, 3)
116
self._timezone = osutils.local_time_offset()
118
self._timezone = int(timezone)
120
self._generate_revision_if_needed()
121
self.__heads = graph.HeadsCache(repository.get_graph()).heads
123
def commit(self, message):
124
"""Make the actual commit.
126
:return: The revision id of the recorded revision.
128
rev = _mod_revision.Revision(
129
timestamp=self._timestamp,
130
timezone=self._timezone,
131
committer=self._committer,
133
inventory_sha1=self.inv_sha1,
134
revision_id=self._new_revision_id,
135
properties=self._revprops)
136
rev.parent_ids = self.parents
137
self.repository.add_revision(self._new_revision_id, rev,
138
self.new_inventory, self._config)
139
self.repository.commit_write_group()
140
return self._new_revision_id
143
"""Abort the commit that is being built.
145
self.repository.abort_write_group()
147
def revision_tree(self):
148
"""Return the tree that was just committed.
150
After calling commit() this can be called to get a RevisionTree
151
representing the newly committed tree. This is preferred to
152
calling Repository.revision_tree() because that may require
153
deserializing the inventory, while we already have a copy in
156
return RevisionTree(self.repository, self.new_inventory,
157
self._new_revision_id)
159
def finish_inventory(self):
160
"""Tell the builder that the inventory is finished."""
161
if self.new_inventory.root is None:
162
raise AssertionError('Root entry should be supplied to'
163
' record_entry_contents, as of bzr 0.10.',
164
DeprecationWarning, stacklevel=2)
165
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
166
self.new_inventory.revision_id = self._new_revision_id
167
self.inv_sha1 = self.repository.add_inventory(
168
self._new_revision_id,
173
def _gen_revision_id(self):
174
"""Return new revision-id."""
175
return generate_ids.gen_revision_id(self._config.username(),
178
def _generate_revision_if_needed(self):
179
"""Create a revision id if None was supplied.
181
If the repository can not support user-specified revision ids
182
they should override this function and raise CannotSetRevisionId
183
if _new_revision_id is not None.
185
:raises: CannotSetRevisionId
187
if self._new_revision_id is None:
188
self._new_revision_id = self._gen_revision_id()
189
self.random_revid = True
191
self.random_revid = False
193
def _heads(self, file_id, revision_ids):
194
"""Calculate the graph heads for revision_ids in the graph of file_id.
196
This can use either a per-file graph or a global revision graph as we
197
have an identity relationship between the two graphs.
199
return self.__heads(revision_ids)
201
def _check_root(self, ie, parent_invs, tree):
202
"""Helper for record_entry_contents.
204
:param ie: An entry being added.
205
:param parent_invs: The inventories of the parent revisions of the
207
:param tree: The tree that is being committed.
209
# In this revision format, root entries have no knit or weave When
210
# serializing out to disk and back in root.revision is always
212
ie.revision = self._new_revision_id
214
def _get_delta(self, ie, basis_inv, path):
215
"""Get a delta against the basis inventory for ie."""
216
if ie.file_id not in basis_inv:
218
return (None, path, ie.file_id, ie)
219
elif ie != basis_inv[ie.file_id]:
221
# TODO: avoid tis id2path call.
222
return (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
227
def record_entry_contents(self, ie, parent_invs, path, tree,
229
"""Record the content of ie from tree into the commit if needed.
231
Side effect: sets ie.revision when unchanged
233
:param ie: An inventory entry present in the commit.
234
:param parent_invs: The inventories of the parent revisions of the
236
:param path: The path the entry is at in the tree.
237
:param tree: The tree which contains this entry and should be used to
239
:param content_summary: Summary data from the tree about the paths
240
content - stat, length, exec, sha/link target. This is only
241
accessed when the entry has a revision of None - that is when it is
242
a candidate to commit.
243
:return: A tuple (change_delta, version_recorded). change_delta is
244
an inventory_delta change for this entry against the basis tree of
245
the commit, or None if no change occured against the basis tree.
246
version_recorded is True if a new version of the entry has been
247
recorded. For instance, committing a merge where a file was only
248
changed on the other side will return (delta, False).
250
if self.new_inventory.root is None:
251
if ie.parent_id is not None:
252
raise errors.RootMissing()
253
self._check_root(ie, parent_invs, tree)
254
if ie.revision is None:
255
kind = content_summary[0]
257
# ie is carried over from a prior commit
259
# XXX: repository specific check for nested tree support goes here - if
260
# the repo doesn't want nested trees we skip it ?
261
if (kind == 'tree-reference' and
262
not self.repository._format.supports_tree_reference):
263
# mismatch between commit builder logic and repository:
264
# this needs the entry creation pushed down into the builder.
265
raise NotImplementedError('Missing repository subtree support.')
266
self.new_inventory.add(ie)
268
# TODO: slow, take it out of the inner loop.
270
basis_inv = parent_invs[0]
272
basis_inv = Inventory(root_id=None)
274
# ie.revision is always None if the InventoryEntry is considered
275
# for committing. We may record the previous parents revision if the
276
# content is actually unchanged against a sole head.
277
if ie.revision is not None:
278
if not self._versioned_root and path == '':
279
# repositories that do not version the root set the root's
280
# revision to the new commit even when no change occurs, and
281
# this masks when a change may have occurred against the basis,
282
# so calculate if one happened.
283
if ie.file_id in basis_inv:
284
delta = (basis_inv.id2path(ie.file_id), path,
288
delta = (None, path, ie.file_id, ie)
291
# we don't need to commit this, because the caller already
292
# determined that an existing revision of this file is
294
return None, (ie.revision == self._new_revision_id)
295
# XXX: Friction: parent_candidates should return a list not a dict
296
# so that we don't have to walk the inventories again.
297
parent_candiate_entries = ie.parent_candidates(parent_invs)
298
head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
300
for inv in parent_invs:
301
if ie.file_id in inv:
302
old_rev = inv[ie.file_id].revision
303
if old_rev in head_set:
304
heads.append(inv[ie.file_id].revision)
305
head_set.remove(inv[ie.file_id].revision)
308
# now we check to see if we need to write a new record to the
310
# We write a new entry unless there is one head to the ancestors, and
311
# the kind-derived content is unchanged.
313
# Cheapest check first: no ancestors, or more the one head in the
314
# ancestors, we write a new node.
318
# There is a single head, look it up for comparison
319
parent_entry = parent_candiate_entries[heads[0]]
320
# if the non-content specific data has changed, we'll be writing a
322
if (parent_entry.parent_id != ie.parent_id or
323
parent_entry.name != ie.name):
325
# now we need to do content specific checks:
327
# if the kind changed the content obviously has
328
if kind != parent_entry.kind:
331
assert content_summary[2] is not None, \
332
"Files must not have executable = None"
334
if (# if the file length changed we have to store:
335
parent_entry.text_size != content_summary[1] or
336
# if the exec bit has changed we have to store:
337
parent_entry.executable != content_summary[2]):
339
elif parent_entry.text_sha1 == content_summary[3]:
340
# all meta and content is unchanged (using a hash cache
341
# hit to check the sha)
342
ie.revision = parent_entry.revision
343
ie.text_size = parent_entry.text_size
344
ie.text_sha1 = parent_entry.text_sha1
345
ie.executable = parent_entry.executable
346
return self._get_delta(ie, basis_inv, path), False
348
# Either there is only a hash change(no hash cache entry,
349
# or same size content change), or there is no change on
351
# Provide the parent's hash to the store layer, so that the
352
# content is unchanged we will not store a new node.
353
nostore_sha = parent_entry.text_sha1
355
# We want to record a new node regardless of the presence or
356
# absence of a content change in the file.
358
ie.executable = content_summary[2]
359
lines = tree.get_file(ie.file_id, path).readlines()
361
ie.text_sha1, ie.text_size = self._add_text_to_weave(
362
ie.file_id, lines, heads, nostore_sha)
363
except errors.ExistingContent:
364
# Turns out that the file content was unchanged, and we were
365
# only going to store a new node if it was changed. Carry over
367
ie.revision = parent_entry.revision
368
ie.text_size = parent_entry.text_size
369
ie.text_sha1 = parent_entry.text_sha1
370
ie.executable = parent_entry.executable
371
return self._get_delta(ie, basis_inv, path), False
372
elif kind == 'directory':
374
# all data is meta here, nothing specific to directory, so
376
ie.revision = parent_entry.revision
377
return self._get_delta(ie, basis_inv, path), False
379
self._add_text_to_weave(ie.file_id, lines, heads, None)
380
elif kind == 'symlink':
381
current_link_target = content_summary[3]
383
# symlink target is not generic metadata, check if it has
385
if current_link_target != parent_entry.symlink_target:
388
# unchanged, carry over.
389
ie.revision = parent_entry.revision
390
ie.symlink_target = parent_entry.symlink_target
391
return self._get_delta(ie, basis_inv, path), False
392
ie.symlink_target = current_link_target
394
self._add_text_to_weave(ie.file_id, lines, heads, None)
395
elif kind == 'tree-reference':
397
if content_summary[3] != parent_entry.reference_revision:
400
# unchanged, carry over.
401
ie.reference_revision = parent_entry.reference_revision
402
ie.revision = parent_entry.revision
403
return self._get_delta(ie, basis_inv, path), False
404
ie.reference_revision = content_summary[3]
406
self._add_text_to_weave(ie.file_id, lines, heads, None)
408
raise NotImplementedError('unknown kind')
409
ie.revision = self._new_revision_id
410
return self._get_delta(ie, basis_inv, path), True
412
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
413
versionedfile = self.repository.weave_store.get_weave_or_empty(
414
file_id, self.repository.get_transaction())
415
# Don't change this to add_lines - add_lines_with_ghosts is cheaper
416
# than add_lines, and allows committing when a parent is ghosted for
418
# Note: as we read the content directly from the tree, we know its not
419
# been turned into unicode or badly split - but a broken tree
420
# implementation could give us bad output from readlines() so this is
421
# not a guarantee of safety. What would be better is always checking
422
# the content during test suite execution. RBC 20070912
424
return versionedfile.add_lines_with_ghosts(
425
self._new_revision_id, parents, new_lines,
426
nostore_sha=nostore_sha, random_id=self.random_revid,
427
check_content=False)[0:2]
429
versionedfile.clear_cache()
432
class RootCommitBuilder(CommitBuilder):
433
"""This commitbuilder actually records the root id"""
435
# the root entry gets versioned properly by this builder.
436
_versioned_root = True
438
def _check_root(self, ie, parent_invs, tree):
439
"""Helper for record_entry_contents.
441
:param ie: An entry being added.
442
:param parent_invs: The inventories of the parent revisions of the
444
:param tree: The tree that is being committed.
448
64
######################################################################
463
# What class to use for a CommitBuilder. Often its simpler to change this
464
# in a Repository class subclass rather than to override
465
# get_commit_builder.
466
_commit_builder_class = CommitBuilder
467
# The search regex used by xml based repositories to determine what things
468
# where changed in a single commit.
469
79
_file_ids_altered_regex = lazy_regex.lazy_compile(
470
80
r'file_id="(?P<file_id>[^"]+)"'
471
r'.* revision="(?P<revision_id>[^"]+)"'
81
r'.*revision="(?P<revision_id>[^"]+)"'
474
def abort_write_group(self):
475
"""Commit the contents accrued within the current write group.
477
:seealso: start_write_group.
479
if self._write_group is not self.get_transaction():
480
# has an unlock or relock occured ?
481
raise errors.BzrError('mismatched lock context and write group.')
482
self._abort_write_group()
483
self._write_group = None
485
def _abort_write_group(self):
486
"""Template method for per-repository write group cleanup.
488
This is called during abort before the write group is considered to be
489
finished and should cleanup any internal state accrued during the write
490
group. There is no requirement that data handed to the repository be
491
*not* made available - this is not a rollback - but neither should any
492
attempt be made to ensure that data added is fully commited. Abort is
493
invoked when an error has occured so futher disk or network operations
494
may not be possible or may error and if possible should not be
498
85
def add_inventory(self, revision_id, inv, parents):
499
86
"""Add the inventory inv to the repository as revision_id.
501
88
:param parents: The revision ids of the parents that revision_id
502
89
is known to have and are in the repository already.
504
:returns: The validator(which is a sha1 digest, though what is sha'd is
505
repository format specific) of the serialized inventory.
91
returns the sha1 of the serialized inventory.
507
assert self.is_in_write_group()
93
revision_id = osutils.safe_revision_id(revision_id)
508
94
_mod_revision.check_not_reserved_id(revision_id)
509
95
assert inv.revision_id is None or inv.revision_id == revision_id, \
510
96
"Mismatch between inventory revision" \
511
97
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
512
98
assert inv.root is not None
513
inv_lines = self._serialise_inventory_to_lines(inv)
514
inv_vf = self.get_inventory_weave()
515
return self._inventory_add_lines(inv_vf, revision_id, parents,
516
inv_lines, check_content=False)
99
inv_text = self.serialise_inventory(inv)
100
inv_sha1 = osutils.sha_string(inv_text)
101
inv_vf = self.control_weaves.get_weave('inventory',
102
self.get_transaction())
103
self._inventory_add_lines(inv_vf, revision_id, parents,
104
osutils.split_lines(inv_text))
518
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines,
520
"""Store lines in inv_vf and return the sha1 of the inventory."""
107
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
521
108
final_parents = []
522
109
for parent in parents:
523
110
if parent in inv_vf:
524
111
final_parents.append(parent)
525
return inv_vf.add_lines(revision_id, final_parents, lines,
526
check_content=check_content)[0]
113
inv_vf.add_lines(revision_id, final_parents, lines)
528
116
def add_revision(self, revision_id, rev, inv=None, config=None):
529
117
"""Add rev to the revision store as revision_id.
766
323
result['size'] = t
769
def find_branches(self, using=False):
770
"""Find branches underneath this repository.
772
This will include branches inside other branches.
774
:param using: If True, list only branches using this repository.
776
if using and not self.is_shared():
778
return [self.bzrdir.open_branch()]
779
except errors.NotBranchError:
781
class Evaluator(object):
784
self.first_call = True
786
def __call__(self, bzrdir):
787
# On the first call, the parameter is always the bzrdir
788
# containing the current repo.
789
if not self.first_call:
791
repository = bzrdir.open_repository()
792
except errors.NoRepositoryPresent:
795
return False, (None, repository)
796
self.first_call = False
798
value = (bzrdir.open_branch(), None)
799
except errors.NotBranchError:
804
for branch, repository in bzrdir.BzrDir.find_bzrdirs(
805
self.bzrdir.root_transport, evaluate=Evaluator()):
806
if branch is not None:
807
branches.append(branch)
808
if not using and repository is not None:
809
branches.extend(repository.find_branches())
812
def get_data_stream(self, revision_ids):
813
raise NotImplementedError(self.get_data_stream)
815
def get_data_stream_for_search(self, search_result):
816
"""Get a data stream that can be inserted to a repository.
818
:param search_result: A bzrlib.graph.SearchResult selecting the
820
:return: A data stream that can be inserted into a repository using
823
raise NotImplementedError(self.get_data_stream_for_search)
825
def insert_data_stream(self, stream):
826
"""XXX What does this really do?
828
Is it a substitute for fetch?
829
Should it manage its own write group ?
831
for item_key, bytes in stream:
832
if item_key[0] == 'file':
833
(file_id,) = item_key[1:]
834
knit = self.weave_store.get_weave_or_empty(
835
file_id, self.get_transaction())
836
elif item_key == ('inventory',):
837
knit = self.get_inventory_weave()
838
elif item_key == ('revisions',):
839
knit = self._revision_store.get_revision_file(
840
self.get_transaction())
841
elif item_key == ('signatures',):
842
knit = self._revision_store.get_signature_file(
843
self.get_transaction())
845
raise errors.RepositoryDataStreamError(
846
"Unrecognised data stream key '%s'" % (item_key,))
847
decoded_list = bencode.bdecode(bytes)
848
format = decoded_list.pop(0)
851
for version, options, parents, some_bytes in decoded_list:
852
data_list.append((version, options, len(some_bytes), parents))
853
knit_bytes += some_bytes
854
buffer = StringIO(knit_bytes)
855
def reader_func(count):
859
return buffer.read(count)
860
knit.insert_data_stream(
861
(format, data_list, reader_func))
864
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
865
"""Return the revision ids that other has that this does not.
867
These are returned in topological order.
869
revision_id: only return revision ids included by revision_id.
871
return InterRepository.get(other, self).search_missing_revision_ids(
872
revision_id, find_ghosts)
874
@deprecated_method(symbol_versioning.one_two)
876
def missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
877
"""Return the revision ids that other has that this does not.
879
These are returned in topological order.
881
revision_id: only return revision ids included by revision_id.
883
keys = self.search_missing_revision_ids(
884
other, revision_id, find_ghosts).get_keys()
887
parents = other.get_graph().get_parent_map(keys)
890
return tsort.topo_sort(parents)
327
def missing_revision_ids(self, other, revision_id=None):
328
"""Return the revision ids that other has that this does not.
330
These are returned in topological order.
332
revision_id: only return revision ids included by revision_id.
334
revision_id = osutils.safe_revision_id(revision_id)
335
return InterRepository.get(other, self).missing_revision_ids(revision_id)
905
350
This is a destructive operation! Do not use it on existing
353
revision_id = osutils.safe_revision_id(revision_id)
908
354
return InterRepository.get(self, destination).copy_content(revision_id)
910
def commit_write_group(self):
911
"""Commit the contents accrued within the current write group.
913
:seealso: start_write_group.
915
if self._write_group is not self.get_transaction():
916
# has an unlock or relock occured ?
917
raise errors.BzrError('mismatched lock context %r and '
919
(self.get_transaction(), self._write_group))
920
self._commit_write_group()
921
self._write_group = None
923
def _commit_write_group(self):
924
"""Template method for per-repository write group cleanup.
926
This is called before the write group is considered to be
927
finished and should ensure that all data handed to the repository
928
for writing during the write group is safely committed (to the
929
extent possible considering file system caching etc).
932
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
356
def fetch(self, source, revision_id=None, pb=None):
933
357
"""Fetch the content required to construct revision_id from source.
935
359
If revision_id is None all content is copied.
936
:param find_ghosts: Find and copy revisions in the source that are
937
ghosts in the target (and not reachable directly by walking out to
938
the first-present revision in target from revision_id).
940
# fast path same-url fetch operations
941
if self.has_same_location(source):
942
# check that last_revision is in 'from' and then return a
944
if (revision_id is not None and
945
not _mod_revision.is_null(revision_id)):
946
self.get_revision(revision_id)
361
revision_id = osutils.safe_revision_id(revision_id)
948
362
inter = InterRepository.get(source, self)
950
return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
364
return inter.fetch(revision_id=revision_id, pb=pb)
951
365
except NotImplementedError:
952
366
raise errors.IncompatibleRepositories(source, self)
954
def create_bundle(self, target, base, fileobj, format=None):
955
return serializer.write_bundle(self, target, base, fileobj, format)
957
def get_commit_builder(self, branch, parents, config, timestamp=None,
958
timezone=None, committer=None, revprops=None,
368
def get_commit_builder(self, branch, parents, config, timestamp=None,
369
timezone=None, committer=None, revprops=None,
959
370
revision_id=None):
960
371
"""Obtain a CommitBuilder for this repository.
1144
517
r = self.get_revision(revision_id)
1145
518
return list(self.get_deltas_for_revisions([r]))[0]
520
def _check_revision_parents(self, revision, inventory):
521
"""Private to Repository and Fetch.
523
This checks the parentage of revision in an inventory weave for
524
consistency and is only applicable to inventory-weave-for-ancestry
525
using repository formats & fetchers.
527
weave_parents = inventory.get_parents(revision.revision_id)
528
weave_names = inventory.versions()
529
for parent_id in revision.parent_ids:
530
if parent_id in weave_names:
531
# this parent must not be a ghost.
532
if not parent_id in weave_parents:
534
raise errors.CorruptRepository(self)
1147
536
@needs_write_lock
1148
537
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
538
revision_id = osutils.safe_revision_id(revision_id)
1149
539
signature = gpg_strategy.sign(plaintext)
1150
self.add_signature_text(revision_id, signature)
1153
def add_signature_text(self, revision_id, signature):
1154
540
self._revision_store.add_revision_signature_text(revision_id,
1156
542
self.get_transaction())
1158
def find_text_key_references(self):
1159
"""Find the text key references within the repository.
544
def fileids_altered_by_revision_ids(self, revision_ids):
545
"""Find the file ids and versions affected by revisions.
1161
:return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
547
:param revisions: an iterable containing revision ids.
548
:return: a dictionary mapping altered file-ids to an iterable of
1162
549
revision_ids. Each altered file-ids has the exact revision_ids that
1163
550
altered it listed explicitly.
1164
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1165
to whether they were referred to by the inventory of the
1166
revision_id that they contain. The inventory texts from all present
1167
revision ids are assessed to generate this report.
1169
revision_ids = self.all_revision_ids()
552
assert self._serializer.support_altered_by_hack, \
553
("fileids_altered_by_revision_ids only supported for branches "
554
"which store inventory as unnested xml, not on %r" % self)
555
selected_revision_ids = set(osutils.safe_revision_id(r)
556
for r in revision_ids)
1170
557
w = self.get_inventory_weave()
1171
pb = ui.ui_factory.nested_progress_bar()
1173
return self._find_text_key_references_from_xml_inventory_lines(
1174
w.iter_lines_added_or_present_in_versions(revision_ids, pb=pb))
1178
def _find_text_key_references_from_xml_inventory_lines(self,
1180
"""Core routine for extracting references to texts from inventories.
1182
This performs the translation of xml lines to revision ids.
1184
:param line_iterator: An iterator of lines, origin_version_id
1185
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1186
to whether they were referred to by the inventory of the
1187
revision_id that they contain. Note that if that revision_id was
1188
not part of the line_iterator's output then False will be given -
1189
even though it may actually refer to that key.
1191
if not self._serializer.support_altered_by_hack:
1192
raise AssertionError(
1193
"_find_text_key_references_from_xml_inventory_lines only "
1194
"supported for branches which store inventory as unnested xml"
1195
", not on %r" % self)
1198
560
# this code needs to read every new line in every inventory for the
1214
576
search = self._file_ids_altered_regex.search
1215
577
unescape = _unescape_xml
1216
578
setdefault = result.setdefault
1217
for line, version_id in line_iterator:
1218
match = search(line)
1221
# One call to match.group() returning multiple items is quite a
1222
# bit faster than 2 calls to match.group() each returning 1
1223
file_id, revision_id = match.group('file_id', 'revision_id')
1225
# Inlining the cache lookups helps a lot when you make 170,000
1226
# lines and 350k ids, versus 8.4 unique ids.
1227
# Using a cache helps in 2 ways:
1228
# 1) Avoids unnecessary decoding calls
1229
# 2) Re-uses cached strings, which helps in future set and
1231
# (2) is enough that removing encoding entirely along with
1232
# the cache (so we are using plain strings) results in no
1233
# performance improvement.
1235
revision_id = unescape_revid_cache[revision_id]
1237
unescaped = unescape(revision_id)
1238
unescape_revid_cache[revision_id] = unescaped
1239
revision_id = unescaped
1241
# Note that unconditionally unescaping means that we deserialise
1242
# every fileid, which for general 'pull' is not great, but we don't
1243
# really want to have some many fulltexts that this matters anyway.
1246
file_id = unescape_fileid_cache[file_id]
1248
unescaped = unescape(file_id)
1249
unescape_fileid_cache[file_id] = unescaped
1252
key = (file_id, revision_id)
1253
setdefault(key, False)
1254
if revision_id == version_id:
1258
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1260
"""Helper routine for fileids_altered_by_revision_ids.
1262
This performs the translation of xml lines to revision ids.
1264
:param line_iterator: An iterator of lines, origin_version_id
1265
:param revision_ids: The revision ids to filter for. This should be a
1266
set or other type which supports efficient __contains__ lookups, as
1267
the revision id from each parsed line will be looked up in the
1268
revision_ids filter.
1269
:return: a dictionary mapping altered file-ids to an iterable of
1270
revision_ids. Each altered file-ids has the exact revision_ids that
1271
altered it listed explicitly.
1274
setdefault = result.setdefault
1275
for file_id, revision_id in \
1276
self._find_text_key_references_from_xml_inventory_lines(
1277
line_iterator).iterkeys():
1278
# once data is all ensured-consistent; then this is
1279
# if revision_id == version_id
1280
if revision_id in revision_ids:
1281
setdefault(file_id, set()).add(revision_id)
1284
def fileids_altered_by_revision_ids(self, revision_ids):
1285
"""Find the file ids and versions affected by revisions.
1287
:param revisions: an iterable containing revision ids.
1288
:return: a dictionary mapping altered file-ids to an iterable of
1289
revision_ids. Each altered file-ids has the exact revision_ids that
1290
altered it listed explicitly.
1292
selected_revision_ids = set(revision_ids)
1293
w = self.get_inventory_weave()
1294
pb = ui.ui_factory.nested_progress_bar()
1296
return self._find_file_ids_from_xml_inventory_lines(
1297
w.iter_lines_added_or_present_in_versions(
1298
selected_revision_ids, pb=pb),
1299
selected_revision_ids)
1303
def iter_files_bytes(self, desired_files):
1304
"""Iterate through file versions.
1306
Files will not necessarily be returned in the order they occur in
1307
desired_files. No specific order is guaranteed.
1309
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1310
value supplied by the caller as part of desired_files. It should
1311
uniquely identify the file version in the caller's context. (Examples:
1312
an index number or a TreeTransform trans_id.)
1314
bytes_iterator is an iterable of bytestrings for the file. The
1315
kind of iterable and length of the bytestrings are unspecified, but for
1316
this implementation, it is a list of lines produced by
1317
VersionedFile.get_lines().
1319
:param desired_files: a list of (file_id, revision_id, identifier)
1322
transaction = self.get_transaction()
1323
for file_id, revision_id, callable_data in desired_files:
1325
weave = self.weave_store.get_weave(file_id, transaction)
1326
except errors.NoSuchFile:
1327
raise errors.NoSuchIdInRepository(self, file_id)
1328
yield callable_data, weave.get_lines(revision_id)
1330
def _generate_text_key_index(self, text_key_references=None,
1332
"""Generate a new text key index for the repository.
1334
This is an expensive function that will take considerable time to run.
1336
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1337
list of parents, also text keys. When a given key has no parents,
1338
the parents list will be [NULL_REVISION].
1340
# All revisions, to find inventory parents.
1341
if ancestors is None:
1342
graph = self.get_graph()
1343
ancestors = graph.get_parent_map(self.all_revision_ids())
1344
if text_key_references is None:
1345
text_key_references = self.find_text_key_references()
1346
pb = ui.ui_factory.nested_progress_bar()
1348
return self._do_generate_text_key_index(ancestors,
1349
text_key_references, pb)
1353
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1354
"""Helper for _generate_text_key_index to avoid deep nesting."""
1355
revision_order = tsort.topo_sort(ancestors)
1356
invalid_keys = set()
1358
for revision_id in revision_order:
1359
revision_keys[revision_id] = set()
1360
text_count = len(text_key_references)
1361
# a cache of the text keys to allow reuse; costs a dict of all the
1362
# keys, but saves a 2-tuple for every child of a given key.
1364
for text_key, valid in text_key_references.iteritems():
1366
invalid_keys.add(text_key)
1368
revision_keys[text_key[1]].add(text_key)
1369
text_key_cache[text_key] = text_key
1370
del text_key_references
1372
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1373
NULL_REVISION = _mod_revision.NULL_REVISION
1374
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1375
# too small for large or very branchy trees. However, for 55K path
1376
# trees, it would be easy to use too much memory trivially. Ideally we
1377
# could gauge this by looking at available real memory etc, but this is
1378
# always a tricky proposition.
1379
inventory_cache = lru_cache.LRUCache(10)
1380
batch_size = 10 # should be ~150MB on a 55K path tree
1381
batch_count = len(revision_order) / batch_size + 1
1383
pb.update("Calculating text parents.", processed_texts, text_count)
1384
for offset in xrange(batch_count):
1385
to_query = revision_order[offset * batch_size:(offset + 1) *
1389
for rev_tree in self.revision_trees(to_query):
1390
revision_id = rev_tree.get_revision_id()
1391
parent_ids = ancestors[revision_id]
1392
for text_key in revision_keys[revision_id]:
1393
pb.update("Calculating text parents.", processed_texts)
1394
processed_texts += 1
1395
candidate_parents = []
1396
for parent_id in parent_ids:
1397
parent_text_key = (text_key[0], parent_id)
1399
check_parent = parent_text_key not in \
1400
revision_keys[parent_id]
1402
# the parent parent_id is a ghost:
1403
check_parent = False
1404
# truncate the derived graph against this ghost.
1405
parent_text_key = None
1407
# look at the parent commit details inventories to
1408
# determine possible candidates in the per file graph.
1411
inv = inventory_cache[parent_id]
1413
inv = self.revision_tree(parent_id).inventory
1414
inventory_cache[parent_id] = inv
1415
parent_entry = inv._byid.get(text_key[0], None)
1416
if parent_entry is not None:
1418
text_key[0], parent_entry.revision)
1420
parent_text_key = None
1421
if parent_text_key is not None:
1422
candidate_parents.append(
1423
text_key_cache[parent_text_key])
1424
parent_heads = text_graph.heads(candidate_parents)
1425
new_parents = list(parent_heads)
1426
new_parents.sort(key=lambda x:candidate_parents.index(x))
1427
if new_parents == []:
1428
new_parents = [NULL_REVISION]
1429
text_index[text_key] = new_parents
1431
for text_key in invalid_keys:
1432
text_index[text_key] = [NULL_REVISION]
1435
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1436
"""Get an iterable listing the keys of all the data introduced by a set
1439
The keys will be ordered so that the corresponding items can be safely
1440
fetched and inserted in that order.
1442
:returns: An iterable producing tuples of (knit-kind, file-id,
1443
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1444
'revisions'. file-id is None unless knit-kind is 'file'.
1446
# XXX: it's a bit weird to control the inventory weave caching in this
1447
# generator. Ideally the caching would be done in fetch.py I think. Or
1448
# maybe this generator should explicitly have the contract that it
1449
# should not be iterated until the previously yielded item has been
1452
inv_w = self.get_inventory_weave()
1453
inv_w.enable_cache()
1455
# file ids that changed
1456
file_ids = self.fileids_altered_by_revision_ids(revision_ids)
1458
num_file_ids = len(file_ids)
1459
for file_id, altered_versions in file_ids.iteritems():
1460
if _files_pb is not None:
1461
_files_pb.update("fetch texts", count, num_file_ids)
1463
yield ("file", file_id, altered_versions)
1464
# We're done with the files_pb. Note that it finished by the caller,
1465
# just as it was created by the caller.
1469
yield ("inventory", None, revision_ids)
1473
revisions_with_signatures = set()
1474
for rev_id in revision_ids:
1476
self.get_signature_text(rev_id)
1477
except errors.NoSuchRevision:
1481
revisions_with_signatures.add(rev_id)
1483
yield ("signatures", None, revisions_with_signatures)
1486
yield ("revisions", None, revision_ids)
579
pb = ui.ui_factory.nested_progress_bar()
581
for line in w.iter_lines_added_or_present_in_versions(
582
selected_revision_ids, pb=pb):
586
# One call to match.group() returning multiple items is quite a
587
# bit faster than 2 calls to match.group() each returning 1
588
file_id, revision_id = match.group('file_id', 'revision_id')
590
# Inlining the cache lookups helps a lot when you make 170,000
591
# lines and 350k ids, versus 8.4 unique ids.
592
# Using a cache helps in 2 ways:
593
# 1) Avoids unnecessary decoding calls
594
# 2) Re-uses cached strings, which helps in future set and
596
# (2) is enough that removing encoding entirely along with
597
# the cache (so we are using plain strings) results in no
598
# performance improvement.
600
revision_id = unescape_revid_cache[revision_id]
602
unescaped = unescape(revision_id)
603
unescape_revid_cache[revision_id] = unescaped
604
revision_id = unescaped
606
if revision_id in selected_revision_ids:
608
file_id = unescape_fileid_cache[file_id]
610
unescaped = unescape(file_id)
611
unescape_fileid_cache[file_id] = unescaped
613
setdefault(file_id, set()).add(revision_id)
1488
618
@needs_read_lock
1489
619
def get_inventory_weave(self):
2369
1351
(copied, failures).
2371
1353
raise NotImplementedError(self.fetch)
2373
def _walk_to_common_revisions(self, revision_ids):
2374
"""Walk out from revision_ids in source to revisions target has.
2376
:param revision_ids: The start point for the search.
2377
:return: A set of revision ids.
2379
graph = self.source.get_graph()
2380
missing_revs = set()
2381
# ensure we don't pay silly lookup costs.
2382
revision_ids = frozenset(revision_ids)
2383
searcher = graph._make_breadth_first_searcher(revision_ids)
2384
null_set = frozenset([_mod_revision.NULL_REVISION])
2387
next_revs, ghosts = searcher.next_with_ghosts()
2388
except StopIteration:
2390
if revision_ids.intersection(ghosts):
2391
absent_ids = set(revision_ids.intersection(ghosts))
2392
# If all absent_ids are present in target, no error is needed.
2393
absent_ids.difference_update(
2394
self.target.has_revisions(absent_ids))
2396
raise errors.NoSuchRevision(self.source, absent_ids.pop())
2397
# we don't care about other ghosts as we can't fetch them and
2398
# haven't been asked to.
2399
next_revs = set(next_revs)
2400
# we always have NULL_REVISION present.
2401
have_revs = self.target.has_revisions(next_revs).union(null_set)
2402
missing_revs.update(next_revs - have_revs)
2403
searcher.stop_searching_any(have_revs)
2404
return searcher.get_result()
2406
@deprecated_method(symbol_versioning.one_two)
2407
1355
@needs_read_lock
2408
def missing_revision_ids(self, revision_id=None, find_ghosts=True):
1356
def missing_revision_ids(self, revision_id=None):
2409
1357
"""Return the revision ids that source has that target does not.
2411
1359
These are returned in topological order.
2413
1361
:param revision_id: only return revision ids included by this
2415
:param find_ghosts: If True find missing revisions in deep history
2416
rather than just finding the surface difference.
2418
return list(self.search_missing_revision_ids(
2419
revision_id, find_ghosts).get_keys())
2422
def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2423
"""Return the revision ids that source has that target does not.
2425
:param revision_id: only return revision ids included by this
2427
:param find_ghosts: If True find missing revisions in deep history
2428
rather than just finding the surface difference.
2429
:return: A bzrlib.graph.SearchResult.
2431
# stop searching at found target revisions.
2432
if not find_ghosts and revision_id is not None:
2433
return self._walk_to_common_revisions([revision_id])
2434
1364
# generic, possibly worst case, slow code path.
2435
1365
target_ids = set(self.target.all_revision_ids())
2436
1366
if revision_id is not None:
1367
# TODO: jam 20070210 InterRepository is internal enough that it
1368
# should assume revision_ids are already utf-8
1369
revision_id = osutils.safe_revision_id(revision_id)
2437
1370
source_ids = self.source.get_ancestry(revision_id)
2438
1371
assert source_ids[0] is None
2439
1372
source_ids.pop(0)
2441
1374
source_ids = self.source.all_revision_ids()
2442
1375
result_set = set(source_ids).difference(target_ids)
2443
return self.source.revision_ids_to_search_result(result_set)
2446
def _same_model(source, target):
2447
"""True if source and target have the same data representation."""
2448
if source.supports_rich_root() != target.supports_rich_root():
2450
if source._serializer != target._serializer:
1376
# this may look like a no-op: its not. It preserves the ordering
1377
# other_ids had while only returning the members from other_ids
1378
# that we've decided we need.
1379
return [rev_id for rev_id in source_ids if rev_id in result_set]
2455
1382
class InterSameDataRepository(InterRepository):
2646
1575
could lead to confusing results, and there is no need to be
2647
1576
overly general.
2649
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
1578
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
2651
are_knits = (isinstance(source._format, RepositoryFormatKnit) and
2652
isinstance(target._format, RepositoryFormatKnit))
1580
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1581
isinstance(target._format, (RepositoryFormatKnit1)))
2653
1582
except AttributeError:
2655
return are_knits and InterRepository._same_model(source, target)
2657
1585
@needs_write_lock
2658
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
1586
def fetch(self, revision_id=None, pb=None):
2659
1587
"""See InterRepository.fetch()."""
2660
1588
from bzrlib.fetch import KnitRepoFetcher
2661
1589
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2662
1590
self.source, self.source._format, self.target, self.target._format)
1591
# TODO: jam 20070210 This should be an assert, not a translate
1592
revision_id = osutils.safe_revision_id(revision_id)
2663
1593
f = KnitRepoFetcher(to_repository=self.target,
2664
1594
from_repository=self.source,
2665
1595
last_revision=revision_id,
2666
pb=pb, find_ghosts=find_ghosts)
2667
1597
return f.count_copied, f.failed_revisions
2669
1599
@needs_read_lock
2670
def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
1600
def missing_revision_ids(self, revision_id=None):
2671
1601
"""See InterRepository.missing_revision_ids()."""
2672
1602
if revision_id is not None:
2673
1603
source_ids = self.source.get_ancestry(revision_id)
2674
1604
assert source_ids[0] is None
2675
1605
source_ids.pop(0)
2677
source_ids = self.source.all_revision_ids()
1607
source_ids = self.source._all_possible_ids()
2678
1608
source_ids_set = set(source_ids)
2679
1609
# source_ids is the worst possible case we may need to pull.
2680
1610
# now we want to filter source_ids against what we actually
2681
1611
# have in target, but don't try to check for existence where we know
2682
1612
# we do not have a revision as that would be pointless.
2683
target_ids = set(self.target.all_revision_ids())
1613
target_ids = set(self.target._all_possible_ids())
2684
1614
possibly_present_revisions = target_ids.intersection(source_ids_set)
2685
actually_present_revisions = set(
2686
self.target._eliminate_revisions_not_present(possibly_present_revisions))
1615
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2687
1616
required_revisions = source_ids_set.difference(actually_present_revisions)
1617
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2688
1618
if revision_id is not None:
2689
1619
# we used get_ancestry to determine source_ids then we are assured all
2690
1620
# revisions referenced are present as they are installed in topological order.
2691
1621
# and the tip revision was validated by get_ancestry.
2692
result_set = required_revisions
1622
return required_topo_revisions
2694
1624
# if we just grabbed the possibly available ids, then
2695
1625
# we only have an estimate of whats available and need to validate
2696
1626
# that against the revision records.
2698
self.source._eliminate_revisions_not_present(required_revisions))
2699
return self.source.revision_ids_to_search_result(result_set)
2702
class InterPackRepo(InterSameDataRepository):
2703
"""Optimised code paths between Pack based repositories."""
2706
def _get_repo_format_to_test(self):
2707
from bzrlib.repofmt import pack_repo
2708
return pack_repo.RepositoryFormatKnitPack1()
2711
def is_compatible(source, target):
2712
"""Be compatible with known Pack formats.
2714
We don't test for the stores being of specific types because that
2715
could lead to confusing results, and there is no need to be
2718
from bzrlib.repofmt.pack_repo import RepositoryFormatPack
2720
are_packs = (isinstance(source._format, RepositoryFormatPack) and
2721
isinstance(target._format, RepositoryFormatPack))
2722
except AttributeError:
2724
return are_packs and InterRepository._same_model(source, target)
2727
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2728
"""See InterRepository.fetch()."""
2729
from bzrlib.repofmt.pack_repo import Packer
2730
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2731
self.source, self.source._format, self.target, self.target._format)
2732
self.count_copied = 0
2733
if revision_id is None:
2735
# everything to do - use pack logic
2736
# to fetch from all packs to one without
2737
# inventory parsing etc, IFF nothing to be copied is in the target.
2739
revision_ids = self.source.all_revision_ids()
2740
# implementing the TODO will involve:
2741
# - detecting when all of a pack is selected
2742
# - avoiding as much as possible pre-selection, so the
2743
# more-core routines such as create_pack_from_packs can filter in
2744
# a just-in-time fashion. (though having a HEADS list on a
2745
# repository might make this a lot easier, because we could
2746
# sensibly detect 'new revisions' without doing a full index scan.
2747
elif _mod_revision.is_null(revision_id):
2752
revision_ids = self.search_missing_revision_ids(revision_id,
2753
find_ghosts=find_ghosts).get_keys()
2754
except errors.NoSuchRevision:
2755
raise errors.InstallFailed([revision_id])
2756
packs = self.source._pack_collection.all_packs()
2757
pack = Packer(self.target._pack_collection, packs, '.fetch',
2758
revision_ids).pack()
2759
if pack is not None:
2760
self.target._pack_collection._save_pack_names()
2761
# Trigger an autopack. This may duplicate effort as we've just done
2762
# a pack creation, but for now it is simpler to think about as
2763
# 'upload data, then repack if needed'.
2764
self.target._pack_collection.autopack()
2765
return (pack.get_revision_count(), [])
2770
def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2771
"""See InterRepository.missing_revision_ids().
2773
:param find_ghosts: Find ghosts throughout the ancestry of
2776
if not find_ghosts and revision_id is not None:
2777
return self._walk_to_common_revisions([revision_id])
2778
elif revision_id is not None:
2779
source_ids = self.source.get_ancestry(revision_id)
2780
assert source_ids[0] is None
2783
source_ids = self.source.all_revision_ids()
2784
# source_ids is the worst possible case we may need to pull.
2785
# now we want to filter source_ids against what we actually
2786
# have in target, but don't try to check for existence where we know
2787
# we do not have a revision as that would be pointless.
2788
target_ids = set(self.target.all_revision_ids())
2789
result_set = set(source_ids).difference(target_ids)
2790
return self.source.revision_ids_to_search_result(result_set)
1627
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2793
1630
class InterModel1and2(InterRepository):
2845
1686
"""Be compatible with Knit1 source and Knit3 target"""
2846
1687
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
2848
from bzrlib.repofmt.knitrepo import (RepositoryFormatKnit1,
2849
RepositoryFormatKnit3)
2850
from bzrlib.repofmt.pack_repo import (
2851
RepositoryFormatKnitPack1,
2852
RepositoryFormatKnitPack3,
2853
RepositoryFormatPackDevelopment0,
2854
RepositoryFormatPackDevelopment0Subtree,
2857
RepositoryFormatKnit1,
2858
RepositoryFormatKnitPack1,
2859
RepositoryFormatPackDevelopment0,
2862
RepositoryFormatKnit3,
2863
RepositoryFormatKnitPack3,
2864
RepositoryFormatPackDevelopment0Subtree,
2866
return (isinstance(source._format, nosubtrees) and
2867
isinstance(target._format, subtrees))
1689
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1690
RepositoryFormatKnit3
1691
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1692
isinstance(target._format, (RepositoryFormatKnit3)))
2868
1693
except AttributeError:
2871
1696
@needs_write_lock
2872
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
1697
def fetch(self, revision_id=None, pb=None):
2873
1698
"""See InterRepository.fetch()."""
2874
1699
from bzrlib.fetch import Knit1to2Fetcher
2875
1700
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2876
1701
self.source, self.source._format, self.target,
2877
1702
self.target._format)
1703
# TODO: jam 20070210 This should be an assert, not a translate
1704
revision_id = osutils.safe_revision_id(revision_id)
2878
1705
f = Knit1to2Fetcher(to_repository=self.target,
2879
1706
from_repository=self.source,
2880
1707
last_revision=revision_id,
2881
pb=pb, find_ghosts=find_ghosts)
2882
return f.count_copied, f.failed_revisions
2885
class InterDifferingSerializer(InterKnitRepo):
2888
def _get_repo_format_to_test(self):
2892
def is_compatible(source, target):
2893
"""Be compatible with Knit2 source and Knit3 target"""
2894
if source.supports_rich_root() != target.supports_rich_root():
2896
# Ideally, we'd support fetching if the source had no tree references
2897
# even if it supported them...
2898
if (getattr(source, '_format.supports_tree_reference', False) and
2899
not getattr(target, '_format.supports_tree_reference', False)):
2904
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2905
"""See InterRepository.fetch()."""
2906
revision_ids = self.target.search_missing_revision_ids(self.source,
2907
revision_id, find_ghosts=find_ghosts).get_keys()
2908
revision_ids = tsort.topo_sort(
2909
self.source.get_graph().get_parent_map(revision_ids))
2910
def revisions_iterator():
2911
for current_revision_id in revision_ids:
2912
revision = self.source.get_revision(current_revision_id)
2913
tree = self.source.revision_tree(current_revision_id)
2915
signature = self.source.get_signature_text(
2916
current_revision_id)
2917
except errors.NoSuchRevision:
2919
yield revision, tree, signature
2921
my_pb = ui.ui_factory.nested_progress_bar()
2926
install_revisions(self.target, revisions_iterator(),
2927
len(revision_ids), pb)
2929
if my_pb is not None:
2931
return len(revision_ids), 0
2934
class InterRemoteToOther(InterRepository):
2936
def __init__(self, source, target):
2937
InterRepository.__init__(self, source, target)
2938
self._real_inter = None
2941
def is_compatible(source, target):
2942
if not isinstance(source, remote.RemoteRepository):
2944
# Is source's model compatible with target's model?
2945
source._ensure_real()
2946
real_source = source._real_repository
2947
assert not isinstance(real_source, remote.RemoteRepository), (
2948
"We don't support remote repos backed by remote repos yet.")
2949
return InterRepository._same_model(real_source, target)
2952
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2953
"""See InterRepository.fetch()."""
2954
from bzrlib.fetch import RemoteToOtherFetcher
2955
mutter("Using fetch logic to copy between %s(remote) and %s(%s)",
2956
self.source, self.target, self.target._format)
2957
# TODO: jam 20070210 This should be an assert, not a translate
2958
revision_id = osutils.safe_revision_id(revision_id)
2959
f = RemoteToOtherFetcher(to_repository=self.target,
2960
from_repository=self.source,
2961
last_revision=revision_id,
2962
pb=pb, find_ghosts=find_ghosts)
2963
return f.count_copied, f.failed_revisions
2966
def _get_repo_format_to_test(self):
2970
class InterOtherToRemote(InterRepository):
2972
def __init__(self, source, target):
2973
InterRepository.__init__(self, source, target)
2974
self._real_inter = None
2977
def is_compatible(source, target):
1709
return f.count_copied, f.failed_revisions
1712
class InterRemoteRepository(InterRepository):
1713
"""Code for converting between RemoteRepository objects.
1715
This just gets an non-remote repository from the RemoteRepository, and calls
1716
InterRepository.get again.
1719
def __init__(self, source, target):
1720
if isinstance(source, remote.RemoteRepository):
1721
source._ensure_real()
1722
real_source = source._real_repository
1724
real_source = source
1725
if isinstance(target, remote.RemoteRepository):
1726
target._ensure_real()
1727
real_target = target._real_repository
1729
real_target = target
1730
self.real_inter = InterRepository.get(real_source, real_target)
1733
def is_compatible(source, target):
1734
if isinstance(source, remote.RemoteRepository):
2978
1736
if isinstance(target, remote.RemoteRepository):
2982
def _ensure_real_inter(self):
2983
if self._real_inter is None:
2984
self.target._ensure_real()
2985
real_target = self.target._real_repository
2986
self._real_inter = InterRepository.get(self.source, real_target)
2988
1740
def copy_content(self, revision_id=None):
2989
self._ensure_real_inter()
2990
self._real_inter.copy_content(revision_id=revision_id)
1741
self.real_inter.copy_content(revision_id=revision_id)
2992
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2993
self._ensure_real_inter()
2994
self._real_inter.fetch(revision_id=revision_id, pb=pb,
2995
find_ghosts=find_ghosts)
1743
def fetch(self, revision_id=None, pb=None):
1744
self.real_inter.fetch(revision_id=revision_id, pb=pb)
2998
1747
def _get_repo_format_to_test(self):
3002
InterRepository.register_optimiser(InterDifferingSerializer)
3003
1751
InterRepository.register_optimiser(InterSameDataRepository)
3004
1752
InterRepository.register_optimiser(InterWeaveRepo)
3005
1753
InterRepository.register_optimiser(InterKnitRepo)
3006
1754
InterRepository.register_optimiser(InterModel1and2)
3007
1755
InterRepository.register_optimiser(InterKnit1and2)
3008
InterRepository.register_optimiser(InterPackRepo)
3009
InterRepository.register_optimiser(InterRemoteToOther)
3010
InterRepository.register_optimiser(InterOtherToRemote)
1756
InterRepository.register_optimiser(InterRemoteRepository)
1759
class RepositoryTestProviderAdapter(object):
1760
"""A tool to generate a suite testing multiple repository formats at once.
1762
This is done by copying the test once for each transport and injecting
1763
the transport_server, transport_readonly_server, and bzrdir_format and
1764
repository_format classes into each copy. Each copy is also given a new id()
1765
to make it easy to identify.
1768
def __init__(self, transport_server, transport_readonly_server, formats,
1769
vfs_transport_factory=None):
1770
self._transport_server = transport_server
1771
self._transport_readonly_server = transport_readonly_server
1772
self._vfs_transport_factory = vfs_transport_factory
1773
self._formats = formats
1775
def adapt(self, test):
1776
result = unittest.TestSuite()
1777
for repository_format, bzrdir_format in self._formats:
1778
from copy import deepcopy
1779
new_test = deepcopy(test)
1780
new_test.transport_server = self._transport_server
1781
new_test.transport_readonly_server = self._transport_readonly_server
1782
# Only override the test's vfs_transport_factory if one was
1783
# specified, otherwise just leave the default in place.
1784
if self._vfs_transport_factory:
1785
new_test.vfs_transport_factory = self._vfs_transport_factory
1786
new_test.bzrdir_format = bzrdir_format
1787
new_test.repository_format = repository_format
1788
def make_new_test_id():
1789
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1790
return lambda: new_id
1791
new_test.id = make_new_test_id()
1792
result.addTest(new_test)
1796
class InterRepositoryTestProviderAdapter(object):
1797
"""A tool to generate a suite testing multiple inter repository formats.
1799
This is done by copying the test once for each interrepo provider and injecting
1800
the transport_server, transport_readonly_server, repository_format and
1801
repository_to_format classes into each copy.
1802
Each copy is also given a new id() to make it easy to identify.
1805
def __init__(self, transport_server, transport_readonly_server, formats):
1806
self._transport_server = transport_server
1807
self._transport_readonly_server = transport_readonly_server
1808
self._formats = formats
1810
def adapt(self, test):
1811
result = unittest.TestSuite()
1812
for interrepo_class, repository_format, repository_format_to in self._formats:
1813
from copy import deepcopy
1814
new_test = deepcopy(test)
1815
new_test.transport_server = self._transport_server
1816
new_test.transport_readonly_server = self._transport_readonly_server
1817
new_test.interrepo_class = interrepo_class
1818
new_test.repository_format = repository_format
1819
new_test.repository_format_to = repository_format_to
1820
def make_new_test_id():
1821
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1822
return lambda: new_id
1823
new_test.id = make_new_test_id()
1824
result.addTest(new_test)
1828
def default_test_list():
1829
"""Generate the default list of interrepo permutations to test."""
1830
from bzrlib.repofmt import knitrepo, weaverepo
1832
# test the default InterRepository between format 6 and the current
1834
# XXX: robertc 20060220 reinstate this when there are two supported
1835
# formats which do not have an optimal code path between them.
1836
#result.append((InterRepository,
1837
# RepositoryFormat6(),
1838
# RepositoryFormatKnit1()))
1839
for optimiser_class in InterRepository._optimisers:
1840
format_to_test = optimiser_class._get_repo_format_to_test()
1841
if format_to_test is not None:
1842
result.append((optimiser_class,
1843
format_to_test, format_to_test))
1844
# if there are specific combinations we want to use, we can add them
1846
result.append((InterModel1and2,
1847
weaverepo.RepositoryFormat5(),
1848
knitrepo.RepositoryFormatKnit3()))
1849
result.append((InterKnit1and2,
1850
knitrepo.RepositoryFormatKnit1(),
1851
knitrepo.RepositoryFormatKnit3()))
3013
1855
class CopyConverter(object):
3062
1904
self.pb.update(message, self.count, self.total)
1907
class CommitBuilder(object):
1908
"""Provides an interface to build up a commit.
1910
This allows describing a tree to be committed without needing to
1911
know the internals of the format of the repository.
1914
record_root_entry = False
1915
def __init__(self, repository, parents, config, timestamp=None,
1916
timezone=None, committer=None, revprops=None,
1918
"""Initiate a CommitBuilder.
1920
:param repository: Repository to commit to.
1921
:param parents: Revision ids of the parents of the new revision.
1922
:param config: Configuration to use.
1923
:param timestamp: Optional timestamp recorded for commit.
1924
:param timezone: Optional timezone for timestamp.
1925
:param committer: Optional committer to set for commit.
1926
:param revprops: Optional dictionary of revision properties.
1927
:param revision_id: Optional revision id.
1929
self._config = config
1931
if committer is None:
1932
self._committer = self._config.username()
1934
assert isinstance(committer, basestring), type(committer)
1935
self._committer = committer
1937
self.new_inventory = Inventory(None)
1938
self._new_revision_id = osutils.safe_revision_id(revision_id)
1939
self.parents = parents
1940
self.repository = repository
1943
if revprops is not None:
1944
self._revprops.update(revprops)
1946
if timestamp is None:
1947
timestamp = time.time()
1948
# Restrict resolution to 1ms
1949
self._timestamp = round(timestamp, 3)
1951
if timezone is None:
1952
self._timezone = osutils.local_time_offset()
1954
self._timezone = int(timezone)
1956
self._generate_revision_if_needed()
1958
def commit(self, message):
1959
"""Make the actual commit.
1961
:return: The revision id of the recorded revision.
1963
rev = _mod_revision.Revision(
1964
timestamp=self._timestamp,
1965
timezone=self._timezone,
1966
committer=self._committer,
1968
inventory_sha1=self.inv_sha1,
1969
revision_id=self._new_revision_id,
1970
properties=self._revprops)
1971
rev.parent_ids = self.parents
1972
self.repository.add_revision(self._new_revision_id, rev,
1973
self.new_inventory, self._config)
1974
return self._new_revision_id
1976
def revision_tree(self):
1977
"""Return the tree that was just committed.
1979
After calling commit() this can be called to get a RevisionTree
1980
representing the newly committed tree. This is preferred to
1981
calling Repository.revision_tree() because that may require
1982
deserializing the inventory, while we already have a copy in
1985
return RevisionTree(self.repository, self.new_inventory,
1986
self._new_revision_id)
1988
def finish_inventory(self):
1989
"""Tell the builder that the inventory is finished."""
1990
if self.new_inventory.root is None:
1991
symbol_versioning.warn('Root entry should be supplied to'
1992
' record_entry_contents, as of bzr 0.10.',
1993
DeprecationWarning, stacklevel=2)
1994
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1995
self.new_inventory.revision_id = self._new_revision_id
1996
self.inv_sha1 = self.repository.add_inventory(
1997
self._new_revision_id,
2002
def _gen_revision_id(self):
2003
"""Return new revision-id."""
2004
return generate_ids.gen_revision_id(self._config.username(),
2007
def _generate_revision_if_needed(self):
2008
"""Create a revision id if None was supplied.
2010
If the repository can not support user-specified revision ids
2011
they should override this function and raise CannotSetRevisionId
2012
if _new_revision_id is not None.
2014
:raises: CannotSetRevisionId
2016
if self._new_revision_id is None:
2017
self._new_revision_id = self._gen_revision_id()
2019
def record_entry_contents(self, ie, parent_invs, path, tree):
2020
"""Record the content of ie from tree into the commit if needed.
2022
Side effect: sets ie.revision when unchanged
2024
:param ie: An inventory entry present in the commit.
2025
:param parent_invs: The inventories of the parent revisions of the
2027
:param path: The path the entry is at in the tree.
2028
:param tree: The tree which contains this entry and should be used to
2031
if self.new_inventory.root is None and ie.parent_id is not None:
2032
symbol_versioning.warn('Root entry should be supplied to'
2033
' record_entry_contents, as of bzr 0.10.',
2034
DeprecationWarning, stacklevel=2)
2035
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2037
self.new_inventory.add(ie)
2039
# ie.revision is always None if the InventoryEntry is considered
2040
# for committing. ie.snapshot will record the correct revision
2041
# which may be the sole parent if it is untouched.
2042
if ie.revision is not None:
2045
# In this revision format, root entries have no knit or weave
2046
if ie is self.new_inventory.root:
2047
# When serializing out to disk and back in
2048
# root.revision is always _new_revision_id
2049
ie.revision = self._new_revision_id
2051
previous_entries = ie.find_previous_heads(
2053
self.repository.weave_store,
2054
self.repository.get_transaction())
2055
# we are creating a new revision for ie in the history store
2057
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2059
def modified_directory(self, file_id, file_parents):
2060
"""Record the presence of a symbolic link.
2062
:param file_id: The file_id of the link to record.
2063
:param file_parents: The per-file parent revision ids.
2065
self._add_text_to_weave(file_id, [], file_parents.keys())
2067
def modified_reference(self, file_id, file_parents):
2068
"""Record the modification of a reference.
2070
:param file_id: The file_id of the link to record.
2071
:param file_parents: The per-file parent revision ids.
2073
self._add_text_to_weave(file_id, [], file_parents.keys())
2075
def modified_file_text(self, file_id, file_parents,
2076
get_content_byte_lines, text_sha1=None,
2078
"""Record the text of file file_id
2080
:param file_id: The file_id of the file to record the text of.
2081
:param file_parents: The per-file parent revision ids.
2082
:param get_content_byte_lines: A callable which will return the byte
2084
:param text_sha1: Optional SHA1 of the file contents.
2085
:param text_size: Optional size of the file contents.
2087
# mutter('storing text of file {%s} in revision {%s} into %r',
2088
# file_id, self._new_revision_id, self.repository.weave_store)
2089
# special case to avoid diffing on renames or
2091
if (len(file_parents) == 1
2092
and text_sha1 == file_parents.values()[0].text_sha1
2093
and text_size == file_parents.values()[0].text_size):
2094
previous_ie = file_parents.values()[0]
2095
versionedfile = self.repository.weave_store.get_weave(file_id,
2096
self.repository.get_transaction())
2097
versionedfile.clone_text(self._new_revision_id,
2098
previous_ie.revision, file_parents.keys())
2099
return text_sha1, text_size
2101
new_lines = get_content_byte_lines()
2102
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2103
# should return the SHA1 and size
2104
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2105
return osutils.sha_strings(new_lines), \
2106
sum(map(len, new_lines))
2108
def modified_link(self, file_id, file_parents, link_target):
2109
"""Record the presence of a symbolic link.
2111
:param file_id: The file_id of the link to record.
2112
:param file_parents: The per-file parent revision ids.
2113
:param link_target: Target location of this link.
2115
self._add_text_to_weave(file_id, [], file_parents.keys())
2117
def _add_text_to_weave(self, file_id, new_lines, parents):
2118
versionedfile = self.repository.weave_store.get_weave_or_empty(
2119
file_id, self.repository.get_transaction())
2120
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2121
versionedfile.clear_cache()
2124
class _CommitBuilder(CommitBuilder):
2125
"""Temporary class so old CommitBuilders are detected properly
2127
Note: CommitBuilder works whether or not root entry is recorded.
2130
record_root_entry = True
2133
class RootCommitBuilder(CommitBuilder):
2134
"""This commitbuilder actually records the root id"""
2136
record_root_entry = True
2138
def record_entry_contents(self, ie, parent_invs, path, tree):
2139
"""Record the content of ie from tree into the commit if needed.
2141
Side effect: sets ie.revision when unchanged
2143
:param ie: An inventory entry present in the commit.
2144
:param parent_invs: The inventories of the parent revisions of the
2146
:param path: The path the entry is at in the tree.
2147
:param tree: The tree which contains this entry and should be used to
2150
assert self.new_inventory.root is not None or ie.parent_id is None
2151
self.new_inventory.add(ie)
2153
# ie.revision is always None if the InventoryEntry is considered
2154
# for committing. ie.snapshot will record the correct revision
2155
# which may be the sole parent if it is untouched.
2156
if ie.revision is not None:
2159
previous_entries = ie.find_previous_heads(
2161
self.repository.weave_store,
2162
self.repository.get_transaction())
2163
# we are creating a new revision for ie in the history store
2165
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
3065
2168
_unescape_map = {