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(), """
37
revision as _mod_revision,
42
from bzrlib.revisiontree import RevisionTree
43
from bzrlib.store.versioned import VersionedFileStore
44
from bzrlib.store.text import TextStore
45
from bzrlib.testament import Testament
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
50
from bzrlib.inter import InterObject
51
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
52
from bzrlib.symbol_versioning import (
56
from bzrlib.trace import mutter, note, warning
59
# Old formats display a warning, but only once
60
_deprecation_warning_done = False
63
class Repository(object):
64
"""Repository holding history for one or more branches.
66
The repository holds and retrieves historical information including
67
revisions and file history. It's normally accessed only by the Branch,
68
which views a particular line of development through that history.
70
The Repository builds on top of Stores and a Transport, which respectively
71
describe the disk data format and the way of accessing the (possibly
75
_file_ids_altered_regex = lazy_regex.lazy_compile(
76
r'file_id="(?P<file_id>[^"]+)"'
77
r'.*revision="(?P<revision_id>[^"]+)"'
81
def add_inventory(self, revid, inv, parents):
82
"""Add the inventory inv to the repository as revid.
84
:param parents: The revision ids of the parents that revid
85
is known to have and are in the repository already.
87
returns the sha1 of the serialized inventory.
89
_mod_revision.check_not_reserved_id(revid)
90
assert inv.revision_id is None or inv.revision_id == revid, \
91
"Mismatch between inventory revision" \
92
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
93
assert inv.root is not None
94
inv_text = self.serialise_inventory(inv)
95
inv_sha1 = osutils.sha_string(inv_text)
96
inv_vf = self.control_weaves.get_weave('inventory',
97
self.get_transaction())
98
self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
101
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
103
for parent in parents:
105
final_parents.append(parent)
107
inv_vf.add_lines(revid, final_parents, lines)
110
def add_revision(self, rev_id, rev, inv=None, config=None):
111
"""Add rev to the revision store as rev_id.
113
:param rev_id: the revision id to use.
114
:param rev: The revision object.
115
:param inv: The inventory for the revision. if None, it will be looked
116
up in the inventory storer
117
:param config: If None no digital signature will be created.
118
If supplied its signature_needed method will be used
119
to determine if a signature should be made.
121
_mod_revision.check_not_reserved_id(rev_id)
122
if config is not None and config.signature_needed():
124
inv = self.get_inventory(rev_id)
125
plaintext = Testament(rev, inv).as_short_text()
126
self.store_revision_signature(
127
gpg.GPGStrategy(config), plaintext, rev_id)
128
if not rev_id in self.get_inventory_weave():
130
raise errors.WeaveRevisionNotPresent(rev_id,
131
self.get_inventory_weave())
133
# yes, this is not suitable for adding with ghosts.
134
self.add_inventory(rev_id, inv, rev.parent_ids)
135
self._revision_store.add_revision(rev, self.get_transaction())
138
def _all_possible_ids(self):
139
"""Return all the possible revisions that we could find."""
140
return self.get_inventory_weave().versions()
142
def all_revision_ids(self):
143
"""Returns a list of all the revision ids in the repository.
145
This is deprecated because code should generally work on the graph
146
reachable from a particular revision, and ignore any other revisions
147
that might be present. There is no direct replacement method.
149
return self._all_revision_ids()
152
def _all_revision_ids(self):
153
"""Returns a list of all the revision ids in the repository.
155
These are in as much topological order as the underlying store can
156
present: for weaves ghosts may lead to a lack of correctness until
157
the reweave updates the parents list.
159
if self._revision_store.text_store.listable():
160
return self._revision_store.all_revision_ids(self.get_transaction())
161
result = self._all_possible_ids()
162
return self._eliminate_revisions_not_present(result)
164
def break_lock(self):
165
"""Break a lock if one is present from another instance.
167
Uses the ui factory to ask for confirmation if the lock may be from
170
self.control_files.break_lock()
173
def _eliminate_revisions_not_present(self, revision_ids):
174
"""Check every revision id in revision_ids to see if we have it.
176
Returns a set of the present revisions.
179
for id in revision_ids:
180
if self.has_revision(id):
185
def create(a_bzrdir):
186
"""Construct the current default format repository in a_bzrdir."""
187
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
189
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
190
"""instantiate a Repository.
192
:param _format: The format of the repository on disk.
193
:param a_bzrdir: The BzrDir of the repository.
195
In the future we will have a single api for all stores for
196
getting file texts, inventories and revisions, then
197
this construct will accept instances of those things.
199
super(Repository, self).__init__()
200
self._format = _format
201
# the following are part of the public API for Repository:
202
self.bzrdir = a_bzrdir
203
self.control_files = control_files
204
self._revision_store = _revision_store
205
self.text_store = text_store
206
# backwards compatibility
207
self.weave_store = text_store
208
# not right yet - should be more semantically clear ?
210
self.control_store = control_store
211
self.control_weaves = control_store
212
# TODO: make sure to construct the right store classes, etc, depending
213
# on whether escaping is required.
214
self._warn_if_deprecated()
217
return '%s(%r)' % (self.__class__.__name__,
218
self.bzrdir.transport.base)
221
return self.control_files.is_locked()
223
def lock_write(self):
224
self.control_files.lock_write()
227
self.control_files.lock_read()
229
def get_physical_lock_status(self):
230
return self.control_files.get_physical_lock_status()
233
def gather_stats(self, revid=None, committers=None):
234
"""Gather statistics from a revision id.
236
:param revid: The revision id to gather statistics from, if None, then
237
no revision specific statistics are gathered.
238
:param committers: Optional parameter controlling whether to grab
239
a count of committers from the revision specific statistics.
240
:return: A dictionary of statistics. Currently this contains:
241
committers: The number of committers if requested.
242
firstrev: A tuple with timestamp, timezone for the penultimate left
243
most ancestor of revid, if revid is not the NULL_REVISION.
244
latestrev: A tuple with timestamp, timezone for revid, if revid is
245
not the NULL_REVISION.
246
revisions: The total revision count in the repository.
247
size: An estimate disk size of the repository in bytes.
250
if revid and committers:
251
result['committers'] = 0
252
if revid and revid != _mod_revision.NULL_REVISION:
254
all_committers = set()
255
revisions = self.get_ancestry(revid)
256
# pop the leading None
258
first_revision = None
260
# ignore the revisions in the middle - just grab first and last
261
revisions = revisions[0], revisions[-1]
262
for revision in self.get_revisions(revisions):
263
if not first_revision:
264
first_revision = revision
266
all_committers.add(revision.committer)
267
last_revision = revision
269
result['committers'] = len(all_committers)
270
result['firstrev'] = (first_revision.timestamp,
271
first_revision.timezone)
272
result['latestrev'] = (last_revision.timestamp,
273
last_revision.timezone)
275
# now gather global repository information
276
if self.bzrdir.root_transport.listable():
277
c, t = self._revision_store.total_size(self.get_transaction())
278
result['revisions'] = c
283
def missing_revision_ids(self, other, revision_id=None):
284
"""Return the revision ids that other has that this does not.
286
These are returned in topological order.
288
revision_id: only return revision ids included by revision_id.
290
return InterRepository.get(other, self).missing_revision_ids(revision_id)
294
"""Open the repository rooted at base.
296
For instance, if the repository is at URL/.bzr/repository,
297
Repository.open(URL) -> a Repository instance.
299
control = bzrdir.BzrDir.open(base)
300
return control.open_repository()
302
def copy_content_into(self, destination, revision_id=None, basis=None):
303
"""Make a complete copy of the content in self into destination.
305
This is a destructive operation! Do not use it on existing
308
return InterRepository.get(self, destination).copy_content(revision_id, basis)
310
def fetch(self, source, revision_id=None, pb=None):
311
"""Fetch the content required to construct revision_id from source.
313
If revision_id is None all content is copied.
315
return InterRepository.get(source, self).fetch(revision_id=revision_id,
318
def get_commit_builder(self, branch, parents, config, timestamp=None,
319
timezone=None, committer=None, revprops=None,
321
"""Obtain a CommitBuilder for this repository.
323
:param branch: Branch to commit to.
324
:param parents: Revision ids of the parents of the new revision.
325
:param config: Configuration to use.
326
:param timestamp: Optional timestamp recorded for commit.
327
:param timezone: Optional timezone for timestamp.
328
:param committer: Optional committer to set for commit.
329
:param revprops: Optional dictionary of revision properties.
330
:param revision_id: Optional revision id.
332
return _CommitBuilder(self, parents, config, timestamp, timezone,
333
committer, revprops, revision_id)
336
self.control_files.unlock()
339
def clone(self, a_bzrdir, revision_id=None, basis=None):
340
"""Clone this repository into a_bzrdir using the current format.
342
Currently no check is made that the format of this repository and
343
the bzrdir format are compatible. FIXME RBC 20060201.
345
:return: The newly created destination repository.
347
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
348
# use target default format.
349
dest_repo = a_bzrdir.create_repository()
351
# Most control formats need the repository to be specifically
352
# created, but on some old all-in-one formats it's not needed
354
dest_repo = self._format.initialize(a_bzrdir, shared=self.is_shared())
355
except errors.UninitializableFormat:
356
dest_repo = a_bzrdir.open_repository()
357
self.copy_content_into(dest_repo, revision_id, basis)
361
def has_revision(self, revision_id):
362
"""True if this repository has a copy of the revision."""
363
return self._revision_store.has_revision_id(revision_id,
364
self.get_transaction())
367
def get_revision_reconcile(self, revision_id):
368
"""'reconcile' helper routine that allows access to a revision always.
370
This variant of get_revision does not cross check the weave graph
371
against the revision one as get_revision does: but it should only
372
be used by reconcile, or reconcile-alike commands that are correcting
373
or testing the revision graph.
375
if not revision_id or not isinstance(revision_id, basestring):
376
raise errors.InvalidRevisionId(revision_id=revision_id,
378
return self._revision_store.get_revisions([revision_id],
379
self.get_transaction())[0]
381
def get_revisions(self, revision_ids):
382
return self._revision_store.get_revisions(revision_ids,
383
self.get_transaction())
386
def get_revision_xml(self, revision_id):
387
rev = self.get_revision(revision_id)
389
# the current serializer..
390
self._revision_store._serializer.write_revision(rev, rev_tmp)
392
return rev_tmp.getvalue()
395
def get_revision(self, revision_id):
396
"""Return the Revision object for a named revision"""
397
r = self.get_revision_reconcile(revision_id)
398
# weave corruption can lead to absent revision markers that should be
400
# the following test is reasonably cheap (it needs a single weave read)
401
# and the weave is cached in read transactions. In write transactions
402
# it is not cached but typically we only read a small number of
403
# revisions. For knits when they are introduced we will probably want
404
# to ensure that caching write transactions are in use.
405
inv = self.get_inventory_weave()
406
self._check_revision_parents(r, inv)
410
def get_deltas_for_revisions(self, revisions):
411
"""Produce a generator of revision deltas.
413
Note that the input is a sequence of REVISIONS, not revision_ids.
414
Trees will be held in memory until the generator exits.
415
Each delta is relative to the revision's lefthand predecessor.
417
required_trees = set()
418
for revision in revisions:
419
required_trees.add(revision.revision_id)
420
required_trees.update(revision.parent_ids[:1])
421
trees = dict((t.get_revision_id(), t) for
422
t in self.revision_trees(required_trees))
423
for revision in revisions:
424
if not revision.parent_ids:
425
old_tree = self.revision_tree(None)
427
old_tree = trees[revision.parent_ids[0]]
428
yield trees[revision.revision_id].changes_from(old_tree)
431
def get_revision_delta(self, revision_id):
432
"""Return the delta for one revision.
434
The delta is relative to the left-hand predecessor of the
437
r = self.get_revision(revision_id)
438
return list(self.get_deltas_for_revisions([r]))[0]
440
def _check_revision_parents(self, revision, inventory):
441
"""Private to Repository and Fetch.
443
This checks the parentage of revision in an inventory weave for
444
consistency and is only applicable to inventory-weave-for-ancestry
445
using repository formats & fetchers.
447
weave_parents = inventory.get_parents(revision.revision_id)
448
weave_names = inventory.versions()
449
for parent_id in revision.parent_ids:
450
if parent_id in weave_names:
451
# this parent must not be a ghost.
452
if not parent_id in weave_parents:
454
raise errors.CorruptRepository(self)
457
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
458
signature = gpg_strategy.sign(plaintext)
459
self._revision_store.add_revision_signature_text(revision_id,
461
self.get_transaction())
463
def fileids_altered_by_revision_ids(self, revision_ids):
464
"""Find the file ids and versions affected by revisions.
466
:param revisions: an iterable containing revision ids.
467
:return: a dictionary mapping altered file-ids to an iterable of
468
revision_ids. Each altered file-ids has the exact revision_ids that
469
altered it listed explicitly.
471
assert self._serializer.support_altered_by_hack, \
472
("fileids_altered_by_revision_ids only supported for branches "
473
"which store inventory as unnested xml, not on %r" % self)
474
selected_revision_ids = set(revision_ids)
475
w = self.get_inventory_weave()
478
# this code needs to read every new line in every inventory for the
479
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
480
# not present in one of those inventories is unnecessary but not
481
# harmful because we are filtering by the revision id marker in the
482
# inventory lines : we only select file ids altered in one of those
483
# revisions. We don't need to see all lines in the inventory because
484
# only those added in an inventory in rev X can contain a revision=X
486
unescape_revid_cache = {}
487
unescape_fileid_cache = {}
489
# jam 20061218 In a big fetch, this handles hundreds of thousands
490
# of lines, so it has had a lot of inlining and optimizing done.
491
# Sorry that it is a little bit messy.
492
# Move several functions to be local variables, since this is a long
494
search = self._file_ids_altered_regex.search
495
unescape = _unescape_xml
496
setdefault = result.setdefault
497
pb = ui.ui_factory.nested_progress_bar()
499
for line in w.iter_lines_added_or_present_in_versions(
500
selected_revision_ids, pb=pb):
504
# One call to match.group() returning multiple items is quite a
505
# bit faster than 2 calls to match.group() each returning 1
506
file_id, revision_id = match.group('file_id', 'revision_id')
508
# Inlining the cache lookups helps a lot when you make 170,000
509
# lines and 350k ids, versus 8.4 unique ids.
510
# Using a cache helps in 2 ways:
511
# 1) Avoids unnecessary decoding calls
512
# 2) Re-uses cached strings, which helps in future set and
514
# (2) is enough that removing encoding entirely along with
515
# the cache (so we are using plain strings) results in no
516
# performance improvement.
518
revision_id = unescape_revid_cache[revision_id]
520
unescaped = unescape(revision_id)
521
unescape_revid_cache[revision_id] = unescaped
522
revision_id = unescaped
524
if revision_id in selected_revision_ids:
526
file_id = unescape_fileid_cache[file_id]
528
unescaped = unescape(file_id)
529
unescape_fileid_cache[file_id] = unescaped
531
setdefault(file_id, set()).add(revision_id)
537
def get_inventory_weave(self):
538
return self.control_weaves.get_weave('inventory',
539
self.get_transaction())
542
def get_inventory(self, revision_id):
543
"""Get Inventory object by hash."""
544
return self.deserialise_inventory(
545
revision_id, self.get_inventory_xml(revision_id))
547
def deserialise_inventory(self, revision_id, xml):
548
"""Transform the xml into an inventory object.
550
:param revision_id: The expected revision id of the inventory.
551
:param xml: A serialised inventory.
553
result = self._serializer.read_inventory_from_string(xml)
554
result.root.revision = revision_id
557
def serialise_inventory(self, inv):
558
return self._serializer.write_inventory_to_string(inv)
561
def get_inventory_xml(self, revision_id):
562
"""Get inventory XML as a file object."""
564
assert isinstance(revision_id, basestring), type(revision_id)
565
iw = self.get_inventory_weave()
566
return iw.get_text(revision_id)
568
raise errors.HistoryMissing(self, 'inventory', revision_id)
571
def get_inventory_sha1(self, revision_id):
572
"""Return the sha1 hash of the inventory entry
574
return self.get_revision(revision_id).inventory_sha1
577
def get_revision_graph(self, revision_id=None):
578
"""Return a dictionary containing the revision graph.
580
:param revision_id: The revision_id to get a graph from. If None, then
581
the entire revision graph is returned. This is a deprecated mode of
582
operation and will be removed in the future.
583
:return: a dictionary of revision_id->revision_parents_list.
585
# special case NULL_REVISION
586
if revision_id == _mod_revision.NULL_REVISION:
588
a_weave = self.get_inventory_weave()
589
all_revisions = self._eliminate_revisions_not_present(
591
entire_graph = dict([(node, a_weave.get_parents(node)) for
592
node in all_revisions])
593
if revision_id is None:
595
elif revision_id not in entire_graph:
596
raise errors.NoSuchRevision(self, revision_id)
598
# add what can be reached from revision_id
600
pending = set([revision_id])
601
while len(pending) > 0:
603
result[node] = entire_graph[node]
604
for revision_id in result[node]:
605
if revision_id not in result:
606
pending.add(revision_id)
610
def get_revision_graph_with_ghosts(self, revision_ids=None):
611
"""Return a graph of the revisions with ghosts marked as applicable.
613
:param revision_ids: an iterable of revisions to graph or None for all.
614
:return: a Graph object with the graph reachable from revision_ids.
616
result = graph.Graph()
618
pending = set(self.all_revision_ids())
621
pending = set(revision_ids)
622
# special case NULL_REVISION
623
if _mod_revision.NULL_REVISION in pending:
624
pending.remove(_mod_revision.NULL_REVISION)
625
required = set(pending)
628
revision_id = pending.pop()
630
rev = self.get_revision(revision_id)
631
except errors.NoSuchRevision:
632
if revision_id in required:
635
result.add_ghost(revision_id)
637
for parent_id in rev.parent_ids:
638
# is this queued or done ?
639
if (parent_id not in pending and
640
parent_id not in done):
642
pending.add(parent_id)
643
result.add_node(revision_id, rev.parent_ids)
644
done.add(revision_id)
647
def _get_history_vf(self):
648
"""Get a versionedfile whose history graph reflects all revisions.
650
For weave repositories, this is the inventory weave.
652
return self.get_inventory_weave()
654
def iter_reverse_revision_history(self, revision_id):
655
"""Iterate backwards through revision ids in the lefthand history
657
:param revision_id: The revision id to start with. All its lefthand
658
ancestors will be traversed.
660
if revision_id in (None, _mod_revision.NULL_REVISION):
662
next_id = revision_id
663
versionedfile = self._get_history_vf()
666
parents = versionedfile.get_parents(next_id)
667
if len(parents) == 0:
673
def get_revision_inventory(self, revision_id):
674
"""Return inventory of a past revision."""
675
# TODO: Unify this with get_inventory()
676
# bzr 0.0.6 and later imposes the constraint that the inventory_id
677
# must be the same as its revision, so this is trivial.
678
if revision_id is None:
679
# This does not make sense: if there is no revision,
680
# then it is the current tree inventory surely ?!
681
# and thus get_root_id() is something that looks at the last
682
# commit on the branch, and the get_root_id is an inventory check.
683
raise NotImplementedError
684
# return Inventory(self.get_root_id())
686
return self.get_inventory(revision_id)
690
"""Return True if this repository is flagged as a shared repository."""
691
raise NotImplementedError(self.is_shared)
694
def reconcile(self, other=None, thorough=False):
695
"""Reconcile this repository."""
696
from bzrlib.reconcile import RepoReconciler
697
reconciler = RepoReconciler(self, thorough=thorough)
698
reconciler.reconcile()
702
def revision_tree(self, revision_id):
703
"""Return Tree for a revision on this branch.
705
`revision_id` may be None for the empty tree revision.
707
# TODO: refactor this to use an existing revision object
708
# so we don't need to read it in twice.
709
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
710
return RevisionTree(self, Inventory(root_id=None),
711
_mod_revision.NULL_REVISION)
713
inv = self.get_revision_inventory(revision_id)
714
return RevisionTree(self, inv, revision_id)
717
def revision_trees(self, revision_ids):
718
"""Return Tree for a revision on this branch.
720
`revision_id` may not be None or 'null:'"""
721
assert None not in revision_ids
722
assert _mod_revision.NULL_REVISION not in revision_ids
723
texts = self.get_inventory_weave().get_texts(revision_ids)
724
for text, revision_id in zip(texts, revision_ids):
725
inv = self.deserialise_inventory(revision_id, text)
726
yield RevisionTree(self, inv, revision_id)
729
def get_ancestry(self, revision_id):
730
"""Return a list of revision-ids integrated by a revision.
732
The first element of the list is always None, indicating the origin
733
revision. This might change when we have history horizons, or
734
perhaps we should have a new API.
736
This is topologically sorted.
738
if revision_id is None:
740
if not self.has_revision(revision_id):
741
raise errors.NoSuchRevision(self, revision_id)
742
w = self.get_inventory_weave()
743
candidates = w.get_ancestry(revision_id)
744
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
747
def print_file(self, file, revision_id):
748
"""Print `file` to stdout.
750
FIXME RBC 20060125 as John Meinel points out this is a bad api
751
- it writes to stdout, it assumes that that is valid etc. Fix
752
by creating a new more flexible convenience function.
754
tree = self.revision_tree(revision_id)
755
# use inventory as it was in that revision
756
file_id = tree.inventory.path2id(file)
758
# TODO: jam 20060427 Write a test for this code path
759
# it had a bug in it, and was raising the wrong
761
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
762
tree.print_file(file_id)
764
def get_transaction(self):
765
return self.control_files.get_transaction()
767
def revision_parents(self, revid):
768
return self.get_inventory_weave().parent_names(revid)
771
def set_make_working_trees(self, new_value):
772
"""Set the policy flag for making working trees when creating branches.
774
This only applies to branches that use this repository.
776
The default is 'True'.
777
:param new_value: True to restore the default, False to disable making
780
raise NotImplementedError(self.set_make_working_trees)
782
def make_working_trees(self):
783
"""Returns the policy for making working trees on new branches."""
784
raise NotImplementedError(self.make_working_trees)
787
def sign_revision(self, revision_id, gpg_strategy):
788
plaintext = Testament.from_revision(self, revision_id).as_short_text()
789
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
792
def has_signature_for_revision_id(self, revision_id):
793
"""Query for a revision signature for revision_id in the repository."""
794
return self._revision_store.has_signature(revision_id,
795
self.get_transaction())
798
def get_signature_text(self, revision_id):
799
"""Return the text for a signature."""
800
return self._revision_store.get_signature_text(revision_id,
801
self.get_transaction())
804
def check(self, revision_ids):
805
"""Check consistency of all history of given revision_ids.
807
Different repository implementations should override _check().
809
:param revision_ids: A non-empty list of revision_ids whose ancestry
810
will be checked. Typically the last revision_id of a branch.
813
raise ValueError("revision_ids must be non-empty in %s.check"
815
return self._check(revision_ids)
817
def _check(self, revision_ids):
818
result = check.Check(self)
822
def _warn_if_deprecated(self):
823
global _deprecation_warning_done
824
if _deprecation_warning_done:
826
_deprecation_warning_done = True
827
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
828
% (self._format, self.bzrdir.transport.base))
830
def supports_rich_root(self):
831
return self._format.rich_root_data
833
def _check_ascii_revisionid(self, revision_id, method):
834
"""Private helper for ascii-only repositories."""
835
# weave repositories refuse to store revisionids that are non-ascii.
836
if revision_id is not None:
837
# weaves require ascii revision ids.
838
if isinstance(revision_id, unicode):
840
revision_id.encode('ascii')
841
except UnicodeEncodeError:
842
raise errors.NonAsciiRevisionId(method, self)
846
# remove these delegates a while after bzr 0.15
847
def __make_delegated(name, from_module):
848
def _deprecated_repository_forwarder():
849
symbol_versioning.warn('%s moved to %s in bzr 0.15'
850
% (name, from_module),
853
m = __import__(from_module, globals(), locals(), [name])
855
return getattr(m, name)
856
except AttributeError:
857
raise AttributeError('module %s has no name %s'
859
globals()[name] = _deprecated_repository_forwarder
862
'AllInOneRepository',
863
'WeaveMetaDirRepository',
864
'PreSplitOutRepositoryFormat',
870
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
875
'RepositoryFormatKnit',
876
'RepositoryFormatKnit1',
877
'RepositoryFormatKnit2',
879
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
882
def install_revision(repository, rev, revision_tree):
883
"""Install all revision data into a repository."""
886
for p_id in rev.parent_ids:
887
if repository.has_revision(p_id):
888
present_parents.append(p_id)
889
parent_trees[p_id] = repository.revision_tree(p_id)
891
parent_trees[p_id] = repository.revision_tree(None)
893
inv = revision_tree.inventory
894
entries = inv.iter_entries()
895
# backwards compatability hack: skip the root id.
896
if not repository.supports_rich_root():
897
path, root = entries.next()
898
if root.revision != rev.revision_id:
899
raise errors.IncompatibleRevision(repr(repository))
900
# Add the texts that are not already present
901
for path, ie in entries:
902
w = repository.weave_store.get_weave_or_empty(ie.file_id,
903
repository.get_transaction())
904
if ie.revision not in w:
906
# FIXME: TODO: The following loop *may* be overlapping/duplicate
907
# with InventoryEntry.find_previous_heads(). if it is, then there
908
# is a latent bug here where the parents may have ancestors of each
910
for revision, tree in parent_trees.iteritems():
911
if ie.file_id not in tree:
913
parent_id = tree.inventory[ie.file_id].revision
914
if parent_id in text_parents:
916
text_parents.append(parent_id)
918
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
919
repository.get_transaction())
920
lines = revision_tree.get_file(ie.file_id).readlines()
921
vfile.add_lines(rev.revision_id, text_parents, lines)
923
# install the inventory
924
repository.add_inventory(rev.revision_id, inv, present_parents)
925
except errors.RevisionAlreadyPresent:
927
repository.add_revision(rev.revision_id, rev, inv)
930
class MetaDirRepository(Repository):
931
"""Repositories in the new meta-dir layout."""
933
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
934
super(MetaDirRepository, self).__init__(_format,
940
dir_mode = self.control_files._dir_mode
941
file_mode = self.control_files._file_mode
945
"""Return True if this repository is flagged as a shared repository."""
946
return self.control_files._transport.has('shared-storage')
949
def set_make_working_trees(self, new_value):
950
"""Set the policy flag for making working trees when creating branches.
952
This only applies to branches that use this repository.
954
The default is 'True'.
955
:param new_value: True to restore the default, False to disable making
960
self.control_files._transport.delete('no-working-trees')
961
except errors.NoSuchFile:
964
self.control_files.put_utf8('no-working-trees', '')
966
def make_working_trees(self):
967
"""Returns the policy for making working trees on new branches."""
968
return not self.control_files._transport.has('no-working-trees')
971
class RepositoryFormatRegistry(registry.Registry):
972
"""Registry of RepositoryFormats.
975
def get(self, format_string):
976
r = registry.Registry.get(self, format_string)
982
format_registry = RepositoryFormatRegistry()
983
"""Registry of formats, indexed by their identifying format string.
985
This can contain either format instances themselves, or classes/factories that
986
can be called to obtain one.
990
class RepositoryFormat(object):
991
"""A repository format.
993
Formats provide three things:
994
* An initialization routine to construct repository data on disk.
995
* a format string which is used when the BzrDir supports versioned
997
* an open routine which returns a Repository instance.
999
Formats are placed in an dict by their format string for reference
1000
during opening. These should be subclasses of RepositoryFormat
1003
Once a format is deprecated, just deprecate the initialize and open
1004
methods on the format class. Do not deprecate the object, as the
1005
object will be created every system load.
1007
Common instance attributes:
1008
_matchingbzrdir - the bzrdir format that the repository format was
1009
originally written to work with. This can be used if manually
1010
constructing a bzrdir and repository, or more commonly for test suite
1015
return "<%s>" % self.__class__.__name__
1017
def __eq__(self, other):
1018
# format objects are generally stateless
1019
return isinstance(other, self.__class__)
1021
def __ne__(self, other):
1022
return not self == other
1025
def find_format(klass, a_bzrdir):
1026
"""Return the format for the repository object in a_bzrdir.
1028
This is used by bzr native formats that have a "format" file in
1029
the repository. Other methods may be used by different types of
1033
transport = a_bzrdir.get_repository_transport(None)
1034
format_string = transport.get("format").read()
1035
return format_registry.get(format_string)
1036
except errors.NoSuchFile:
1037
raise errors.NoRepositoryPresent(a_bzrdir)
1039
raise errors.UnknownFormatError(format=format_string)
1042
def register_format(klass, format):
1043
format_registry.register(format.get_format_string(), format)
1046
def unregister_format(klass, format):
1047
format_registry.remove(format.get_format_string())
1050
def get_default_format(klass):
1051
"""Return the current default format."""
1052
from bzrlib import bzrdir
1053
return bzrdir.format_registry.make_bzrdir('default').repository_format
1055
def _get_control_store(self, repo_transport, control_files):
1056
"""Return the control store for this repository."""
1057
raise NotImplementedError(self._get_control_store)
1059
def get_format_string(self):
1060
"""Return the ASCII format string that identifies this format.
1062
Note that in pre format ?? repositories the format string is
1063
not permitted nor written to disk.
1065
raise NotImplementedError(self.get_format_string)
1067
def get_format_description(self):
1068
"""Return the short description for this format."""
1069
raise NotImplementedError(self.get_format_description)
1071
def _get_revision_store(self, repo_transport, control_files):
1072
"""Return the revision store object for this a_bzrdir."""
1073
raise NotImplementedError(self._get_revision_store)
1075
def _get_text_rev_store(self,
1082
"""Common logic for getting a revision store for a repository.
1084
see self._get_revision_store for the subclass-overridable method to
1085
get the store for a repository.
1087
from bzrlib.store.revision.text import TextRevisionStore
1088
dir_mode = control_files._dir_mode
1089
file_mode = control_files._file_mode
1090
text_store =TextStore(transport.clone(name),
1092
compressed=compressed,
1094
file_mode=file_mode)
1095
_revision_store = TextRevisionStore(text_store, serializer)
1096
return _revision_store
1098
# TODO: this shouldn't be in the base class, it's specific to things that
1099
# use weaves or knits -- mbp 20070207
1100
def _get_versioned_file_store(self,
1105
versionedfile_class=None,
1106
versionedfile_kwargs={},
1108
if versionedfile_class is None:
1109
versionedfile_class = self._versionedfile_class
1110
weave_transport = control_files._transport.clone(name)
1111
dir_mode = control_files._dir_mode
1112
file_mode = control_files._file_mode
1113
return VersionedFileStore(weave_transport, prefixed=prefixed,
1115
file_mode=file_mode,
1116
versionedfile_class=versionedfile_class,
1117
versionedfile_kwargs=versionedfile_kwargs,
1120
def initialize(self, a_bzrdir, shared=False):
1121
"""Initialize a repository of this format in a_bzrdir.
1123
:param a_bzrdir: The bzrdir to put the new repository in it.
1124
:param shared: The repository should be initialized as a sharable one.
1126
This may raise UninitializableFormat if shared repository are not
1127
compatible the a_bzrdir.
1130
def is_supported(self):
1131
"""Is this format supported?
1133
Supported formats must be initializable and openable.
1134
Unsupported formats may not support initialization or committing or
1135
some other features depending on the reason for not being supported.
1139
def check_conversion_target(self, target_format):
1140
raise NotImplementedError(self.check_conversion_target)
1142
def open(self, a_bzrdir, _found=False):
1143
"""Return an instance of this format for the bzrdir a_bzrdir.
1145
_found is a private parameter, do not use it.
1147
raise NotImplementedError(self.open)
1150
class MetaDirRepositoryFormat(RepositoryFormat):
1151
"""Common base class for the new repositories using the metadir layout."""
1153
rich_root_data = False
1154
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1157
super(MetaDirRepositoryFormat, self).__init__()
1159
def _create_control_files(self, a_bzrdir):
1160
"""Create the required files and the initial control_files object."""
1161
# FIXME: RBC 20060125 don't peek under the covers
1162
# NB: no need to escape relative paths that are url safe.
1163
repository_transport = a_bzrdir.get_repository_transport(self)
1164
control_files = lockable_files.LockableFiles(repository_transport,
1165
'lock', lockdir.LockDir)
1166
control_files.create_lock()
1167
return control_files
1169
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1170
"""Upload the initial blank content."""
1171
control_files = self._create_control_files(a_bzrdir)
1172
control_files.lock_write()
1174
control_files._transport.mkdir_multi(dirs,
1175
mode=control_files._dir_mode)
1176
for file, content in files:
1177
control_files.put(file, content)
1178
for file, content in utf8_files:
1179
control_files.put_utf8(file, content)
1181
control_files.put_utf8('shared-storage', '')
1183
control_files.unlock()
1186
# formats which have no format string are not discoverable
1187
# and not independently creatable, so are not registered. They're
1188
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1189
# needed, it's constructed directly by the BzrDir. Non-native formats where
1190
# the repository is not separately opened are similar.
1192
format_registry.register_lazy(
1193
'Bazaar-NG Repository format 7',
1194
'bzrlib.repofmt.weaverepo',
1197
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1198
# default control directory format
1200
format_registry.register_lazy(
1201
'Bazaar-NG Knit Repository Format 1',
1202
'bzrlib.repofmt.knitrepo',
1203
'RepositoryFormatKnit1',
1205
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1207
format_registry.register_lazy(
1208
'Bazaar Knit Repository Format 2\n',
1209
'bzrlib.repofmt.knitrepo',
1210
'RepositoryFormatKnit2',
1213
format_registry.register_lazy(
1214
'Bazaar Knit Repository Format 3\n',
1215
'bzrlib.repofmt.knitrepo',
1216
'RepositoryFormatKnit3',
1220
class InterRepository(InterObject):
1221
"""This class represents operations taking place between two repositories.
1223
Its instances have methods like copy_content and fetch, and contain
1224
references to the source and target repositories these operations can be
1227
Often we will provide convenience methods on 'repository' which carry out
1228
operations with another repository - they will always forward to
1229
InterRepository.get(other).method_name(parameters).
1233
"""The available optimised InterRepository types."""
1235
def copy_content(self, revision_id=None, basis=None):
1236
raise NotImplementedError(self.copy_content)
1238
def fetch(self, revision_id=None, pb=None):
1239
"""Fetch the content required to construct revision_id.
1241
The content is copied from self.source to self.target.
1243
:param revision_id: if None all content is copied, if NULL_REVISION no
1245
:param pb: optional progress bar to use for progress reports. If not
1246
provided a default one will be created.
1248
Returns the copied revision count and the failed revisions in a tuple:
1251
raise NotImplementedError(self.fetch)
1254
def missing_revision_ids(self, revision_id=None):
1255
"""Return the revision ids that source has that target does not.
1257
These are returned in topological order.
1259
:param revision_id: only return revision ids included by this
1262
# generic, possibly worst case, slow code path.
1263
target_ids = set(self.target.all_revision_ids())
1264
if revision_id is not None:
1265
source_ids = self.source.get_ancestry(revision_id)
1266
assert source_ids[0] is None
1269
source_ids = self.source.all_revision_ids()
1270
result_set = set(source_ids).difference(target_ids)
1271
# this may look like a no-op: its not. It preserves the ordering
1272
# other_ids had while only returning the members from other_ids
1273
# that we've decided we need.
1274
return [rev_id for rev_id in source_ids if rev_id in result_set]
1277
class InterSameDataRepository(InterRepository):
1278
"""Code for converting between repositories that represent the same data.
1280
Data format and model must match for this to work.
1284
def _get_repo_format_to_test(self):
1285
"""Repository format for testing with."""
1286
return RepositoryFormat.get_default_format()
1289
def is_compatible(source, target):
1290
if not isinstance(source, Repository):
1292
if not isinstance(target, Repository):
1294
if source._format.rich_root_data != target._format.rich_root_data:
1296
if source._serializer != target._serializer:
1302
def copy_content(self, revision_id=None, basis=None):
1303
"""Make a complete copy of the content in self into destination.
1305
This is a destructive operation! Do not use it on existing
1308
:param revision_id: Only copy the content needed to construct
1309
revision_id and its parents.
1310
:param basis: Copy the needed data preferentially from basis.
1313
self.target.set_make_working_trees(self.source.make_working_trees())
1314
except NotImplementedError:
1316
# grab the basis available data
1317
if basis is not None:
1318
self.target.fetch(basis, revision_id=revision_id)
1319
# but don't bother fetching if we have the needed data now.
1320
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1321
self.target.has_revision(revision_id)):
1323
self.target.fetch(self.source, revision_id=revision_id)
1326
def fetch(self, revision_id=None, pb=None):
1327
"""See InterRepository.fetch()."""
1328
from bzrlib.fetch import GenericRepoFetcher
1329
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1330
self.source, self.source._format, self.target,
1331
self.target._format)
1332
f = GenericRepoFetcher(to_repository=self.target,
1333
from_repository=self.source,
1334
last_revision=revision_id,
1336
return f.count_copied, f.failed_revisions
1339
class InterWeaveRepo(InterSameDataRepository):
1340
"""Optimised code paths between Weave based repositories."""
1343
def _get_repo_format_to_test(self):
1344
from bzrlib.repofmt import weaverepo
1345
return weaverepo.RepositoryFormat7()
1348
def is_compatible(source, target):
1349
"""Be compatible with known Weave formats.
1351
We don't test for the stores being of specific types because that
1352
could lead to confusing results, and there is no need to be
1355
from bzrlib.repofmt.weaverepo import (
1361
return (isinstance(source._format, (RepositoryFormat5,
1363
RepositoryFormat7)) and
1364
isinstance(target._format, (RepositoryFormat5,
1366
RepositoryFormat7)))
1367
except AttributeError:
1371
def copy_content(self, revision_id=None, basis=None):
1372
"""See InterRepository.copy_content()."""
1373
# weave specific optimised path:
1374
if basis is not None:
1375
# copy the basis in, then fetch remaining data.
1376
basis.copy_content_into(self.target, revision_id)
1377
# the basis copy_content_into could miss-set this.
1379
self.target.set_make_working_trees(self.source.make_working_trees())
1380
except NotImplementedError:
1382
self.target.fetch(self.source, revision_id=revision_id)
1385
self.target.set_make_working_trees(self.source.make_working_trees())
1386
except NotImplementedError:
1388
# FIXME do not peek!
1389
if self.source.control_files._transport.listable():
1390
pb = ui.ui_factory.nested_progress_bar()
1392
self.target.weave_store.copy_all_ids(
1393
self.source.weave_store,
1395
from_transaction=self.source.get_transaction(),
1396
to_transaction=self.target.get_transaction())
1397
pb.update('copying inventory', 0, 1)
1398
self.target.control_weaves.copy_multi(
1399
self.source.control_weaves, ['inventory'],
1400
from_transaction=self.source.get_transaction(),
1401
to_transaction=self.target.get_transaction())
1402
self.target._revision_store.text_store.copy_all_ids(
1403
self.source._revision_store.text_store,
1408
self.target.fetch(self.source, revision_id=revision_id)
1411
def fetch(self, revision_id=None, pb=None):
1412
"""See InterRepository.fetch()."""
1413
from bzrlib.fetch import GenericRepoFetcher
1414
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1415
self.source, self.source._format, self.target, self.target._format)
1416
f = GenericRepoFetcher(to_repository=self.target,
1417
from_repository=self.source,
1418
last_revision=revision_id,
1420
return f.count_copied, f.failed_revisions
1423
def missing_revision_ids(self, revision_id=None):
1424
"""See InterRepository.missing_revision_ids()."""
1425
# we want all revisions to satisfy revision_id in source.
1426
# but we don't want to stat every file here and there.
1427
# we want then, all revisions other needs to satisfy revision_id
1428
# checked, but not those that we have locally.
1429
# so the first thing is to get a subset of the revisions to
1430
# satisfy revision_id in source, and then eliminate those that
1431
# we do already have.
1432
# this is slow on high latency connection to self, but as as this
1433
# disk format scales terribly for push anyway due to rewriting
1434
# inventory.weave, this is considered acceptable.
1436
if revision_id is not None:
1437
source_ids = self.source.get_ancestry(revision_id)
1438
assert source_ids[0] is None
1441
source_ids = self.source._all_possible_ids()
1442
source_ids_set = set(source_ids)
1443
# source_ids is the worst possible case we may need to pull.
1444
# now we want to filter source_ids against what we actually
1445
# have in target, but don't try to check for existence where we know
1446
# we do not have a revision as that would be pointless.
1447
target_ids = set(self.target._all_possible_ids())
1448
possibly_present_revisions = target_ids.intersection(source_ids_set)
1449
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1450
required_revisions = source_ids_set.difference(actually_present_revisions)
1451
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1452
if revision_id is not None:
1453
# we used get_ancestry to determine source_ids then we are assured all
1454
# revisions referenced are present as they are installed in topological order.
1455
# and the tip revision was validated by get_ancestry.
1456
return required_topo_revisions
1458
# if we just grabbed the possibly available ids, then
1459
# we only have an estimate of whats available and need to validate
1460
# that against the revision records.
1461
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1464
class InterKnitRepo(InterSameDataRepository):
1465
"""Optimised code paths between Knit based repositories."""
1468
def _get_repo_format_to_test(self):
1469
from bzrlib.repofmt import knitrepo
1470
return knitrepo.RepositoryFormatKnit1()
1473
def is_compatible(source, target):
1474
"""Be compatible with known Knit formats.
1476
We don't test for the stores being of specific types because that
1477
could lead to confusing results, and there is no need to be
1480
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
1482
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1483
isinstance(target._format, (RepositoryFormatKnit1)))
1484
except AttributeError:
1488
def fetch(self, revision_id=None, pb=None):
1489
"""See InterRepository.fetch()."""
1490
from bzrlib.fetch import KnitRepoFetcher
1491
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1492
self.source, self.source._format, self.target, self.target._format)
1493
f = KnitRepoFetcher(to_repository=self.target,
1494
from_repository=self.source,
1495
last_revision=revision_id,
1497
return f.count_copied, f.failed_revisions
1500
def missing_revision_ids(self, revision_id=None):
1501
"""See InterRepository.missing_revision_ids()."""
1502
if revision_id is not None:
1503
source_ids = self.source.get_ancestry(revision_id)
1504
assert source_ids[0] is None
1507
source_ids = self.source._all_possible_ids()
1508
source_ids_set = set(source_ids)
1509
# source_ids is the worst possible case we may need to pull.
1510
# now we want to filter source_ids against what we actually
1511
# have in target, but don't try to check for existence where we know
1512
# we do not have a revision as that would be pointless.
1513
target_ids = set(self.target._all_possible_ids())
1514
possibly_present_revisions = target_ids.intersection(source_ids_set)
1515
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1516
required_revisions = source_ids_set.difference(actually_present_revisions)
1517
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1518
if revision_id is not None:
1519
# we used get_ancestry to determine source_ids then we are assured all
1520
# revisions referenced are present as they are installed in topological order.
1521
# and the tip revision was validated by get_ancestry.
1522
return required_topo_revisions
1524
# if we just grabbed the possibly available ids, then
1525
# we only have an estimate of whats available and need to validate
1526
# that against the revision records.
1527
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1530
class InterModel1and2(InterRepository):
1533
def _get_repo_format_to_test(self):
1537
def is_compatible(source, target):
1538
if not isinstance(source, Repository):
1540
if not isinstance(target, Repository):
1542
if not source._format.rich_root_data and target._format.rich_root_data:
1548
def fetch(self, revision_id=None, pb=None):
1549
"""See InterRepository.fetch()."""
1550
from bzrlib.fetch import Model1toKnit2Fetcher
1551
f = Model1toKnit2Fetcher(to_repository=self.target,
1552
from_repository=self.source,
1553
last_revision=revision_id,
1555
return f.count_copied, f.failed_revisions
1558
def copy_content(self, revision_id=None, basis=None):
1559
"""Make a complete copy of the content in self into destination.
1561
This is a destructive operation! Do not use it on existing
1564
:param revision_id: Only copy the content needed to construct
1565
revision_id and its parents.
1566
:param basis: Copy the needed data preferentially from basis.
1569
self.target.set_make_working_trees(self.source.make_working_trees())
1570
except NotImplementedError:
1572
# grab the basis available data
1573
if basis is not None:
1574
self.target.fetch(basis, revision_id=revision_id)
1575
# but don't bother fetching if we have the needed data now.
1576
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1577
self.target.has_revision(revision_id)):
1579
self.target.fetch(self.source, revision_id=revision_id)
1582
class InterKnit1and2(InterKnitRepo):
1585
def _get_repo_format_to_test(self):
1589
def is_compatible(source, target):
1590
"""Be compatible with Knit1 source and Knit2 target"""
1591
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit2
1593
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1594
RepositoryFormatKnit2
1595
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1596
isinstance(target._format, (RepositoryFormatKnit2)))
1597
except AttributeError:
1601
def fetch(self, revision_id=None, pb=None):
1602
"""See InterRepository.fetch()."""
1603
from bzrlib.fetch import Knit1to2Fetcher
1604
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1605
self.source, self.source._format, self.target,
1606
self.target._format)
1607
f = Knit1to2Fetcher(to_repository=self.target,
1608
from_repository=self.source,
1609
last_revision=revision_id,
1611
return f.count_copied, f.failed_revisions
1614
InterRepository.register_optimiser(InterSameDataRepository)
1615
InterRepository.register_optimiser(InterWeaveRepo)
1616
InterRepository.register_optimiser(InterKnitRepo)
1617
InterRepository.register_optimiser(InterModel1and2)
1618
InterRepository.register_optimiser(InterKnit1and2)
1621
class RepositoryTestProviderAdapter(object):
1622
"""A tool to generate a suite testing multiple repository formats at once.
1624
This is done by copying the test once for each transport and injecting
1625
the transport_server, transport_readonly_server, and bzrdir_format and
1626
repository_format classes into each copy. Each copy is also given a new id()
1627
to make it easy to identify.
1630
def __init__(self, transport_server, transport_readonly_server, formats):
1631
self._transport_server = transport_server
1632
self._transport_readonly_server = transport_readonly_server
1633
self._formats = formats
1635
def adapt(self, test):
1636
result = unittest.TestSuite()
1637
for repository_format, bzrdir_format in self._formats:
1638
from copy import deepcopy
1639
new_test = deepcopy(test)
1640
new_test.transport_server = self._transport_server
1641
new_test.transport_readonly_server = self._transport_readonly_server
1642
new_test.bzrdir_format = bzrdir_format
1643
new_test.repository_format = repository_format
1644
def make_new_test_id():
1645
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1646
return lambda: new_id
1647
new_test.id = make_new_test_id()
1648
result.addTest(new_test)
1652
class InterRepositoryTestProviderAdapter(object):
1653
"""A tool to generate a suite testing multiple inter repository formats.
1655
This is done by copying the test once for each interrepo provider and injecting
1656
the transport_server, transport_readonly_server, repository_format and
1657
repository_to_format classes into each copy.
1658
Each copy is also given a new id() to make it easy to identify.
1661
def __init__(self, transport_server, transport_readonly_server, formats):
1662
self._transport_server = transport_server
1663
self._transport_readonly_server = transport_readonly_server
1664
self._formats = formats
1666
def adapt(self, test):
1667
result = unittest.TestSuite()
1668
for interrepo_class, repository_format, repository_format_to in self._formats:
1669
from copy import deepcopy
1670
new_test = deepcopy(test)
1671
new_test.transport_server = self._transport_server
1672
new_test.transport_readonly_server = self._transport_readonly_server
1673
new_test.interrepo_class = interrepo_class
1674
new_test.repository_format = repository_format
1675
new_test.repository_format_to = repository_format_to
1676
def make_new_test_id():
1677
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1678
return lambda: new_id
1679
new_test.id = make_new_test_id()
1680
result.addTest(new_test)
1684
def default_test_list():
1685
"""Generate the default list of interrepo permutations to test."""
1686
from bzrlib.repofmt import knitrepo, weaverepo
1688
# test the default InterRepository between format 6 and the current
1690
# XXX: robertc 20060220 reinstate this when there are two supported
1691
# formats which do not have an optimal code path between them.
1692
#result.append((InterRepository,
1693
# RepositoryFormat6(),
1694
# RepositoryFormatKnit1()))
1695
for optimiser_class in InterRepository._optimisers:
1696
format_to_test = optimiser_class._get_repo_format_to_test()
1697
if format_to_test is not None:
1698
result.append((optimiser_class,
1699
format_to_test, format_to_test))
1700
# if there are specific combinations we want to use, we can add them
1702
result.append((InterModel1and2,
1703
weaverepo.RepositoryFormat5(),
1704
knitrepo.RepositoryFormatKnit2()))
1705
result.append((InterKnit1and2,
1706
knitrepo.RepositoryFormatKnit1(),
1707
knitrepo.RepositoryFormatKnit2()))
1711
class CopyConverter(object):
1712
"""A repository conversion tool which just performs a copy of the content.
1714
This is slow but quite reliable.
1717
def __init__(self, target_format):
1718
"""Create a CopyConverter.
1720
:param target_format: The format the resulting repository should be.
1722
self.target_format = target_format
1724
def convert(self, repo, pb):
1725
"""Perform the conversion of to_convert, giving feedback via pb.
1727
:param to_convert: The disk object to convert.
1728
:param pb: a progress bar to use for progress information.
1733
# this is only useful with metadir layouts - separated repo content.
1734
# trigger an assertion if not such
1735
repo._format.get_format_string()
1736
self.repo_dir = repo.bzrdir
1737
self.step('Moving repository to repository.backup')
1738
self.repo_dir.transport.move('repository', 'repository.backup')
1739
backup_transport = self.repo_dir.transport.clone('repository.backup')
1740
repo._format.check_conversion_target(self.target_format)
1741
self.source_repo = repo._format.open(self.repo_dir,
1743
_override_transport=backup_transport)
1744
self.step('Creating new repository')
1745
converted = self.target_format.initialize(self.repo_dir,
1746
self.source_repo.is_shared())
1747
converted.lock_write()
1749
self.step('Copying content into repository.')
1750
self.source_repo.copy_content_into(converted)
1753
self.step('Deleting old repository content.')
1754
self.repo_dir.transport.delete_tree('repository.backup')
1755
self.pb.note('repository converted')
1757
def step(self, message):
1758
"""Update the pb by a step."""
1760
self.pb.update(message, self.count, self.total)
1763
class CommitBuilder(object):
1764
"""Provides an interface to build up a commit.
1766
This allows describing a tree to be committed without needing to
1767
know the internals of the format of the repository.
1770
record_root_entry = False
1771
def __init__(self, repository, parents, config, timestamp=None,
1772
timezone=None, committer=None, revprops=None,
1774
"""Initiate a CommitBuilder.
1776
:param repository: Repository to commit to.
1777
:param parents: Revision ids of the parents of the new revision.
1778
:param config: Configuration to use.
1779
:param timestamp: Optional timestamp recorded for commit.
1780
:param timezone: Optional timezone for timestamp.
1781
:param committer: Optional committer to set for commit.
1782
:param revprops: Optional dictionary of revision properties.
1783
:param revision_id: Optional revision id.
1785
self._config = config
1787
if committer is None:
1788
self._committer = self._config.username()
1790
assert isinstance(committer, basestring), type(committer)
1791
self._committer = committer
1793
self.new_inventory = Inventory(None)
1794
self._new_revision_id = revision_id
1795
self.parents = parents
1796
self.repository = repository
1799
if revprops is not None:
1800
self._revprops.update(revprops)
1802
if timestamp is None:
1803
timestamp = time.time()
1804
# Restrict resolution to 1ms
1805
self._timestamp = round(timestamp, 3)
1807
if timezone is None:
1808
self._timezone = osutils.local_time_offset()
1810
self._timezone = int(timezone)
1812
self._generate_revision_if_needed()
1814
def commit(self, message):
1815
"""Make the actual commit.
1817
:return: The revision id of the recorded revision.
1819
rev = _mod_revision.Revision(
1820
timestamp=self._timestamp,
1821
timezone=self._timezone,
1822
committer=self._committer,
1824
inventory_sha1=self.inv_sha1,
1825
revision_id=self._new_revision_id,
1826
properties=self._revprops)
1827
rev.parent_ids = self.parents
1828
self.repository.add_revision(self._new_revision_id, rev,
1829
self.new_inventory, self._config)
1830
return self._new_revision_id
1832
def revision_tree(self):
1833
"""Return the tree that was just committed.
1835
After calling commit() this can be called to get a RevisionTree
1836
representing the newly committed tree. This is preferred to
1837
calling Repository.revision_tree() because that may require
1838
deserializing the inventory, while we already have a copy in
1841
return RevisionTree(self.repository, self.new_inventory,
1842
self._new_revision_id)
1844
def finish_inventory(self):
1845
"""Tell the builder that the inventory is finished."""
1846
if self.new_inventory.root is None:
1847
symbol_versioning.warn('Root entry should be supplied to'
1848
' record_entry_contents, as of bzr 0.10.',
1849
DeprecationWarning, stacklevel=2)
1850
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1851
self.new_inventory.revision_id = self._new_revision_id
1852
self.inv_sha1 = self.repository.add_inventory(
1853
self._new_revision_id,
1858
def _gen_revision_id(self):
1859
"""Return new revision-id."""
1860
return generate_ids.gen_revision_id(self._config.username(),
1863
def _generate_revision_if_needed(self):
1864
"""Create a revision id if None was supplied.
1866
If the repository can not support user-specified revision ids
1867
they should override this function and raise CannotSetRevisionId
1868
if _new_revision_id is not None.
1870
:raises: CannotSetRevisionId
1872
if self._new_revision_id is None:
1873
self._new_revision_id = self._gen_revision_id()
1875
def record_entry_contents(self, ie, parent_invs, path, tree):
1876
"""Record the content of ie from tree into the commit if needed.
1878
Side effect: sets ie.revision when unchanged
1880
:param ie: An inventory entry present in the commit.
1881
:param parent_invs: The inventories of the parent revisions of the
1883
:param path: The path the entry is at in the tree.
1884
:param tree: The tree which contains this entry and should be used to
1887
if self.new_inventory.root is None and ie.parent_id is not None:
1888
symbol_versioning.warn('Root entry should be supplied to'
1889
' record_entry_contents, as of bzr 0.10.',
1890
DeprecationWarning, stacklevel=2)
1891
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
1893
self.new_inventory.add(ie)
1895
# ie.revision is always None if the InventoryEntry is considered
1896
# for committing. ie.snapshot will record the correct revision
1897
# which may be the sole parent if it is untouched.
1898
if ie.revision is not None:
1901
# In this revision format, root entries have no knit or weave
1902
if ie is self.new_inventory.root:
1903
# When serializing out to disk and back in
1904
# root.revision is always _new_revision_id
1905
ie.revision = self._new_revision_id
1907
previous_entries = ie.find_previous_heads(
1909
self.repository.weave_store,
1910
self.repository.get_transaction())
1911
# we are creating a new revision for ie in the history store
1913
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1915
def modified_directory(self, file_id, file_parents):
1916
"""Record the presence of a symbolic link.
1918
:param file_id: The file_id of the link to record.
1919
:param file_parents: The per-file parent revision ids.
1921
self._add_text_to_weave(file_id, [], file_parents.keys())
1923
def modified_reference(self, file_id, file_parents):
1924
"""Record the modification of a reference.
1926
:param file_id: The file_id of the link to record.
1927
:param file_parents: The per-file parent revision ids.
1929
self._add_text_to_weave(file_id, [], file_parents.keys())
1931
def modified_file_text(self, file_id, file_parents,
1932
get_content_byte_lines, text_sha1=None,
1934
"""Record the text of file file_id
1936
:param file_id: The file_id of the file to record the text of.
1937
:param file_parents: The per-file parent revision ids.
1938
:param get_content_byte_lines: A callable which will return the byte
1940
:param text_sha1: Optional SHA1 of the file contents.
1941
:param text_size: Optional size of the file contents.
1943
# mutter('storing text of file {%s} in revision {%s} into %r',
1944
# file_id, self._new_revision_id, self.repository.weave_store)
1945
# special case to avoid diffing on renames or
1947
if (len(file_parents) == 1
1948
and text_sha1 == file_parents.values()[0].text_sha1
1949
and text_size == file_parents.values()[0].text_size):
1950
previous_ie = file_parents.values()[0]
1951
versionedfile = self.repository.weave_store.get_weave(file_id,
1952
self.repository.get_transaction())
1953
versionedfile.clone_text(self._new_revision_id,
1954
previous_ie.revision, file_parents.keys())
1955
return text_sha1, text_size
1957
new_lines = get_content_byte_lines()
1958
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
1959
# should return the SHA1 and size
1960
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
1961
return osutils.sha_strings(new_lines), \
1962
sum(map(len, new_lines))
1964
def modified_link(self, file_id, file_parents, link_target):
1965
"""Record the presence of a symbolic link.
1967
:param file_id: The file_id of the link to record.
1968
:param file_parents: The per-file parent revision ids.
1969
:param link_target: Target location of this link.
1971
self._add_text_to_weave(file_id, [], file_parents.keys())
1973
def _add_text_to_weave(self, file_id, new_lines, parents):
1974
versionedfile = self.repository.weave_store.get_weave_or_empty(
1975
file_id, self.repository.get_transaction())
1976
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
1977
versionedfile.clear_cache()
1980
class _CommitBuilder(CommitBuilder):
1981
"""Temporary class so old CommitBuilders are detected properly
1983
Note: CommitBuilder works whether or not root entry is recorded.
1986
record_root_entry = True
1989
class RootCommitBuilder(CommitBuilder):
1990
"""This commitbuilder actually records the root id"""
1992
record_root_entry = True
1994
def record_entry_contents(self, ie, parent_invs, path, tree):
1995
"""Record the content of ie from tree into the commit if needed.
1997
Side effect: sets ie.revision when unchanged
1999
:param ie: An inventory entry present in the commit.
2000
:param parent_invs: The inventories of the parent revisions of the
2002
:param path: The path the entry is at in the tree.
2003
:param tree: The tree which contains this entry and should be used to
2006
assert self.new_inventory.root is not None or ie.parent_id is None
2007
self.new_inventory.add(ie)
2009
# ie.revision is always None if the InventoryEntry is considered
2010
# for committing. ie.snapshot will record the correct revision
2011
# which may be the sole parent if it is untouched.
2012
if ie.revision is not None:
2015
previous_entries = ie.find_previous_heads(
2017
self.repository.weave_store,
2018
self.repository.get_transaction())
2019
# we are creating a new revision for ie in the history store
2021
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2033
def _unescaper(match, _map=_unescape_map):
2034
return _map[match.group(1)]
2040
def _unescape_xml(data):
2041
"""Unescape predefined XML entities in a string of data."""
2043
if _unescape_re is None:
2044
_unescape_re = re.compile('\&([^;]*);')
2045
return _unescape_re.sub(_unescaper, data)