52
56
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
53
57
from bzrlib.symbol_versioning import (
57
from bzrlib.trace import mutter, note, warning
60
from bzrlib.trace import mutter, mutter_callsite, note, warning
60
63
# Old formats display a warning, but only once
61
64
_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.
64
448
######################################################################
323
766
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 insert_data_stream(self, stream):
816
"""XXX What does this really do?
818
Is it a substitute for fetch?
819
Should it manage its own write group ?
821
for item_key, bytes in stream:
822
if item_key[0] == 'file':
823
(file_id,) = item_key[1:]
824
knit = self.weave_store.get_weave_or_empty(
825
file_id, self.get_transaction())
826
elif item_key == ('inventory',):
827
knit = self.get_inventory_weave()
828
elif item_key == ('revisions',):
829
knit = self._revision_store.get_revision_file(
830
self.get_transaction())
831
elif item_key == ('signatures',):
832
knit = self._revision_store.get_signature_file(
833
self.get_transaction())
835
raise RepositoryDataStreamError(
836
"Unrecognised data stream key '%s'" % (item_key,))
837
decoded_list = bencode.bdecode(bytes)
838
format = decoded_list.pop(0)
841
for version, options, parents, some_bytes in decoded_list:
842
data_list.append((version, options, len(some_bytes), parents))
843
knit_bytes += some_bytes
844
knit.insert_data_stream(
845
(format, data_list, StringIO(knit_bytes).read))
327
def missing_revision_ids(self, other, revision_id=None):
848
def missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
328
849
"""Return the revision ids that other has that this does not.
330
851
These are returned in topological order.
332
853
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)
855
return InterRepository.get(other, self).missing_revision_ids(
856
revision_id, find_ghosts)
350
871
This is a destructive operation! Do not use it on existing
353
revision_id = osutils.safe_revision_id(revision_id)
354
874
return InterRepository.get(self, destination).copy_content(revision_id)
356
def fetch(self, source, revision_id=None, pb=None):
876
def commit_write_group(self):
877
"""Commit the contents accrued within the current write group.
879
:seealso: start_write_group.
881
if self._write_group is not self.get_transaction():
882
# has an unlock or relock occured ?
883
raise errors.BzrError('mismatched lock context %r and '
885
(self.get_transaction(), self._write_group))
886
self._commit_write_group()
887
self._write_group = None
889
def _commit_write_group(self):
890
"""Template method for per-repository write group cleanup.
892
This is called before the write group is considered to be
893
finished and should ensure that all data handed to the repository
894
for writing during the write group is safely committed (to the
895
extent possible considering file system caching etc).
898
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
357
899
"""Fetch the content required to construct revision_id from source.
359
901
If revision_id is None all content is copied.
902
:param find_ghosts: Find and copy revisions in the source that are
903
ghosts in the target (and not reachable directly by walking out to
904
the first-present revision in target from revision_id).
361
revision_id = osutils.safe_revision_id(revision_id)
906
# fast path same-url fetch operations
907
if self.has_same_location(source):
908
# check that last_revision is in 'from' and then return a
910
if (revision_id is not None and
911
not _mod_revision.is_null(revision_id)):
912
self.get_revision(revision_id)
362
914
inter = InterRepository.get(source, self)
364
return inter.fetch(revision_id=revision_id, pb=pb)
916
return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
365
917
except NotImplementedError:
366
918
raise errors.IncompatibleRepositories(source, self)
368
def get_commit_builder(self, branch, parents, config, timestamp=None,
369
timezone=None, committer=None, revprops=None,
920
def create_bundle(self, target, base, fileobj, format=None):
921
return serializer.write_bundle(self, target, base, fileobj, format)
923
def get_commit_builder(self, branch, parents, config, timestamp=None,
924
timezone=None, committer=None, revprops=None,
370
925
revision_id=None):
371
926
"""Obtain a CommitBuilder for this repository.
517
1102
r = self.get_revision(revision_id)
518
1103
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)
536
1105
@needs_write_lock
537
1106
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
538
revision_id = osutils.safe_revision_id(revision_id)
539
1107
signature = gpg_strategy.sign(plaintext)
1108
self.add_signature_text(revision_id, signature)
1111
def add_signature_text(self, revision_id, signature):
540
1112
self._revision_store.add_revision_signature_text(revision_id,
542
1114
self.get_transaction())
544
def fileids_altered_by_revision_ids(self, revision_ids):
545
"""Find the file ids and versions affected by revisions.
1116
def find_text_key_references(self):
1117
"""Find the text key references within the repository.
547
:param revisions: an iterable containing revision ids.
548
:return: a dictionary mapping altered file-ids to an iterable of
1119
:return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
549
1120
revision_ids. Each altered file-ids has the exact revision_ids that
550
1121
altered it listed explicitly.
1122
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1123
to whether they were referred to by the inventory of the
1124
revision_id that they contain. The inventory texts from all present
1125
revision ids are assessed to generate this report.
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)
1127
revision_ids = self.all_revision_ids()
557
1128
w = self.get_inventory_weave()
1129
pb = ui.ui_factory.nested_progress_bar()
1131
return self._find_text_key_references_from_xml_inventory_lines(
1132
w.iter_lines_added_or_present_in_versions(revision_ids, pb=pb))
1136
def _find_text_key_references_from_xml_inventory_lines(self,
1138
"""Core routine for extracting references to texts from inventories.
1140
This performs the translation of xml lines to revision ids.
1142
:param line_iterator: An iterator of lines, origin_version_id
1143
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1144
to whether they were referred to by the inventory of the
1145
revision_id that they contain. Note that if that revision_id was
1146
not part of the line_iterator's output then False will be given -
1147
even though it may actually refer to that key.
1149
if not self._serializer.support_altered_by_hack:
1150
raise AssertionError(
1151
"_find_text_key_references_from_xml_inventory_lines only "
1152
"supported for branches which store inventory as unnested xml"
1153
", not on %r" % self)
560
1156
# this code needs to read every new line in every inventory for the
576
1172
search = self._file_ids_altered_regex.search
577
1173
unescape = _unescape_xml
578
1174
setdefault = result.setdefault
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)
1175
for line, version_id in line_iterator:
1176
match = search(line)
1179
# One call to match.group() returning multiple items is quite a
1180
# bit faster than 2 calls to match.group() each returning 1
1181
file_id, revision_id = match.group('file_id', 'revision_id')
1183
# Inlining the cache lookups helps a lot when you make 170,000
1184
# lines and 350k ids, versus 8.4 unique ids.
1185
# Using a cache helps in 2 ways:
1186
# 1) Avoids unnecessary decoding calls
1187
# 2) Re-uses cached strings, which helps in future set and
1189
# (2) is enough that removing encoding entirely along with
1190
# the cache (so we are using plain strings) results in no
1191
# performance improvement.
1193
revision_id = unescape_revid_cache[revision_id]
1195
unescaped = unescape(revision_id)
1196
unescape_revid_cache[revision_id] = unescaped
1197
revision_id = unescaped
1199
# Note that unconditionally unescaping means that we deserialise
1200
# every fileid, which for general 'pull' is not great, but we don't
1201
# really want to have some many fulltexts that this matters anyway.
1204
file_id = unescape_fileid_cache[file_id]
1206
unescaped = unescape(file_id)
1207
unescape_fileid_cache[file_id] = unescaped
1210
key = (file_id, revision_id)
1211
setdefault(key, False)
1212
if revision_id == version_id:
1216
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1218
"""Helper routine for fileids_altered_by_revision_ids.
1220
This performs the translation of xml lines to revision ids.
1222
:param line_iterator: An iterator of lines, origin_version_id
1223
:param revision_ids: The revision ids to filter for. This should be a
1224
set or other type which supports efficient __contains__ lookups, as
1225
the revision id from each parsed line will be looked up in the
1226
revision_ids filter.
1227
:return: a dictionary mapping altered file-ids to an iterable of
1228
revision_ids. Each altered file-ids has the exact revision_ids that
1229
altered it listed explicitly.
1232
setdefault = result.setdefault
1233
for file_id, revision_id in \
1234
self._find_text_key_references_from_xml_inventory_lines(
1235
line_iterator).iterkeys():
1236
# once data is all ensured-consistent; then this is
1237
# if revision_id == version_id
1238
if revision_id in revision_ids:
1239
setdefault(file_id, set()).add(revision_id)
1242
def fileids_altered_by_revision_ids(self, revision_ids):
1243
"""Find the file ids and versions affected by revisions.
1245
:param revisions: an iterable containing revision ids.
1246
:return: a dictionary mapping altered file-ids to an iterable of
1247
revision_ids. Each altered file-ids has the exact revision_ids that
1248
altered it listed explicitly.
1250
selected_revision_ids = set(revision_ids)
1251
w = self.get_inventory_weave()
1252
pb = ui.ui_factory.nested_progress_bar()
1254
return self._find_file_ids_from_xml_inventory_lines(
1255
w.iter_lines_added_or_present_in_versions(
1256
selected_revision_ids, pb=pb),
1257
selected_revision_ids)
1261
def iter_files_bytes(self, desired_files):
1262
"""Iterate through file versions.
1264
Files will not necessarily be returned in the order they occur in
1265
desired_files. No specific order is guaranteed.
1267
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1268
value supplied by the caller as part of desired_files. It should
1269
uniquely identify the file version in the caller's context. (Examples:
1270
an index number or a TreeTransform trans_id.)
1272
bytes_iterator is an iterable of bytestrings for the file. The
1273
kind of iterable and length of the bytestrings are unspecified, but for
1274
this implementation, it is a list of lines produced by
1275
VersionedFile.get_lines().
1277
:param desired_files: a list of (file_id, revision_id, identifier)
1280
transaction = self.get_transaction()
1281
for file_id, revision_id, callable_data in desired_files:
1283
weave = self.weave_store.get_weave(file_id, transaction)
1284
except errors.NoSuchFile:
1285
raise errors.NoSuchIdInRepository(self, file_id)
1286
yield callable_data, weave.get_lines(revision_id)
1288
def _generate_text_key_index(self, text_key_references=None,
1290
"""Generate a new text key index for the repository.
1292
This is an expensive function that will take considerable time to run.
1294
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1295
list of parents, also text keys. When a given key has no parents,
1296
the parents list will be [NULL_REVISION].
1298
# All revisions, to find inventory parents.
1299
if ancestors is None:
1300
revision_graph = self.get_revision_graph_with_ghosts()
1301
ancestors = revision_graph.get_ancestors()
1302
if text_key_references is None:
1303
text_key_references = self.find_text_key_references()
1304
pb = ui.ui_factory.nested_progress_bar()
1306
return self._do_generate_text_key_index(ancestors,
1307
text_key_references, pb)
1311
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1312
"""Helper for _generate_text_key_index to avoid deep nesting."""
1313
revision_order = tsort.topo_sort(ancestors)
1314
invalid_keys = set()
1316
for revision_id in revision_order:
1317
revision_keys[revision_id] = set()
1318
text_count = len(text_key_references)
1319
# a cache of the text keys to allow reuse; costs a dict of all the
1320
# keys, but saves a 2-tuple for every child of a given key.
1322
for text_key, valid in text_key_references.iteritems():
1324
invalid_keys.add(text_key)
1326
revision_keys[text_key[1]].add(text_key)
1327
text_key_cache[text_key] = text_key
1328
del text_key_references
1330
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1331
NULL_REVISION = _mod_revision.NULL_REVISION
1332
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1333
# too small for large or very branchy trees. However, for 55K path
1334
# trees, it would be easy to use too much memory trivially. Ideally we
1335
# could gauge this by looking at available real memory etc, but this is
1336
# always a tricky proposition.
1337
inventory_cache = lru_cache.LRUCache(10)
1338
batch_size = 10 # should be ~150MB on a 55K path tree
1339
batch_count = len(revision_order) / batch_size + 1
1341
pb.update("Calculating text parents.", processed_texts, text_count)
1342
for offset in xrange(batch_count):
1343
to_query = revision_order[offset * batch_size:(offset + 1) *
1347
for rev_tree in self.revision_trees(to_query):
1348
revision_id = rev_tree.get_revision_id()
1349
parent_ids = ancestors[revision_id]
1350
for text_key in revision_keys[revision_id]:
1351
pb.update("Calculating text parents.", processed_texts)
1352
processed_texts += 1
1353
candidate_parents = []
1354
for parent_id in parent_ids:
1355
parent_text_key = (text_key[0], parent_id)
1357
check_parent = parent_text_key not in \
1358
revision_keys[parent_id]
1360
# the parent parent_id is a ghost:
1361
check_parent = False
1362
# truncate the derived graph against this ghost.
1363
parent_text_key = None
1365
# look at the parent commit details inventories to
1366
# determine possible candidates in the per file graph.
1369
inv = inventory_cache[parent_id]
1371
inv = self.revision_tree(parent_id).inventory
1372
inventory_cache[parent_id] = inv
1373
parent_entry = inv._byid.get(text_key[0], None)
1374
if parent_entry is not None:
1376
text_key[0], parent_entry.revision)
1378
parent_text_key = None
1379
if parent_text_key is not None:
1380
candidate_parents.append(
1381
text_key_cache[parent_text_key])
1382
parent_heads = text_graph.heads(candidate_parents)
1383
new_parents = list(parent_heads)
1384
new_parents.sort(key=lambda x:candidate_parents.index(x))
1385
if new_parents == []:
1386
new_parents = [NULL_REVISION]
1387
text_index[text_key] = new_parents
1389
for text_key in invalid_keys:
1390
text_index[text_key] = [NULL_REVISION]
1393
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1394
"""Get an iterable listing the keys of all the data introduced by a set
1397
The keys will be ordered so that the corresponding items can be safely
1398
fetched and inserted in that order.
1400
:returns: An iterable producing tuples of (knit-kind, file-id,
1401
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1402
'revisions'. file-id is None unless knit-kind is 'file'.
1404
# XXX: it's a bit weird to control the inventory weave caching in this
1405
# generator. Ideally the caching would be done in fetch.py I think. Or
1406
# maybe this generator should explicitly have the contract that it
1407
# should not be iterated until the previously yielded item has been
1410
inv_w = self.get_inventory_weave()
1411
inv_w.enable_cache()
1413
# file ids that changed
1414
file_ids = self.fileids_altered_by_revision_ids(revision_ids)
1416
num_file_ids = len(file_ids)
1417
for file_id, altered_versions in file_ids.iteritems():
1418
if _files_pb is not None:
1419
_files_pb.update("fetch texts", count, num_file_ids)
1421
yield ("file", file_id, altered_versions)
1422
# We're done with the files_pb. Note that it finished by the caller,
1423
# just as it was created by the caller.
1427
yield ("inventory", None, revision_ids)
1431
revisions_with_signatures = set()
1432
for rev_id in revision_ids:
1434
self.get_signature_text(rev_id)
1435
except errors.NoSuchRevision:
1439
revisions_with_signatures.add(rev_id)
1441
yield ("signatures", None, revisions_with_signatures)
1444
yield ("revisions", None, revision_ids)
618
1446
@needs_read_lock
619
1447
def get_inventory_weave(self):
1627
2550
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2553
class InterPackRepo(InterSameDataRepository):
2554
"""Optimised code paths between Pack based repositories."""
2557
def _get_repo_format_to_test(self):
2558
from bzrlib.repofmt import pack_repo
2559
return pack_repo.RepositoryFormatKnitPack1()
2562
def is_compatible(source, target):
2563
"""Be compatible with known Pack formats.
2565
We don't test for the stores being of specific types because that
2566
could lead to confusing results, and there is no need to be
2569
from bzrlib.repofmt.pack_repo import RepositoryFormatPack
2571
are_packs = (isinstance(source._format, RepositoryFormatPack) and
2572
isinstance(target._format, RepositoryFormatPack))
2573
except AttributeError:
2575
return are_packs and InterRepository._same_model(source, target)
2578
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2579
"""See InterRepository.fetch()."""
2580
from bzrlib.repofmt.pack_repo import Packer
2581
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2582
self.source, self.source._format, self.target, self.target._format)
2583
self.count_copied = 0
2584
if revision_id is None:
2586
# everything to do - use pack logic
2587
# to fetch from all packs to one without
2588
# inventory parsing etc, IFF nothing to be copied is in the target.
2590
revision_ids = self.source.all_revision_ids()
2591
# implementing the TODO will involve:
2592
# - detecting when all of a pack is selected
2593
# - avoiding as much as possible pre-selection, so the
2594
# more-core routines such as create_pack_from_packs can filter in
2595
# a just-in-time fashion. (though having a HEADS list on a
2596
# repository might make this a lot easier, because we could
2597
# sensibly detect 'new revisions' without doing a full index scan.
2598
elif _mod_revision.is_null(revision_id):
2603
revision_ids = self.missing_revision_ids(revision_id,
2604
find_ghosts=find_ghosts)
2605
except errors.NoSuchRevision:
2606
raise errors.InstallFailed([revision_id])
2607
packs = self.source._pack_collection.all_packs()
2608
pack = Packer(self.target._pack_collection, packs, '.fetch',
2609
revision_ids).pack()
2610
if pack is not None:
2611
self.target._pack_collection._save_pack_names()
2612
# Trigger an autopack. This may duplicate effort as we've just done
2613
# a pack creation, but for now it is simpler to think about as
2614
# 'upload data, then repack if needed'.
2615
self.target._pack_collection.autopack()
2616
return (pack.get_revision_count(), [])
2621
def missing_revision_ids(self, revision_id=None, find_ghosts=True):
2622
"""See InterRepository.missing_revision_ids().
2624
:param find_ghosts: Find ghosts throughough the ancestry of
2627
if not find_ghosts and revision_id is not None:
2628
graph = self.source.get_graph()
2629
missing_revs = set()
2630
searcher = graph._make_breadth_first_searcher([revision_id])
2632
self.target._pack_collection.revision_index.combined_index
2633
null_set = frozenset([_mod_revision.NULL_REVISION])
2636
next_revs = set(searcher.next())
2637
except StopIteration:
2639
next_revs.difference_update(null_set)
2640
target_keys = [(key,) for key in next_revs]
2641
have_revs = frozenset(node[1][0] for node in
2642
target_index.iter_entries(target_keys))
2643
missing_revs.update(next_revs - have_revs)
2644
searcher.stop_searching_any(have_revs)
2645
if next_revs - have_revs == set([revision_id]):
2646
# we saw the start rev itself, but no parents from it (or
2647
# next_revs would have been updated to e.g. set(). We remove
2648
# have_revs because if we found revision_id locally we
2649
# stop_searching at the first time around.
2650
raise errors.NoSuchRevision(self.source, revision_id)
2652
elif revision_id is not None:
2653
source_ids = self.source.get_ancestry(revision_id)
2654
assert source_ids[0] is None
2657
source_ids = self.source.all_revision_ids()
2658
# source_ids is the worst possible case we may need to pull.
2659
# now we want to filter source_ids against what we actually
2660
# have in target, but don't try to check for existence where we know
2661
# we do not have a revision as that would be pointless.
2662
target_ids = set(self.target.all_revision_ids())
2663
return [r for r in source_ids if (r not in target_ids)]
1630
2666
class InterModel1and2(InterRepository):
1709
2744
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):
2747
class InterDifferingSerializer(InterKnitRepo):
2750
def _get_repo_format_to_test(self):
2754
def is_compatible(source, target):
2755
"""Be compatible with Knit2 source and Knit3 target"""
2756
if source.supports_rich_root() != target.supports_rich_root():
2758
# Ideally, we'd support fetching if the source had no tree references
2759
# even if it supported them...
2760
if (getattr(source, '_format.supports_tree_reference', False) and
2761
not getattr(target, '_format.supports_tree_reference', False)):
2766
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2767
"""See InterRepository.fetch()."""
2768
revision_ids = self.target.missing_revision_ids(self.source,
2770
def revisions_iterator():
2771
for current_revision_id in revision_ids:
2772
revision = self.source.get_revision(current_revision_id)
2773
tree = self.source.revision_tree(current_revision_id)
2775
signature = self.source.get_signature_text(
2776
current_revision_id)
2777
except errors.NoSuchRevision:
2779
yield revision, tree, signature
2780
install_revisions(self.target, revisions_iterator())
2781
return len(revision_ids), 0
2784
class InterRemoteToOther(InterRepository):
2786
def __init__(self, source, target):
2787
InterRepository.__init__(self, source, target)
2788
self._real_inter = None
2791
def is_compatible(source, target):
2792
if not isinstance(source, remote.RemoteRepository):
2794
source._ensure_real()
2795
real_source = source._real_repository
2796
# Is source's model compatible with target's model, and are they the
2797
# same format? Currently we can only optimise fetching from an
2798
# identical model & format repo.
2799
assert not isinstance(real_source, remote.RemoteRepository), (
2800
"We don't support remote repos backed by remote repos yet.")
2801
return real_source._format == target._format
2804
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2805
"""See InterRepository.fetch()."""
2806
from bzrlib.fetch import RemoteToOtherFetcher
2807
mutter("Using fetch logic to copy between %s(remote) and %s(%s)",
2808
self.source, self.target, self.target._format)
2809
# TODO: jam 20070210 This should be an assert, not a translate
2810
revision_id = osutils.safe_revision_id(revision_id)
2811
f = RemoteToOtherFetcher(to_repository=self.target,
2812
from_repository=self.source,
2813
last_revision=revision_id,
2815
return f.count_copied, f.failed_revisions
2818
def _get_repo_format_to_test(self):
2822
class InterOtherToRemote(InterRepository):
2824
def __init__(self, source, target):
2825
InterRepository.__init__(self, source, target)
2826
self._real_inter = None
2829
def is_compatible(source, target):
1736
2830
if isinstance(target, remote.RemoteRepository):
2834
def _ensure_real_inter(self):
2835
if self._real_inter is None:
2836
self.target._ensure_real()
2837
real_target = self.target._real_repository
2838
self._real_inter = InterRepository.get(self.source, real_target)
1740
2840
def copy_content(self, revision_id=None):
1741
self.real_inter.copy_content(revision_id=revision_id)
2841
self._ensure_real_inter()
2842
self._real_inter.copy_content(revision_id=revision_id)
1743
def fetch(self, revision_id=None, pb=None):
1744
self.real_inter.fetch(revision_id=revision_id, pb=pb)
2844
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2845
self._ensure_real_inter()
2846
self._real_inter.fetch(revision_id=revision_id, pb=pb)
1747
2849
def _get_repo_format_to_test(self):
2853
InterRepository.register_optimiser(InterDifferingSerializer)
1751
2854
InterRepository.register_optimiser(InterSameDataRepository)
1752
2855
InterRepository.register_optimiser(InterWeaveRepo)
1753
2856
InterRepository.register_optimiser(InterKnitRepo)
1754
2857
InterRepository.register_optimiser(InterModel1and2)
1755
2858
InterRepository.register_optimiser(InterKnit1and2)
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()))
2859
InterRepository.register_optimiser(InterPackRepo)
2860
InterRepository.register_optimiser(InterRemoteToOther)
2861
InterRepository.register_optimiser(InterOtherToRemote)
1855
2864
class CopyConverter(object):
1904
2913
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)
2168
2916
_unescape_map = {