1
# Copyright (C) 2005, 2006 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 copy import deepcopy
18
from cStringIO import StringIO
19
from unittest import TestSuite
21
import bzrlib.bzrdir as bzrdir
22
from bzrlib.decorators import needs_read_lock, needs_write_lock
23
import bzrlib.errors as errors
24
from bzrlib.errors import InvalidRevisionId
25
import bzrlib.gpg as gpg
26
from bzrlib.graph import Graph
27
from bzrlib.inter import InterObject
28
from bzrlib.knit import KnitVersionedFile, KnitPlainFactory
29
from bzrlib.lockable_files import LockableFiles, TransportLock
30
from bzrlib.lockdir import LockDir
31
from bzrlib.osutils import safe_unicode
32
from bzrlib.revision import NULL_REVISION
33
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
34
from bzrlib.store.text import TextStore
35
from bzrlib.symbol_versioning import *
36
from bzrlib.trace import mutter, note
37
from bzrlib.tree import RevisionTree
38
from bzrlib.tsort import topo_sort
39
from bzrlib.testament import Testament
40
from bzrlib.tree import EmptyTree
42
from bzrlib.weave import WeaveFile
46
class Repository(object):
47
"""Repository holding history for one or more branches.
49
The repository holds and retrieves historical information including
50
revisions and file history. It's normally accessed only by the Branch,
51
which views a particular line of development through that history.
53
The Repository builds on top of Stores and a Transport, which respectively
54
describe the disk data format and the way of accessing the (possibly
59
def add_inventory(self, revid, inv, parents):
60
"""Add the inventory inv to the repository as revid.
62
:param parents: The revision ids of the parents that revid
63
is known to have and are in the repository already.
65
returns the sha1 of the serialized inventory.
67
inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
68
inv_sha1 = bzrlib.osutils.sha_string(inv_text)
69
inv_vf = self.control_weaves.get_weave('inventory',
70
self.get_transaction())
71
inv_vf.add_lines(revid, parents, bzrlib.osutils.split_lines(inv_text))
75
def add_revision(self, rev_id, rev, inv=None, config=None):
76
"""Add rev to the revision store as rev_id.
78
:param rev_id: the revision id to use.
79
:param rev: The revision object.
80
:param inv: The inventory for the revision. if None, it will be looked
81
up in the inventory storer
82
:param config: If None no digital signature will be created.
83
If supplied its signature_needed method will be used
84
to determine if a signature should be made.
86
if config is not None and config.signature_needed():
88
inv = self.get_inventory(rev_id)
89
plaintext = Testament(rev, inv).as_short_text()
90
self.store_revision_signature(
91
gpg.GPGStrategy(config), plaintext, rev_id)
92
if not rev_id in self.get_inventory_weave():
94
raise errors.WeaveRevisionNotPresent(rev_id,
95
self.get_inventory_weave())
97
# yes, this is not suitable for adding with ghosts.
98
self.add_inventory(rev_id, inv, rev.parent_ids)
99
self._revision_store.add_revision(rev, self.get_transaction())
102
def _all_possible_ids(self):
103
"""Return all the possible revisions that we could find."""
104
return self.get_inventory_weave().versions()
107
def all_revision_ids(self):
108
"""Returns a list of all the revision ids in the repository.
110
These are in as much topological order as the underlying store can
111
present: for weaves ghosts may lead to a lack of correctness until
112
the reweave updates the parents list.
114
if self._revision_store.text_store.listable():
115
return self._revision_store.all_revision_ids(self.get_transaction())
116
result = self._all_possible_ids()
117
return self._eliminate_revisions_not_present(result)
119
def break_lock(self):
120
"""Break a lock if one is present from another instance.
122
Uses the ui factory to ask for confirmation if the lock may be from
125
self.control_files.break_lock()
128
def _eliminate_revisions_not_present(self, revision_ids):
129
"""Check every revision id in revision_ids to see if we have it.
131
Returns a set of the present revisions.
134
for id in revision_ids:
135
if self.has_revision(id):
140
def create(a_bzrdir):
141
"""Construct the current default format repository in a_bzrdir."""
142
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
144
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
145
"""instantiate a Repository.
147
:param _format: The format of the repository on disk.
148
:param a_bzrdir: The BzrDir of the repository.
150
In the future we will have a single api for all stores for
151
getting file texts, inventories and revisions, then
152
this construct will accept instances of those things.
154
super(Repository, self).__init__()
155
self._format = _format
156
# the following are part of the public API for Repository:
157
self.bzrdir = a_bzrdir
158
self.control_files = control_files
159
self._revision_store = _revision_store
160
self.text_store = text_store
161
# backwards compatability
162
self.weave_store = text_store
163
# not right yet - should be more semantically clear ?
165
self.control_store = control_store
166
self.control_weaves = control_store
167
# TODO: make sure to construct the right store classes, etc, depending
168
# on whether escaping is required.
171
return '%s(%r)' % (self.__class__.__name__,
172
self.bzrdir.transport.base)
175
return self.control_files.is_locked()
177
def lock_write(self):
178
self.control_files.lock_write()
181
self.control_files.lock_read()
183
def get_physical_lock_status(self):
184
return self.control_files.get_physical_lock_status()
187
def missing_revision_ids(self, other, revision_id=None):
188
"""Return the revision ids that other has that this does not.
190
These are returned in topological order.
192
revision_id: only return revision ids included by revision_id.
194
return InterRepository.get(other, self).missing_revision_ids(revision_id)
198
"""Open the repository rooted at base.
200
For instance, if the repository is at URL/.bzr/repository,
201
Repository.open(URL) -> a Repository instance.
203
control = bzrlib.bzrdir.BzrDir.open(base)
204
return control.open_repository()
206
def copy_content_into(self, destination, revision_id=None, basis=None):
207
"""Make a complete copy of the content in self into destination.
209
This is a destructive operation! Do not use it on existing
212
return InterRepository.get(self, destination).copy_content(revision_id, basis)
214
def fetch(self, source, revision_id=None, pb=None):
215
"""Fetch the content required to construct revision_id from source.
217
If revision_id is None all content is copied.
219
return InterRepository.get(source, self).fetch(revision_id=revision_id,
223
self.control_files.unlock()
226
def clone(self, a_bzrdir, revision_id=None, basis=None):
227
"""Clone this repository into a_bzrdir using the current format.
229
Currently no check is made that the format of this repository and
230
the bzrdir format are compatible. FIXME RBC 20060201.
232
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
233
# use target default format.
234
result = a_bzrdir.create_repository()
235
# FIXME RBC 20060209 split out the repository type to avoid this check ?
236
elif isinstance(a_bzrdir._format,
237
(bzrlib.bzrdir.BzrDirFormat4,
238
bzrlib.bzrdir.BzrDirFormat5,
239
bzrlib.bzrdir.BzrDirFormat6)):
240
result = a_bzrdir.open_repository()
242
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
243
self.copy_content_into(result, revision_id, basis)
247
def has_revision(self, revision_id):
248
"""True if this repository has a copy of the revision."""
249
return self._revision_store.has_revision_id(revision_id,
250
self.get_transaction())
253
def get_revision_reconcile(self, revision_id):
254
"""'reconcile' helper routine that allows access to a revision always.
256
This variant of get_revision does not cross check the weave graph
257
against the revision one as get_revision does: but it should only
258
be used by reconcile, or reconcile-alike commands that are correcting
259
or testing the revision graph.
261
if not revision_id or not isinstance(revision_id, basestring):
262
raise InvalidRevisionId(revision_id=revision_id, branch=self)
263
return self._revision_store.get_revision(revision_id,
264
self.get_transaction())
267
def get_revision_xml(self, revision_id):
268
rev = self.get_revision(revision_id)
270
# the current serializer..
271
self._revision_store._serializer.write_revision(rev, rev_tmp)
273
return rev_tmp.getvalue()
276
def get_revision(self, revision_id):
277
"""Return the Revision object for a named revision"""
278
r = self.get_revision_reconcile(revision_id)
279
# weave corruption can lead to absent revision markers that should be
281
# the following test is reasonably cheap (it needs a single weave read)
282
# and the weave is cached in read transactions. In write transactions
283
# it is not cached but typically we only read a small number of
284
# revisions. For knits when they are introduced we will probably want
285
# to ensure that caching write transactions are in use.
286
inv = self.get_inventory_weave()
287
self._check_revision_parents(r, inv)
290
def _check_revision_parents(self, revision, inventory):
291
"""Private to Repository and Fetch.
293
This checks the parentage of revision in an inventory weave for
294
consistency and is only applicable to inventory-weave-for-ancestry
295
using repository formats & fetchers.
297
weave_parents = inventory.get_parents(revision.revision_id)
298
weave_names = inventory.versions()
299
for parent_id in revision.parent_ids:
300
if parent_id in weave_names:
301
# this parent must not be a ghost.
302
if not parent_id in weave_parents:
304
raise errors.CorruptRepository(self)
307
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
308
signature = gpg_strategy.sign(plaintext)
309
self._revision_store.add_revision_signature_text(revision_id,
311
self.get_transaction())
313
def fileids_altered_by_revision_ids(self, revision_ids):
314
"""Find the file ids and versions affected by revisions.
316
:param revisions: an iterable containing revision ids.
317
:return: a dictionary mapping altered file-ids to an iterable of
318
revision_ids. Each altered file-ids has the exact revision_ids that
319
altered it listed explicitly.
321
assert isinstance(self._format, (RepositoryFormat5,
324
RepositoryFormatKnit1)), \
325
"fileid_involved only supported for branches which store inventory as unnested xml"
326
selected_revision_ids = set(revision_ids)
327
w = self.get_inventory_weave()
330
# this code needs to read every new line in every inventory for the
331
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
332
# not pesent in one of those inventories is unnecessary but not
333
# harmful because we are filtering by the revision id marker in the
334
# inventory lines : we only select file ids altered in one of those
335
# revisions. We dont need to see all lines in the inventory because
336
# only those added in an inventory in rev X can contain a revision=X
338
for line in w.iter_lines_added_or_present_in_versions(selected_revision_ids):
339
start = line.find('file_id="')+9
340
if start < 9: continue
341
end = line.find('"', start)
343
file_id = _unescape_xml(line[start:end])
345
start = line.find('revision="')+10
346
if start < 10: continue
347
end = line.find('"', start)
349
revision_id = _unescape_xml(line[start:end])
350
if revision_id in selected_revision_ids:
351
result.setdefault(file_id, set()).add(revision_id)
355
def get_inventory_weave(self):
356
return self.control_weaves.get_weave('inventory',
357
self.get_transaction())
360
def get_inventory(self, revision_id):
361
"""Get Inventory object by hash."""
362
xml = self.get_inventory_xml(revision_id)
363
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
366
def get_inventory_xml(self, revision_id):
367
"""Get inventory XML as a file object."""
369
assert isinstance(revision_id, basestring), type(revision_id)
370
iw = self.get_inventory_weave()
371
return iw.get_text(revision_id)
373
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
376
def get_inventory_sha1(self, revision_id):
377
"""Return the sha1 hash of the inventory entry
379
return self.get_revision(revision_id).inventory_sha1
382
def get_revision_graph(self, revision_id=None):
383
"""Return a dictionary containing the revision graph.
385
:return: a dictionary of revision_id->revision_parents_list.
387
weave = self.get_inventory_weave()
388
all_revisions = self._eliminate_revisions_not_present(weave.versions())
389
entire_graph = dict([(node, weave.get_parents(node)) for
390
node in all_revisions])
391
if revision_id is None:
393
elif revision_id not in entire_graph:
394
raise errors.NoSuchRevision(self, revision_id)
396
# add what can be reached from revision_id
398
pending = set([revision_id])
399
while len(pending) > 0:
401
result[node] = entire_graph[node]
402
for revision_id in result[node]:
403
if revision_id not in result:
404
pending.add(revision_id)
408
def get_revision_graph_with_ghosts(self, revision_ids=None):
409
"""Return a graph of the revisions with ghosts marked as applicable.
411
:param revision_ids: an iterable of revisions to graph or None for all.
412
:return: a Graph object with the graph reachable from revision_ids.
416
pending = set(self.all_revision_ids())
419
pending = set(revision_ids)
420
required = set(revision_ids)
423
revision_id = pending.pop()
425
rev = self.get_revision(revision_id)
426
except errors.NoSuchRevision:
427
if revision_id in required:
430
result.add_ghost(revision_id)
432
for parent_id in rev.parent_ids:
433
# is this queued or done ?
434
if (parent_id not in pending and
435
parent_id not in done):
437
pending.add(parent_id)
438
result.add_node(revision_id, rev.parent_ids)
439
done.add(revision_id)
443
def get_revision_inventory(self, revision_id):
444
"""Return inventory of a past revision."""
445
# TODO: Unify this with get_inventory()
446
# bzr 0.0.6 and later imposes the constraint that the inventory_id
447
# must be the same as its revision, so this is trivial.
448
if revision_id is None:
449
# This does not make sense: if there is no revision,
450
# then it is the current tree inventory surely ?!
451
# and thus get_root_id() is something that looks at the last
452
# commit on the branch, and the get_root_id is an inventory check.
453
raise NotImplementedError
454
# return Inventory(self.get_root_id())
456
return self.get_inventory(revision_id)
460
"""Return True if this repository is flagged as a shared repository."""
461
raise NotImplementedError(self.is_shared)
464
def reconcile(self, other=None, thorough=False):
465
"""Reconcile this repository."""
466
from bzrlib.reconcile import RepoReconciler
467
reconciler = RepoReconciler(self, thorough=thorough)
468
reconciler.reconcile()
472
def revision_tree(self, revision_id):
473
"""Return Tree for a revision on this branch.
475
`revision_id` may be None for the null revision, in which case
476
an `EmptyTree` is returned."""
477
# TODO: refactor this to use an existing revision object
478
# so we don't need to read it in twice.
479
if revision_id is None or revision_id == NULL_REVISION:
482
inv = self.get_revision_inventory(revision_id)
483
return RevisionTree(self, inv, revision_id)
486
def get_ancestry(self, revision_id):
487
"""Return a list of revision-ids integrated by a revision.
489
This is topologically sorted.
491
if revision_id is None:
493
if not self.has_revision(revision_id):
494
raise errors.NoSuchRevision(self, revision_id)
495
w = self.get_inventory_weave()
496
candidates = w.get_ancestry(revision_id)
497
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
500
def print_file(self, file, revision_id):
501
"""Print `file` to stdout.
503
FIXME RBC 20060125 as John Meinel points out this is a bad api
504
- it writes to stdout, it assumes that that is valid etc. Fix
505
by creating a new more flexible convenience function.
507
tree = self.revision_tree(revision_id)
508
# use inventory as it was in that revision
509
file_id = tree.inventory.path2id(file)
511
# TODO: jam 20060427 Write a test for this code path
512
# it had a bug in it, and was raising the wrong
514
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
515
tree.print_file(file_id)
517
def get_transaction(self):
518
return self.control_files.get_transaction()
520
def revision_parents(self, revid):
521
return self.get_inventory_weave().parent_names(revid)
524
def set_make_working_trees(self, new_value):
525
"""Set the policy flag for making working trees when creating branches.
527
This only applies to branches that use this repository.
529
The default is 'True'.
530
:param new_value: True to restore the default, False to disable making
533
raise NotImplementedError(self.set_make_working_trees)
535
def make_working_trees(self):
536
"""Returns the policy for making working trees on new branches."""
537
raise NotImplementedError(self.make_working_trees)
540
def sign_revision(self, revision_id, gpg_strategy):
541
plaintext = Testament.from_revision(self, revision_id).as_short_text()
542
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
545
def has_signature_for_revision_id(self, revision_id):
546
"""Query for a revision signature for revision_id in the repository."""
547
return self._revision_store.has_signature(revision_id,
548
self.get_transaction())
551
def get_signature_text(self, revision_id):
552
"""Return the text for a signature."""
553
return self._revision_store.get_signature_text(revision_id,
554
self.get_transaction())
557
class AllInOneRepository(Repository):
558
"""Legacy support - the repository behaviour for all-in-one branches."""
560
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
561
# we reuse one control files instance.
562
dir_mode = a_bzrdir._control_files._dir_mode
563
file_mode = a_bzrdir._control_files._file_mode
565
def get_store(name, compressed=True, prefixed=False):
566
# FIXME: This approach of assuming stores are all entirely compressed
567
# or entirely uncompressed is tidy, but breaks upgrade from
568
# some existing branches where there's a mixture; we probably
569
# still want the option to look for both.
570
relpath = a_bzrdir._control_files._escape(name)
571
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
572
prefixed=prefixed, compressed=compressed,
575
#if self._transport.should_cache():
576
# cache_path = os.path.join(self.cache_root, name)
577
# os.mkdir(cache_path)
578
# store = bzrlib.store.CachedStore(store, cache_path)
581
# not broken out yet because the controlweaves|inventory_store
582
# and text_store | weave_store bits are still different.
583
if isinstance(_format, RepositoryFormat4):
584
# cannot remove these - there is still no consistent api
585
# which allows access to this old info.
586
self.inventory_store = get_store('inventory-store')
587
text_store = get_store('text-store')
588
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
592
"""AllInOne repositories cannot be shared."""
596
def set_make_working_trees(self, new_value):
597
"""Set the policy flag for making working trees when creating branches.
599
This only applies to branches that use this repository.
601
The default is 'True'.
602
:param new_value: True to restore the default, False to disable making
605
raise NotImplementedError(self.set_make_working_trees)
607
def make_working_trees(self):
608
"""Returns the policy for making working trees on new branches."""
612
def install_revision(repository, rev, revision_tree):
613
"""Install all revision data into a repository."""
616
for p_id in rev.parent_ids:
617
if repository.has_revision(p_id):
618
present_parents.append(p_id)
619
parent_trees[p_id] = repository.revision_tree(p_id)
621
parent_trees[p_id] = EmptyTree()
623
inv = revision_tree.inventory
625
# Add the texts that are not already present
626
for path, ie in inv.iter_entries():
627
w = repository.weave_store.get_weave_or_empty(ie.file_id,
628
repository.get_transaction())
629
if ie.revision not in w:
631
for revision, tree in parent_trees.iteritems():
632
if ie.file_id not in tree:
634
parent_id = tree.inventory[ie.file_id].revision
635
if parent_id in text_parents:
637
text_parents.append(parent_id)
639
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
640
repository.get_transaction())
641
lines = revision_tree.get_file(ie.file_id).readlines()
642
vfile.add_lines(rev.revision_id, text_parents, lines)
644
# install the inventory
645
repository.add_inventory(rev.revision_id, inv, present_parents)
646
except errors.RevisionAlreadyPresent:
648
repository.add_revision(rev.revision_id, rev, inv)
651
class MetaDirRepository(Repository):
652
"""Repositories in the new meta-dir layout."""
654
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
655
super(MetaDirRepository, self).__init__(_format,
662
dir_mode = self.control_files._dir_mode
663
file_mode = self.control_files._file_mode
667
"""Return True if this repository is flagged as a shared repository."""
668
return self.control_files._transport.has('shared-storage')
671
def set_make_working_trees(self, new_value):
672
"""Set the policy flag for making working trees when creating branches.
674
This only applies to branches that use this repository.
676
The default is 'True'.
677
:param new_value: True to restore the default, False to disable making
682
self.control_files._transport.delete('no-working-trees')
683
except errors.NoSuchFile:
686
self.control_files.put_utf8('no-working-trees', '')
688
def make_working_trees(self):
689
"""Returns the policy for making working trees on new branches."""
690
return not self.control_files._transport.has('no-working-trees')
693
class KnitRepository(MetaDirRepository):
694
"""Knit format repository."""
697
def all_revision_ids(self):
698
"""See Repository.all_revision_ids()."""
699
return self._revision_store.all_revision_ids(self.get_transaction())
701
def fileid_involved_between_revs(self, from_revid, to_revid):
702
"""Find file_id(s) which are involved in the changes between revisions.
704
This determines the set of revisions which are involved, and then
705
finds all file ids affected by those revisions.
707
vf = self._get_revision_vf()
708
from_set = set(vf.get_ancestry(from_revid))
709
to_set = set(vf.get_ancestry(to_revid))
710
changed = to_set.difference(from_set)
711
return self._fileid_involved_by_set(changed)
713
def fileid_involved(self, last_revid=None):
714
"""Find all file_ids modified in the ancestry of last_revid.
716
:param last_revid: If None, last_revision() will be used.
719
changed = set(self.all_revision_ids())
721
changed = set(self.get_ancestry(last_revid))
724
return self._fileid_involved_by_set(changed)
727
def get_ancestry(self, revision_id):
728
"""Return a list of revision-ids integrated by a revision.
730
This is topologically sorted.
732
if revision_id is None:
734
vf = self._get_revision_vf()
736
return [None] + vf.get_ancestry(revision_id)
737
except errors.RevisionNotPresent:
738
raise errors.NoSuchRevision(self, revision_id)
741
def get_revision(self, revision_id):
742
"""Return the Revision object for a named revision"""
743
return self.get_revision_reconcile(revision_id)
746
def get_revision_graph(self, revision_id=None):
747
"""Return a dictionary containing the revision graph.
749
:return: a dictionary of revision_id->revision_parents_list.
751
weave = self._get_revision_vf()
752
entire_graph = weave.get_graph()
753
if revision_id is None:
754
return weave.get_graph()
755
elif revision_id not in weave:
756
raise errors.NoSuchRevision(self, revision_id)
758
# add what can be reached from revision_id
760
pending = set([revision_id])
761
while len(pending) > 0:
763
result[node] = weave.get_parents(node)
764
for revision_id in result[node]:
765
if revision_id not in result:
766
pending.add(revision_id)
770
def get_revision_graph_with_ghosts(self, revision_ids=None):
771
"""Return a graph of the revisions with ghosts marked as applicable.
773
:param revision_ids: an iterable of revisions to graph or None for all.
774
:return: a Graph object with the graph reachable from revision_ids.
777
vf = self._get_revision_vf()
778
versions = set(vf.versions())
780
pending = set(self.all_revision_ids())
783
pending = set(revision_ids)
784
required = set(revision_ids)
787
revision_id = pending.pop()
788
if not revision_id in versions:
789
if revision_id in required:
790
raise errors.NoSuchRevision(self, revision_id)
792
result.add_ghost(revision_id)
793
# mark it as done so we dont try for it again.
794
done.add(revision_id)
796
parent_ids = vf.get_parents_with_ghosts(revision_id)
797
for parent_id in parent_ids:
798
# is this queued or done ?
799
if (parent_id not in pending and
800
parent_id not in done):
802
pending.add(parent_id)
803
result.add_node(revision_id, parent_ids)
804
done.add(revision_id)
807
def _get_revision_vf(self):
808
""":return: a versioned file containing the revisions."""
809
vf = self._revision_store.get_revision_file(self.get_transaction())
813
def reconcile(self, other=None, thorough=False):
814
"""Reconcile this repository."""
815
from bzrlib.reconcile import KnitReconciler
816
reconciler = KnitReconciler(self, thorough=thorough)
817
reconciler.reconcile()
820
def revision_parents(self, revid):
821
return self._get_revision_vf().get_parents(rev_id)
823
class RepositoryFormat(object):
824
"""A repository format.
826
Formats provide three things:
827
* An initialization routine to construct repository data on disk.
828
* a format string which is used when the BzrDir supports versioned
830
* an open routine which returns a Repository instance.
832
Formats are placed in an dict by their format string for reference
833
during opening. These should be subclasses of RepositoryFormat
836
Once a format is deprecated, just deprecate the initialize and open
837
methods on the format class. Do not deprecate the object, as the
838
object will be created every system load.
840
Common instance attributes:
841
_matchingbzrdir - the bzrdir format that the repository format was
842
originally written to work with. This can be used if manually
843
constructing a bzrdir and repository, or more commonly for test suite
847
_default_format = None
848
"""The default format used for new repositories."""
851
"""The known formats."""
854
def find_format(klass, a_bzrdir):
855
"""Return the format for the repository object in a_bzrdir."""
857
transport = a_bzrdir.get_repository_transport(None)
858
format_string = transport.get("format").read()
859
return klass._formats[format_string]
860
except errors.NoSuchFile:
861
raise errors.NoRepositoryPresent(a_bzrdir)
863
raise errors.UnknownFormatError(format_string)
865
def _get_control_store(self, repo_transport, control_files):
866
"""Return the control store for this repository."""
867
raise NotImplementedError(self._get_control_store)
870
def get_default_format(klass):
871
"""Return the current default format."""
872
return klass._default_format
874
def get_format_string(self):
875
"""Return the ASCII format string that identifies this format.
877
Note that in pre format ?? repositories the format string is
878
not permitted nor written to disk.
880
raise NotImplementedError(self.get_format_string)
882
def get_format_description(self):
883
"""Return the short desciption for this format."""
884
raise NotImplementedError(self.get_format_description)
886
def _get_revision_store(self, repo_transport, control_files):
887
"""Return the revision store object for this a_bzrdir."""
888
raise NotImplementedError(self._get_revision_store)
890
def _get_text_rev_store(self,
897
"""Common logic for getting a revision store for a repository.
899
see self._get_revision_store for the subclass-overridable method to
900
get the store for a repository.
902
from bzrlib.store.revision.text import TextRevisionStore
903
dir_mode = control_files._dir_mode
904
file_mode = control_files._file_mode
905
text_store =TextStore(transport.clone(name),
907
compressed=compressed,
910
_revision_store = TextRevisionStore(text_store, serializer)
911
return _revision_store
913
def _get_versioned_file_store(self,
918
versionedfile_class=WeaveFile,
920
weave_transport = control_files._transport.clone(name)
921
dir_mode = control_files._dir_mode
922
file_mode = control_files._file_mode
923
return VersionedFileStore(weave_transport, prefixed=prefixed,
926
versionedfile_class=versionedfile_class,
929
def initialize(self, a_bzrdir, shared=False):
930
"""Initialize a repository of this format in a_bzrdir.
932
:param a_bzrdir: The bzrdir to put the new repository in it.
933
:param shared: The repository should be initialized as a sharable one.
935
This may raise UninitializableFormat if shared repository are not
936
compatible the a_bzrdir.
939
def is_supported(self):
940
"""Is this format supported?
942
Supported formats must be initializable and openable.
943
Unsupported formats may not support initialization or committing or
944
some other features depending on the reason for not being supported.
948
def open(self, a_bzrdir, _found=False):
949
"""Return an instance of this format for the bzrdir a_bzrdir.
951
_found is a private parameter, do not use it.
953
raise NotImplementedError(self.open)
956
def register_format(klass, format):
957
klass._formats[format.get_format_string()] = format
960
def set_default_format(klass, format):
961
klass._default_format = format
964
def unregister_format(klass, format):
965
assert klass._formats[format.get_format_string()] is format
966
del klass._formats[format.get_format_string()]
969
class PreSplitOutRepositoryFormat(RepositoryFormat):
970
"""Base class for the pre split out repository formats."""
972
def initialize(self, a_bzrdir, shared=False, _internal=False):
973
"""Create a weave repository.
975
TODO: when creating split out bzr branch formats, move this to a common
976
base for Format5, Format6. or something like that.
978
from bzrlib.weavefile import write_weave_v5
979
from bzrlib.weave import Weave
982
raise errors.IncompatibleFormat(self, a_bzrdir._format)
985
# always initialized when the bzrdir is.
986
return self.open(a_bzrdir, _found=True)
988
# Create an empty weave
990
bzrlib.weavefile.write_weave_v5(Weave(), sio)
991
empty_weave = sio.getvalue()
993
mutter('creating repository in %s.', a_bzrdir.transport.base)
994
dirs = ['revision-store', 'weaves']
995
files = [('inventory.weave', StringIO(empty_weave)),
998
# FIXME: RBC 20060125 dont peek under the covers
999
# NB: no need to escape relative paths that are url safe.
1000
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
1002
control_files.create_lock()
1003
control_files.lock_write()
1004
control_files._transport.mkdir_multi(dirs,
1005
mode=control_files._dir_mode)
1007
for file, content in files:
1008
control_files.put(file, content)
1010
control_files.unlock()
1011
return self.open(a_bzrdir, _found=True)
1013
def _get_control_store(self, repo_transport, control_files):
1014
"""Return the control store for this repository."""
1015
return self._get_versioned_file_store('',
1020
def _get_text_store(self, transport, control_files):
1021
"""Get a store for file texts for this format."""
1022
raise NotImplementedError(self._get_text_store)
1024
def open(self, a_bzrdir, _found=False):
1025
"""See RepositoryFormat.open()."""
1027
# we are being called directly and must probe.
1028
raise NotImplementedError
1030
repo_transport = a_bzrdir.get_repository_transport(None)
1031
control_files = a_bzrdir._control_files
1032
text_store = self._get_text_store(repo_transport, control_files)
1033
control_store = self._get_control_store(repo_transport, control_files)
1034
_revision_store = self._get_revision_store(repo_transport, control_files)
1035
return AllInOneRepository(_format=self,
1037
_revision_store=_revision_store,
1038
control_store=control_store,
1039
text_store=text_store)
1042
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1043
"""Bzr repository format 4.
1045
This repository format has:
1047
- TextStores for texts, inventories,revisions.
1049
This format is deprecated: it indexes texts using a text id which is
1050
removed in format 5; initializationa and write support for this format
1055
super(RepositoryFormat4, self).__init__()
1056
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1058
def get_format_description(self):
1059
"""See RepositoryFormat.get_format_description()."""
1060
return "Repository format 4"
1062
def initialize(self, url, shared=False, _internal=False):
1063
"""Format 4 branches cannot be created."""
1064
raise errors.UninitializableFormat(self)
1066
def is_supported(self):
1067
"""Format 4 is not supported.
1069
It is not supported because the model changed from 4 to 5 and the
1070
conversion logic is expensive - so doing it on the fly was not
1075
def _get_control_store(self, repo_transport, control_files):
1076
"""Format 4 repositories have no formal control store at this point.
1078
This will cause any control-file-needing apis to fail - this is desired.
1082
def _get_revision_store(self, repo_transport, control_files):
1083
"""See RepositoryFormat._get_revision_store()."""
1084
from bzrlib.xml4 import serializer_v4
1085
return self._get_text_rev_store(repo_transport,
1088
serializer=serializer_v4)
1090
def _get_text_store(self, transport, control_files):
1091
"""See RepositoryFormat._get_text_store()."""
1094
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1095
"""Bzr control format 5.
1097
This repository format has:
1098
- weaves for file texts and inventory
1100
- TextStores for revisions and signatures.
1104
super(RepositoryFormat5, self).__init__()
1105
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1107
def get_format_description(self):
1108
"""See RepositoryFormat.get_format_description()."""
1109
return "Weave repository format 5"
1111
def _get_revision_store(self, repo_transport, control_files):
1112
"""See RepositoryFormat._get_revision_store()."""
1113
"""Return the revision store object for this a_bzrdir."""
1114
return self._get_text_rev_store(repo_transport,
1119
def _get_text_store(self, transport, control_files):
1120
"""See RepositoryFormat._get_text_store()."""
1121
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1124
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1125
"""Bzr control format 6.
1127
This repository format has:
1128
- weaves for file texts and inventory
1129
- hash subdirectory based stores.
1130
- TextStores for revisions and signatures.
1134
super(RepositoryFormat6, self).__init__()
1135
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1137
def get_format_description(self):
1138
"""See RepositoryFormat.get_format_description()."""
1139
return "Weave repository format 6"
1141
def _get_revision_store(self, repo_transport, control_files):
1142
"""See RepositoryFormat._get_revision_store()."""
1143
return self._get_text_rev_store(repo_transport,
1149
def _get_text_store(self, transport, control_files):
1150
"""See RepositoryFormat._get_text_store()."""
1151
return self._get_versioned_file_store('weaves', transport, control_files)
1154
class MetaDirRepositoryFormat(RepositoryFormat):
1155
"""Common base class for the new repositories using the metadir layour."""
1158
super(MetaDirRepositoryFormat, self).__init__()
1159
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
1161
def _create_control_files(self, a_bzrdir):
1162
"""Create the required files and the initial control_files object."""
1163
# FIXME: RBC 20060125 dont peek under the covers
1164
# NB: no need to escape relative paths that are url safe.
1165
repository_transport = a_bzrdir.get_repository_transport(self)
1166
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1167
control_files.create_lock()
1168
return control_files
1170
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1171
"""Upload the initial blank content."""
1172
control_files = self._create_control_files(a_bzrdir)
1173
control_files.lock_write()
1175
control_files._transport.mkdir_multi(dirs,
1176
mode=control_files._dir_mode)
1177
for file, content in files:
1178
control_files.put(file, content)
1179
for file, content in utf8_files:
1180
control_files.put_utf8(file, content)
1182
control_files.put_utf8('shared-storage', '')
1184
control_files.unlock()
1187
class RepositoryFormat7(MetaDirRepositoryFormat):
1188
"""Bzr repository 7.
1190
This repository format has:
1191
- weaves for file texts and inventory
1192
- hash subdirectory based stores.
1193
- TextStores for revisions and signatures.
1194
- a format marker of its own
1195
- an optional 'shared-storage' flag
1196
- an optional 'no-working-trees' flag
1199
def _get_control_store(self, repo_transport, control_files):
1200
"""Return the control store for this repository."""
1201
return self._get_versioned_file_store('',
1206
def get_format_string(self):
1207
"""See RepositoryFormat.get_format_string()."""
1208
return "Bazaar-NG Repository format 7"
1210
def get_format_description(self):
1211
"""See RepositoryFormat.get_format_description()."""
1212
return "Weave repository format 7"
1214
def _get_revision_store(self, repo_transport, control_files):
1215
"""See RepositoryFormat._get_revision_store()."""
1216
return self._get_text_rev_store(repo_transport,
1223
def _get_text_store(self, transport, control_files):
1224
"""See RepositoryFormat._get_text_store()."""
1225
return self._get_versioned_file_store('weaves',
1229
def initialize(self, a_bzrdir, shared=False):
1230
"""Create a weave repository.
1232
:param shared: If true the repository will be initialized as a shared
1235
from bzrlib.weavefile import write_weave_v5
1236
from bzrlib.weave import Weave
1238
# Create an empty weave
1240
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1241
empty_weave = sio.getvalue()
1243
mutter('creating repository in %s.', a_bzrdir.transport.base)
1244
dirs = ['revision-store', 'weaves']
1245
files = [('inventory.weave', StringIO(empty_weave)),
1247
utf8_files = [('format', self.get_format_string())]
1249
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1250
return self.open(a_bzrdir=a_bzrdir, _found=True)
1252
def open(self, a_bzrdir, _found=False, _override_transport=None):
1253
"""See RepositoryFormat.open().
1255
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1256
repository at a slightly different url
1257
than normal. I.e. during 'upgrade'.
1260
format = RepositoryFormat.find_format(a_bzrdir)
1261
assert format.__class__ == self.__class__
1262
if _override_transport is not None:
1263
repo_transport = _override_transport
1265
repo_transport = a_bzrdir.get_repository_transport(None)
1266
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1267
text_store = self._get_text_store(repo_transport, control_files)
1268
control_store = self._get_control_store(repo_transport, control_files)
1269
_revision_store = self._get_revision_store(repo_transport, control_files)
1270
return MetaDirRepository(_format=self,
1272
control_files=control_files,
1273
_revision_store=_revision_store,
1274
control_store=control_store,
1275
text_store=text_store)
1278
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1279
"""Bzr repository knit format 1.
1281
This repository format has:
1282
- knits for file texts and inventory
1283
- hash subdirectory based stores.
1284
- knits for revisions and signatures
1285
- TextStores for revisions and signatures.
1286
- a format marker of its own
1287
- an optional 'shared-storage' flag
1288
- an optional 'no-working-trees' flag
1291
This format was introduced in bzr 0.8.
1294
def _get_control_store(self, repo_transport, control_files):
1295
"""Return the control store for this repository."""
1296
return VersionedFileStore(
1299
file_mode=control_files._file_mode,
1300
versionedfile_class=KnitVersionedFile,
1301
versionedfile_kwargs={'factory':KnitPlainFactory()},
1304
def get_format_string(self):
1305
"""See RepositoryFormat.get_format_string()."""
1306
return "Bazaar-NG Knit Repository Format 1"
1308
def get_format_description(self):
1309
"""See RepositoryFormat.get_format_description()."""
1310
return "Knit repository format 1"
1312
def _get_revision_store(self, repo_transport, control_files):
1313
"""See RepositoryFormat._get_revision_store()."""
1314
from bzrlib.store.revision.knit import KnitRevisionStore
1315
versioned_file_store = VersionedFileStore(
1317
file_mode=control_files._file_mode,
1320
versionedfile_class=KnitVersionedFile,
1321
versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
1324
return KnitRevisionStore(versioned_file_store)
1326
def _get_text_store(self, transport, control_files):
1327
"""See RepositoryFormat._get_text_store()."""
1328
return self._get_versioned_file_store('knits',
1331
versionedfile_class=KnitVersionedFile,
1334
def initialize(self, a_bzrdir, shared=False):
1335
"""Create a knit format 1 repository.
1337
:param a_bzrdir: bzrdir to contain the new repository; must already
1339
:param shared: If true the repository will be initialized as a shared
1342
mutter('creating repository in %s.', a_bzrdir.transport.base)
1343
dirs = ['revision-store', 'knits']
1345
utf8_files = [('format', self.get_format_string())]
1347
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1348
repo_transport = a_bzrdir.get_repository_transport(None)
1349
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1350
control_store = self._get_control_store(repo_transport, control_files)
1351
transaction = bzrlib.transactions.WriteTransaction()
1352
# trigger a write of the inventory store.
1353
control_store.get_weave_or_empty('inventory', transaction)
1354
_revision_store = self._get_revision_store(repo_transport, control_files)
1355
_revision_store.has_revision_id('A', transaction)
1356
_revision_store.get_signature_file(transaction)
1357
return self.open(a_bzrdir=a_bzrdir, _found=True)
1359
def open(self, a_bzrdir, _found=False, _override_transport=None):
1360
"""See RepositoryFormat.open().
1362
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1363
repository at a slightly different url
1364
than normal. I.e. during 'upgrade'.
1367
format = RepositoryFormat.find_format(a_bzrdir)
1368
assert format.__class__ == self.__class__
1369
if _override_transport is not None:
1370
repo_transport = _override_transport
1372
repo_transport = a_bzrdir.get_repository_transport(None)
1373
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1374
text_store = self._get_text_store(repo_transport, control_files)
1375
control_store = self._get_control_store(repo_transport, control_files)
1376
_revision_store = self._get_revision_store(repo_transport, control_files)
1377
return KnitRepository(_format=self,
1379
control_files=control_files,
1380
_revision_store=_revision_store,
1381
control_store=control_store,
1382
text_store=text_store)
1385
# formats which have no format string are not discoverable
1386
# and not independently creatable, so are not registered.
1387
RepositoryFormat.register_format(RepositoryFormat7())
1388
_default_format = RepositoryFormatKnit1()
1389
RepositoryFormat.register_format(_default_format)
1390
RepositoryFormat.set_default_format(_default_format)
1391
_legacy_formats = [RepositoryFormat4(),
1392
RepositoryFormat5(),
1393
RepositoryFormat6()]
1396
class InterRepository(InterObject):
1397
"""This class represents operations taking place between two repositories.
1399
Its instances have methods like copy_content and fetch, and contain
1400
references to the source and target repositories these operations can be
1403
Often we will provide convenience methods on 'repository' which carry out
1404
operations with another repository - they will always forward to
1405
InterRepository.get(other).method_name(parameters).
1409
"""The available optimised InterRepository types."""
1412
def copy_content(self, revision_id=None, basis=None):
1413
"""Make a complete copy of the content in self into destination.
1415
This is a destructive operation! Do not use it on existing
1418
:param revision_id: Only copy the content needed to construct
1419
revision_id and its parents.
1420
:param basis: Copy the needed data preferentially from basis.
1423
self.target.set_make_working_trees(self.source.make_working_trees())
1424
except NotImplementedError:
1426
# grab the basis available data
1427
if basis is not None:
1428
self.target.fetch(basis, revision_id=revision_id)
1429
# but dont bother fetching if we have the needed data now.
1430
if (revision_id not in (None, NULL_REVISION) and
1431
self.target.has_revision(revision_id)):
1433
self.target.fetch(self.source, revision_id=revision_id)
1435
def _double_lock(self, lock_source, lock_target):
1436
"""Take out too locks, rolling back the first if the second throws."""
1441
# we want to ensure that we don't leave source locked by mistake.
1442
# and any error on target should not confuse source.
1443
self.source.unlock()
1447
def fetch(self, revision_id=None, pb=None):
1448
"""Fetch the content required to construct revision_id.
1450
The content is copied from source to target.
1452
:param revision_id: if None all content is copied, if NULL_REVISION no
1454
:param pb: optional progress bar to use for progress reports. If not
1455
provided a default one will be created.
1457
Returns the copied revision count and the failed revisions in a tuple:
1460
from bzrlib.fetch import GenericRepoFetcher
1461
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1462
self.source, self.source._format, self.target, self.target._format)
1463
f = GenericRepoFetcher(to_repository=self.target,
1464
from_repository=self.source,
1465
last_revision=revision_id,
1467
return f.count_copied, f.failed_revisions
1469
def lock_read(self):
1470
"""Take out a logical read lock.
1472
This will lock the source branch and the target branch. The source gets
1473
a read lock and the target a read lock.
1475
self._double_lock(self.source.lock_read, self.target.lock_read)
1477
def lock_write(self):
1478
"""Take out a logical write lock.
1480
This will lock the source branch and the target branch. The source gets
1481
a read lock and the target a write lock.
1483
self._double_lock(self.source.lock_read, self.target.lock_write)
1486
def missing_revision_ids(self, revision_id=None):
1487
"""Return the revision ids that source has that target does not.
1489
These are returned in topological order.
1491
:param revision_id: only return revision ids included by this
1494
# generic, possibly worst case, slow code path.
1495
target_ids = set(self.target.all_revision_ids())
1496
if revision_id is not None:
1497
source_ids = self.source.get_ancestry(revision_id)
1498
assert source_ids[0] == None
1501
source_ids = self.source.all_revision_ids()
1502
result_set = set(source_ids).difference(target_ids)
1503
# this may look like a no-op: its not. It preserves the ordering
1504
# other_ids had while only returning the members from other_ids
1505
# that we've decided we need.
1506
return [rev_id for rev_id in source_ids if rev_id in result_set]
1509
"""Release the locks on source and target."""
1511
self.target.unlock()
1513
self.source.unlock()
1516
class InterWeaveRepo(InterRepository):
1517
"""Optimised code paths between Weave based repositories."""
1519
_matching_repo_format = RepositoryFormat7()
1520
"""Repository format for testing with."""
1523
def is_compatible(source, target):
1524
"""Be compatible with known Weave formats.
1526
We dont test for the stores being of specific types becase that
1527
could lead to confusing results, and there is no need to be
1531
return (isinstance(source._format, (RepositoryFormat5,
1533
RepositoryFormat7)) and
1534
isinstance(target._format, (RepositoryFormat5,
1536
RepositoryFormat7)))
1537
except AttributeError:
1541
def copy_content(self, revision_id=None, basis=None):
1542
"""See InterRepository.copy_content()."""
1543
# weave specific optimised path:
1544
if basis is not None:
1545
# copy the basis in, then fetch remaining data.
1546
basis.copy_content_into(self.target, revision_id)
1547
# the basis copy_content_into could misset this.
1549
self.target.set_make_working_trees(self.source.make_working_trees())
1550
except NotImplementedError:
1552
self.target.fetch(self.source, revision_id=revision_id)
1555
self.target.set_make_working_trees(self.source.make_working_trees())
1556
except NotImplementedError:
1558
# FIXME do not peek!
1559
if self.source.control_files._transport.listable():
1560
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1562
self.target.weave_store.copy_all_ids(
1563
self.source.weave_store,
1565
from_transaction=self.source.get_transaction(),
1566
to_transaction=self.target.get_transaction())
1567
pb.update('copying inventory', 0, 1)
1568
self.target.control_weaves.copy_multi(
1569
self.source.control_weaves, ['inventory'],
1570
from_transaction=self.source.get_transaction(),
1571
to_transaction=self.target.get_transaction())
1572
self.target._revision_store.text_store.copy_all_ids(
1573
self.source._revision_store.text_store,
1578
self.target.fetch(self.source, revision_id=revision_id)
1581
def fetch(self, revision_id=None, pb=None):
1582
"""See InterRepository.fetch()."""
1583
from bzrlib.fetch import GenericRepoFetcher
1584
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1585
self.source, self.source._format, self.target, self.target._format)
1586
f = GenericRepoFetcher(to_repository=self.target,
1587
from_repository=self.source,
1588
last_revision=revision_id,
1590
return f.count_copied, f.failed_revisions
1593
def missing_revision_ids(self, revision_id=None):
1594
"""See InterRepository.missing_revision_ids()."""
1595
# we want all revisions to satisfy revision_id in source.
1596
# but we dont want to stat every file here and there.
1597
# we want then, all revisions other needs to satisfy revision_id
1598
# checked, but not those that we have locally.
1599
# so the first thing is to get a subset of the revisions to
1600
# satisfy revision_id in source, and then eliminate those that
1601
# we do already have.
1602
# this is slow on high latency connection to self, but as as this
1603
# disk format scales terribly for push anyway due to rewriting
1604
# inventory.weave, this is considered acceptable.
1606
if revision_id is not None:
1607
source_ids = self.source.get_ancestry(revision_id)
1608
assert source_ids[0] == None
1611
source_ids = self.source._all_possible_ids()
1612
source_ids_set = set(source_ids)
1613
# source_ids is the worst possible case we may need to pull.
1614
# now we want to filter source_ids against what we actually
1615
# have in target, but dont try to check for existence where we know
1616
# we do not have a revision as that would be pointless.
1617
target_ids = set(self.target._all_possible_ids())
1618
possibly_present_revisions = target_ids.intersection(source_ids_set)
1619
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1620
required_revisions = source_ids_set.difference(actually_present_revisions)
1621
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1622
if revision_id is not None:
1623
# we used get_ancestry to determine source_ids then we are assured all
1624
# revisions referenced are present as they are installed in topological order.
1625
# and the tip revision was validated by get_ancestry.
1626
return required_topo_revisions
1628
# if we just grabbed the possibly available ids, then
1629
# we only have an estimate of whats available and need to validate
1630
# that against the revision records.
1631
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1634
class InterKnitRepo(InterRepository):
1635
"""Optimised code paths between Knit based repositories."""
1637
_matching_repo_format = RepositoryFormatKnit1()
1638
"""Repository format for testing with."""
1641
def is_compatible(source, target):
1642
"""Be compatible with known Knit formats.
1644
We dont test for the stores being of specific types becase that
1645
could lead to confusing results, and there is no need to be
1649
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1650
isinstance(target._format, (RepositoryFormatKnit1)))
1651
except AttributeError:
1655
def fetch(self, revision_id=None, pb=None):
1656
"""See InterRepository.fetch()."""
1657
from bzrlib.fetch import KnitRepoFetcher
1658
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1659
self.source, self.source._format, self.target, self.target._format)
1660
f = KnitRepoFetcher(to_repository=self.target,
1661
from_repository=self.source,
1662
last_revision=revision_id,
1664
return f.count_copied, f.failed_revisions
1667
def missing_revision_ids(self, revision_id=None):
1668
"""See InterRepository.missing_revision_ids()."""
1669
if revision_id is not None:
1670
source_ids = self.source.get_ancestry(revision_id)
1671
assert source_ids[0] == None
1674
source_ids = self.source._all_possible_ids()
1675
source_ids_set = set(source_ids)
1676
# source_ids is the worst possible case we may need to pull.
1677
# now we want to filter source_ids against what we actually
1678
# have in target, but dont try to check for existence where we know
1679
# we do not have a revision as that would be pointless.
1680
target_ids = set(self.target._all_possible_ids())
1681
possibly_present_revisions = target_ids.intersection(source_ids_set)
1682
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1683
required_revisions = source_ids_set.difference(actually_present_revisions)
1684
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1685
if revision_id is not None:
1686
# we used get_ancestry to determine source_ids then we are assured all
1687
# revisions referenced are present as they are installed in topological order.
1688
# and the tip revision was validated by get_ancestry.
1689
return required_topo_revisions
1691
# if we just grabbed the possibly available ids, then
1692
# we only have an estimate of whats available and need to validate
1693
# that against the revision records.
1694
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1696
InterRepository.register_optimiser(InterWeaveRepo)
1697
InterRepository.register_optimiser(InterKnitRepo)
1700
class RepositoryTestProviderAdapter(object):
1701
"""A tool to generate a suite testing multiple repository formats at once.
1703
This is done by copying the test once for each transport and injecting
1704
the transport_server, transport_readonly_server, and bzrdir_format and
1705
repository_format classes into each copy. Each copy is also given a new id()
1706
to make it easy to identify.
1709
def __init__(self, transport_server, transport_readonly_server, formats):
1710
self._transport_server = transport_server
1711
self._transport_readonly_server = transport_readonly_server
1712
self._formats = formats
1714
def adapt(self, test):
1715
result = TestSuite()
1716
for repository_format, bzrdir_format in self._formats:
1717
new_test = deepcopy(test)
1718
new_test.transport_server = self._transport_server
1719
new_test.transport_readonly_server = self._transport_readonly_server
1720
new_test.bzrdir_format = bzrdir_format
1721
new_test.repository_format = repository_format
1722
def make_new_test_id():
1723
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1724
return lambda: new_id
1725
new_test.id = make_new_test_id()
1726
result.addTest(new_test)
1730
class InterRepositoryTestProviderAdapter(object):
1731
"""A tool to generate a suite testing multiple inter repository formats.
1733
This is done by copying the test once for each interrepo provider and injecting
1734
the transport_server, transport_readonly_server, repository_format and
1735
repository_to_format classes into each copy.
1736
Each copy is also given a new id() to make it easy to identify.
1739
def __init__(self, transport_server, transport_readonly_server, formats):
1740
self._transport_server = transport_server
1741
self._transport_readonly_server = transport_readonly_server
1742
self._formats = formats
1744
def adapt(self, test):
1745
result = TestSuite()
1746
for interrepo_class, repository_format, repository_format_to in self._formats:
1747
new_test = deepcopy(test)
1748
new_test.transport_server = self._transport_server
1749
new_test.transport_readonly_server = self._transport_readonly_server
1750
new_test.interrepo_class = interrepo_class
1751
new_test.repository_format = repository_format
1752
new_test.repository_format_to = repository_format_to
1753
def make_new_test_id():
1754
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1755
return lambda: new_id
1756
new_test.id = make_new_test_id()
1757
result.addTest(new_test)
1761
def default_test_list():
1762
"""Generate the default list of interrepo permutations to test."""
1764
# test the default InterRepository between format 6 and the current
1766
# XXX: robertc 20060220 reinstate this when there are two supported
1767
# formats which do not have an optimal code path between them.
1768
result.append((InterRepository,
1769
RepositoryFormat6(),
1770
RepositoryFormatKnit1()))
1771
for optimiser in InterRepository._optimisers:
1772
result.append((optimiser,
1773
optimiser._matching_repo_format,
1774
optimiser._matching_repo_format
1776
# if there are specific combinations we want to use, we can add them
1781
class CopyConverter(object):
1782
"""A repository conversion tool which just performs a copy of the content.
1784
This is slow but quite reliable.
1787
def __init__(self, target_format):
1788
"""Create a CopyConverter.
1790
:param target_format: The format the resulting repository should be.
1792
self.target_format = target_format
1794
def convert(self, repo, pb):
1795
"""Perform the conversion of to_convert, giving feedback via pb.
1797
:param to_convert: The disk object to convert.
1798
:param pb: a progress bar to use for progress information.
1803
# this is only useful with metadir layouts - separated repo content.
1804
# trigger an assertion if not such
1805
repo._format.get_format_string()
1806
self.repo_dir = repo.bzrdir
1807
self.step('Moving repository to repository.backup')
1808
self.repo_dir.transport.move('repository', 'repository.backup')
1809
backup_transport = self.repo_dir.transport.clone('repository.backup')
1810
self.source_repo = repo._format.open(self.repo_dir,
1812
_override_transport=backup_transport)
1813
self.step('Creating new repository')
1814
converted = self.target_format.initialize(self.repo_dir,
1815
self.source_repo.is_shared())
1816
converted.lock_write()
1818
self.step('Copying content into repository.')
1819
self.source_repo.copy_content_into(converted)
1822
self.step('Deleting old repository content.')
1823
self.repo_dir.transport.delete_tree('repository.backup')
1824
self.pb.note('repository converted')
1826
def step(self, message):
1827
"""Update the pb by a step."""
1829
self.pb.update(message, self.count, self.total)
1832
# Copied from xml.sax.saxutils
1833
def _unescape_xml(data):
1834
"""Unescape &, <, and > in a string of data.
1836
data = data.replace("<", "<")
1837
data = data.replace(">", ">")
1838
# must do ampersand last
1839
return data.replace("&", "&")