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,
44
from bzrlib.bundle import serializer
45
from bzrlib.revisiontree import RevisionTree
46
from bzrlib.store.versioned import VersionedFileStore
47
from bzrlib.store.text import TextStore
48
from bzrlib.testament import Testament
51
from bzrlib.decorators import needs_read_lock, needs_write_lock
52
from bzrlib.inter import InterObject
53
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
54
from bzrlib.symbol_versioning import (
57
from bzrlib.trace import mutter, mutter_callsite, note, warning
60
# Old formats display a warning, but only once
61
_deprecation_warning_done = False
64
class CommitBuilder(object):
65
"""Provides an interface to build up a commit.
67
This allows describing a tree to be committed without needing to
68
know the internals of the format of the repository.
71
# all clients should supply tree roots.
72
record_root_entry = True
73
# the default CommitBuilder does not manage trees whose root is versioned.
74
_versioned_root = False
76
def __init__(self, repository, parents, config, timestamp=None,
77
timezone=None, committer=None, revprops=None,
79
"""Initiate a CommitBuilder.
81
:param repository: Repository to commit to.
82
:param parents: Revision ids of the parents of the new revision.
83
:param config: Configuration to use.
84
:param timestamp: Optional timestamp recorded for commit.
85
:param timezone: Optional timezone for timestamp.
86
:param committer: Optional committer to set for commit.
87
:param revprops: Optional dictionary of revision properties.
88
:param revision_id: Optional revision id.
93
self._committer = self._config.username()
95
assert isinstance(committer, basestring), type(committer)
96
self._committer = committer
98
self.new_inventory = Inventory(None)
99
self._new_revision_id = revision_id
100
self.parents = parents
101
self.repository = repository
104
if revprops is not None:
105
self._revprops.update(revprops)
107
if timestamp is None:
108
timestamp = time.time()
109
# Restrict resolution to 1ms
110
self._timestamp = round(timestamp, 3)
113
self._timezone = osutils.local_time_offset()
115
self._timezone = int(timezone)
117
self._generate_revision_if_needed()
119
def commit(self, message):
120
"""Make the actual commit.
122
:return: The revision id of the recorded revision.
124
rev = _mod_revision.Revision(
125
timestamp=self._timestamp,
126
timezone=self._timezone,
127
committer=self._committer,
129
inventory_sha1=self.inv_sha1,
130
revision_id=self._new_revision_id,
131
properties=self._revprops)
132
rev.parent_ids = self.parents
133
self.repository.add_revision(self._new_revision_id, rev,
134
self.new_inventory, self._config)
135
self.repository.commit_write_group()
136
return self._new_revision_id
139
"""Abort the commit that is being built.
141
self.repository.abort_write_group()
143
def revision_tree(self):
144
"""Return the tree that was just committed.
146
After calling commit() this can be called to get a RevisionTree
147
representing the newly committed tree. This is preferred to
148
calling Repository.revision_tree() because that may require
149
deserializing the inventory, while we already have a copy in
152
return RevisionTree(self.repository, self.new_inventory,
153
self._new_revision_id)
155
def finish_inventory(self):
156
"""Tell the builder that the inventory is finished."""
157
if self.new_inventory.root is None:
158
symbol_versioning.warn('Root entry should be supplied to'
159
' record_entry_contents, as of bzr 0.10.',
160
DeprecationWarning, stacklevel=2)
161
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
162
self.new_inventory.revision_id = self._new_revision_id
163
self.inv_sha1 = self.repository.add_inventory(
164
self._new_revision_id,
169
def _gen_revision_id(self):
170
"""Return new revision-id."""
171
return generate_ids.gen_revision_id(self._config.username(),
174
def _generate_revision_if_needed(self):
175
"""Create a revision id if None was supplied.
177
If the repository can not support user-specified revision ids
178
they should override this function and raise CannotSetRevisionId
179
if _new_revision_id is not None.
181
:raises: CannotSetRevisionId
183
if self._new_revision_id is None:
184
self._new_revision_id = self._gen_revision_id()
185
self.random_revid = True
187
self.random_revid = False
189
def _check_root(self, ie, parent_invs, tree):
190
"""Helper for record_entry_contents.
192
:param ie: An entry being added.
193
:param parent_invs: The inventories of the parent revisions of the
195
:param tree: The tree that is being committed.
197
if ie.parent_id is not None:
198
# if ie is not root, add a root automatically.
199
symbol_versioning.warn('Root entry should be supplied to'
200
' record_entry_contents, as of bzr 0.10.',
201
DeprecationWarning, stacklevel=2)
202
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
205
# In this revision format, root entries have no knit or weave When
206
# serializing out to disk and back in root.revision is always
208
ie.revision = self._new_revision_id
210
def record_entry_contents(self, ie, parent_invs, path, tree):
211
"""Record the content of ie from tree into the commit if needed.
213
Side effect: sets ie.revision when unchanged
215
:param ie: An inventory entry present in the commit.
216
:param parent_invs: The inventories of the parent revisions of the
218
:param path: The path the entry is at in the tree.
219
:param tree: The tree which contains this entry and should be used to
221
:return: True if a new version of the entry has been recorded.
222
(Committing a merge where a file was only changed on the other side
223
will not return True.)
225
if self.new_inventory.root is None:
226
self._check_root(ie, parent_invs, tree)
227
self.new_inventory.add(ie)
229
# ie.revision is always None if the InventoryEntry is considered
230
# for committing. ie.snapshot will record the correct revision
231
# which may be the sole parent if it is untouched.
232
if ie.revision is not None:
233
return ie.revision == self._new_revision_id and (path != '' or
234
self._versioned_root)
236
parent_candiate_entries = ie.parent_candidates(parent_invs)
237
heads = self.repository.get_graph().heads(parent_candiate_entries.keys())
238
# XXX: Note that this is unordered - and this is tolerable because
239
# the previous code was also unordered.
240
previous_entries = dict((head, parent_candiate_entries[head]) for head
242
# we are creating a new revision for ie in the history store and
244
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
245
return ie.revision == self._new_revision_id and (path != '' or
246
self._versioned_root)
248
def modified_directory(self, file_id, file_parents):
249
"""Record the presence of a symbolic link.
251
:param file_id: The file_id of the link to record.
252
:param file_parents: The per-file parent revision ids.
254
self._add_text_to_weave(file_id, [], file_parents.keys())
256
def modified_reference(self, file_id, file_parents):
257
"""Record the modification of a reference.
259
:param file_id: The file_id of the link to record.
260
:param file_parents: The per-file parent revision ids.
262
self._add_text_to_weave(file_id, [], file_parents.keys())
264
def modified_file_text(self, file_id, file_parents,
265
get_content_byte_lines, text_sha1=None,
267
"""Record the text of file file_id
269
:param file_id: The file_id of the file to record the text of.
270
:param file_parents: The per-file parent revision ids.
271
:param get_content_byte_lines: A callable which will return the byte
273
:param text_sha1: Optional SHA1 of the file contents.
274
:param text_size: Optional size of the file contents.
276
# mutter('storing text of file {%s} in revision {%s} into %r',
277
# file_id, self._new_revision_id, self.repository.weave_store)
278
# special case to avoid diffing on renames or
280
if (len(file_parents) == 1
281
and text_sha1 == file_parents.values()[0].text_sha1
282
and text_size == file_parents.values()[0].text_size):
283
previous_ie = file_parents.values()[0]
284
versionedfile = self.repository.weave_store.get_weave(file_id,
285
self.repository.get_transaction())
286
versionedfile.clone_text(self._new_revision_id,
287
previous_ie.revision, file_parents.keys())
288
return text_sha1, text_size
290
new_lines = get_content_byte_lines()
291
return self._add_text_to_weave(file_id, new_lines,
294
def modified_link(self, file_id, file_parents, link_target):
295
"""Record the presence of a symbolic link.
297
:param file_id: The file_id of the link to record.
298
:param file_parents: The per-file parent revision ids.
299
:param link_target: Target location of this link.
301
self._add_text_to_weave(file_id, [], file_parents.keys())
303
def _add_text_to_weave(self, file_id, new_lines, parents):
304
versionedfile = self.repository.weave_store.get_weave_or_empty(
305
file_id, self.repository.get_transaction())
306
# Don't change this to add_lines - add_lines_with_ghosts is cheaper
307
# than add_lines, and allows committing when a parent is ghosted for
309
# Note: as we read the content directly from the tree, we know its not
310
# been turned into unicode or badly split - but a broken tree
311
# implementation could give us bad output from readlines() so this is
312
# not a guarantee of safety. What would be better is always checking
313
# the content during test suite execution. RBC 20070912
314
result = versionedfile.add_lines_with_ghosts(
315
self._new_revision_id, parents, new_lines,
316
random_id=self.random_revid, check_content=False)[0:2]
317
versionedfile.clear_cache()
321
class RootCommitBuilder(CommitBuilder):
322
"""This commitbuilder actually records the root id"""
324
# the root entry gets versioned properly by this builder.
325
_versioned_root = True
327
def _check_root(self, ie, parent_invs, tree):
328
"""Helper for record_entry_contents.
330
:param ie: An entry being added.
331
:param parent_invs: The inventories of the parent revisions of the
333
:param tree: The tree that is being committed.
335
# ie must be root for this builder
336
assert ie.parent_id is None
339
######################################################################
342
class Repository(object):
343
"""Repository holding history for one or more branches.
345
The repository holds and retrieves historical information including
346
revisions and file history. It's normally accessed only by the Branch,
347
which views a particular line of development through that history.
349
The Repository builds on top of Stores and a Transport, which respectively
350
describe the disk data format and the way of accessing the (possibly
354
# What class to use for a CommitBuilder. Often its simpler to change this
355
# in a Repository class subclass rather than to override
356
# get_commit_builder.
357
_commit_builder_class = CommitBuilder
358
# The search regex used by xml based repositories to determine what things
359
# where changed in a single commit.
360
_file_ids_altered_regex = lazy_regex.lazy_compile(
361
r'file_id="(?P<file_id>[^"]+)"'
362
r'.* revision="(?P<revision_id>[^"]+)"'
365
def abort_write_group(self):
366
"""Commit the contents accrued within the current write group.
368
:seealso: start_write_group.
370
if self._write_group is not self.get_transaction():
371
# has an unlock or relock occured ?
372
raise errors.BzrError('mismatched lock context and write group.')
373
self._abort_write_group()
374
self._write_group = None
376
def _abort_write_group(self):
377
"""Template method for per-repository write group cleanup.
379
This is called during abort before the write group is considered to be
380
finished and should cleanup any internal state accrued during the write
381
group. There is no requirement that data handed to the repository be
382
*not* made available - this is not a rollback - but neither should any
383
attempt be made to ensure that data added is fully commited. Abort is
384
invoked when an error has occured so futher disk or network operations
385
may not be possible or may error and if possible should not be
390
def add_inventory(self, revision_id, inv, parents):
391
"""Add the inventory inv to the repository as revision_id.
393
:param parents: The revision ids of the parents that revision_id
394
is known to have and are in the repository already.
396
returns the sha1 of the serialized inventory.
398
_mod_revision.check_not_reserved_id(revision_id)
399
assert inv.revision_id is None or inv.revision_id == revision_id, \
400
"Mismatch between inventory revision" \
401
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
402
assert inv.root is not None
403
inv_lines = self._serialise_inventory_to_lines(inv)
404
inv_vf = self.get_inventory_weave()
405
return self._inventory_add_lines(inv_vf, revision_id, parents,
406
inv_lines, check_content=False)
408
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines,
410
"""Store lines in inv_vf and return the sha1 of the inventory."""
412
for parent in parents:
414
final_parents.append(parent)
415
return inv_vf.add_lines(revision_id, final_parents, lines,
416
check_content=check_content)[0]
419
def add_revision(self, revision_id, rev, inv=None, config=None):
420
"""Add rev to the revision store as revision_id.
422
:param revision_id: the revision id to use.
423
:param rev: The revision object.
424
:param inv: The inventory for the revision. if None, it will be looked
425
up in the inventory storer
426
:param config: If None no digital signature will be created.
427
If supplied its signature_needed method will be used
428
to determine if a signature should be made.
430
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
432
_mod_revision.check_not_reserved_id(revision_id)
433
if config is not None and config.signature_needed():
435
inv = self.get_inventory(revision_id)
436
plaintext = Testament(rev, inv).as_short_text()
437
self.store_revision_signature(
438
gpg.GPGStrategy(config), plaintext, revision_id)
439
if not revision_id in self.get_inventory_weave():
441
raise errors.WeaveRevisionNotPresent(revision_id,
442
self.get_inventory_weave())
444
# yes, this is not suitable for adding with ghosts.
445
self.add_inventory(revision_id, inv, rev.parent_ids)
446
self._revision_store.add_revision(rev, self.get_transaction())
448
def _add_revision_text(self, revision_id, text):
449
revision = self._revision_store._serializer.read_revision_from_string(
451
self._revision_store._add_revision(revision, StringIO(text),
452
self.get_transaction())
454
def all_revision_ids(self):
455
"""Returns a list of all the revision ids in the repository.
457
This is deprecated because code should generally work on the graph
458
reachable from a particular revision, and ignore any other revisions
459
that might be present. There is no direct replacement method.
461
if 'evil' in debug.debug_flags:
462
mutter_callsite(2, "all_revision_ids is linear with history.")
463
return self._all_revision_ids()
465
def _all_revision_ids(self):
466
"""Returns a list of all the revision ids in the repository.
468
These are in as much topological order as the underlying store can
471
raise NotImplementedError(self._all_revision_ids)
473
def break_lock(self):
474
"""Break a lock if one is present from another instance.
476
Uses the ui factory to ask for confirmation if the lock may be from
479
self.control_files.break_lock()
482
def _eliminate_revisions_not_present(self, revision_ids):
483
"""Check every revision id in revision_ids to see if we have it.
485
Returns a set of the present revisions.
488
for id in revision_ids:
489
if self.has_revision(id):
494
def create(a_bzrdir):
495
"""Construct the current default format repository in a_bzrdir."""
496
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
498
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
499
"""instantiate a Repository.
501
:param _format: The format of the repository on disk.
502
:param a_bzrdir: The BzrDir of the repository.
504
In the future we will have a single api for all stores for
505
getting file texts, inventories and revisions, then
506
this construct will accept instances of those things.
508
super(Repository, self).__init__()
509
self._format = _format
510
# the following are part of the public API for Repository:
511
self.bzrdir = a_bzrdir
512
self.control_files = control_files
513
self._revision_store = _revision_store
514
# backwards compatibility
515
self.weave_store = text_store
517
self._reconcile_does_inventory_gc = True
518
# not right yet - should be more semantically clear ?
520
self.control_store = control_store
521
self.control_weaves = control_store
522
# TODO: make sure to construct the right store classes, etc, depending
523
# on whether escaping is required.
524
self._warn_if_deprecated()
525
self._write_group = None
528
return '%s(%r)' % (self.__class__.__name__,
529
self.bzrdir.transport.base)
531
def has_same_location(self, other):
532
"""Returns a boolean indicating if this repository is at the same
533
location as another repository.
535
This might return False even when two repository objects are accessing
536
the same physical repository via different URLs.
538
if self.__class__ is not other.__class__:
540
return (self.control_files._transport.base ==
541
other.control_files._transport.base)
543
def is_in_write_group(self):
544
"""Return True if there is an open write group.
546
:seealso: start_write_group.
548
return self._write_group is not None
551
return self.control_files.is_locked()
553
def lock_write(self, token=None):
554
"""Lock this repository for writing.
556
This causes caching within the repository obejct to start accumlating
557
data during reads, and allows a 'write_group' to be obtained. Write
558
groups must be used for actual data insertion.
560
:param token: if this is already locked, then lock_write will fail
561
unless the token matches the existing lock.
562
:returns: a token if this instance supports tokens, otherwise None.
563
:raises TokenLockingNotSupported: when a token is given but this
564
instance doesn't support using token locks.
565
:raises MismatchedToken: if the specified token doesn't match the token
566
of the existing lock.
567
:seealso: start_write_group.
569
A token should be passed in if you know that you have locked the object
570
some other way, and need to synchronise this object's state with that
573
XXX: this docstring is duplicated in many places, e.g. lockable_files.py
575
result = self.control_files.lock_write(token=token)
580
self.control_files.lock_read()
583
def get_physical_lock_status(self):
584
return self.control_files.get_physical_lock_status()
586
def leave_lock_in_place(self):
587
"""Tell this repository not to release the physical lock when this
590
If lock_write doesn't return a token, then this method is not supported.
592
self.control_files.leave_in_place()
594
def dont_leave_lock_in_place(self):
595
"""Tell this repository to release the physical lock when this
596
object is unlocked, even if it didn't originally acquire it.
598
If lock_write doesn't return a token, then this method is not supported.
600
self.control_files.dont_leave_in_place()
603
def gather_stats(self, revid=None, committers=None):
604
"""Gather statistics from a revision id.
606
:param revid: The revision id to gather statistics from, if None, then
607
no revision specific statistics are gathered.
608
:param committers: Optional parameter controlling whether to grab
609
a count of committers from the revision specific statistics.
610
:return: A dictionary of statistics. Currently this contains:
611
committers: The number of committers if requested.
612
firstrev: A tuple with timestamp, timezone for the penultimate left
613
most ancestor of revid, if revid is not the NULL_REVISION.
614
latestrev: A tuple with timestamp, timezone for revid, if revid is
615
not the NULL_REVISION.
616
revisions: The total revision count in the repository.
617
size: An estimate disk size of the repository in bytes.
620
if revid and committers:
621
result['committers'] = 0
622
if revid and revid != _mod_revision.NULL_REVISION:
624
all_committers = set()
625
revisions = self.get_ancestry(revid)
626
# pop the leading None
628
first_revision = None
630
# ignore the revisions in the middle - just grab first and last
631
revisions = revisions[0], revisions[-1]
632
for revision in self.get_revisions(revisions):
633
if not first_revision:
634
first_revision = revision
636
all_committers.add(revision.committer)
637
last_revision = revision
639
result['committers'] = len(all_committers)
640
result['firstrev'] = (first_revision.timestamp,
641
first_revision.timezone)
642
result['latestrev'] = (last_revision.timestamp,
643
last_revision.timezone)
645
# now gather global repository information
646
if self.bzrdir.root_transport.listable():
647
c, t = self._revision_store.total_size(self.get_transaction())
648
result['revisions'] = c
653
def missing_revision_ids(self, other, revision_id=None):
654
"""Return the revision ids that other has that this does not.
656
These are returned in topological order.
658
revision_id: only return revision ids included by revision_id.
660
return InterRepository.get(other, self).missing_revision_ids(revision_id)
664
"""Open the repository rooted at base.
666
For instance, if the repository is at URL/.bzr/repository,
667
Repository.open(URL) -> a Repository instance.
669
control = bzrdir.BzrDir.open(base)
670
return control.open_repository()
672
def copy_content_into(self, destination, revision_id=None):
673
"""Make a complete copy of the content in self into destination.
675
This is a destructive operation! Do not use it on existing
678
return InterRepository.get(self, destination).copy_content(revision_id)
680
def commit_write_group(self):
681
"""Commit the contents accrued within the current write group.
683
:seealso: start_write_group.
685
if self._write_group is not self.get_transaction():
686
# has an unlock or relock occured ?
687
raise errors.BzrError('mismatched lock context and write group.')
688
self._commit_write_group()
689
self._write_group = None
691
def _commit_write_group(self):
692
"""Template method for per-repository write group cleanup.
694
This is called before the write group is considered to be
695
finished and should ensure that all data handed to the repository
696
for writing during the write group is safely committed (to the
697
extent possible considering file system caching etc).
700
def fetch(self, source, revision_id=None, pb=None):
701
"""Fetch the content required to construct revision_id from source.
703
If revision_id is None all content is copied.
705
inter = InterRepository.get(source, self)
707
return inter.fetch(revision_id=revision_id, pb=pb)
708
except NotImplementedError:
709
raise errors.IncompatibleRepositories(source, self)
711
def create_bundle(self, target, base, fileobj, format=None):
712
return serializer.write_bundle(self, target, base, fileobj, format)
714
def get_commit_builder(self, branch, parents, config, timestamp=None,
715
timezone=None, committer=None, revprops=None,
717
"""Obtain a CommitBuilder for this repository.
719
:param branch: Branch to commit to.
720
:param parents: Revision ids of the parents of the new revision.
721
:param config: Configuration to use.
722
:param timestamp: Optional timestamp recorded for commit.
723
:param timezone: Optional timezone for timestamp.
724
:param committer: Optional committer to set for commit.
725
:param revprops: Optional dictionary of revision properties.
726
:param revision_id: Optional revision id.
728
result = self._commit_builder_class(self, parents, config,
729
timestamp, timezone, committer, revprops, revision_id)
730
self.start_write_group()
734
if (self.control_files._lock_count == 1 and
735
self.control_files._lock_mode == 'w'):
736
if self._write_group is not None:
737
raise errors.BzrError(
738
'Must end write groups before releasing write locks.')
739
self.control_files.unlock()
742
def clone(self, a_bzrdir, revision_id=None):
743
"""Clone this repository into a_bzrdir using the current format.
745
Currently no check is made that the format of this repository and
746
the bzrdir format are compatible. FIXME RBC 20060201.
748
:return: The newly created destination repository.
750
# TODO: deprecate after 0.16; cloning this with all its settings is
751
# probably not very useful -- mbp 20070423
752
dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
753
self.copy_content_into(dest_repo, revision_id)
756
def start_write_group(self):
757
"""Start a write group in the repository.
759
Write groups are used by repositories which do not have a 1:1 mapping
760
between file ids and backend store to manage the insertion of data from
761
both fetch and commit operations.
763
A write lock is required around the start_write_group/commit_write_group
764
for the support of lock-requiring repository formats.
766
One can only insert data into a repository inside a write group.
770
if not self.is_locked() or self.control_files._lock_mode != 'w':
771
raise errors.NotWriteLocked(self)
772
if self._write_group:
773
raise errors.BzrError('already in a write group')
774
self._start_write_group()
775
# so we can detect unlock/relock - the write group is now entered.
776
self._write_group = self.get_transaction()
778
def _start_write_group(self):
779
"""Template method for per-repository write group startup.
781
This is called before the write group is considered to be
786
def sprout(self, to_bzrdir, revision_id=None):
787
"""Create a descendent repository for new development.
789
Unlike clone, this does not copy the settings of the repository.
791
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
792
dest_repo.fetch(self, revision_id=revision_id)
795
def _create_sprouting_repo(self, a_bzrdir, shared):
796
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
797
# use target default format.
798
dest_repo = a_bzrdir.create_repository()
800
# Most control formats need the repository to be specifically
801
# created, but on some old all-in-one formats it's not needed
803
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
804
except errors.UninitializableFormat:
805
dest_repo = a_bzrdir.open_repository()
809
def has_revision(self, revision_id):
810
"""True if this repository has a copy of the revision."""
811
if 'evil' in debug.debug_flags:
812
mutter_callsite(2, "has_revision is a LBYL symptom.")
813
return self._revision_store.has_revision_id(revision_id,
814
self.get_transaction())
817
def get_revision(self, revision_id):
818
"""Return the Revision object for a named revision."""
819
return self.get_revisions([revision_id])[0]
822
def get_revision_reconcile(self, revision_id):
823
"""'reconcile' helper routine that allows access to a revision always.
825
This variant of get_revision does not cross check the weave graph
826
against the revision one as get_revision does: but it should only
827
be used by reconcile, or reconcile-alike commands that are correcting
828
or testing the revision graph.
830
return self._get_revisions([revision_id])[0]
833
def get_revisions(self, revision_ids):
834
"""Get many revisions at once."""
835
return self._get_revisions(revision_ids)
838
def _get_revisions(self, revision_ids):
839
"""Core work logic to get many revisions without sanity checks."""
840
for rev_id in revision_ids:
841
if not rev_id or not isinstance(rev_id, basestring):
842
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
843
revs = self._revision_store.get_revisions(revision_ids,
844
self.get_transaction())
846
assert not isinstance(rev.revision_id, unicode)
847
for parent_id in rev.parent_ids:
848
assert not isinstance(parent_id, unicode)
852
def get_revision_xml(self, revision_id):
853
# TODO: jam 20070210 This shouldn't be necessary since get_revision
854
# would have already do it.
855
# TODO: jam 20070210 Just use _serializer.write_revision_to_string()
856
rev = self.get_revision(revision_id)
858
# the current serializer..
859
self._revision_store._serializer.write_revision(rev, rev_tmp)
861
return rev_tmp.getvalue()
864
def get_deltas_for_revisions(self, revisions):
865
"""Produce a generator of revision deltas.
867
Note that the input is a sequence of REVISIONS, not revision_ids.
868
Trees will be held in memory until the generator exits.
869
Each delta is relative to the revision's lefthand predecessor.
871
required_trees = set()
872
for revision in revisions:
873
required_trees.add(revision.revision_id)
874
required_trees.update(revision.parent_ids[:1])
875
trees = dict((t.get_revision_id(), t) for
876
t in self.revision_trees(required_trees))
877
for revision in revisions:
878
if not revision.parent_ids:
879
old_tree = self.revision_tree(None)
881
old_tree = trees[revision.parent_ids[0]]
882
yield trees[revision.revision_id].changes_from(old_tree)
885
def get_revision_delta(self, revision_id):
886
"""Return the delta for one revision.
888
The delta is relative to the left-hand predecessor of the
891
r = self.get_revision(revision_id)
892
return list(self.get_deltas_for_revisions([r]))[0]
895
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
896
signature = gpg_strategy.sign(plaintext)
897
self._revision_store.add_revision_signature_text(revision_id,
899
self.get_transaction())
901
def fileids_altered_by_revision_ids(self, revision_ids):
902
"""Find the file ids and versions affected by revisions.
904
:param revisions: an iterable containing revision ids.
905
:return: a dictionary mapping altered file-ids to an iterable of
906
revision_ids. Each altered file-ids has the exact revision_ids that
907
altered it listed explicitly.
909
assert self._serializer.support_altered_by_hack, \
910
("fileids_altered_by_revision_ids only supported for branches "
911
"which store inventory as unnested xml, not on %r" % self)
912
selected_revision_ids = set(revision_ids)
913
w = self.get_inventory_weave()
916
# this code needs to read every new line in every inventory for the
917
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
918
# not present in one of those inventories is unnecessary but not
919
# harmful because we are filtering by the revision id marker in the
920
# inventory lines : we only select file ids altered in one of those
921
# revisions. We don't need to see all lines in the inventory because
922
# only those added in an inventory in rev X can contain a revision=X
924
unescape_revid_cache = {}
925
unescape_fileid_cache = {}
927
# jam 20061218 In a big fetch, this handles hundreds of thousands
928
# of lines, so it has had a lot of inlining and optimizing done.
929
# Sorry that it is a little bit messy.
930
# Move several functions to be local variables, since this is a long
932
search = self._file_ids_altered_regex.search
933
unescape = _unescape_xml
934
setdefault = result.setdefault
935
pb = ui.ui_factory.nested_progress_bar()
937
for line in w.iter_lines_added_or_present_in_versions(
938
selected_revision_ids, pb=pb):
942
# One call to match.group() returning multiple items is quite a
943
# bit faster than 2 calls to match.group() each returning 1
944
file_id, revision_id = match.group('file_id', 'revision_id')
946
# Inlining the cache lookups helps a lot when you make 170,000
947
# lines and 350k ids, versus 8.4 unique ids.
948
# Using a cache helps in 2 ways:
949
# 1) Avoids unnecessary decoding calls
950
# 2) Re-uses cached strings, which helps in future set and
952
# (2) is enough that removing encoding entirely along with
953
# the cache (so we are using plain strings) results in no
954
# performance improvement.
956
revision_id = unescape_revid_cache[revision_id]
958
unescaped = unescape(revision_id)
959
unescape_revid_cache[revision_id] = unescaped
960
revision_id = unescaped
962
if revision_id in selected_revision_ids:
964
file_id = unescape_fileid_cache[file_id]
966
unescaped = unescape(file_id)
967
unescape_fileid_cache[file_id] = unescaped
969
setdefault(file_id, set()).add(revision_id)
974
def iter_files_bytes(self, desired_files):
975
"""Iterate through file versions.
977
Files will not necessarily be returned in the order they occur in
978
desired_files. No specific order is guaranteed.
980
Yields pairs of identifier, bytes_iterator. identifier is an opaque
981
value supplied by the caller as part of desired_files. It should
982
uniquely identify the file version in the caller's context. (Examples:
983
an index number or a TreeTransform trans_id.)
985
bytes_iterator is an iterable of bytestrings for the file. The
986
kind of iterable and length of the bytestrings are unspecified, but for
987
this implementation, it is a list of lines produced by
988
VersionedFile.get_lines().
990
:param desired_files: a list of (file_id, revision_id, identifier)
993
transaction = self.get_transaction()
994
for file_id, revision_id, callable_data in desired_files:
996
weave = self.weave_store.get_weave(file_id, transaction)
997
except errors.NoSuchFile:
998
raise errors.NoSuchIdInRepository(self, file_id)
999
yield callable_data, weave.get_lines(revision_id)
1001
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1002
"""Get an iterable listing the keys of all the data introduced by a set
1005
The keys will be ordered so that the corresponding items can be safely
1006
fetched and inserted in that order.
1008
:returns: An iterable producing tuples of (knit-kind, file-id,
1009
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1010
'revisions'. file-id is None unless knit-kind is 'file'.
1012
# XXX: it's a bit weird to control the inventory weave caching in this
1013
# generator. Ideally the caching would be done in fetch.py I think. Or
1014
# maybe this generator should explicitly have the contract that it
1015
# should not be iterated until the previously yielded item has been
1017
inv_w = self.get_inventory_weave()
1018
inv_w.enable_cache()
1020
# file ids that changed
1021
file_ids = self.fileids_altered_by_revision_ids(revision_ids)
1023
num_file_ids = len(file_ids)
1024
for file_id, altered_versions in file_ids.iteritems():
1025
if _files_pb is not None:
1026
_files_pb.update("fetch texts", count, num_file_ids)
1028
yield ("file", file_id, altered_versions)
1029
# We're done with the files_pb. Note that it finished by the caller,
1030
# just as it was created by the caller.
1034
yield ("inventory", None, revision_ids)
1038
revisions_with_signatures = set()
1039
for rev_id in revision_ids:
1041
self.get_signature_text(rev_id)
1042
except errors.NoSuchRevision:
1046
revisions_with_signatures.add(rev_id)
1047
yield ("signatures", None, revisions_with_signatures)
1050
yield ("revisions", None, revision_ids)
1053
def get_inventory_weave(self):
1054
return self.control_weaves.get_weave('inventory',
1055
self.get_transaction())
1058
def get_inventory(self, revision_id):
1059
"""Get Inventory object by hash."""
1060
# TODO: jam 20070210 Technically we don't need to sanitize, since all
1061
# called functions must sanitize.
1062
return self.deserialise_inventory(
1063
revision_id, self.get_inventory_xml(revision_id))
1065
def deserialise_inventory(self, revision_id, xml):
1066
"""Transform the xml into an inventory object.
1068
:param revision_id: The expected revision id of the inventory.
1069
:param xml: A serialised inventory.
1071
result = self._serializer.read_inventory_from_string(xml)
1072
result.root.revision = revision_id
1075
def serialise_inventory(self, inv):
1076
return self._serializer.write_inventory_to_string(inv)
1078
def _serialise_inventory_to_lines(self, inv):
1079
return self._serializer.write_inventory_to_lines(inv)
1081
def get_serializer_format(self):
1082
return self._serializer.format_num
1085
def get_inventory_xml(self, revision_id):
1086
"""Get inventory XML as a file object."""
1088
assert isinstance(revision_id, str), type(revision_id)
1089
iw = self.get_inventory_weave()
1090
return iw.get_text(revision_id)
1092
raise errors.HistoryMissing(self, 'inventory', revision_id)
1095
def get_inventory_sha1(self, revision_id):
1096
"""Return the sha1 hash of the inventory entry
1098
# TODO: jam 20070210 Shouldn't this be deprecated / removed?
1099
return self.get_revision(revision_id).inventory_sha1
1102
def get_revision_graph(self, revision_id=None):
1103
"""Return a dictionary containing the revision graph.
1105
NB: This method should not be used as it accesses the entire graph all
1106
at once, which is much more data than most operations should require.
1108
:param revision_id: The revision_id to get a graph from. If None, then
1109
the entire revision graph is returned. This is a deprecated mode of
1110
operation and will be removed in the future.
1111
:return: a dictionary of revision_id->revision_parents_list.
1113
raise NotImplementedError(self.get_revision_graph)
1116
def get_revision_graph_with_ghosts(self, revision_ids=None):
1117
"""Return a graph of the revisions with ghosts marked as applicable.
1119
:param revision_ids: an iterable of revisions to graph or None for all.
1120
:return: a Graph object with the graph reachable from revision_ids.
1122
if 'evil' in debug.debug_flags:
1124
"get_revision_graph_with_ghosts scales with size of history.")
1125
result = deprecated_graph.Graph()
1126
if not revision_ids:
1127
pending = set(self.all_revision_ids())
1130
pending = set(revision_ids)
1131
# special case NULL_REVISION
1132
if _mod_revision.NULL_REVISION in pending:
1133
pending.remove(_mod_revision.NULL_REVISION)
1134
required = set(pending)
1137
revision_id = pending.pop()
1139
rev = self.get_revision(revision_id)
1140
except errors.NoSuchRevision:
1141
if revision_id in required:
1144
result.add_ghost(revision_id)
1146
for parent_id in rev.parent_ids:
1147
# is this queued or done ?
1148
if (parent_id not in pending and
1149
parent_id not in done):
1151
pending.add(parent_id)
1152
result.add_node(revision_id, rev.parent_ids)
1153
done.add(revision_id)
1156
def _get_history_vf(self):
1157
"""Get a versionedfile whose history graph reflects all revisions.
1159
For weave repositories, this is the inventory weave.
1161
return self.get_inventory_weave()
1163
def iter_reverse_revision_history(self, revision_id):
1164
"""Iterate backwards through revision ids in the lefthand history
1166
:param revision_id: The revision id to start with. All its lefthand
1167
ancestors will be traversed.
1169
if revision_id in (None, _mod_revision.NULL_REVISION):
1171
next_id = revision_id
1172
versionedfile = self._get_history_vf()
1175
parents = versionedfile.get_parents(next_id)
1176
if len(parents) == 0:
1179
next_id = parents[0]
1182
def get_revision_inventory(self, revision_id):
1183
"""Return inventory of a past revision."""
1184
# TODO: Unify this with get_inventory()
1185
# bzr 0.0.6 and later imposes the constraint that the inventory_id
1186
# must be the same as its revision, so this is trivial.
1187
if revision_id is None:
1188
# This does not make sense: if there is no revision,
1189
# then it is the current tree inventory surely ?!
1190
# and thus get_root_id() is something that looks at the last
1191
# commit on the branch, and the get_root_id is an inventory check.
1192
raise NotImplementedError
1193
# return Inventory(self.get_root_id())
1195
return self.get_inventory(revision_id)
1198
def is_shared(self):
1199
"""Return True if this repository is flagged as a shared repository."""
1200
raise NotImplementedError(self.is_shared)
1203
def reconcile(self, other=None, thorough=False):
1204
"""Reconcile this repository."""
1205
from bzrlib.reconcile import RepoReconciler
1206
reconciler = RepoReconciler(self, thorough=thorough)
1207
reconciler.reconcile()
1210
def _refresh_data(self):
1211
"""Helper called from lock_* to ensure coherency with disk.
1213
The default implementation does nothing; it is however possible
1214
for repositories to maintain loaded indices across multiple locks
1215
by checking inside their implementation of this method to see
1216
whether their indices are still valid. This depends of course on
1217
the disk format being validatable in this manner.
1221
def revision_tree(self, revision_id):
1222
"""Return Tree for a revision on this branch.
1224
`revision_id` may be None for the empty tree revision.
1226
# TODO: refactor this to use an existing revision object
1227
# so we don't need to read it in twice.
1228
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
1229
return RevisionTree(self, Inventory(root_id=None),
1230
_mod_revision.NULL_REVISION)
1232
inv = self.get_revision_inventory(revision_id)
1233
return RevisionTree(self, inv, revision_id)
1236
def revision_trees(self, revision_ids):
1237
"""Return Tree for a revision on this branch.
1239
`revision_id` may not be None or 'null:'"""
1240
assert None not in revision_ids
1241
assert _mod_revision.NULL_REVISION not in revision_ids
1242
texts = self.get_inventory_weave().get_texts(revision_ids)
1243
for text, revision_id in zip(texts, revision_ids):
1244
inv = self.deserialise_inventory(revision_id, text)
1245
yield RevisionTree(self, inv, revision_id)
1248
def get_ancestry(self, revision_id, topo_sorted=True):
1249
"""Return a list of revision-ids integrated by a revision.
1251
The first element of the list is always None, indicating the origin
1252
revision. This might change when we have history horizons, or
1253
perhaps we should have a new API.
1255
This is topologically sorted.
1257
if _mod_revision.is_null(revision_id):
1259
if not self.has_revision(revision_id):
1260
raise errors.NoSuchRevision(self, revision_id)
1261
w = self.get_inventory_weave()
1262
candidates = w.get_ancestry(revision_id, topo_sorted)
1263
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
1266
"""Compress the data within the repository.
1268
This operation only makes sense for some repository types. For other
1269
types it should be a no-op that just returns.
1271
This stub method does not require a lock, but subclasses should use
1272
@needs_write_lock as this is a long running call its reasonable to
1273
implicitly lock for the user.
1277
def print_file(self, file, revision_id):
1278
"""Print `file` to stdout.
1280
FIXME RBC 20060125 as John Meinel points out this is a bad api
1281
- it writes to stdout, it assumes that that is valid etc. Fix
1282
by creating a new more flexible convenience function.
1284
tree = self.revision_tree(revision_id)
1285
# use inventory as it was in that revision
1286
file_id = tree.inventory.path2id(file)
1288
# TODO: jam 20060427 Write a test for this code path
1289
# it had a bug in it, and was raising the wrong
1291
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
1292
tree.print_file(file_id)
1294
def get_transaction(self):
1295
return self.control_files.get_transaction()
1297
def revision_parents(self, revision_id):
1298
return self.get_inventory_weave().parent_names(revision_id)
1300
def get_parents(self, revision_ids):
1301
"""See StackedParentsProvider.get_parents"""
1303
for revision_id in revision_ids:
1304
if revision_id == _mod_revision.NULL_REVISION:
1308
parents = self.get_revision(revision_id).parent_ids
1309
except errors.NoSuchRevision:
1312
if len(parents) == 0:
1313
parents = [_mod_revision.NULL_REVISION]
1314
parents_list.append(parents)
1317
def _make_parents_provider(self):
1320
def get_graph(self, other_repository=None):
1321
"""Return the graph walker for this repository format"""
1322
parents_provider = self._make_parents_provider()
1323
if (other_repository is not None and
1324
other_repository.bzrdir.transport.base !=
1325
self.bzrdir.transport.base):
1326
parents_provider = graph._StackedParentsProvider(
1327
[parents_provider, other_repository._make_parents_provider()])
1328
return graph.Graph(parents_provider)
1331
def set_make_working_trees(self, new_value):
1332
"""Set the policy flag for making working trees when creating branches.
1334
This only applies to branches that use this repository.
1336
The default is 'True'.
1337
:param new_value: True to restore the default, False to disable making
1340
raise NotImplementedError(self.set_make_working_trees)
1342
def make_working_trees(self):
1343
"""Returns the policy for making working trees on new branches."""
1344
raise NotImplementedError(self.make_working_trees)
1347
def sign_revision(self, revision_id, gpg_strategy):
1348
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1349
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1352
def has_signature_for_revision_id(self, revision_id):
1353
"""Query for a revision signature for revision_id in the repository."""
1354
return self._revision_store.has_signature(revision_id,
1355
self.get_transaction())
1358
def get_signature_text(self, revision_id):
1359
"""Return the text for a signature."""
1360
return self._revision_store.get_signature_text(revision_id,
1361
self.get_transaction())
1364
def check(self, revision_ids):
1365
"""Check consistency of all history of given revision_ids.
1367
Different repository implementations should override _check().
1369
:param revision_ids: A non-empty list of revision_ids whose ancestry
1370
will be checked. Typically the last revision_id of a branch.
1372
if not revision_ids:
1373
raise ValueError("revision_ids must be non-empty in %s.check"
1375
return self._check(revision_ids)
1377
def _check(self, revision_ids):
1378
result = check.Check(self)
1382
def _warn_if_deprecated(self):
1383
global _deprecation_warning_done
1384
if _deprecation_warning_done:
1386
_deprecation_warning_done = True
1387
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
1388
% (self._format, self.bzrdir.transport.base))
1390
def supports_rich_root(self):
1391
return self._format.rich_root_data
1393
def _check_ascii_revisionid(self, revision_id, method):
1394
"""Private helper for ascii-only repositories."""
1395
# weave repositories refuse to store revisionids that are non-ascii.
1396
if revision_id is not None:
1397
# weaves require ascii revision ids.
1398
if isinstance(revision_id, unicode):
1400
revision_id.encode('ascii')
1401
except UnicodeEncodeError:
1402
raise errors.NonAsciiRevisionId(method, self)
1405
revision_id.decode('ascii')
1406
except UnicodeDecodeError:
1407
raise errors.NonAsciiRevisionId(method, self)
1411
# remove these delegates a while after bzr 0.15
1412
def __make_delegated(name, from_module):
1413
def _deprecated_repository_forwarder():
1414
symbol_versioning.warn('%s moved to %s in bzr 0.15'
1415
% (name, from_module),
1418
m = __import__(from_module, globals(), locals(), [name])
1420
return getattr(m, name)
1421
except AttributeError:
1422
raise AttributeError('module %s has no name %s'
1424
globals()[name] = _deprecated_repository_forwarder
1427
'AllInOneRepository',
1428
'WeaveMetaDirRepository',
1429
'PreSplitOutRepositoryFormat',
1430
'RepositoryFormat4',
1431
'RepositoryFormat5',
1432
'RepositoryFormat6',
1433
'RepositoryFormat7',
1435
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1439
'RepositoryFormatKnit',
1440
'RepositoryFormatKnit1',
1442
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1445
def install_revision(repository, rev, revision_tree):
1446
"""Install all revision data into a repository."""
1447
present_parents = []
1449
for p_id in rev.parent_ids:
1450
if repository.has_revision(p_id):
1451
present_parents.append(p_id)
1452
parent_trees[p_id] = repository.revision_tree(p_id)
1454
parent_trees[p_id] = repository.revision_tree(None)
1456
inv = revision_tree.inventory
1457
entries = inv.iter_entries()
1458
# backwards compatibility hack: skip the root id.
1459
if not repository.supports_rich_root():
1460
path, root = entries.next()
1461
if root.revision != rev.revision_id:
1462
raise errors.IncompatibleRevision(repr(repository))
1463
# Add the texts that are not already present
1464
for path, ie in entries:
1465
w = repository.weave_store.get_weave_or_empty(ie.file_id,
1466
repository.get_transaction())
1467
if ie.revision not in w:
1469
# FIXME: TODO: The following loop *may* be overlapping/duplicate
1470
# with InventoryEntry.find_previous_heads(). if it is, then there
1471
# is a latent bug here where the parents may have ancestors of each
1473
for revision, tree in parent_trees.iteritems():
1474
if ie.file_id not in tree:
1476
parent_id = tree.inventory[ie.file_id].revision
1477
if parent_id in text_parents:
1479
text_parents.append(parent_id)
1481
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
1482
repository.get_transaction())
1483
lines = revision_tree.get_file(ie.file_id).readlines()
1484
vfile.add_lines(rev.revision_id, text_parents, lines)
1486
# install the inventory
1487
repository.add_inventory(rev.revision_id, inv, present_parents)
1488
except errors.RevisionAlreadyPresent:
1490
repository.add_revision(rev.revision_id, rev, inv)
1493
class MetaDirRepository(Repository):
1494
"""Repositories in the new meta-dir layout."""
1496
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1497
super(MetaDirRepository, self).__init__(_format,
1503
dir_mode = self.control_files._dir_mode
1504
file_mode = self.control_files._file_mode
1507
def is_shared(self):
1508
"""Return True if this repository is flagged as a shared repository."""
1509
return self.control_files._transport.has('shared-storage')
1512
def set_make_working_trees(self, new_value):
1513
"""Set the policy flag for making working trees when creating branches.
1515
This only applies to branches that use this repository.
1517
The default is 'True'.
1518
:param new_value: True to restore the default, False to disable making
1523
self.control_files._transport.delete('no-working-trees')
1524
except errors.NoSuchFile:
1527
self.control_files.put_utf8('no-working-trees', '')
1529
def make_working_trees(self):
1530
"""Returns the policy for making working trees on new branches."""
1531
return not self.control_files._transport.has('no-working-trees')
1534
class RepositoryFormatRegistry(registry.Registry):
1535
"""Registry of RepositoryFormats.
1538
def get(self, format_string):
1539
r = registry.Registry.get(self, format_string)
1545
format_registry = RepositoryFormatRegistry()
1546
"""Registry of formats, indexed by their identifying format string.
1548
This can contain either format instances themselves, or classes/factories that
1549
can be called to obtain one.
1553
#####################################################################
1554
# Repository Formats
1556
class RepositoryFormat(object):
1557
"""A repository format.
1559
Formats provide three things:
1560
* An initialization routine to construct repository data on disk.
1561
* a format string which is used when the BzrDir supports versioned
1563
* an open routine which returns a Repository instance.
1565
Formats are placed in an dict by their format string for reference
1566
during opening. These should be subclasses of RepositoryFormat
1569
Once a format is deprecated, just deprecate the initialize and open
1570
methods on the format class. Do not deprecate the object, as the
1571
object will be created every system load.
1573
Common instance attributes:
1574
_matchingbzrdir - the bzrdir format that the repository format was
1575
originally written to work with. This can be used if manually
1576
constructing a bzrdir and repository, or more commonly for test suite
1581
return "<%s>" % self.__class__.__name__
1583
def __eq__(self, other):
1584
# format objects are generally stateless
1585
return isinstance(other, self.__class__)
1587
def __ne__(self, other):
1588
return not self == other
1591
def find_format(klass, a_bzrdir):
1592
"""Return the format for the repository object in a_bzrdir.
1594
This is used by bzr native formats that have a "format" file in
1595
the repository. Other methods may be used by different types of
1599
transport = a_bzrdir.get_repository_transport(None)
1600
format_string = transport.get("format").read()
1601
return format_registry.get(format_string)
1602
except errors.NoSuchFile:
1603
raise errors.NoRepositoryPresent(a_bzrdir)
1605
raise errors.UnknownFormatError(format=format_string)
1608
def register_format(klass, format):
1609
format_registry.register(format.get_format_string(), format)
1612
def unregister_format(klass, format):
1613
format_registry.remove(format.get_format_string())
1616
def get_default_format(klass):
1617
"""Return the current default format."""
1618
from bzrlib import bzrdir
1619
return bzrdir.format_registry.make_bzrdir('default').repository_format
1621
def _get_control_store(self, repo_transport, control_files):
1622
"""Return the control store for this repository."""
1623
raise NotImplementedError(self._get_control_store)
1625
def get_format_string(self):
1626
"""Return the ASCII format string that identifies this format.
1628
Note that in pre format ?? repositories the format string is
1629
not permitted nor written to disk.
1631
raise NotImplementedError(self.get_format_string)
1633
def get_format_description(self):
1634
"""Return the short description for this format."""
1635
raise NotImplementedError(self.get_format_description)
1637
def _get_revision_store(self, repo_transport, control_files):
1638
"""Return the revision store object for this a_bzrdir."""
1639
raise NotImplementedError(self._get_revision_store)
1641
def _get_text_rev_store(self,
1648
"""Common logic for getting a revision store for a repository.
1650
see self._get_revision_store for the subclass-overridable method to
1651
get the store for a repository.
1653
from bzrlib.store.revision.text import TextRevisionStore
1654
dir_mode = control_files._dir_mode
1655
file_mode = control_files._file_mode
1656
text_store = TextStore(transport.clone(name),
1658
compressed=compressed,
1660
file_mode=file_mode)
1661
_revision_store = TextRevisionStore(text_store, serializer)
1662
return _revision_store
1664
# TODO: this shouldn't be in the base class, it's specific to things that
1665
# use weaves or knits -- mbp 20070207
1666
def _get_versioned_file_store(self,
1671
versionedfile_class=None,
1672
versionedfile_kwargs={},
1674
if versionedfile_class is None:
1675
versionedfile_class = self._versionedfile_class
1676
weave_transport = control_files._transport.clone(name)
1677
dir_mode = control_files._dir_mode
1678
file_mode = control_files._file_mode
1679
return VersionedFileStore(weave_transport, prefixed=prefixed,
1681
file_mode=file_mode,
1682
versionedfile_class=versionedfile_class,
1683
versionedfile_kwargs=versionedfile_kwargs,
1686
def initialize(self, a_bzrdir, shared=False):
1687
"""Initialize a repository of this format in a_bzrdir.
1689
:param a_bzrdir: The bzrdir to put the new repository in it.
1690
:param shared: The repository should be initialized as a sharable one.
1691
:returns: The new repository object.
1693
This may raise UninitializableFormat if shared repository are not
1694
compatible the a_bzrdir.
1696
raise NotImplementedError(self.initialize)
1698
def is_supported(self):
1699
"""Is this format supported?
1701
Supported formats must be initializable and openable.
1702
Unsupported formats may not support initialization or committing or
1703
some other features depending on the reason for not being supported.
1707
def check_conversion_target(self, target_format):
1708
raise NotImplementedError(self.check_conversion_target)
1710
def open(self, a_bzrdir, _found=False):
1711
"""Return an instance of this format for the bzrdir a_bzrdir.
1713
_found is a private parameter, do not use it.
1715
raise NotImplementedError(self.open)
1718
class MetaDirRepositoryFormat(RepositoryFormat):
1719
"""Common base class for the new repositories using the metadir layout."""
1721
rich_root_data = False
1722
supports_tree_reference = False
1723
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1726
super(MetaDirRepositoryFormat, self).__init__()
1728
def _create_control_files(self, a_bzrdir):
1729
"""Create the required files and the initial control_files object."""
1730
# FIXME: RBC 20060125 don't peek under the covers
1731
# NB: no need to escape relative paths that are url safe.
1732
repository_transport = a_bzrdir.get_repository_transport(self)
1733
control_files = lockable_files.LockableFiles(repository_transport,
1734
'lock', lockdir.LockDir)
1735
control_files.create_lock()
1736
return control_files
1738
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1739
"""Upload the initial blank content."""
1740
control_files = self._create_control_files(a_bzrdir)
1741
control_files.lock_write()
1743
control_files._transport.mkdir_multi(dirs,
1744
mode=control_files._dir_mode)
1745
for file, content in files:
1746
control_files.put(file, content)
1747
for file, content in utf8_files:
1748
control_files.put_utf8(file, content)
1750
control_files.put_utf8('shared-storage', '')
1752
control_files.unlock()
1755
# formats which have no format string are not discoverable
1756
# and not independently creatable, so are not registered. They're
1757
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1758
# needed, it's constructed directly by the BzrDir. Non-native formats where
1759
# the repository is not separately opened are similar.
1761
format_registry.register_lazy(
1762
'Bazaar-NG Repository format 7',
1763
'bzrlib.repofmt.weaverepo',
1766
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1767
# default control directory format
1769
format_registry.register_lazy(
1770
'Bazaar-NG Knit Repository Format 1',
1771
'bzrlib.repofmt.knitrepo',
1772
'RepositoryFormatKnit1',
1774
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1776
format_registry.register_lazy(
1777
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1778
'bzrlib.repofmt.knitrepo',
1779
'RepositoryFormatKnit3',
1783
class InterRepository(InterObject):
1784
"""This class represents operations taking place between two repositories.
1786
Its instances have methods like copy_content and fetch, and contain
1787
references to the source and target repositories these operations can be
1790
Often we will provide convenience methods on 'repository' which carry out
1791
operations with another repository - they will always forward to
1792
InterRepository.get(other).method_name(parameters).
1796
"""The available optimised InterRepository types."""
1798
def copy_content(self, revision_id=None):
1799
raise NotImplementedError(self.copy_content)
1801
def fetch(self, revision_id=None, pb=None):
1802
"""Fetch the content required to construct revision_id.
1804
The content is copied from self.source to self.target.
1806
:param revision_id: if None all content is copied, if NULL_REVISION no
1808
:param pb: optional progress bar to use for progress reports. If not
1809
provided a default one will be created.
1811
Returns the copied revision count and the failed revisions in a tuple:
1814
raise NotImplementedError(self.fetch)
1817
def missing_revision_ids(self, revision_id=None):
1818
"""Return the revision ids that source has that target does not.
1820
These are returned in topological order.
1822
:param revision_id: only return revision ids included by this
1825
# generic, possibly worst case, slow code path.
1826
target_ids = set(self.target.all_revision_ids())
1827
if revision_id is not None:
1828
# TODO: jam 20070210 InterRepository is internal enough that it
1829
# should assume revision_ids are already utf-8
1830
source_ids = self.source.get_ancestry(revision_id)
1831
assert source_ids[0] is None
1834
source_ids = self.source.all_revision_ids()
1835
result_set = set(source_ids).difference(target_ids)
1836
# this may look like a no-op: its not. It preserves the ordering
1837
# other_ids had while only returning the members from other_ids
1838
# that we've decided we need.
1839
return [rev_id for rev_id in source_ids if rev_id in result_set]
1842
class InterSameDataRepository(InterRepository):
1843
"""Code for converting between repositories that represent the same data.
1845
Data format and model must match for this to work.
1849
def _get_repo_format_to_test(self):
1850
"""Repository format for testing with.
1852
InterSameData can pull from subtree to subtree and from non-subtree to
1853
non-subtree, so we test this with the richest repository format.
1855
from bzrlib.repofmt import knitrepo
1856
return knitrepo.RepositoryFormatKnit3()
1859
def is_compatible(source, target):
1860
if source.supports_rich_root() != target.supports_rich_root():
1862
if source._serializer != target._serializer:
1867
def copy_content(self, revision_id=None):
1868
"""Make a complete copy of the content in self into destination.
1870
This copies both the repository's revision data, and configuration information
1871
such as the make_working_trees setting.
1873
This is a destructive operation! Do not use it on existing
1876
:param revision_id: Only copy the content needed to construct
1877
revision_id and its parents.
1880
self.target.set_make_working_trees(self.source.make_working_trees())
1881
except NotImplementedError:
1883
# but don't bother fetching if we have the needed data now.
1884
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1885
self.target.has_revision(revision_id)):
1887
self.target.fetch(self.source, revision_id=revision_id)
1890
def fetch(self, revision_id=None, pb=None):
1891
"""See InterRepository.fetch()."""
1892
from bzrlib.fetch import GenericRepoFetcher
1893
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1894
self.source, self.source._format, self.target,
1895
self.target._format)
1896
f = GenericRepoFetcher(to_repository=self.target,
1897
from_repository=self.source,
1898
last_revision=revision_id,
1900
return f.count_copied, f.failed_revisions
1903
class InterWeaveRepo(InterSameDataRepository):
1904
"""Optimised code paths between Weave based repositories.
1906
This should be in bzrlib/repofmt/weaverepo.py but we have not yet
1907
implemented lazy inter-object optimisation.
1911
def _get_repo_format_to_test(self):
1912
from bzrlib.repofmt import weaverepo
1913
return weaverepo.RepositoryFormat7()
1916
def is_compatible(source, target):
1917
"""Be compatible with known Weave formats.
1919
We don't test for the stores being of specific types because that
1920
could lead to confusing results, and there is no need to be
1923
from bzrlib.repofmt.weaverepo import (
1929
return (isinstance(source._format, (RepositoryFormat5,
1931
RepositoryFormat7)) and
1932
isinstance(target._format, (RepositoryFormat5,
1934
RepositoryFormat7)))
1935
except AttributeError:
1939
def copy_content(self, revision_id=None):
1940
"""See InterRepository.copy_content()."""
1941
# weave specific optimised path:
1943
self.target.set_make_working_trees(self.source.make_working_trees())
1944
except NotImplementedError:
1946
# FIXME do not peek!
1947
if self.source.control_files._transport.listable():
1948
pb = ui.ui_factory.nested_progress_bar()
1950
self.target.weave_store.copy_all_ids(
1951
self.source.weave_store,
1953
from_transaction=self.source.get_transaction(),
1954
to_transaction=self.target.get_transaction())
1955
pb.update('copying inventory', 0, 1)
1956
self.target.control_weaves.copy_multi(
1957
self.source.control_weaves, ['inventory'],
1958
from_transaction=self.source.get_transaction(),
1959
to_transaction=self.target.get_transaction())
1960
self.target._revision_store.text_store.copy_all_ids(
1961
self.source._revision_store.text_store,
1966
self.target.fetch(self.source, revision_id=revision_id)
1969
def fetch(self, revision_id=None, pb=None):
1970
"""See InterRepository.fetch()."""
1971
from bzrlib.fetch import GenericRepoFetcher
1972
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1973
self.source, self.source._format, self.target, self.target._format)
1974
f = GenericRepoFetcher(to_repository=self.target,
1975
from_repository=self.source,
1976
last_revision=revision_id,
1978
return f.count_copied, f.failed_revisions
1981
def missing_revision_ids(self, revision_id=None):
1982
"""See InterRepository.missing_revision_ids()."""
1983
# we want all revisions to satisfy revision_id in source.
1984
# but we don't want to stat every file here and there.
1985
# we want then, all revisions other needs to satisfy revision_id
1986
# checked, but not those that we have locally.
1987
# so the first thing is to get a subset of the revisions to
1988
# satisfy revision_id in source, and then eliminate those that
1989
# we do already have.
1990
# this is slow on high latency connection to self, but as as this
1991
# disk format scales terribly for push anyway due to rewriting
1992
# inventory.weave, this is considered acceptable.
1994
if revision_id is not None:
1995
source_ids = self.source.get_ancestry(revision_id)
1996
assert source_ids[0] is None
1999
source_ids = self.source._all_possible_ids()
2000
source_ids_set = set(source_ids)
2001
# source_ids is the worst possible case we may need to pull.
2002
# now we want to filter source_ids against what we actually
2003
# have in target, but don't try to check for existence where we know
2004
# we do not have a revision as that would be pointless.
2005
target_ids = set(self.target._all_possible_ids())
2006
possibly_present_revisions = target_ids.intersection(source_ids_set)
2007
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2008
required_revisions = source_ids_set.difference(actually_present_revisions)
2009
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2010
if revision_id is not None:
2011
# we used get_ancestry to determine source_ids then we are assured all
2012
# revisions referenced are present as they are installed in topological order.
2013
# and the tip revision was validated by get_ancestry.
2014
return required_topo_revisions
2016
# if we just grabbed the possibly available ids, then
2017
# we only have an estimate of whats available and need to validate
2018
# that against the revision records.
2019
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2022
class InterKnitRepo(InterSameDataRepository):
2023
"""Optimised code paths between Knit based repositories."""
2026
def _get_repo_format_to_test(self):
2027
from bzrlib.repofmt import knitrepo
2028
return knitrepo.RepositoryFormatKnit1()
2031
def is_compatible(source, target):
2032
"""Be compatible with known Knit formats.
2034
We don't test for the stores being of specific types because that
2035
could lead to confusing results, and there is no need to be
2038
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
2040
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2041
isinstance(target._format, (RepositoryFormatKnit1)))
2042
except AttributeError:
2046
def fetch(self, revision_id=None, pb=None):
2047
"""See InterRepository.fetch()."""
2048
from bzrlib.fetch import KnitRepoFetcher
2049
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2050
self.source, self.source._format, self.target, self.target._format)
2051
f = KnitRepoFetcher(to_repository=self.target,
2052
from_repository=self.source,
2053
last_revision=revision_id,
2055
return f.count_copied, f.failed_revisions
2058
def missing_revision_ids(self, revision_id=None):
2059
"""See InterRepository.missing_revision_ids()."""
2060
if revision_id is not None:
2061
source_ids = self.source.get_ancestry(revision_id)
2062
assert source_ids[0] is None
2065
source_ids = self.source.all_revision_ids()
2066
source_ids_set = set(source_ids)
2067
# source_ids is the worst possible case we may need to pull.
2068
# now we want to filter source_ids against what we actually
2069
# have in target, but don't try to check for existence where we know
2070
# we do not have a revision as that would be pointless.
2071
target_ids = set(self.target.all_revision_ids())
2072
possibly_present_revisions = target_ids.intersection(source_ids_set)
2073
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2074
required_revisions = source_ids_set.difference(actually_present_revisions)
2075
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2076
if revision_id is not None:
2077
# we used get_ancestry to determine source_ids then we are assured all
2078
# revisions referenced are present as they are installed in topological order.
2079
# and the tip revision was validated by get_ancestry.
2080
return required_topo_revisions
2082
# if we just grabbed the possibly available ids, then
2083
# we only have an estimate of whats available and need to validate
2084
# that against the revision records.
2085
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2088
class InterModel1and2(InterRepository):
2091
def _get_repo_format_to_test(self):
2095
def is_compatible(source, target):
2096
if not source.supports_rich_root() and target.supports_rich_root():
2102
def fetch(self, revision_id=None, pb=None):
2103
"""See InterRepository.fetch()."""
2104
from bzrlib.fetch import Model1toKnit2Fetcher
2105
f = Model1toKnit2Fetcher(to_repository=self.target,
2106
from_repository=self.source,
2107
last_revision=revision_id,
2109
return f.count_copied, f.failed_revisions
2112
def copy_content(self, revision_id=None):
2113
"""Make a complete copy of the content in self into destination.
2115
This is a destructive operation! Do not use it on existing
2118
:param revision_id: Only copy the content needed to construct
2119
revision_id and its parents.
2122
self.target.set_make_working_trees(self.source.make_working_trees())
2123
except NotImplementedError:
2125
# but don't bother fetching if we have the needed data now.
2126
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
2127
self.target.has_revision(revision_id)):
2129
self.target.fetch(self.source, revision_id=revision_id)
2132
class InterKnit1and2(InterKnitRepo):
2135
def _get_repo_format_to_test(self):
2139
def is_compatible(source, target):
2140
"""Be compatible with Knit1 source and Knit3 target"""
2141
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
2143
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
2144
RepositoryFormatKnit3
2145
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2146
isinstance(target._format, (RepositoryFormatKnit3)))
2147
except AttributeError:
2151
def fetch(self, revision_id=None, pb=None):
2152
"""See InterRepository.fetch()."""
2153
from bzrlib.fetch import Knit1to2Fetcher
2154
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2155
self.source, self.source._format, self.target,
2156
self.target._format)
2157
f = Knit1to2Fetcher(to_repository=self.target,
2158
from_repository=self.source,
2159
last_revision=revision_id,
2161
return f.count_copied, f.failed_revisions
2164
class InterRemoteRepository(InterRepository):
2165
"""Code for converting between RemoteRepository objects.
2167
This just gets an non-remote repository from the RemoteRepository, and calls
2168
InterRepository.get again.
2171
def __init__(self, source, target):
2172
if isinstance(source, remote.RemoteRepository):
2173
source._ensure_real()
2174
real_source = source._real_repository
2176
real_source = source
2177
if isinstance(target, remote.RemoteRepository):
2178
target._ensure_real()
2179
real_target = target._real_repository
2181
real_target = target
2182
self.real_inter = InterRepository.get(real_source, real_target)
2185
def is_compatible(source, target):
2186
if isinstance(source, remote.RemoteRepository):
2188
if isinstance(target, remote.RemoteRepository):
2192
def copy_content(self, revision_id=None):
2193
self.real_inter.copy_content(revision_id=revision_id)
2195
def fetch(self, revision_id=None, pb=None):
2196
self.real_inter.fetch(revision_id=revision_id, pb=pb)
2199
def _get_repo_format_to_test(self):
2203
InterRepository.register_optimiser(InterSameDataRepository)
2204
InterRepository.register_optimiser(InterWeaveRepo)
2205
InterRepository.register_optimiser(InterKnitRepo)
2206
InterRepository.register_optimiser(InterModel1and2)
2207
InterRepository.register_optimiser(InterKnit1and2)
2208
InterRepository.register_optimiser(InterRemoteRepository)
2211
class CopyConverter(object):
2212
"""A repository conversion tool which just performs a copy of the content.
2214
This is slow but quite reliable.
2217
def __init__(self, target_format):
2218
"""Create a CopyConverter.
2220
:param target_format: The format the resulting repository should be.
2222
self.target_format = target_format
2224
def convert(self, repo, pb):
2225
"""Perform the conversion of to_convert, giving feedback via pb.
2227
:param to_convert: The disk object to convert.
2228
:param pb: a progress bar to use for progress information.
2233
# this is only useful with metadir layouts - separated repo content.
2234
# trigger an assertion if not such
2235
repo._format.get_format_string()
2236
self.repo_dir = repo.bzrdir
2237
self.step('Moving repository to repository.backup')
2238
self.repo_dir.transport.move('repository', 'repository.backup')
2239
backup_transport = self.repo_dir.transport.clone('repository.backup')
2240
repo._format.check_conversion_target(self.target_format)
2241
self.source_repo = repo._format.open(self.repo_dir,
2243
_override_transport=backup_transport)
2244
self.step('Creating new repository')
2245
converted = self.target_format.initialize(self.repo_dir,
2246
self.source_repo.is_shared())
2247
converted.lock_write()
2249
self.step('Copying content into repository.')
2250
self.source_repo.copy_content_into(converted)
2253
self.step('Deleting old repository content.')
2254
self.repo_dir.transport.delete_tree('repository.backup')
2255
self.pb.note('repository converted')
2257
def step(self, message):
2258
"""Update the pb by a step."""
2260
self.pb.update(message, self.count, self.total)
2272
def _unescaper(match, _map=_unescape_map):
2273
code = match.group(1)
2277
if not code.startswith('#'):
2279
return unichr(int(code[1:])).encode('utf8')
2285
def _unescape_xml(data):
2286
"""Unescape predefined XML entities in a string of data."""
2288
if _unescape_re is None:
2289
_unescape_re = re.compile('\&([^;]*);')
2290
return _unescape_re.sub(_unescaper, data)