1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from cStringIO import StringIO
19
from bzrlib.lazy_import import lazy_import
20
lazy_import(globals(), """
39
revision as _mod_revision,
45
from bzrlib.bundle import serializer
46
from bzrlib.revisiontree import RevisionTree
47
from bzrlib.store.versioned import VersionedFileStore
48
from bzrlib.store.text import TextStore
49
from bzrlib.testament import Testament
50
from bzrlib.util import bencode
53
from bzrlib.decorators import needs_read_lock, needs_write_lock
54
from bzrlib.inter import InterObject
55
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
56
from bzrlib.symbol_versioning import (
59
from bzrlib.trace import mutter, mutter_callsite, note, warning
62
# Old formats display a warning, but only once
63
_deprecation_warning_done = False
66
class CommitBuilder(object):
67
"""Provides an interface to build up a commit.
69
This allows describing a tree to be committed without needing to
70
know the internals of the format of the repository.
73
# all clients should supply tree roots.
74
record_root_entry = True
75
# the default CommitBuilder does not manage trees whose root is versioned.
76
_versioned_root = False
78
def __init__(self, repository, parents, config, timestamp=None,
79
timezone=None, committer=None, revprops=None,
81
"""Initiate a CommitBuilder.
83
:param repository: Repository to commit to.
84
:param parents: Revision ids of the parents of the new revision.
85
:param config: Configuration to use.
86
:param timestamp: Optional timestamp recorded for commit.
87
:param timezone: Optional timezone for timestamp.
88
:param committer: Optional committer to set for commit.
89
:param revprops: Optional dictionary of revision properties.
90
:param revision_id: Optional revision id.
95
self._committer = self._config.username()
97
self._committer = committer
99
self.new_inventory = Inventory(None)
100
self._new_revision_id = revision_id
101
self.parents = parents
102
self.repository = repository
105
if revprops is not None:
106
self._revprops.update(revprops)
108
if timestamp is None:
109
timestamp = time.time()
110
# Restrict resolution to 1ms
111
self._timestamp = round(timestamp, 3)
114
self._timezone = osutils.local_time_offset()
116
self._timezone = int(timezone)
118
self._generate_revision_if_needed()
119
self.__heads = graph.HeadsCache(repository.get_graph()).heads
121
def commit(self, message):
122
"""Make the actual commit.
124
:return: The revision id of the recorded revision.
126
rev = _mod_revision.Revision(
127
timestamp=self._timestamp,
128
timezone=self._timezone,
129
committer=self._committer,
131
inventory_sha1=self.inv_sha1,
132
revision_id=self._new_revision_id,
133
properties=self._revprops)
134
rev.parent_ids = self.parents
135
self.repository.add_revision(self._new_revision_id, rev,
136
self.new_inventory, self._config)
137
self.repository.commit_write_group()
138
return self._new_revision_id
141
"""Abort the commit that is being built.
143
self.repository.abort_write_group()
145
def revision_tree(self):
146
"""Return the tree that was just committed.
148
After calling commit() this can be called to get a RevisionTree
149
representing the newly committed tree. This is preferred to
150
calling Repository.revision_tree() because that may require
151
deserializing the inventory, while we already have a copy in
154
return RevisionTree(self.repository, self.new_inventory,
155
self._new_revision_id)
157
def finish_inventory(self):
158
"""Tell the builder that the inventory is finished."""
159
if self.new_inventory.root is None:
160
raise AssertionError('Root entry should be supplied to'
161
' record_entry_contents, as of bzr 0.10.',
162
DeprecationWarning, stacklevel=2)
163
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
164
self.new_inventory.revision_id = self._new_revision_id
165
self.inv_sha1 = self.repository.add_inventory(
166
self._new_revision_id,
171
def _gen_revision_id(self):
172
"""Return new revision-id."""
173
return generate_ids.gen_revision_id(self._config.username(),
176
def _generate_revision_if_needed(self):
177
"""Create a revision id if None was supplied.
179
If the repository can not support user-specified revision ids
180
they should override this function and raise CannotSetRevisionId
181
if _new_revision_id is not None.
183
:raises: CannotSetRevisionId
185
if self._new_revision_id is None:
186
self._new_revision_id = self._gen_revision_id()
187
self.random_revid = True
189
self.random_revid = False
191
def _heads(self, file_id, revision_ids):
192
"""Calculate the graph heads for revision_ids in the graph of file_id.
194
This can use either a per-file graph or a global revision graph as we
195
have an identity relationship between the two graphs.
197
return self.__heads(revision_ids)
199
def _check_root(self, ie, parent_invs, tree):
200
"""Helper for record_entry_contents.
202
:param ie: An entry being added.
203
:param parent_invs: The inventories of the parent revisions of the
205
:param tree: The tree that is being committed.
207
# In this revision format, root entries have no knit or weave When
208
# serializing out to disk and back in root.revision is always
210
ie.revision = self._new_revision_id
212
def _get_delta(self, ie, basis_inv, path):
213
"""Get a delta against the basis inventory for ie."""
214
if ie.file_id not in basis_inv:
216
return (None, path, ie.file_id, ie)
217
elif ie != basis_inv[ie.file_id]:
219
# TODO: avoid tis id2path call.
220
return (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
225
def record_entry_contents(self, ie, parent_invs, path, tree,
227
"""Record the content of ie from tree into the commit if needed.
229
Side effect: sets ie.revision when unchanged
231
:param ie: An inventory entry present in the commit.
232
:param parent_invs: The inventories of the parent revisions of the
234
:param path: The path the entry is at in the tree.
235
:param tree: The tree which contains this entry and should be used to
237
:param content_summary: Summary data from the tree about the paths
238
content - stat, length, exec, sha/link target. This is only
239
accessed when the entry has a revision of None - that is when it is
240
a candidate to commit.
241
:return: A tuple (change_delta, version_recorded). change_delta is
242
an inventory_delta change for this entry against the basis tree of
243
the commit, or None if no change occured against the basis tree.
244
version_recorded is True if a new version of the entry has been
245
recorded. For instance, committing a merge where a file was only
246
changed on the other side will return (delta, False).
248
if self.new_inventory.root is None:
249
if ie.parent_id is not None:
250
raise errors.RootMissing()
251
self._check_root(ie, parent_invs, tree)
252
if ie.revision is None:
253
kind = content_summary[0]
255
# ie is carried over from a prior commit
257
# XXX: repository specific check for nested tree support goes here - if
258
# the repo doesn't want nested trees we skip it ?
259
if (kind == 'tree-reference' and
260
not self.repository._format.supports_tree_reference):
261
# mismatch between commit builder logic and repository:
262
# this needs the entry creation pushed down into the builder.
263
raise NotImplementedError('Missing repository subtree support.')
264
self.new_inventory.add(ie)
266
# TODO: slow, take it out of the inner loop.
268
basis_inv = parent_invs[0]
270
basis_inv = Inventory(root_id=None)
272
# ie.revision is always None if the InventoryEntry is considered
273
# for committing. We may record the previous parents revision if the
274
# content is actually unchanged against a sole head.
275
if ie.revision is not None:
276
if not self._versioned_root and path == '':
277
# repositories that do not version the root set the root's
278
# revision to the new commit even when no change occurs, and
279
# this masks when a change may have occurred against the basis,
280
# so calculate if one happened.
281
if ie.file_id in basis_inv:
282
delta = (basis_inv.id2path(ie.file_id), path,
286
delta = (None, path, ie.file_id, ie)
289
# we don't need to commit this, because the caller already
290
# determined that an existing revision of this file is
292
return None, (ie.revision == self._new_revision_id)
293
# XXX: Friction: parent_candidates should return a list not a dict
294
# so that we don't have to walk the inventories again.
295
parent_candiate_entries = ie.parent_candidates(parent_invs)
296
head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
298
for inv in parent_invs:
299
if ie.file_id in inv:
300
old_rev = inv[ie.file_id].revision
301
if old_rev in head_set:
302
heads.append(inv[ie.file_id].revision)
303
head_set.remove(inv[ie.file_id].revision)
306
# now we check to see if we need to write a new record to the
308
# We write a new entry unless there is one head to the ancestors, and
309
# the kind-derived content is unchanged.
311
# Cheapest check first: no ancestors, or more the one head in the
312
# ancestors, we write a new node.
316
# There is a single head, look it up for comparison
317
parent_entry = parent_candiate_entries[heads[0]]
318
# if the non-content specific data has changed, we'll be writing a
320
if (parent_entry.parent_id != ie.parent_id or
321
parent_entry.name != ie.name):
323
# now we need to do content specific checks:
325
# if the kind changed the content obviously has
326
if kind != parent_entry.kind:
329
if content_summary[2] is None:
330
raise ValueError("Files must not have executable = None")
332
if (# if the file length changed we have to store:
333
parent_entry.text_size != content_summary[1] or
334
# if the exec bit has changed we have to store:
335
parent_entry.executable != content_summary[2]):
337
elif parent_entry.text_sha1 == content_summary[3]:
338
# all meta and content is unchanged (using a hash cache
339
# hit to check the sha)
340
ie.revision = parent_entry.revision
341
ie.text_size = parent_entry.text_size
342
ie.text_sha1 = parent_entry.text_sha1
343
ie.executable = parent_entry.executable
344
return self._get_delta(ie, basis_inv, path), False
346
# Either there is only a hash change(no hash cache entry,
347
# or same size content change), or there is no change on
349
# Provide the parent's hash to the store layer, so that the
350
# content is unchanged we will not store a new node.
351
nostore_sha = parent_entry.text_sha1
353
# We want to record a new node regardless of the presence or
354
# absence of a content change in the file.
356
ie.executable = content_summary[2]
357
lines = tree.get_file(ie.file_id, path).readlines()
359
ie.text_sha1, ie.text_size = self._add_text_to_weave(
360
ie.file_id, lines, heads, nostore_sha)
361
except errors.ExistingContent:
362
# Turns out that the file content was unchanged, and we were
363
# only going to store a new node if it was changed. Carry over
365
ie.revision = parent_entry.revision
366
ie.text_size = parent_entry.text_size
367
ie.text_sha1 = parent_entry.text_sha1
368
ie.executable = parent_entry.executable
369
return self._get_delta(ie, basis_inv, path), False
370
elif kind == 'directory':
372
# all data is meta here, nothing specific to directory, so
374
ie.revision = parent_entry.revision
375
return self._get_delta(ie, basis_inv, path), False
377
self._add_text_to_weave(ie.file_id, lines, heads, None)
378
elif kind == 'symlink':
379
current_link_target = content_summary[3]
381
# symlink target is not generic metadata, check if it has
383
if current_link_target != parent_entry.symlink_target:
386
# unchanged, carry over.
387
ie.revision = parent_entry.revision
388
ie.symlink_target = parent_entry.symlink_target
389
return self._get_delta(ie, basis_inv, path), False
390
ie.symlink_target = current_link_target
392
self._add_text_to_weave(ie.file_id, lines, heads, None)
393
elif kind == 'tree-reference':
395
if content_summary[3] != parent_entry.reference_revision:
398
# unchanged, carry over.
399
ie.reference_revision = parent_entry.reference_revision
400
ie.revision = parent_entry.revision
401
return self._get_delta(ie, basis_inv, path), False
402
ie.reference_revision = content_summary[3]
404
self._add_text_to_weave(ie.file_id, lines, heads, None)
406
raise NotImplementedError('unknown kind')
407
ie.revision = self._new_revision_id
408
return self._get_delta(ie, basis_inv, path), True
410
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
411
# Note: as we read the content directly from the tree, we know its not
412
# been turned into unicode or badly split - but a broken tree
413
# implementation could give us bad output from readlines() so this is
414
# not a guarantee of safety. What would be better is always checking
415
# the content during test suite execution. RBC 20070912
416
parent_keys = tuple((file_id, parent) for parent in parents)
417
return self.repository.texts.add_lines(
418
(file_id, self._new_revision_id), parent_keys, new_lines,
419
nostore_sha=nostore_sha, random_id=self.random_revid,
420
check_content=False)[0:2]
423
class RootCommitBuilder(CommitBuilder):
424
"""This commitbuilder actually records the root id"""
426
# the root entry gets versioned properly by this builder.
427
_versioned_root = True
429
def _check_root(self, ie, parent_invs, tree):
430
"""Helper for record_entry_contents.
432
:param ie: An entry being added.
433
:param parent_invs: The inventories of the parent revisions of the
435
:param tree: The tree that is being committed.
439
######################################################################
442
class Repository(object):
443
"""Repository holding history for one or more branches.
445
The repository holds and retrieves historical information including
446
revisions and file history. It's normally accessed only by the Branch,
447
which views a particular line of development through that history.
449
The Repository builds on top of Stores and a Transport, which respectively
450
describe the disk data format and the way of accessing the (possibly
453
:ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
454
the serialised revisions for the repository. This can be used to obtain
455
revision graph information or to access raw serialised revisions.
456
The result of trying to insert data into the repository via this store
457
is undefined: it should be considered read-only except for implementors
459
:ivar _transport: Transport for file access to repository, typically
460
pointing to .bzr/repository.
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
_file_ids_altered_regex = lazy_regex.lazy_compile(
470
r'file_id="(?P<file_id>[^"]+)"'
471
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
def add_inventory(self, revision_id, inv, parents):
499
"""Add the inventory inv to the repository as revision_id.
501
:param parents: The revision ids of the parents that revision_id
502
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.
507
if not self.is_in_write_group():
508
raise AssertionError("%r not in write group" % (self,))
509
_mod_revision.check_not_reserved_id(revision_id)
510
if not (inv.revision_id is None or inv.revision_id == revision_id):
511
raise AssertionError(
512
"Mismatch between inventory revision"
513
" id and insertion revid (%r, %r)"
514
% (inv.revision_id, revision_id))
516
raise AssertionError()
517
inv_lines = self._serialise_inventory_to_lines(inv)
518
return self._inventory_add_lines(revision_id, parents,
519
inv_lines, check_content=False)
521
def _inventory_add_lines(self, revision_id, parents, lines,
523
"""Store lines in inv_vf and return the sha1 of the inventory."""
524
parents = [(parent,) for parent in parents]
525
return self.inventories.add_lines((revision_id,), parents, lines,
526
check_content=check_content)[0]
528
def add_revision(self, revision_id, rev, inv=None, config=None):
529
"""Add rev to the revision store as revision_id.
531
:param revision_id: the revision id to use.
532
:param rev: The revision object.
533
:param inv: The inventory for the revision. if None, it will be looked
534
up in the inventory storer
535
:param config: If None no digital signature will be created.
536
If supplied its signature_needed method will be used
537
to determine if a signature should be made.
539
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
541
_mod_revision.check_not_reserved_id(revision_id)
542
if config is not None and config.signature_needed():
544
inv = self.get_inventory(revision_id)
545
plaintext = Testament(rev, inv).as_short_text()
546
self.store_revision_signature(
547
gpg.GPGStrategy(config), plaintext, revision_id)
548
# check inventory present
549
if not self.inventories.get_parent_map([(revision_id,)]):
551
raise errors.WeaveRevisionNotPresent(revision_id,
554
# yes, this is not suitable for adding with ghosts.
555
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
558
rev.inventory_sha1 = self.inventories.get_sha1s([(revision_id,)])[0]
559
self._add_revision(rev)
561
def _add_revision(self, revision):
562
text = self._serializer.write_revision_to_string(revision)
563
key = (revision.revision_id,)
564
parents = tuple((parent,) for parent in revision.parent_ids)
565
self.revisions.add_lines(key, parents, osutils.split_lines(text))
567
def all_revision_ids(self):
568
"""Returns a list of all the revision ids in the repository.
570
This is deprecated because code should generally work on the graph
571
reachable from a particular revision, and ignore any other revisions
572
that might be present. There is no direct replacement method.
574
if 'evil' in debug.debug_flags:
575
mutter_callsite(2, "all_revision_ids is linear with history.")
576
return self._all_revision_ids()
578
def _all_revision_ids(self):
579
"""Returns a list of all the revision ids in the repository.
581
These are in as much topological order as the underlying store can
584
raise NotImplementedError(self._all_revision_ids)
586
def break_lock(self):
587
"""Break a lock if one is present from another instance.
589
Uses the ui factory to ask for confirmation if the lock may be from
592
self.control_files.break_lock()
595
def _eliminate_revisions_not_present(self, revision_ids):
596
"""Check every revision id in revision_ids to see if we have it.
598
Returns a set of the present revisions.
601
graph = self.get_graph()
602
parent_map = graph.get_parent_map(revision_ids)
603
# The old API returned a list, should this actually be a set?
604
return parent_map.keys()
607
def create(a_bzrdir):
608
"""Construct the current default format repository in a_bzrdir."""
609
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
611
def __init__(self, _format, a_bzrdir, control_files):
612
"""instantiate a Repository.
614
:param _format: The format of the repository on disk.
615
:param a_bzrdir: The BzrDir of the repository.
616
:param revisions: The revisions store for the repository.
618
In the future we will have a single api for all stores for
619
getting file texts, inventories and revisions, then
620
this construct will accept instances of those things.
622
super(Repository, self).__init__()
623
self._format = _format
624
# the following are part of the public API for Repository:
625
self.bzrdir = a_bzrdir
626
self.control_files = control_files
627
self._transport = control_files._transport
628
self.base = self._transport.base
630
self._reconcile_does_inventory_gc = True
631
self._reconcile_fixes_text_parents = False
632
self._reconcile_backsup_inventory = True
633
# not right yet - should be more semantically clear ?
635
# TODO: make sure to construct the right store classes, etc, depending
636
# on whether escaping is required.
637
self._warn_if_deprecated()
638
self._write_group = None
641
return '%s(%r)' % (self.__class__.__name__,
644
def has_same_location(self, other):
645
"""Returns a boolean indicating if this repository is at the same
646
location as another repository.
648
This might return False even when two repository objects are accessing
649
the same physical repository via different URLs.
651
if self.__class__ is not other.__class__:
653
return (self._transport.base == other._transport.base)
655
def is_in_write_group(self):
656
"""Return True if there is an open write group.
658
:seealso: start_write_group.
660
return self._write_group is not None
663
return self.control_files.is_locked()
665
def is_write_locked(self):
666
"""Return True if this object is write locked."""
667
return self.is_locked() and self.control_files._lock_mode == 'w'
669
def lock_write(self, token=None):
670
"""Lock this repository for writing.
672
This causes caching within the repository obejct to start accumlating
673
data during reads, and allows a 'write_group' to be obtained. Write
674
groups must be used for actual data insertion.
676
:param token: if this is already locked, then lock_write will fail
677
unless the token matches the existing lock.
678
:returns: a token if this instance supports tokens, otherwise None.
679
:raises TokenLockingNotSupported: when a token is given but this
680
instance doesn't support using token locks.
681
:raises MismatchedToken: if the specified token doesn't match the token
682
of the existing lock.
683
:seealso: start_write_group.
685
A token should be passed in if you know that you have locked the object
686
some other way, and need to synchronise this object's state with that
689
XXX: this docstring is duplicated in many places, e.g. lockable_files.py
691
result = self.control_files.lock_write(token=token)
696
self.control_files.lock_read()
699
def get_physical_lock_status(self):
700
return self.control_files.get_physical_lock_status()
702
def leave_lock_in_place(self):
703
"""Tell this repository not to release the physical lock when this
706
If lock_write doesn't return a token, then this method is not supported.
708
self.control_files.leave_in_place()
710
def dont_leave_lock_in_place(self):
711
"""Tell this repository to release the physical lock when this
712
object is unlocked, even if it didn't originally acquire it.
714
If lock_write doesn't return a token, then this method is not supported.
716
self.control_files.dont_leave_in_place()
719
def gather_stats(self, revid=None, committers=None):
720
"""Gather statistics from a revision id.
722
:param revid: The revision id to gather statistics from, if None, then
723
no revision specific statistics are gathered.
724
:param committers: Optional parameter controlling whether to grab
725
a count of committers from the revision specific statistics.
726
:return: A dictionary of statistics. Currently this contains:
727
committers: The number of committers if requested.
728
firstrev: A tuple with timestamp, timezone for the penultimate left
729
most ancestor of revid, if revid is not the NULL_REVISION.
730
latestrev: A tuple with timestamp, timezone for revid, if revid is
731
not the NULL_REVISION.
732
revisions: The total revision count in the repository.
733
size: An estimate disk size of the repository in bytes.
736
if revid and committers:
737
result['committers'] = 0
738
if revid and revid != _mod_revision.NULL_REVISION:
740
all_committers = set()
741
revisions = self.get_ancestry(revid)
742
# pop the leading None
744
first_revision = None
746
# ignore the revisions in the middle - just grab first and last
747
revisions = revisions[0], revisions[-1]
748
for revision in self.get_revisions(revisions):
749
if not first_revision:
750
first_revision = revision
752
all_committers.add(revision.committer)
753
last_revision = revision
755
result['committers'] = len(all_committers)
756
result['firstrev'] = (first_revision.timestamp,
757
first_revision.timezone)
758
result['latestrev'] = (last_revision.timestamp,
759
last_revision.timezone)
761
# now gather global repository information
762
# XXX: This is available for many repos regardless of listability.
763
if self.bzrdir.root_transport.listable():
764
# XXX: do we want to __define len__() ?
765
result['revisions'] = len(self.revisions.keys())
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())
813
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
814
"""Return the revision ids that other has that this does not.
816
These are returned in topological order.
818
revision_id: only return revision ids included by revision_id.
820
return InterRepository.get(other, self).search_missing_revision_ids(
821
revision_id, find_ghosts)
823
@deprecated_method(symbol_versioning.one_two)
825
def missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
826
"""Return the revision ids that other has that this does not.
828
These are returned in topological order.
830
revision_id: only return revision ids included by revision_id.
832
keys = self.search_missing_revision_ids(
833
other, revision_id, find_ghosts).get_keys()
836
parents = other.get_graph().get_parent_map(keys)
839
return tsort.topo_sort(parents)
843
"""Open the repository rooted at base.
845
For instance, if the repository is at URL/.bzr/repository,
846
Repository.open(URL) -> a Repository instance.
848
control = bzrdir.BzrDir.open(base)
849
return control.open_repository()
851
def copy_content_into(self, destination, revision_id=None):
852
"""Make a complete copy of the content in self into destination.
854
This is a destructive operation! Do not use it on existing
857
return InterRepository.get(self, destination).copy_content(revision_id)
859
def commit_write_group(self):
860
"""Commit the contents accrued within the current write group.
862
:seealso: start_write_group.
864
if self._write_group is not self.get_transaction():
865
# has an unlock or relock occured ?
866
raise errors.BzrError('mismatched lock context %r and '
868
(self.get_transaction(), self._write_group))
869
self._commit_write_group()
870
self._write_group = None
872
def _commit_write_group(self):
873
"""Template method for per-repository write group cleanup.
875
This is called before the write group is considered to be
876
finished and should ensure that all data handed to the repository
877
for writing during the write group is safely committed (to the
878
extent possible considering file system caching etc).
881
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
882
"""Fetch the content required to construct revision_id from source.
884
If revision_id is None all content is copied.
885
:param find_ghosts: Find and copy revisions in the source that are
886
ghosts in the target (and not reachable directly by walking out to
887
the first-present revision in target from revision_id).
889
# fast path same-url fetch operations
890
if self.has_same_location(source):
891
# check that last_revision is in 'from' and then return a
893
if (revision_id is not None and
894
not _mod_revision.is_null(revision_id)):
895
self.get_revision(revision_id)
897
inter = InterRepository.get(source, self)
899
return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
900
except NotImplementedError:
901
raise errors.IncompatibleRepositories(source, self)
903
def create_bundle(self, target, base, fileobj, format=None):
904
return serializer.write_bundle(self, target, base, fileobj, format)
906
def get_commit_builder(self, branch, parents, config, timestamp=None,
907
timezone=None, committer=None, revprops=None,
909
"""Obtain a CommitBuilder for this repository.
911
:param branch: Branch to commit to.
912
:param parents: Revision ids of the parents of the new revision.
913
:param config: Configuration to use.
914
:param timestamp: Optional timestamp recorded for commit.
915
:param timezone: Optional timezone for timestamp.
916
:param committer: Optional committer to set for commit.
917
:param revprops: Optional dictionary of revision properties.
918
:param revision_id: Optional revision id.
920
result = self._commit_builder_class(self, parents, config,
921
timestamp, timezone, committer, revprops, revision_id)
922
self.start_write_group()
926
if (self.control_files._lock_count == 1 and
927
self.control_files._lock_mode == 'w'):
928
if self._write_group is not None:
929
self.abort_write_group()
930
self.control_files.unlock()
931
raise errors.BzrError(
932
'Must end write groups before releasing write locks.')
933
self.control_files.unlock()
936
def clone(self, a_bzrdir, revision_id=None):
937
"""Clone this repository into a_bzrdir using the current format.
939
Currently no check is made that the format of this repository and
940
the bzrdir format are compatible. FIXME RBC 20060201.
942
:return: The newly created destination repository.
944
# TODO: deprecate after 0.16; cloning this with all its settings is
945
# probably not very useful -- mbp 20070423
946
dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
947
self.copy_content_into(dest_repo, revision_id)
950
def start_write_group(self):
951
"""Start a write group in the repository.
953
Write groups are used by repositories which do not have a 1:1 mapping
954
between file ids and backend store to manage the insertion of data from
955
both fetch and commit operations.
957
A write lock is required around the start_write_group/commit_write_group
958
for the support of lock-requiring repository formats.
960
One can only insert data into a repository inside a write group.
964
if not self.is_write_locked():
965
raise errors.NotWriteLocked(self)
966
if self._write_group:
967
raise errors.BzrError('already in a write group')
968
self._start_write_group()
969
# so we can detect unlock/relock - the write group is now entered.
970
self._write_group = self.get_transaction()
972
def _start_write_group(self):
973
"""Template method for per-repository write group startup.
975
This is called before the write group is considered to be
980
def sprout(self, to_bzrdir, revision_id=None):
981
"""Create a descendent repository for new development.
983
Unlike clone, this does not copy the settings of the repository.
985
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
986
dest_repo.fetch(self, revision_id=revision_id)
989
def _create_sprouting_repo(self, a_bzrdir, shared):
990
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
991
# use target default format.
992
dest_repo = a_bzrdir.create_repository()
994
# Most control formats need the repository to be specifically
995
# created, but on some old all-in-one formats it's not needed
997
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
998
except errors.UninitializableFormat:
999
dest_repo = a_bzrdir.open_repository()
1003
def has_revision(self, revision_id):
1004
"""True if this repository has a copy of the revision."""
1005
return revision_id in self.has_revisions((revision_id,))
1008
def has_revisions(self, revision_ids):
1009
"""Probe to find out the presence of multiple revisions.
1011
:param revision_ids: An iterable of revision_ids.
1012
:return: A set of the revision_ids that were present.
1014
parent_map = self.revisions.get_parent_map(
1015
[(rev_id,) for rev_id in revision_ids])
1017
if _mod_revision.NULL_REVISION in revision_ids:
1018
result.add(_mod_revision.NULL_REVISION)
1019
result.update([key[0] for key in parent_map])
1023
def get_revision(self, revision_id):
1024
"""Return the Revision object for a named revision."""
1025
return self.get_revisions([revision_id])[0]
1028
def get_revision_reconcile(self, revision_id):
1029
"""'reconcile' helper routine that allows access to a revision always.
1031
This variant of get_revision does not cross check the weave graph
1032
against the revision one as get_revision does: but it should only
1033
be used by reconcile, or reconcile-alike commands that are correcting
1034
or testing the revision graph.
1036
return self._get_revisions([revision_id])[0]
1039
def get_revisions(self, revision_ids):
1040
"""Get many revisions at once."""
1041
return self._get_revisions(revision_ids)
1044
def _get_revisions(self, revision_ids):
1045
"""Core work logic to get many revisions without sanity checks."""
1046
for rev_id in revision_ids:
1047
if not rev_id or not isinstance(rev_id, basestring):
1048
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1049
keys = [(key,) for key in revision_ids]
1050
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1052
for record in stream:
1053
if record.storage_kind == 'absent':
1054
raise errors.NoSuchRevision(self, record.key[0])
1055
text = record.get_bytes_as('fulltext')
1056
rev = self._serializer.read_revision_from_string(text)
1057
revs[record.key[0]] = rev
1058
return [revs[revid] for revid in revision_ids]
1061
def get_revision_xml(self, revision_id):
1062
# TODO: jam 20070210 This shouldn't be necessary since get_revision
1063
# would have already do it.
1064
# TODO: jam 20070210 Just use _serializer.write_revision_to_string()
1065
rev = self.get_revision(revision_id)
1066
rev_tmp = StringIO()
1067
# the current serializer..
1068
self._serializer.write_revision(rev, rev_tmp)
1070
return rev_tmp.getvalue()
1072
def get_deltas_for_revisions(self, revisions):
1073
"""Produce a generator of revision deltas.
1075
Note that the input is a sequence of REVISIONS, not revision_ids.
1076
Trees will be held in memory until the generator exits.
1077
Each delta is relative to the revision's lefthand predecessor.
1079
required_trees = set()
1080
for revision in revisions:
1081
required_trees.add(revision.revision_id)
1082
required_trees.update(revision.parent_ids[:1])
1083
trees = dict((t.get_revision_id(), t) for
1084
t in self.revision_trees(required_trees))
1085
for revision in revisions:
1086
if not revision.parent_ids:
1087
old_tree = self.revision_tree(None)
1089
old_tree = trees[revision.parent_ids[0]]
1090
yield trees[revision.revision_id].changes_from(old_tree)
1093
def get_revision_delta(self, revision_id):
1094
"""Return the delta for one revision.
1096
The delta is relative to the left-hand predecessor of the
1099
r = self.get_revision(revision_id)
1100
return list(self.get_deltas_for_revisions([r]))[0]
1103
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1104
signature = gpg_strategy.sign(plaintext)
1105
self.add_signature_text(revision_id, signature)
1108
def add_signature_text(self, revision_id, signature):
1109
self.signatures.add_lines((revision_id,), (),
1110
osutils.split_lines(signature))
1112
def find_text_key_references(self):
1113
"""Find the text key references within the repository.
1115
:return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
1116
revision_ids. Each altered file-ids has the exact revision_ids that
1117
altered it listed explicitly.
1118
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1119
to whether they were referred to by the inventory of the
1120
revision_id that they contain. The inventory texts from all present
1121
revision ids are assessed to generate this report.
1123
revision_keys = self.revisions.keys()
1124
w = self.inventories
1125
pb = ui.ui_factory.nested_progress_bar()
1127
return self._find_text_key_references_from_xml_inventory_lines(
1128
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1132
def _find_text_key_references_from_xml_inventory_lines(self,
1134
"""Core routine for extracting references to texts from inventories.
1136
This performs the translation of xml lines to revision ids.
1138
:param line_iterator: An iterator of lines, origin_version_id
1139
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1140
to whether they were referred to by the inventory of the
1141
revision_id that they contain. Note that if that revision_id was
1142
not part of the line_iterator's output then False will be given -
1143
even though it may actually refer to that key.
1145
if not self._serializer.support_altered_by_hack:
1146
raise AssertionError(
1147
"_find_text_key_references_from_xml_inventory_lines only "
1148
"supported for branches which store inventory as unnested xml"
1149
", not on %r" % self)
1152
# this code needs to read every new line in every inventory for the
1153
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
1154
# not present in one of those inventories is unnecessary but not
1155
# harmful because we are filtering by the revision id marker in the
1156
# inventory lines : we only select file ids altered in one of those
1157
# revisions. We don't need to see all lines in the inventory because
1158
# only those added in an inventory in rev X can contain a revision=X
1160
unescape_revid_cache = {}
1161
unescape_fileid_cache = {}
1163
# jam 20061218 In a big fetch, this handles hundreds of thousands
1164
# of lines, so it has had a lot of inlining and optimizing done.
1165
# Sorry that it is a little bit messy.
1166
# Move several functions to be local variables, since this is a long
1168
search = self._file_ids_altered_regex.search
1169
unescape = _unescape_xml
1170
setdefault = result.setdefault
1171
for line, line_key in line_iterator:
1172
match = search(line)
1175
# One call to match.group() returning multiple items is quite a
1176
# bit faster than 2 calls to match.group() each returning 1
1177
file_id, revision_id = match.group('file_id', 'revision_id')
1179
# Inlining the cache lookups helps a lot when you make 170,000
1180
# lines and 350k ids, versus 8.4 unique ids.
1181
# Using a cache helps in 2 ways:
1182
# 1) Avoids unnecessary decoding calls
1183
# 2) Re-uses cached strings, which helps in future set and
1185
# (2) is enough that removing encoding entirely along with
1186
# the cache (so we are using plain strings) results in no
1187
# performance improvement.
1189
revision_id = unescape_revid_cache[revision_id]
1191
unescaped = unescape(revision_id)
1192
unescape_revid_cache[revision_id] = unescaped
1193
revision_id = unescaped
1195
# Note that unconditionally unescaping means that we deserialise
1196
# every fileid, which for general 'pull' is not great, but we don't
1197
# really want to have some many fulltexts that this matters anyway.
1200
file_id = unescape_fileid_cache[file_id]
1202
unescaped = unescape(file_id)
1203
unescape_fileid_cache[file_id] = unescaped
1206
key = (file_id, revision_id)
1207
setdefault(key, False)
1208
if revision_id == line_key[-1]:
1212
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1214
"""Helper routine for fileids_altered_by_revision_ids.
1216
This performs the translation of xml lines to revision ids.
1218
:param line_iterator: An iterator of lines, origin_version_id
1219
:param revision_ids: The revision ids to filter for. This should be a
1220
set or other type which supports efficient __contains__ lookups, as
1221
the revision id from each parsed line will be looked up in the
1222
revision_ids filter.
1223
:return: a dictionary mapping altered file-ids to an iterable of
1224
revision_ids. Each altered file-ids has the exact revision_ids that
1225
altered it listed explicitly.
1228
setdefault = result.setdefault
1230
self._find_text_key_references_from_xml_inventory_lines(
1231
line_iterator).iterkeys():
1232
# once data is all ensured-consistent; then this is
1233
# if revision_id == version_id
1234
if key[-1:] in revision_ids:
1235
setdefault(key[0], set()).add(key[-1])
1238
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1239
"""Find the file ids and versions affected by revisions.
1241
:param revisions: an iterable containing revision ids.
1242
:param _inv_weave: The inventory weave from this repository or None.
1243
If None, the inventory weave will be opened automatically.
1244
:return: a dictionary mapping altered file-ids to an iterable of
1245
revision_ids. Each altered file-ids has the exact revision_ids that
1246
altered it listed explicitly.
1248
selected_keys = set((revid,) for revid in revision_ids)
1249
w = _inv_weave or self.inventories
1250
pb = ui.ui_factory.nested_progress_bar()
1252
return self._find_file_ids_from_xml_inventory_lines(
1253
w.iter_lines_added_or_present_in_keys(
1254
selected_keys, pb=pb),
1259
def iter_files_bytes(self, desired_files):
1260
"""Iterate through file versions.
1262
Files will not necessarily be returned in the order they occur in
1263
desired_files. No specific order is guaranteed.
1265
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1266
value supplied by the caller as part of desired_files. It should
1267
uniquely identify the file version in the caller's context. (Examples:
1268
an index number or a TreeTransform trans_id.)
1270
bytes_iterator is an iterable of bytestrings for the file. The
1271
kind of iterable and length of the bytestrings are unspecified, but for
1272
this implementation, it is a list of bytes produced by
1273
VersionedFile.get_record_stream().
1275
:param desired_files: a list of (file_id, revision_id, identifier)
1278
transaction = self.get_transaction()
1280
for file_id, revision_id, callable_data in desired_files:
1281
text_keys[(file_id, revision_id)] = callable_data
1282
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1283
if record.storage_kind == 'absent':
1284
raise errors.RevisionNotPresent(record.key, self)
1285
yield text_keys[record.key], record.get_bytes_as('fulltext')
1287
def _generate_text_key_index(self, text_key_references=None,
1289
"""Generate a new text key index for the repository.
1291
This is an expensive function that will take considerable time to run.
1293
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1294
list of parents, also text keys. When a given key has no parents,
1295
the parents list will be [NULL_REVISION].
1297
# All revisions, to find inventory parents.
1298
if ancestors is None:
1299
graph = self.get_graph()
1300
ancestors = graph.get_parent_map(self.all_revision_ids())
1301
if text_key_references is None:
1302
text_key_references = self.find_text_key_references()
1303
pb = ui.ui_factory.nested_progress_bar()
1305
return self._do_generate_text_key_index(ancestors,
1306
text_key_references, pb)
1310
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1311
"""Helper for _generate_text_key_index to avoid deep nesting."""
1312
revision_order = tsort.topo_sort(ancestors)
1313
invalid_keys = set()
1315
for revision_id in revision_order:
1316
revision_keys[revision_id] = set()
1317
text_count = len(text_key_references)
1318
# a cache of the text keys to allow reuse; costs a dict of all the
1319
# keys, but saves a 2-tuple for every child of a given key.
1321
for text_key, valid in text_key_references.iteritems():
1323
invalid_keys.add(text_key)
1325
revision_keys[text_key[1]].add(text_key)
1326
text_key_cache[text_key] = text_key
1327
del text_key_references
1329
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1330
NULL_REVISION = _mod_revision.NULL_REVISION
1331
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1332
# too small for large or very branchy trees. However, for 55K path
1333
# trees, it would be easy to use too much memory trivially. Ideally we
1334
# could gauge this by looking at available real memory etc, but this is
1335
# always a tricky proposition.
1336
inventory_cache = lru_cache.LRUCache(10)
1337
batch_size = 10 # should be ~150MB on a 55K path tree
1338
batch_count = len(revision_order) / batch_size + 1
1340
pb.update("Calculating text parents.", processed_texts, text_count)
1341
for offset in xrange(batch_count):
1342
to_query = revision_order[offset * batch_size:(offset + 1) *
1346
for rev_tree in self.revision_trees(to_query):
1347
revision_id = rev_tree.get_revision_id()
1348
parent_ids = ancestors[revision_id]
1349
for text_key in revision_keys[revision_id]:
1350
pb.update("Calculating text parents.", processed_texts)
1351
processed_texts += 1
1352
candidate_parents = []
1353
for parent_id in parent_ids:
1354
parent_text_key = (text_key[0], parent_id)
1356
check_parent = parent_text_key not in \
1357
revision_keys[parent_id]
1359
# the parent parent_id is a ghost:
1360
check_parent = False
1361
# truncate the derived graph against this ghost.
1362
parent_text_key = None
1364
# look at the parent commit details inventories to
1365
# determine possible candidates in the per file graph.
1368
inv = inventory_cache[parent_id]
1370
inv = self.revision_tree(parent_id).inventory
1371
inventory_cache[parent_id] = inv
1372
parent_entry = inv._byid.get(text_key[0], None)
1373
if parent_entry is not None:
1375
text_key[0], parent_entry.revision)
1377
parent_text_key = None
1378
if parent_text_key is not None:
1379
candidate_parents.append(
1380
text_key_cache[parent_text_key])
1381
parent_heads = text_graph.heads(candidate_parents)
1382
new_parents = list(parent_heads)
1383
new_parents.sort(key=lambda x:candidate_parents.index(x))
1384
if new_parents == []:
1385
new_parents = [NULL_REVISION]
1386
text_index[text_key] = new_parents
1388
for text_key in invalid_keys:
1389
text_index[text_key] = [NULL_REVISION]
1392
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1393
"""Get an iterable listing the keys of all the data introduced by a set
1396
The keys will be ordered so that the corresponding items can be safely
1397
fetched and inserted in that order.
1399
:returns: An iterable producing tuples of (knit-kind, file-id,
1400
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1401
'revisions'. file-id is None unless knit-kind is 'file'.
1403
# XXX: it's a bit weird to control the inventory weave caching in this
1404
# generator. Ideally the caching would be done in fetch.py I think. Or
1405
# maybe this generator should explicitly have the contract that it
1406
# should not be iterated until the previously yielded item has been
1408
inv_w = self.inventories
1410
# file ids that changed
1411
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
1413
num_file_ids = len(file_ids)
1414
for file_id, altered_versions in file_ids.iteritems():
1415
if _files_pb is not None:
1416
_files_pb.update("fetch texts", count, num_file_ids)
1418
yield ("file", file_id, altered_versions)
1419
# We're done with the files_pb. Note that it finished by the caller,
1420
# just as it was created by the caller.
1424
yield ("inventory", None, revision_ids)
1427
revisions_with_signatures = set()
1428
for rev_id in revision_ids:
1430
self.get_signature_text(rev_id)
1431
except errors.NoSuchRevision:
1435
revisions_with_signatures.add(rev_id)
1436
yield ("signatures", None, revisions_with_signatures)
1439
yield ("revisions", None, revision_ids)
1442
def get_inventory(self, revision_id):
1443
"""Get Inventory object by revision id."""
1444
return self.iter_inventories([revision_id]).next()
1446
def iter_inventories(self, revision_ids):
1447
"""Get many inventories by revision_ids.
1449
This will buffer some or all of the texts used in constructing the
1450
inventories in memory, but will only parse a single inventory at a
1453
:return: An iterator of inventories.
1455
if ((None in revision_ids)
1456
or (_mod_revision.NULL_REVISION in revision_ids)):
1457
raise ValueError('cannot get null revision inventory')
1458
return self._iter_inventories(revision_ids)
1460
def _iter_inventories(self, revision_ids):
1461
"""single-document based inventory iteration."""
1462
for text, revision_id in self._iter_inventory_xmls(revision_ids):
1463
yield self.deserialise_inventory(revision_id, text)
1465
def _iter_inventory_xmls(self, revision_ids):
1466
keys = [(revision_id,) for revision_id in revision_ids]
1467
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1469
for record in stream:
1470
if record.storage_kind != 'absent':
1471
texts[record.key] = record.get_bytes_as('fulltext')
1473
raise errors.NoSuchRevision(self, record.key)
1475
yield texts[key], key[-1]
1477
def deserialise_inventory(self, revision_id, xml):
1478
"""Transform the xml into an inventory object.
1480
:param revision_id: The expected revision id of the inventory.
1481
:param xml: A serialised inventory.
1483
result = self._serializer.read_inventory_from_string(xml, revision_id)
1484
if result.revision_id != revision_id:
1485
raise AssertionError('revision id mismatch %s != %s' % (
1486
result.revision_id, revision_id))
1489
def serialise_inventory(self, inv):
1490
return self._serializer.write_inventory_to_string(inv)
1492
def _serialise_inventory_to_lines(self, inv):
1493
return self._serializer.write_inventory_to_lines(inv)
1495
def get_serializer_format(self):
1496
return self._serializer.format_num
1499
def get_inventory_xml(self, revision_id):
1500
"""Get inventory XML as a file object."""
1501
texts = self._iter_inventory_xmls([revision_id])
1503
text, revision_id = texts.next()
1504
except StopIteration:
1505
raise errors.HistoryMissing(self, 'inventory', revision_id)
1509
def get_inventory_sha1(self, revision_id):
1510
"""Return the sha1 hash of the inventory entry
1512
return self.get_revision(revision_id).inventory_sha1
1514
def iter_reverse_revision_history(self, revision_id):
1515
"""Iterate backwards through revision ids in the lefthand history
1517
:param revision_id: The revision id to start with. All its lefthand
1518
ancestors will be traversed.
1520
graph = self.get_graph()
1521
next_id = revision_id
1523
if next_id in (None, _mod_revision.NULL_REVISION):
1526
# Note: The following line may raise KeyError in the event of
1527
# truncated history. We decided not to have a try:except:raise
1528
# RevisionNotPresent here until we see a use for it, because of the
1529
# cost in an inner loop that is by its very nature O(history).
1530
# Robert Collins 20080326
1531
parents = graph.get_parent_map([next_id])[next_id]
1532
if len(parents) == 0:
1535
next_id = parents[0]
1538
def get_revision_inventory(self, revision_id):
1539
"""Return inventory of a past revision."""
1540
# TODO: Unify this with get_inventory()
1541
# bzr 0.0.6 and later imposes the constraint that the inventory_id
1542
# must be the same as its revision, so this is trivial.
1543
if revision_id is None:
1544
# This does not make sense: if there is no revision,
1545
# then it is the current tree inventory surely ?!
1546
# and thus get_root_id() is something that looks at the last
1547
# commit on the branch, and the get_root_id is an inventory check.
1548
raise NotImplementedError
1549
# return Inventory(self.get_root_id())
1551
return self.get_inventory(revision_id)
1554
def is_shared(self):
1555
"""Return True if this repository is flagged as a shared repository."""
1556
raise NotImplementedError(self.is_shared)
1559
def reconcile(self, other=None, thorough=False):
1560
"""Reconcile this repository."""
1561
from bzrlib.reconcile import RepoReconciler
1562
reconciler = RepoReconciler(self, thorough=thorough)
1563
reconciler.reconcile()
1566
def _refresh_data(self):
1567
"""Helper called from lock_* to ensure coherency with disk.
1569
The default implementation does nothing; it is however possible
1570
for repositories to maintain loaded indices across multiple locks
1571
by checking inside their implementation of this method to see
1572
whether their indices are still valid. This depends of course on
1573
the disk format being validatable in this manner.
1577
def revision_tree(self, revision_id):
1578
"""Return Tree for a revision on this branch.
1580
`revision_id` may be None for the empty tree revision.
1582
# TODO: refactor this to use an existing revision object
1583
# so we don't need to read it in twice.
1584
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
1585
return RevisionTree(self, Inventory(root_id=None),
1586
_mod_revision.NULL_REVISION)
1588
inv = self.get_revision_inventory(revision_id)
1589
return RevisionTree(self, inv, revision_id)
1591
def revision_trees(self, revision_ids):
1592
"""Return Tree for a revision on this branch.
1594
`revision_id` may not be None or 'null:'"""
1595
inventories = self.iter_inventories(revision_ids)
1596
for inv in inventories:
1597
yield RevisionTree(self, inv, inv.revision_id)
1600
def get_ancestry(self, revision_id, topo_sorted=True):
1601
"""Return a list of revision-ids integrated by a revision.
1603
The first element of the list is always None, indicating the origin
1604
revision. This might change when we have history horizons, or
1605
perhaps we should have a new API.
1607
This is topologically sorted.
1609
if _mod_revision.is_null(revision_id):
1611
if not self.has_revision(revision_id):
1612
raise errors.NoSuchRevision(self, revision_id)
1613
graph = self.get_graph()
1615
search = graph._make_breadth_first_searcher([revision_id])
1618
found, ghosts = search.next_with_ghosts()
1619
except StopIteration:
1622
if _mod_revision.NULL_REVISION in keys:
1623
keys.remove(_mod_revision.NULL_REVISION)
1625
parent_map = graph.get_parent_map(keys)
1626
keys = tsort.topo_sort(parent_map)
1627
return [None] + list(keys)
1630
"""Compress the data within the repository.
1632
This operation only makes sense for some repository types. For other
1633
types it should be a no-op that just returns.
1635
This stub method does not require a lock, but subclasses should use
1636
@needs_write_lock as this is a long running call its reasonable to
1637
implicitly lock for the user.
1641
def print_file(self, file, revision_id):
1642
"""Print `file` to stdout.
1644
FIXME RBC 20060125 as John Meinel points out this is a bad api
1645
- it writes to stdout, it assumes that that is valid etc. Fix
1646
by creating a new more flexible convenience function.
1648
tree = self.revision_tree(revision_id)
1649
# use inventory as it was in that revision
1650
file_id = tree.inventory.path2id(file)
1652
# TODO: jam 20060427 Write a test for this code path
1653
# it had a bug in it, and was raising the wrong
1655
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
1656
tree.print_file(file_id)
1658
def get_transaction(self):
1659
return self.control_files.get_transaction()
1661
@deprecated_method(symbol_versioning.one_one)
1662
def get_parents(self, revision_ids):
1663
"""See StackedParentsProvider.get_parents"""
1664
parent_map = self.get_parent_map(revision_ids)
1665
return [parent_map.get(r, None) for r in revision_ids]
1667
def get_parent_map(self, keys):
1668
"""See graph._StackedParentsProvider.get_parent_map"""
1670
for revision_id in keys:
1671
if revision_id is None:
1672
raise ValueError('get_parent_map(None) is not valid')
1673
if revision_id == _mod_revision.NULL_REVISION:
1674
parent_map[revision_id] = ()
1677
parent_id_list = self.get_revision(revision_id).parent_ids
1678
except errors.NoSuchRevision:
1681
if len(parent_id_list) == 0:
1682
parent_ids = (_mod_revision.NULL_REVISION,)
1684
parent_ids = tuple(parent_id_list)
1685
parent_map[revision_id] = parent_ids
1688
def _make_parents_provider(self):
1691
def get_graph(self, other_repository=None):
1692
"""Return the graph walker for this repository format"""
1693
parents_provider = self._make_parents_provider()
1694
if (other_repository is not None and
1695
not self.has_same_location(other_repository)):
1696
parents_provider = graph._StackedParentsProvider(
1697
[parents_provider, other_repository._make_parents_provider()])
1698
return graph.Graph(parents_provider)
1700
def _get_versioned_file_checker(self):
1701
"""Return an object suitable for checking versioned files."""
1702
return _VersionedFileChecker(self)
1704
def revision_ids_to_search_result(self, result_set):
1705
"""Convert a set of revision ids to a graph SearchResult."""
1706
result_parents = set()
1707
for parents in self.get_graph().get_parent_map(
1708
result_set).itervalues():
1709
result_parents.update(parents)
1710
included_keys = result_set.intersection(result_parents)
1711
start_keys = result_set.difference(included_keys)
1712
exclude_keys = result_parents.difference(result_set)
1713
result = graph.SearchResult(start_keys, exclude_keys,
1714
len(result_set), result_set)
1718
def set_make_working_trees(self, new_value):
1719
"""Set the policy flag for making working trees when creating branches.
1721
This only applies to branches that use this repository.
1723
The default is 'True'.
1724
:param new_value: True to restore the default, False to disable making
1727
raise NotImplementedError(self.set_make_working_trees)
1729
def make_working_trees(self):
1730
"""Returns the policy for making working trees on new branches."""
1731
raise NotImplementedError(self.make_working_trees)
1734
def sign_revision(self, revision_id, gpg_strategy):
1735
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1736
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1739
def has_signature_for_revision_id(self, revision_id):
1740
"""Query for a revision signature for revision_id in the repository."""
1741
if not self.has_revision(revision_id):
1742
raise errors.NoSuchRevision(self, revision_id)
1743
sig_present = (1 == len(
1744
self.signatures.get_parent_map([(revision_id,)])))
1748
def get_signature_text(self, revision_id):
1749
"""Return the text for a signature."""
1750
stream = self.signatures.get_record_stream([(revision_id,)],
1752
record = stream.next()
1753
if record.storage_kind == 'absent':
1754
raise errors.NoSuchRevision(self, revision_id)
1755
return record.get_bytes_as('fulltext')
1758
def check(self, revision_ids=None):
1759
"""Check consistency of all history of given revision_ids.
1761
Different repository implementations should override _check().
1763
:param revision_ids: A non-empty list of revision_ids whose ancestry
1764
will be checked. Typically the last revision_id of a branch.
1766
return self._check(revision_ids)
1768
def _check(self, revision_ids):
1769
result = check.Check(self)
1773
def _warn_if_deprecated(self):
1774
global _deprecation_warning_done
1775
if _deprecation_warning_done:
1777
_deprecation_warning_done = True
1778
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
1779
% (self._format, self.bzrdir.transport.base))
1781
def supports_rich_root(self):
1782
return self._format.rich_root_data
1784
def _check_ascii_revisionid(self, revision_id, method):
1785
"""Private helper for ascii-only repositories."""
1786
# weave repositories refuse to store revisionids that are non-ascii.
1787
if revision_id is not None:
1788
# weaves require ascii revision ids.
1789
if isinstance(revision_id, unicode):
1791
revision_id.encode('ascii')
1792
except UnicodeEncodeError:
1793
raise errors.NonAsciiRevisionId(method, self)
1796
revision_id.decode('ascii')
1797
except UnicodeDecodeError:
1798
raise errors.NonAsciiRevisionId(method, self)
1800
def revision_graph_can_have_wrong_parents(self):
1801
"""Is it possible for this repository to have a revision graph with
1804
If True, then this repository must also implement
1805
_find_inconsistent_revision_parents so that check and reconcile can
1806
check for inconsistencies before proceeding with other checks that may
1807
depend on the revision index being consistent.
1809
raise NotImplementedError(self.revision_graph_can_have_wrong_parents)
1812
# remove these delegates a while after bzr 0.15
1813
def __make_delegated(name, from_module):
1814
def _deprecated_repository_forwarder():
1815
symbol_versioning.warn('%s moved to %s in bzr 0.15'
1816
% (name, from_module),
1819
m = __import__(from_module, globals(), locals(), [name])
1821
return getattr(m, name)
1822
except AttributeError:
1823
raise AttributeError('module %s has no name %s'
1825
globals()[name] = _deprecated_repository_forwarder
1828
'AllInOneRepository',
1829
'WeaveMetaDirRepository',
1830
'PreSplitOutRepositoryFormat',
1831
'RepositoryFormat4',
1832
'RepositoryFormat5',
1833
'RepositoryFormat6',
1834
'RepositoryFormat7',
1836
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1840
'RepositoryFormatKnit',
1841
'RepositoryFormatKnit1',
1843
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1846
def install_revision(repository, rev, revision_tree):
1847
"""Install all revision data into a repository."""
1848
install_revisions(repository, [(rev, revision_tree, None)])
1851
def install_revisions(repository, iterable, num_revisions=None, pb=None):
1852
"""Install all revision data into a repository.
1854
Accepts an iterable of revision, tree, signature tuples. The signature
1857
repository.start_write_group()
1859
for n, (revision, revision_tree, signature) in enumerate(iterable):
1860
_install_revision(repository, revision, revision_tree, signature)
1862
pb.update('Transferring revisions', n + 1, num_revisions)
1864
repository.abort_write_group()
1867
repository.commit_write_group()
1870
def _install_revision(repository, rev, revision_tree, signature):
1871
"""Install all revision data into a repository."""
1872
present_parents = []
1874
for p_id in rev.parent_ids:
1875
if repository.has_revision(p_id):
1876
present_parents.append(p_id)
1877
parent_trees[p_id] = repository.revision_tree(p_id)
1879
parent_trees[p_id] = repository.revision_tree(None)
1881
inv = revision_tree.inventory
1882
entries = inv.iter_entries()
1883
# backwards compatibility hack: skip the root id.
1884
if not repository.supports_rich_root():
1885
path, root = entries.next()
1886
if root.revision != rev.revision_id:
1887
raise errors.IncompatibleRevision(repr(repository))
1889
for path, ie in entries:
1890
text_keys[(ie.file_id, ie.revision)] = ie
1891
text_parent_map = repository.texts.get_parent_map(text_keys)
1892
missing_texts = set(text_keys) - set(text_parent_map)
1893
# Add the texts that are not already present
1894
for text_key in missing_texts:
1895
ie = text_keys[text_key]
1897
# FIXME: TODO: The following loop overlaps/duplicates that done by
1898
# commit to determine parents. There is a latent/real bug here where
1899
# the parents inserted are not those commit would do - in particular
1900
# they are not filtered by heads(). RBC, AB
1901
for revision, tree in parent_trees.iteritems():
1902
if ie.file_id not in tree:
1904
parent_id = tree.inventory[ie.file_id].revision
1905
if parent_id in text_parents:
1907
text_parents.append((ie.file_id, parent_id))
1908
lines = revision_tree.get_file(ie.file_id).readlines()
1909
repository.texts.add_lines(text_key, text_parents, lines)
1911
# install the inventory
1912
repository.add_inventory(rev.revision_id, inv, present_parents)
1913
except errors.RevisionAlreadyPresent:
1915
if signature is not None:
1916
repository.add_signature_text(rev.revision_id, signature)
1917
repository.add_revision(rev.revision_id, rev, inv)
1920
class MetaDirRepository(Repository):
1921
"""Repositories in the new meta-dir layout.
1923
:ivar _transport: Transport for access to repository control files,
1924
typically pointing to .bzr/repository.
1927
def __init__(self, _format, a_bzrdir, control_files):
1928
super(MetaDirRepository, self).__init__(_format, a_bzrdir, control_files)
1929
self._transport = control_files._transport
1932
def is_shared(self):
1933
"""Return True if this repository is flagged as a shared repository."""
1934
return self._transport.has('shared-storage')
1937
def set_make_working_trees(self, new_value):
1938
"""Set the policy flag for making working trees when creating branches.
1940
This only applies to branches that use this repository.
1942
The default is 'True'.
1943
:param new_value: True to restore the default, False to disable making
1948
self._transport.delete('no-working-trees')
1949
except errors.NoSuchFile:
1952
self._transport.put_bytes('no-working-trees', '',
1953
mode=self.bzrdir._get_file_mode())
1955
def make_working_trees(self):
1956
"""Returns the policy for making working trees on new branches."""
1957
return not self._transport.has('no-working-trees')
1960
class MetaDirVersionedFileRepository(MetaDirRepository):
1961
"""Repositories in a meta-dir, that work via versioned file objects."""
1963
def __init__(self, _format, a_bzrdir, control_files):
1964
super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
1968
class RepositoryFormatRegistry(registry.Registry):
1969
"""Registry of RepositoryFormats."""
1971
def get(self, format_string):
1972
r = registry.Registry.get(self, format_string)
1978
format_registry = RepositoryFormatRegistry()
1979
"""Registry of formats, indexed by their identifying format string.
1981
This can contain either format instances themselves, or classes/factories that
1982
can be called to obtain one.
1986
#####################################################################
1987
# Repository Formats
1989
class RepositoryFormat(object):
1990
"""A repository format.
1992
Formats provide three things:
1993
* An initialization routine to construct repository data on disk.
1994
* a format string which is used when the BzrDir supports versioned
1996
* an open routine which returns a Repository instance.
1998
There is one and only one Format subclass for each on-disk format. But
1999
there can be one Repository subclass that is used for several different
2000
formats. The _format attribute on a Repository instance can be used to
2001
determine the disk format.
2003
Formats are placed in an dict by their format string for reference
2004
during opening. These should be subclasses of RepositoryFormat
2007
Once a format is deprecated, just deprecate the initialize and open
2008
methods on the format class. Do not deprecate the object, as the
2009
object will be created every system load.
2011
Common instance attributes:
2012
_matchingbzrdir - the bzrdir format that the repository format was
2013
originally written to work with. This can be used if manually
2014
constructing a bzrdir and repository, or more commonly for test suite
2018
# Set to True or False in derived classes. True indicates that the format
2019
# supports ghosts gracefully.
2020
supports_ghosts = None
2021
# Can this repository be given external locations to lookup additional
2022
# data. Set to True or False in derived classes.
2023
supports_external_lookups = None
2026
return "<%s>" % self.__class__.__name__
2028
def __eq__(self, other):
2029
# format objects are generally stateless
2030
return isinstance(other, self.__class__)
2032
def __ne__(self, other):
2033
return not self == other
2036
def find_format(klass, a_bzrdir):
2037
"""Return the format for the repository object in a_bzrdir.
2039
This is used by bzr native formats that have a "format" file in
2040
the repository. Other methods may be used by different types of
2044
transport = a_bzrdir.get_repository_transport(None)
2045
format_string = transport.get("format").read()
2046
return format_registry.get(format_string)
2047
except errors.NoSuchFile:
2048
raise errors.NoRepositoryPresent(a_bzrdir)
2050
raise errors.UnknownFormatError(format=format_string,
2054
def register_format(klass, format):
2055
format_registry.register(format.get_format_string(), format)
2058
def unregister_format(klass, format):
2059
format_registry.remove(format.get_format_string())
2062
def get_default_format(klass):
2063
"""Return the current default format."""
2064
from bzrlib import bzrdir
2065
return bzrdir.format_registry.make_bzrdir('default').repository_format
2067
def get_format_string(self):
2068
"""Return the ASCII format string that identifies this format.
2070
Note that in pre format ?? repositories the format string is
2071
not permitted nor written to disk.
2073
raise NotImplementedError(self.get_format_string)
2075
def get_format_description(self):
2076
"""Return the short description for this format."""
2077
raise NotImplementedError(self.get_format_description)
2079
# TODO: this shouldn't be in the base class, it's specific to things that
2080
# use weaves or knits -- mbp 20070207
2081
def _get_versioned_file_store(self,
2086
versionedfile_class=None,
2087
versionedfile_kwargs={},
2089
if versionedfile_class is None:
2090
versionedfile_class = self._versionedfile_class
2091
weave_transport = control_files._transport.clone(name)
2092
dir_mode = control_files._dir_mode
2093
file_mode = control_files._file_mode
2094
return VersionedFileStore(weave_transport, prefixed=prefixed,
2096
file_mode=file_mode,
2097
versionedfile_class=versionedfile_class,
2098
versionedfile_kwargs=versionedfile_kwargs,
2101
def initialize(self, a_bzrdir, shared=False):
2102
"""Initialize a repository of this format in a_bzrdir.
2104
:param a_bzrdir: The bzrdir to put the new repository in it.
2105
:param shared: The repository should be initialized as a sharable one.
2106
:returns: The new repository object.
2108
This may raise UninitializableFormat if shared repository are not
2109
compatible the a_bzrdir.
2111
raise NotImplementedError(self.initialize)
2113
def is_supported(self):
2114
"""Is this format supported?
2116
Supported formats must be initializable and openable.
2117
Unsupported formats may not support initialization or committing or
2118
some other features depending on the reason for not being supported.
2122
def check_conversion_target(self, target_format):
2123
raise NotImplementedError(self.check_conversion_target)
2125
def open(self, a_bzrdir, _found=False):
2126
"""Return an instance of this format for the bzrdir a_bzrdir.
2128
_found is a private parameter, do not use it.
2130
raise NotImplementedError(self.open)
2133
class MetaDirRepositoryFormat(RepositoryFormat):
2134
"""Common base class for the new repositories using the metadir layout."""
2136
rich_root_data = False
2137
supports_tree_reference = False
2138
supports_external_lookups = False
2139
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2142
super(MetaDirRepositoryFormat, self).__init__()
2144
def _create_control_files(self, a_bzrdir):
2145
"""Create the required files and the initial control_files object."""
2146
# FIXME: RBC 20060125 don't peek under the covers
2147
# NB: no need to escape relative paths that are url safe.
2148
repository_transport = a_bzrdir.get_repository_transport(self)
2149
control_files = lockable_files.LockableFiles(repository_transport,
2150
'lock', lockdir.LockDir)
2151
control_files.create_lock()
2152
return control_files
2154
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
2155
"""Upload the initial blank content."""
2156
control_files = self._create_control_files(a_bzrdir)
2157
control_files.lock_write()
2158
transport = control_files._transport
2160
utf8_files += [('shared-storage', '')]
2162
transport.mkdir_multi(dirs, mode=a_bzrdir._get_dir_mode())
2163
for (filename, content_stream) in files:
2164
transport.put_file(filename, content_stream,
2165
mode=a_bzrdir._get_file_mode())
2166
for (filename, content_bytes) in utf8_files:
2167
transport.put_bytes_non_atomic(filename, content_bytes,
2168
mode=a_bzrdir._get_file_mode())
2170
control_files.unlock()
2173
# formats which have no format string are not discoverable
2174
# and not independently creatable, so are not registered. They're
2175
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
2176
# needed, it's constructed directly by the BzrDir. Non-native formats where
2177
# the repository is not separately opened are similar.
2179
format_registry.register_lazy(
2180
'Bazaar-NG Repository format 7',
2181
'bzrlib.repofmt.weaverepo',
2185
format_registry.register_lazy(
2186
'Bazaar-NG Knit Repository Format 1',
2187
'bzrlib.repofmt.knitrepo',
2188
'RepositoryFormatKnit1',
2191
format_registry.register_lazy(
2192
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
2193
'bzrlib.repofmt.knitrepo',
2194
'RepositoryFormatKnit3',
2197
format_registry.register_lazy(
2198
'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
2199
'bzrlib.repofmt.knitrepo',
2200
'RepositoryFormatKnit4',
2203
# Pack-based formats. There is one format for pre-subtrees, and one for
2204
# post-subtrees to allow ease of testing.
2205
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
2206
format_registry.register_lazy(
2207
'Bazaar pack repository format 1 (needs bzr 0.92)\n',
2208
'bzrlib.repofmt.pack_repo',
2209
'RepositoryFormatKnitPack1',
2211
format_registry.register_lazy(
2212
'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
2213
'bzrlib.repofmt.pack_repo',
2214
'RepositoryFormatKnitPack3',
2216
format_registry.register_lazy(
2217
'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
2218
'bzrlib.repofmt.pack_repo',
2219
'RepositoryFormatKnitPack4',
2221
# Development formats.
2223
# development 0 - stub to introduce development versioning scheme.
2224
format_registry.register_lazy(
2225
"Bazaar development format 0 (needs bzr.dev from before 1.3)\n",
2226
'bzrlib.repofmt.pack_repo',
2227
'RepositoryFormatPackDevelopment0',
2229
format_registry.register_lazy(
2230
("Bazaar development format 0 with subtree support "
2231
"(needs bzr.dev from before 1.3)\n"),
2232
'bzrlib.repofmt.pack_repo',
2233
'RepositoryFormatPackDevelopment0Subtree',
2235
# 1.3->1.4 go below here
2238
class InterRepository(InterObject):
2239
"""This class represents operations taking place between two repositories.
2241
Its instances have methods like copy_content and fetch, and contain
2242
references to the source and target repositories these operations can be
2245
Often we will provide convenience methods on 'repository' which carry out
2246
operations with another repository - they will always forward to
2247
InterRepository.get(other).method_name(parameters).
2251
"""The available optimised InterRepository types."""
2253
def copy_content(self, revision_id=None):
2254
raise NotImplementedError(self.copy_content)
2256
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2257
"""Fetch the content required to construct revision_id.
2259
The content is copied from self.source to self.target.
2261
:param revision_id: if None all content is copied, if NULL_REVISION no
2263
:param pb: optional progress bar to use for progress reports. If not
2264
provided a default one will be created.
2266
Returns the copied revision count and the failed revisions in a tuple:
2269
raise NotImplementedError(self.fetch)
2271
def _walk_to_common_revisions(self, revision_ids):
2272
"""Walk out from revision_ids in source to revisions target has.
2274
:param revision_ids: The start point for the search.
2275
:return: A set of revision ids.
2277
target_graph = self.target.get_graph()
2278
revision_ids = frozenset(revision_ids)
2279
if set(target_graph.get_parent_map(revision_ids)) == revision_ids:
2280
return graph.SearchResult(revision_ids, set(), 0, set())
2281
missing_revs = set()
2282
source_graph = self.source.get_graph()
2283
# ensure we don't pay silly lookup costs.
2284
searcher = source_graph._make_breadth_first_searcher(revision_ids)
2285
null_set = frozenset([_mod_revision.NULL_REVISION])
2288
next_revs, ghosts = searcher.next_with_ghosts()
2289
except StopIteration:
2291
if revision_ids.intersection(ghosts):
2292
absent_ids = set(revision_ids.intersection(ghosts))
2293
# If all absent_ids are present in target, no error is needed.
2294
absent_ids.difference_update(
2295
set(target_graph.get_parent_map(absent_ids)))
2297
raise errors.NoSuchRevision(self.source, absent_ids.pop())
2298
# we don't care about other ghosts as we can't fetch them and
2299
# haven't been asked to.
2300
next_revs = set(next_revs)
2301
# we always have NULL_REVISION present.
2302
have_revs = set(target_graph.get_parent_map(next_revs)).union(null_set)
2303
missing_revs.update(next_revs - have_revs)
2304
searcher.stop_searching_any(have_revs)
2305
return searcher.get_result()
2307
@deprecated_method(symbol_versioning.one_two)
2309
def missing_revision_ids(self, revision_id=None, find_ghosts=True):
2310
"""Return the revision ids that source has that target does not.
2312
These are returned in topological order.
2314
:param revision_id: only return revision ids included by this
2316
:param find_ghosts: If True find missing revisions in deep history
2317
rather than just finding the surface difference.
2319
return list(self.search_missing_revision_ids(
2320
revision_id, find_ghosts).get_keys())
2323
def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2324
"""Return the revision ids that source has that target does not.
2326
:param revision_id: only return revision ids included by this
2328
:param find_ghosts: If True find missing revisions in deep history
2329
rather than just finding the surface difference.
2330
:return: A bzrlib.graph.SearchResult.
2332
# stop searching at found target revisions.
2333
if not find_ghosts and revision_id is not None:
2334
return self._walk_to_common_revisions([revision_id])
2335
# generic, possibly worst case, slow code path.
2336
target_ids = set(self.target.all_revision_ids())
2337
if revision_id is not None:
2338
source_ids = self.source.get_ancestry(revision_id)
2339
if source_ids[0] is not None:
2340
raise AssertionError()
2343
source_ids = self.source.all_revision_ids()
2344
result_set = set(source_ids).difference(target_ids)
2345
return self.source.revision_ids_to_search_result(result_set)
2348
def _same_model(source, target):
2349
"""True if source and target have the same data representation."""
2350
if source.supports_rich_root() != target.supports_rich_root():
2352
if source._serializer != target._serializer:
2357
class InterSameDataRepository(InterRepository):
2358
"""Code for converting between repositories that represent the same data.
2360
Data format and model must match for this to work.
2364
def _get_repo_format_to_test(self):
2365
"""Repository format for testing with.
2367
InterSameData can pull from subtree to subtree and from non-subtree to
2368
non-subtree, so we test this with the richest repository format.
2370
from bzrlib.repofmt import knitrepo
2371
return knitrepo.RepositoryFormatKnit3()
2374
def is_compatible(source, target):
2375
return InterRepository._same_model(source, target)
2378
def copy_content(self, revision_id=None):
2379
"""Make a complete copy of the content in self into destination.
2381
This copies both the repository's revision data, and configuration information
2382
such as the make_working_trees setting.
2384
This is a destructive operation! Do not use it on existing
2387
:param revision_id: Only copy the content needed to construct
2388
revision_id and its parents.
2391
self.target.set_make_working_trees(self.source.make_working_trees())
2392
except NotImplementedError:
2394
# but don't bother fetching if we have the needed data now.
2395
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
2396
self.target.has_revision(revision_id)):
2398
self.target.fetch(self.source, revision_id=revision_id)
2401
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2402
"""See InterRepository.fetch()."""
2403
from bzrlib.fetch import GenericRepoFetcher
2404
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2405
self.source, self.source._format, self.target,
2406
self.target._format)
2407
f = GenericRepoFetcher(to_repository=self.target,
2408
from_repository=self.source,
2409
last_revision=revision_id,
2410
pb=pb, find_ghosts=find_ghosts)
2411
return f.count_copied, f.failed_revisions
2414
class InterWeaveRepo(InterSameDataRepository):
2415
"""Optimised code paths between Weave based repositories.
2417
This should be in bzrlib/repofmt/weaverepo.py but we have not yet
2418
implemented lazy inter-object optimisation.
2422
def _get_repo_format_to_test(self):
2423
from bzrlib.repofmt import weaverepo
2424
return weaverepo.RepositoryFormat7()
2427
def is_compatible(source, target):
2428
"""Be compatible with known Weave formats.
2430
We don't test for the stores being of specific types because that
2431
could lead to confusing results, and there is no need to be
2434
from bzrlib.repofmt.weaverepo import (
2440
return (isinstance(source._format, (RepositoryFormat5,
2442
RepositoryFormat7)) and
2443
isinstance(target._format, (RepositoryFormat5,
2445
RepositoryFormat7)))
2446
except AttributeError:
2450
def copy_content(self, revision_id=None):
2451
"""See InterRepository.copy_content()."""
2452
# weave specific optimised path:
2454
self.target.set_make_working_trees(self.source.make_working_trees())
2455
except (errors.RepositoryUpgradeRequired, NotImplemented):
2457
# FIXME do not peek!
2458
if self.source._transport.listable():
2459
pb = ui.ui_factory.nested_progress_bar()
2461
self.target.texts.insert_record_stream(
2462
self.source.texts.get_record_stream(
2463
self.source.texts.keys(), 'topological', False))
2464
pb.update('copying inventory', 0, 1)
2465
self.target.inventories.insert_record_stream(
2466
self.source.inventories.get_record_stream(
2467
self.source.inventories.keys(), 'topological', False))
2468
self.target.signatures.insert_record_stream(
2469
self.source.signatures.get_record_stream(
2470
self.source.signatures.keys(),
2472
self.target.revisions.insert_record_stream(
2473
self.source.revisions.get_record_stream(
2474
self.source.revisions.keys(),
2475
'topological', True))
2479
self.target.fetch(self.source, revision_id=revision_id)
2482
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2483
"""See InterRepository.fetch()."""
2484
from bzrlib.fetch import GenericRepoFetcher
2485
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2486
self.source, self.source._format, self.target, self.target._format)
2487
f = GenericRepoFetcher(to_repository=self.target,
2488
from_repository=self.source,
2489
last_revision=revision_id,
2490
pb=pb, find_ghosts=find_ghosts)
2491
return f.count_copied, f.failed_revisions
2494
def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2495
"""See InterRepository.missing_revision_ids()."""
2496
# we want all revisions to satisfy revision_id in source.
2497
# but we don't want to stat every file here and there.
2498
# we want then, all revisions other needs to satisfy revision_id
2499
# checked, but not those that we have locally.
2500
# so the first thing is to get a subset of the revisions to
2501
# satisfy revision_id in source, and then eliminate those that
2502
# we do already have.
2503
# this is slow on high latency connection to self, but as as this
2504
# disk format scales terribly for push anyway due to rewriting
2505
# inventory.weave, this is considered acceptable.
2507
if revision_id is not None:
2508
source_ids = self.source.get_ancestry(revision_id)
2509
if source_ids[0] is not None:
2510
raise AssertionError()
2513
source_ids = self.source._all_possible_ids()
2514
source_ids_set = set(source_ids)
2515
# source_ids is the worst possible case we may need to pull.
2516
# now we want to filter source_ids against what we actually
2517
# have in target, but don't try to check for existence where we know
2518
# we do not have a revision as that would be pointless.
2519
target_ids = set(self.target._all_possible_ids())
2520
possibly_present_revisions = target_ids.intersection(source_ids_set)
2521
actually_present_revisions = set(
2522
self.target._eliminate_revisions_not_present(possibly_present_revisions))
2523
required_revisions = source_ids_set.difference(actually_present_revisions)
2524
if revision_id is not None:
2525
# we used get_ancestry to determine source_ids then we are assured all
2526
# revisions referenced are present as they are installed in topological order.
2527
# and the tip revision was validated by get_ancestry.
2528
result_set = required_revisions
2530
# if we just grabbed the possibly available ids, then
2531
# we only have an estimate of whats available and need to validate
2532
# that against the revision records.
2534
self.source._eliminate_revisions_not_present(required_revisions))
2535
return self.source.revision_ids_to_search_result(result_set)
2538
class InterKnitRepo(InterSameDataRepository):
2539
"""Optimised code paths between Knit based repositories."""
2542
def _get_repo_format_to_test(self):
2543
from bzrlib.repofmt import knitrepo
2544
return knitrepo.RepositoryFormatKnit1()
2547
def is_compatible(source, target):
2548
"""Be compatible with known Knit formats.
2550
We don't test for the stores being of specific types because that
2551
could lead to confusing results, and there is no need to be
2554
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
2556
are_knits = (isinstance(source._format, RepositoryFormatKnit) and
2557
isinstance(target._format, RepositoryFormatKnit))
2558
except AttributeError:
2560
return are_knits and InterRepository._same_model(source, target)
2563
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2564
"""See InterRepository.fetch()."""
2565
from bzrlib.fetch import KnitRepoFetcher
2566
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2567
self.source, self.source._format, self.target, self.target._format)
2568
f = KnitRepoFetcher(to_repository=self.target,
2569
from_repository=self.source,
2570
last_revision=revision_id,
2571
pb=pb, find_ghosts=find_ghosts)
2572
return f.count_copied, f.failed_revisions
2575
def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2576
"""See InterRepository.missing_revision_ids()."""
2577
if revision_id is not None:
2578
source_ids = self.source.get_ancestry(revision_id)
2579
if source_ids[0] is not None:
2580
raise AssertionError()
2583
source_ids = self.source.all_revision_ids()
2584
source_ids_set = set(source_ids)
2585
# source_ids is the worst possible case we may need to pull.
2586
# now we want to filter source_ids against what we actually
2587
# have in target, but don't try to check for existence where we know
2588
# we do not have a revision as that would be pointless.
2589
target_ids = set(self.target.all_revision_ids())
2590
possibly_present_revisions = target_ids.intersection(source_ids_set)
2591
actually_present_revisions = set(
2592
self.target._eliminate_revisions_not_present(possibly_present_revisions))
2593
required_revisions = source_ids_set.difference(actually_present_revisions)
2594
if revision_id is not None:
2595
# we used get_ancestry to determine source_ids then we are assured all
2596
# revisions referenced are present as they are installed in topological order.
2597
# and the tip revision was validated by get_ancestry.
2598
result_set = required_revisions
2600
# if we just grabbed the possibly available ids, then
2601
# we only have an estimate of whats available and need to validate
2602
# that against the revision records.
2604
self.source._eliminate_revisions_not_present(required_revisions))
2605
return self.source.revision_ids_to_search_result(result_set)
2608
class InterPackRepo(InterSameDataRepository):
2609
"""Optimised code paths between Pack based repositories."""
2612
def _get_repo_format_to_test(self):
2613
from bzrlib.repofmt import pack_repo
2614
return pack_repo.RepositoryFormatKnitPack1()
2617
def is_compatible(source, target):
2618
"""Be compatible with known Pack formats.
2620
We don't test for the stores being of specific types because that
2621
could lead to confusing results, and there is no need to be
2624
from bzrlib.repofmt.pack_repo import RepositoryFormatPack
2626
are_packs = (isinstance(source._format, RepositoryFormatPack) and
2627
isinstance(target._format, RepositoryFormatPack))
2628
except AttributeError:
2630
return are_packs and InterRepository._same_model(source, target)
2633
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2634
"""See InterRepository.fetch()."""
2635
from bzrlib.repofmt.pack_repo import Packer
2636
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2637
self.source, self.source._format, self.target, self.target._format)
2638
self.count_copied = 0
2639
if revision_id is None:
2641
# everything to do - use pack logic
2642
# to fetch from all packs to one without
2643
# inventory parsing etc, IFF nothing to be copied is in the target.
2645
revision_ids = self.source.all_revision_ids()
2646
revision_keys = [(revid,) for revid in revision_ids]
2647
index = self.target._pack_collection.revision_index.combined_index
2648
present_revision_ids = set(item[1][0] for item in
2649
index.iter_entries(revision_keys))
2650
revision_ids = set(revision_ids) - present_revision_ids
2651
# implementing the TODO will involve:
2652
# - detecting when all of a pack is selected
2653
# - avoiding as much as possible pre-selection, so the
2654
# more-core routines such as create_pack_from_packs can filter in
2655
# a just-in-time fashion. (though having a HEADS list on a
2656
# repository might make this a lot easier, because we could
2657
# sensibly detect 'new revisions' without doing a full index scan.
2658
elif _mod_revision.is_null(revision_id):
2663
revision_ids = self.search_missing_revision_ids(revision_id,
2664
find_ghosts=find_ghosts).get_keys()
2665
except errors.NoSuchRevision:
2666
raise errors.InstallFailed([revision_id])
2667
if len(revision_ids) == 0:
2669
packs = self.source._pack_collection.all_packs()
2670
pack = Packer(self.target._pack_collection, packs, '.fetch',
2671
revision_ids).pack()
2672
if pack is not None:
2673
self.target._pack_collection._save_pack_names()
2674
# Trigger an autopack. This may duplicate effort as we've just done
2675
# a pack creation, but for now it is simpler to think about as
2676
# 'upload data, then repack if needed'.
2677
self.target._pack_collection.autopack()
2678
return (pack.get_revision_count(), [])
2683
def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2684
"""See InterRepository.missing_revision_ids().
2686
:param find_ghosts: Find ghosts throughout the ancestry of
2689
if not find_ghosts and revision_id is not None:
2690
return self._walk_to_common_revisions([revision_id])
2691
elif revision_id is not None:
2692
source_ids = self.source.get_ancestry(revision_id)
2693
if source_ids[0] is not None:
2694
raise AssertionError()
2697
source_ids = self.source.all_revision_ids()
2698
# source_ids is the worst possible case we may need to pull.
2699
# now we want to filter source_ids against what we actually
2700
# have in target, but don't try to check for existence where we know
2701
# we do not have a revision as that would be pointless.
2702
target_ids = set(self.target.all_revision_ids())
2703
result_set = set(source_ids).difference(target_ids)
2704
return self.source.revision_ids_to_search_result(result_set)
2707
class InterModel1and2(InterRepository):
2710
def _get_repo_format_to_test(self):
2714
def is_compatible(source, target):
2715
if not source.supports_rich_root() and target.supports_rich_root():
2721
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2722
"""See InterRepository.fetch()."""
2723
from bzrlib.fetch import Model1toKnit2Fetcher
2724
f = Model1toKnit2Fetcher(to_repository=self.target,
2725
from_repository=self.source,
2726
last_revision=revision_id,
2727
pb=pb, find_ghosts=find_ghosts)
2728
return f.count_copied, f.failed_revisions
2731
def copy_content(self, revision_id=None):
2732
"""Make a complete copy of the content in self into destination.
2734
This is a destructive operation! Do not use it on existing
2737
:param revision_id: Only copy the content needed to construct
2738
revision_id and its parents.
2741
self.target.set_make_working_trees(self.source.make_working_trees())
2742
except NotImplementedError:
2744
# but don't bother fetching if we have the needed data now.
2745
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
2746
self.target.has_revision(revision_id)):
2748
self.target.fetch(self.source, revision_id=revision_id)
2751
class InterKnit1and2(InterKnitRepo):
2754
def _get_repo_format_to_test(self):
2758
def is_compatible(source, target):
2759
"""Be compatible with Knit1 source and Knit3 target"""
2760
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
2762
from bzrlib.repofmt.knitrepo import (RepositoryFormatKnit1,
2763
RepositoryFormatKnit3)
2764
from bzrlib.repofmt.pack_repo import (
2765
RepositoryFormatKnitPack1,
2766
RepositoryFormatKnitPack3,
2767
RepositoryFormatPackDevelopment0,
2768
RepositoryFormatPackDevelopment0Subtree,
2771
RepositoryFormatKnit1,
2772
RepositoryFormatKnitPack1,
2773
RepositoryFormatPackDevelopment0,
2776
RepositoryFormatKnit3,
2777
RepositoryFormatKnitPack3,
2778
RepositoryFormatPackDevelopment0Subtree,
2780
return (isinstance(source._format, nosubtrees) and
2781
isinstance(target._format, subtrees))
2782
except AttributeError:
2786
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2787
"""See InterRepository.fetch()."""
2788
from bzrlib.fetch import Knit1to2Fetcher
2789
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2790
self.source, self.source._format, self.target,
2791
self.target._format)
2792
f = Knit1to2Fetcher(to_repository=self.target,
2793
from_repository=self.source,
2794
last_revision=revision_id,
2795
pb=pb, find_ghosts=find_ghosts)
2796
return f.count_copied, f.failed_revisions
2799
class InterDifferingSerializer(InterKnitRepo):
2802
def _get_repo_format_to_test(self):
2806
def is_compatible(source, target):
2807
"""Be compatible with Knit2 source and Knit3 target"""
2808
if source.supports_rich_root() != target.supports_rich_root():
2810
# Ideally, we'd support fetching if the source had no tree references
2811
# even if it supported them...
2812
if (getattr(source, '_format.supports_tree_reference', False) and
2813
not getattr(target, '_format.supports_tree_reference', False)):
2818
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2819
"""See InterRepository.fetch()."""
2820
revision_ids = self.target.search_missing_revision_ids(self.source,
2821
revision_id, find_ghosts=find_ghosts).get_keys()
2822
revision_ids = tsort.topo_sort(
2823
self.source.get_graph().get_parent_map(revision_ids))
2824
def revisions_iterator():
2825
for current_revision_id in revision_ids:
2826
revision = self.source.get_revision(current_revision_id)
2827
tree = self.source.revision_tree(current_revision_id)
2829
signature = self.source.get_signature_text(
2830
current_revision_id)
2831
except errors.NoSuchRevision:
2833
yield revision, tree, signature
2835
my_pb = ui.ui_factory.nested_progress_bar()
2840
install_revisions(self.target, revisions_iterator(),
2841
len(revision_ids), pb)
2843
if my_pb is not None:
2845
return len(revision_ids), 0
2848
class InterOtherToRemote(InterRepository):
2850
def __init__(self, source, target):
2851
InterRepository.__init__(self, source, target)
2852
self._real_inter = None
2855
def is_compatible(source, target):
2856
if isinstance(target, remote.RemoteRepository):
2860
def _ensure_real_inter(self):
2861
if self._real_inter is None:
2862
self.target._ensure_real()
2863
real_target = self.target._real_repository
2864
self._real_inter = InterRepository.get(self.source, real_target)
2866
def copy_content(self, revision_id=None):
2867
self._ensure_real_inter()
2868
self._real_inter.copy_content(revision_id=revision_id)
2870
def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2871
self._ensure_real_inter()
2872
self._real_inter.fetch(revision_id=revision_id, pb=pb,
2873
find_ghosts=find_ghosts)
2876
def _get_repo_format_to_test(self):
2880
InterRepository.register_optimiser(InterDifferingSerializer)
2881
InterRepository.register_optimiser(InterSameDataRepository)
2882
InterRepository.register_optimiser(InterWeaveRepo)
2883
InterRepository.register_optimiser(InterKnitRepo)
2884
InterRepository.register_optimiser(InterModel1and2)
2885
InterRepository.register_optimiser(InterKnit1and2)
2886
InterRepository.register_optimiser(InterPackRepo)
2887
InterRepository.register_optimiser(InterOtherToRemote)
2890
class CopyConverter(object):
2891
"""A repository conversion tool which just performs a copy of the content.
2893
This is slow but quite reliable.
2896
def __init__(self, target_format):
2897
"""Create a CopyConverter.
2899
:param target_format: The format the resulting repository should be.
2901
self.target_format = target_format
2903
def convert(self, repo, pb):
2904
"""Perform the conversion of to_convert, giving feedback via pb.
2906
:param to_convert: The disk object to convert.
2907
:param pb: a progress bar to use for progress information.
2912
# this is only useful with metadir layouts - separated repo content.
2913
# trigger an assertion if not such
2914
repo._format.get_format_string()
2915
self.repo_dir = repo.bzrdir
2916
self.step('Moving repository to repository.backup')
2917
self.repo_dir.transport.move('repository', 'repository.backup')
2918
backup_transport = self.repo_dir.transport.clone('repository.backup')
2919
repo._format.check_conversion_target(self.target_format)
2920
self.source_repo = repo._format.open(self.repo_dir,
2922
_override_transport=backup_transport)
2923
self.step('Creating new repository')
2924
converted = self.target_format.initialize(self.repo_dir,
2925
self.source_repo.is_shared())
2926
converted.lock_write()
2928
self.step('Copying content into repository.')
2929
self.source_repo.copy_content_into(converted)
2932
self.step('Deleting old repository content.')
2933
self.repo_dir.transport.delete_tree('repository.backup')
2934
self.pb.note('repository converted')
2936
def step(self, message):
2937
"""Update the pb by a step."""
2939
self.pb.update(message, self.count, self.total)
2951
def _unescaper(match, _map=_unescape_map):
2952
code = match.group(1)
2956
if not code.startswith('#'):
2958
return unichr(int(code[1:])).encode('utf8')
2964
def _unescape_xml(data):
2965
"""Unescape predefined XML entities in a string of data."""
2967
if _unescape_re is None:
2968
_unescape_re = re.compile('\&([^;]*);')
2969
return _unescape_re.sub(_unescaper, data)
2972
class _VersionedFileChecker(object):
2974
def __init__(self, repository):
2975
self.repository = repository
2976
self.text_index = self.repository._generate_text_key_index()
2978
def calculate_file_version_parents(self, text_key):
2979
"""Calculate the correct parents for a file version according to
2982
parent_keys = self.text_index[text_key]
2983
if parent_keys == [_mod_revision.NULL_REVISION]:
2985
return tuple(parent_keys)
2987
def check_file_version_parents(self, texts, progress_bar=None):
2988
"""Check the parents stored in a versioned file are correct.
2990
It also detects file versions that are not referenced by their
2991
corresponding revision's inventory.
2993
:returns: A tuple of (wrong_parents, dangling_file_versions).
2994
wrong_parents is a dict mapping {revision_id: (stored_parents,
2995
correct_parents)} for each revision_id where the stored parents
2996
are not correct. dangling_file_versions is a set of (file_id,
2997
revision_id) tuples for versions that are present in this versioned
2998
file, but not used by the corresponding inventory.
3001
self.file_ids = set([file_id for file_id, _ in
3002
self.text_index.iterkeys()])
3003
# text keys is now grouped by file_id
3004
n_weaves = len(self.file_ids)
3005
files_in_revisions = {}
3006
revisions_of_files = {}
3007
n_versions = len(self.text_index)
3008
progress_bar.update('loading text store', 0, n_versions)
3009
parent_map = self.repository.texts.get_parent_map(self.text_index)
3010
# On unlistable transports this could well be empty/error...
3011
text_keys = self.repository.texts.keys()
3012
unused_keys = frozenset(text_keys) - set(self.text_index)
3013
for num, key in enumerate(self.text_index.iterkeys()):
3014
if progress_bar is not None:
3015
progress_bar.update('checking text graph', num, n_versions)
3016
correct_parents = self.calculate_file_version_parents(key)
3018
knit_parents = parent_map[key]
3019
except errors.RevisionNotPresent:
3022
if correct_parents != knit_parents:
3023
wrong_parents[key] = (knit_parents, correct_parents)
3024
return wrong_parents, unused_keys
3027
def _old_get_graph(repository, revision_id):
3028
"""DO NOT USE. That is all. I'm serious."""
3029
graph = repository.get_graph()
3030
revision_graph = dict(((key, value) for key, value in
3031
graph.iter_ancestry([revision_id]) if value is not None))
3032
return _strip_NULL_ghosts(revision_graph)
3035
def _strip_NULL_ghosts(revision_graph):
3036
"""Also don't use this. more compatibility code for unmigrated clients."""
3037
# Filter ghosts, and null:
3038
if _mod_revision.NULL_REVISION in revision_graph:
3039
del revision_graph[_mod_revision.NULL_REVISION]
3040
for key, parents in revision_graph.items():
3041
revision_graph[key] = tuple(parent for parent in parents if parent
3043
return revision_graph